Payable in Solidity

I'm starting a new series on my blog where I explain Solidity concepts in a short and concise manner. This is the first out of many more to come!

Payable in Solidity

What is Payable in Solidity?

When writing a smart contract, you need to ensure that money is being sent to the contract and out of the contract as well. Payable does this for you, any function in Solidity with the modifier Payable ensures that the function can send and receive Ether. It can process transactions with non-zero Ether values and rejects any transactions with a zero Ether value. Additionally, if you want a function to process transactions and have not included the payable keyword in them the transaction will be automatically rejected. An example of this is supposing you have a receive() function with the payable modifier, this means that this function can receive money in the contract and now imagine there is a function send() without a payable modifier it will reject the transaction when you want to send money out of the contract.

Fallback payable functions are also a big help in Solidity. Imagine if someone sends funds to your contract in a function without the payable modifier, you can define such function to have a fallback payable function which ensures that the transaction will go through regardless. This is why it is considered good practice to use some version of a function with noname and a payable modifier. Notice here the name of the function is 'noname' and not payable, payable is the modifier.

 function *noname* () payable { }

You can define a payable function using the following syntax:

      function receive() payable {}

      function send() payable {}

As you can see the payable keyword is not a function but a modifier. Sometimes, people confuse it for a function and end up changing the meaning of the whole function causing the code to malfunction. As we specified before this about the 'noname' function, if someone tries calling another function without the payable modifier it acts as a fallback and transfers the ether being sent to this noname function.

pragma solidity ^0.7.0; 
contract payableSample { 
//add the keyword payable to the state variable 
address payable public Owner;
 //set the owner to the msg.sender 
constructor () public { 
Owner = msg.sender; 
}
 //create a modifier that the msg.sender must be the owner modifier 
onlyOwner() {
 require(msg.sender == Owner, 'Not owner'); 
_;
 } 
//the owner can withdraw from the contract because payable was added to the state variable above
 function withdraw (uint _amount) public onlyOwner { 
Owner.transfer(_amount); 
}
 //to.transfer works because we made the address above payable. 
function transfer(address payable _to, uint _amount) public onlyOwner { 
_to.transfer(_amount);
 //to.transfer works because we made the address above payable.
 } }

If you have any more questions you can find me on my Twitter and LinkedIn