1

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 2

0

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.

0

The msg.value contains the amount of ETH that was received, so you can send that amount back to msg.sender.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.