Solidity – How to Send Ether to a Smart Contract Address

remixsolidityweb3js

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

Best Answer

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.

Related Topic