Skip to content

Instantly share code, notes, and snippets.

@ashwinYardi
Created February 24, 2023 12:51
Show Gist options
  • Save ashwinYardi/573b5af59af6c59841676808c1fc1922 to your computer and use it in GitHub Desktop.
Save ashwinYardi/573b5af59af6c59841676808c1fc1922 to your computer and use it in GitHub Desktop.
Contract to demo fallback function and receive function.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract DemoFallbackFunctions {
event Log(string typeOfFunction, uint gas);
// Fallback function must be declared as external.
fallback() external payable {
// send / transfer (forwards 2300 gas to this fallback function)
// call (forwards all of the gas)
emit Log("fallback", gasleft());
}
// Receive is a variant of fallback that is triggered when msg.data is empty
receive() external payable {
emit Log("receive", gasleft());
}
// Helper function to check the balance of this contract
function getBalance() public view returns (uint) {
return address(this).balance;
}
}
contract TestFallbackFunctions {
address payable contractAddress;
constructor(address payable _addr) {
contractAddress = _addr;
}
function callReceiveFunction() public payable {
contractAddress.transfer(msg.value);
}
function callFallbackFunction() public payable {
(bool sent,) = contractAddress.call{value: msg.value}("abcd");
require(sent, "Fallback function call failed");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment