Is there a way to get and keep the value sent to the fallback/receive functions? Let's say, I want to send back Ethers that sent to my contract. Okay, existence of fallback function is enough to deal with receiving ether but I want to keep value sent to me. How can I do it?
2 Answers
If you want to send the amount back to the original sender, you can do this:
fallback() external payable {
address _to = msg.sender;
(bool success, ) = _to.call{value: msg.value}("");
require(success, "send failed")
}
If you want to send to a specific address, replace the _to. You might face some complexities due to gas if your contract balance is zero, then send will fail.
The msg.value
contains the amount of ETH that was received, so you can send that amount back to msg.sender
.