0

I have read a few similar question's but nothing with my exact question. I'm trying to make a function to send ether to the contract. But only the owner should be able to send ether to the contract. Until now I’ve only used the fallback (), receive() In this matter shown below.

fallback() external payable {
    // custom function code
}

receive() external payable {
    // custom function code
}

And then I use the transact in the remix IDE to transfer the Ether and it works fine. My only doubt is, would people be able to transfer the ether from the contract to them?

Below is the function to transfer Ether, but I cant get it to work. The error im getting is "The called function should be payable if you send value and the value you send should be less than your current balance."

   function _SendEth(uint256 _EthAmount) public payable {

   payable(msg.sender).transfer(_EthAmount);
    }

note: i am using pragma solidity ^0.8.0

1
  • 1
    What you're doing should work. Although you don't have any owner restrictions, as you desired. Jul 7, 2022 at 5:00

1 Answer 1

1

Firstly, I think that you should remove payable declaration for fallback. The receive is usually used to be a payable fallback, and fallback is usually used as a non-payable fallback function.

Secondly, anyone is allowed to call these functions. You need to implement access control to limit the execution of the functions to a given address. You can do so by using the OpenZeppelin's access control smart contracts, or implement it yourself.

If you use OpenZeppelin's access control, you would only need to add the onlyOwner modifier to your functions like this:

function _SendEth(uint256 _EthAmount) public payable onlyOwner {
    payable(msg.sender).transfer(_EthAmount);
}

You could do the same for the receive and fallback function if you'd like.

1
  • thank you for the feedback, i haven't used OpenZeppelin's yet but i will do so. What ive been doing it programming it my self in Remix. So what i will do is add the only owner modifier , and also make a function called change owner that only the owner can call in case i need to change owners for some reason. Jul 8, 2022 at 13:43

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.