Solidity Assignment 3
In this assignment, we will test the behavior of receive, fallback, and no fallback function. We write a contract fallback. It implements the functions fallback() and receive(). See the code snippet below.
pragma solidity 0.8.20;
contract fallbackContract{
string public calledMethod;
fallback() external payable{
calledMethod = "Fallback";
}
receive() external payable{
calledMethod = "Receive";
}
}
Deploy the contract above and copy the address. Then we implement the caller contract fallbackCall.
pragma solidity 0.8.20;
contract fallbackSend{
address payable public receiver = payable (Address here);
uint256 public balance;
constructor() payable{
}
function testCall() public{
receiver.call{value:50}("");
}
function getBalance() public{
balance = address(this).balance;
}
}
Copy the address of the fallback contract to the address variable, compile it and deploy it while sending some wei along. Execute the function testCall.
When looking at the content of the variable calledMethod from the fallback contract, it should display “Receive”. Now, we want to add some data to the call method. In the contract fallbackCall, change line 13 to
receiver.call{value:50}(abi.encodeWithSignature("Test()"));
It calls a method Test. But since this method doesn’t exist, the fallback() function is executed instead. Compile and deploy the contract and try it out. The variable calledMethod should now display “Fallback”.
You can now play a bit with functions, payable modifier or data transferred.