Fallback Functions in Solidity

By akohad Feb27,2023

[ad_1]

  • If a function that doesn’t exist is called
  • Ether is sent directly to a contract but receive() doesn’t exist or msg.data isn’t empty, fallback has a 2300 gas limit when called by transfer or send.
  • It is called when the contract names a function that doesn’t exist.
  • Must be marked as external.
  • It has no name.
  • It has no arguments
  • It can’t return anything back.
  • It’s usually defined together with contracts.
  • If the contract is not marked as payable, it will throw an exception if it gets just plain ether without any data.
  • If a contract only gets plain Ether and no other information about the transaction, fallback functions are called.
  • This choice for the default design is smart and helps protect users.
  • But for our use case, it will be very important that our smart contract has a fallback function that lets it receive plain Ether.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Fallback {
event Log(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(gasleft());
}
// Helper function to check the balance of this contract
function getBalance() public view returns (uint) {
return address(this).balance;
}
}
contract SendToFallback {
function transferToFallback(address payable to) public payable {
to.transfer(msg.value);
}
function callFallback(address payable to) public payable {
(bool sent, ) = to.call{value: msg.value}("");
require(sent, "Failed to send Ether");
}
}

New to trading? Try crypto trading bots or copy trading on best crypto exchanges

[ad_2]

Source link

By akohad

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *