payable is a keyword in the Solidity language, primarily used to enable functions to receive Ether payments. In smart contracts, when you want the contract to receive and process Ether, you must use the payable modifier in the function declaration. This keyword ensures that the function can receive Ether upon invocation.
Example
Suppose we have a smart contract that allows users to pay for a service. Here is a simple example using the payable keyword:
solidity// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; contract PaymentContract { address payable public owner; // Constructor to set the contract owner constructor() { owner = payable(msg.sender); // Sets the deployer's address as the owner } // A function that can receive payments function payForService() public payable { require(msg.value > 0, "Payment must be greater than 0"); // Add service logic here } // Withdraw all stored Ether to the owner's account function withdraw() public { require(msg.sender == owner, "Only owner can withdraw"); owner.transfer(address(this).balance); } }
In the above example, the payForService function uses the payable modifier, meaning users can send Ether when calling this function. The contract checks if the sent Ether exceeds zero; if so, it proceeds with the service-related logic. Additionally, the withdraw function allows the contract owner to withdraw all stored Ether to their account.
Through this mechanism, the payable keyword provides smart contracts with the ability to receive and process Ether payments, which is particularly valuable for applications such as crowdfunding platforms, online marketplaces, or any application involving Ether transactions.