当前位置:网站首页>Solidy - fallback function - 2 trigger execution modes
Solidy - fallback function - 2 trigger execution modes
2022-06-30 05:36:00 【ling1998】
fallback brief introduction
Details refer to : contract — Solidity develop file
fallback Function is an unnamed function in the contract , No parameters and no return value .
fallback conditions for execution :
- If in the call of a contract , When no other function matches the given function identifier ( Or no call data provided ),fallback The function will be executed ;
- When the contract receives ether ,fallback The function will be executed .
The following is for 2 Three execution methods are used to show examples , For the source code, see :smartcontract/Fallback at main · tracyzhang1998/smartcontract · GitHub
conditions for execution 1
If in the call of a contract , When no other function matches the given function identifier ( Or no call data provided ),fallback The function will be executed
Test contract code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
// Base contract implementation
contract TestFallback {
string message;
// Constructors , Initialize state variables message
constructor() {
message = "hello";
}
fallback() external {
message = "fallback";
}
// Call a function that does not exist in this contract
function testFallback() external returns (bytes memory) {
// Call a function that does not exist getMsgNew()
bytes memory method = abi.encodeWithSignature("getMsgNew()");
(bool success, bytes memory returnData) = address(this).call(method);
require(success, "get fail");
return returnData;
}
// Calling a function that already exists in this contract , But no parameters are passed
function testFallbackWithNoParam() external returns (bytes memory) {
// Call an existing function setMsg(), Parameter not passed
bytes memory method = abi.encodeWithSignature("setMsg()");
(bool success, bytes memory returnData) = address(this).call(method);
require(success, "set fail");
return returnData;
}
function getMsg() external view returns (string memory) {
return message;
}
function setMsg(string memory _message) external {
message = _message;
}
}
Test steps and results
(1) Call a function that does not exist
0、 Deployment contract , call getMsg Function to view the initial value of the state variable "hello"
1、 Call function testFallback, Call a function that does not exist
2、 call getMsg Function to view that the state variable has been modified fallback Function "fallback" 了

(2) Call an existing function without passing arguments
1、 call setMsg Function to set the initial value of the state variable to "hello"
2、 Call function testFallbackWithNoParam, Call an existing function without passing arguments
3、 call getMsg Function to view that the state variable has been modified fallback Function "fallback" 了

conditions for execution 2
When the contract receives ether ,fallback The function will be executed , To receive ether ,fallback Function must be marked with payable. If there is no such function , The contract cannot receive ether through a regular transaction .
Test contract code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
// contain fallback Contract of function , The contract account can receive etheric money transferred from other contracts
contract TestFallback {
string message;
// Constructors , Initialize state variables message, At the same time, you can deposit into the contract account
constructor() payable {
message = "hello";
}
// Fallback function , Be able to receive ether for this contract account
fallback() external payable {
}
// deposit , If you forget to deposit when deploying , You can directly call this function to deposit into the contract account
function deposit() external payable {
}
// Send Ethernet
function sendEther(address _addr) external {
bool result = payable(_addr).send(2);
require(result, "send fail");
}
// Check the contract account balance
function getContractBalance() external view returns (uint256) {
return address(this).balance;
}
}
// It doesn't contain fallback Contract of function
contract TestWithoutFallback {
// Constructors , Deposit to the contract account during initialization
constructor() payable{
}
// deposit , If you forget to deposit when deploying , You can directly call this function to deposit into the contract account
function deposit() external payable {
}
// Send Ethernet
function sendEther(address _addr) external returns (bool) {
bool result = payable(_addr).send(2);
return result;
}
// Check the contract account balance
function getContractBalance() external view returns (uint256) {
return address(this).balance;
}
}
Deploy
It can be transferred directly to the contract during deployment 20Wei, If you forget to switch to , In the contract deposit The deposit function is transferred to the contract 20Wei, As shown in the figure below :

Test steps and results
(1) Use does not include fallback The contract function has fabllback Contract sending Ethernet
- Call does not contain fallback contract (TestWithoutFallback) Send Ethernet function in sendEther, The parameter contains fallback contract (TestFallback) Address , turn 2Wei;
- see TestWithoutFallback Contract account balance , Less found 2Wei, At present, it is 18Wei 了 , Prove that the transfer was successful ;
- see TestFallback Contract account balance , Found more 2Wei, At present, it is 22Wei, Prove successful reception , The contract account is able to receive ether , Because the contract contains fallback function ( And for payable).

(2) Use with fallback The contract function does not contain fabllback Contract sending Ethernet
Use with fallback The contract function does not contain fabllback Contract sending Ethernet , Transfer failure found , Wrong report ( As shown in the figure below ), That is, no fallback The contract of the function cannot accept currency . The official website documents are explained as follows :
An undefined fallback Contract of function , Receive ether directly ( There are no function calls , That is to use
sendortransfer) It throws an exception , And return ether ( stay Solidity v0.4.0 The previous behavior will be different ). So if you want your contract to receive ether , Must be realized fallback function .

Problems encountered
At testing time , You want to view the state variables message See if a call occurs fallback, stay fallback Pair of functions message Change the value of the state variable , As shown below :
fallback() external payable {
message = "fallback";
}
Test use does not include fallback The contract function has fabllback Contract sending Ethernet , If the above test results show that the transfer is successful , But the transfer will fail , As shown in the figure below :

Finally, the fallback Function message State variables , The function body contains nothing , Transfer succeeded , With the first (1) The test results are the same .
fallback() external payable {
}
边栏推荐
- Uboot reads the DDR memory size by sending 'R' characters through the terminal
- Vfpbs uploads excel and saves MSSQL to the database
- Unity mobile end sliding screen rotation
- 2022年,谁在推动音视频产业的新拐点?
- [learning notes] AssetBundle, xlua, hot update (use steps)
- Delete the repeating elements in the sorting list (simple questions)
- Who is promoting the new inflection point of audio and video industry in 2022?
- Revit二次开发---未打开项目使用面板功能
- Visualization of 3D geological model based on borehole data by map flapping software
- Responsive layout
猜你喜欢

The minecraft server address cannot be refreshed.

Sound network, standing in the "soil" of the Internet of things

Unity scroll view element drag and drop to automatically adsorb centering and card effect

Assembly learning tutorial: accessing memory (3)

抓取手机端变体组合思路设想

9. naive Bayes

How to judge the quality of network transformer? What symptom is network filter transformer broken?

Terminal convenient SSH connection

3D rotation album

86. 分隔链表
随机推荐
Promise知识点拾遗
[typescript] experimentaldecorators of vscode stepping pit
Revit secondary development - use panel function without opening the project
Unity gets the resolution of the game view
终端便捷ssh(免密)连接
Unity publishing /build settings
【板栗糖GIS】global mapper—如何把栅格的高程值赋予给点
D. Big Brush
Bessel curve with n control points
Unity3d- use animator and code to control task walking
Bev instance prediction based on monocular camera (iccv 2021)
Online assignment of C language program design in the 22nd spring of Western Polytechnic University
Use the code cloud publicholiday project to determine whether a day is a working day
剑指 Offer 22. 链表中倒数第k个节点
VFPBS上传EXCEL并保存MSSQL到数据库中
C # uses monopinvokecallback to directly call back C # function
Rotating frame target detection mmrotate v0.3.1 training dota data set (II)
Solitidy - fallback 回退函数 - 2种触发执行方式
Vfpbs uploads excel and saves MSSQL to the database
Sound network, standing in the "soil" of the Internet of things