Receive function is used to get ether on contract call. It must be external with payable visibility. it only call from other contract with call method and send, transfer throw an error.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract testFallBack{
uint public x = 1;
function getBalance()public view returns(uint balance){
balance = address(this).balance;
}
fallback() external{
}
receive() external payable{
x++;
}
}
contract CallerContract{
constructor() payable{}
//it will not execute because fallback function in other contract is not payable
function callOtherContractunknownMethod(testFallBack testObj)public returns(bool success){
(success,) = address(testObj).call{value: 1 ether}(abi.encodeWithSignature("Non_existing()"));
}
//send ether successfully
function onlySendEtherToOtherContract(testFallBack testObj)public returns(bool success){
(success, ) = address(testObj).call{value: 1 ether}("");
}
//send function not execute on receive method
function sendEtherWithSendFunction(testFallBack testObj)public returns(bool success){
success = payable(address(testObj)).send(1 ether);
}
}