当前位置:网站首页>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 {
}
边栏推荐
- Is it safe to open an account and trade with a compass?
- 使用码云PublicHoliday项目判断某天是否为工作日
- Does the tester need to analyze the cause of the bug?
- 剑指 Offer 18. 删除链表的节点
- Responding with flow layout
- Database SQL language 06 single line function
- 剑指 Offer 22. 链表中倒数第k个节点
- What kind of answer has Inspur given in the big AI model landing test?
- Operation of JSON file
- Answer sheet for online assignment of "motor and drive" of Xijiao 21 autumn (IV) [standard answer]
猜你喜欢

Rotation, translation and scaling of unity VR objects

使用码云PublicHoliday项目判断某天是否为工作日

Unityshader learning notes - Basic Attributes

We strongly recommend more than a dozen necessary plug-ins for idea development

OpenCL线程代数库ViennaCL的使用

The minecraft server address cannot be refreshed.

Sword finger offer 18 Delete the node of the linked list

【LeetCode】Easy | 225. Using queue to realize stack (pure C manual tearing queue)

Unity shader flat shadow

如何制作CSR(Certificate Signing Request)文件?
随机推荐
Configuration and use of controllers and routes in nestjs
[Blue Bridge Road -- bug free code] DS1302 time module code analysis
The definition of strain was originally from stretch_ Ratio started
Nestjs configures static resources, template engine, and post examples
Sword finger offer 18 Delete the node of the linked list
Online assignment of C language program design in the 22nd spring of Western Polytechnic University
PWN Introduction (2) stack overflow Foundation
PyGame. Why can't I exit when I click X in the window? I can only exit when I return idle
Sound network, standing in the "soil" of the Internet of things
抓取手机端变体组合思路设想
Unity determines whether the UI is clicked
Xijiao 21 autumn "motor and drive" online homework answer sheet (I) [standard answer]
[typescript] cannot redeclare block range variables
《谁动了我的奶酪》读后感
Rotating box target detection mmrotate v0.3.1 getting started
Summary of common loss functions in pytorch
Revit Secondary Development - - Project use Panel features not opened
遥感图像/UDA:Curriculum-Style Local-to-Global Adaptation for Cross-Domain Remote Sensing Image Segmentat
Learning about functions QAQ
Baiwen.com 7 days Internet of things smart home learning experience punch in the third day