Here i would shortly give a detailed explanation of what a payable function is. We need to understand that Solidity provides us with a special modifier (payable) among others, which gives us the possibility of sending money in to function. In this article, the payable function will be explicitly explained to solidify your knowledge about payable modifiers.
The payable modifier is added to a function such that it behaves in a particular way. Therefore, a Payable Function is a special type of function that can receive ether. It enables us send ether to a contract after it’s been called. This type of function is what makes Solidity and Ethereum so interesting.
This is what a payable function looks like.
Lets simplify this altogether. In a traditional settings, when you call a function on the normal web server, you cant send funds along with your function. This can only happen in Ethereum because money(ether), the data and contract code is all live on the Ethereum blockchain, which makes it possible to send ether to the contract at the same time.
Having explained the concept above, i would for example sake create a smart contract, a Marketplace for NFTs , and in this contract , users would practically buy NFTs. So we would be creating a function to buyNFT which takes a payable modifier. Taking it further, we would want to ensure that the money(ether) sent is equals to the NFT price. If this condition have been met, a transferNft function is called that then sends the NFT to the buyer (msg.sender: this is the sender of the transaction);
In this article, i have been able to explain the payable modifier and its effects when used in a function. We have also looked at an example where it’s applicable. So basically, a payable function helps us receive ether, send ether to a contract on call.
My next article would be on Modifiers in Solidity.. So watch out!!!
Hope you were able to get value out of this article! Thanks for reading and stay glued for more!!!