0
0
BlockchainConceptBeginner · 3 min read

What is payable in Solidity: Explanation and Example

In Solidity, payable is a keyword used to mark functions or addresses that can receive Ether. It allows a contract or function to accept and handle incoming payments securely.
⚙️

How It Works

Think of payable as a special permission slip in Solidity. When a function or an address is marked as payable, it means it can safely receive money (Ether) sent to it. Without this keyword, the contract or function will reject any Ether sent, like a locked mailbox that won’t accept letters.

This mechanism helps protect contracts from accidentally receiving Ether where they shouldn't. It also makes it clear to developers which parts of the contract are designed to handle payments, improving security and clarity.

💻

Example

This example shows a simple contract with a payable function that accepts Ether and stores the amount sent.

solidity
pragma solidity ^0.8.0;

contract PayableExample {
    uint public receivedAmount;

    // This function can receive Ether because it is payable
    function receiveFunds() external payable {
        receivedAmount += msg.value;
    }

    // Function to check contract balance
    function getBalance() external view returns (uint) {
        return address(this).balance;
    }
}
🎯

When to Use

Use payable when you want your contract to accept Ether payments. For example, in crowdfunding contracts, token sales, or any service where users send Ether to interact with the contract.

Marking functions or addresses as payable ensures that the contract can receive and handle funds properly, preventing accidental loss of Ether and making your contract’s intent clear.

Key Points

  • payable allows functions or addresses to receive Ether.
  • Without payable, sending Ether to a function will fail.
  • It improves contract security by explicitly marking where payments are accepted.
  • Use it in functions that handle deposits, purchases, or any Ether transfer.

Key Takeaways

payable marks functions or addresses that can receive Ether.
Functions without payable will reject incoming Ether.
Use payable to safely accept payments in your contract.
It helps prevent accidental Ether loss and clarifies contract design.