0
0
Blockchain / Solidityprogramming~5 mins

Payable functions in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Payable functions let a program receive money when someone uses them. This is important to handle payments safely and clearly.

When you want users to send money to your program, like buying a ticket.
When you need to accept donations or tips.
When creating a contract that sells digital items or services.
When you want to collect fees for using a service.
When you want to store money inside the program for later use.
Syntax
Blockchain / Solidity
function functionName() public payable {
    // function code
}

The keyword payable marks the function to accept money.

Without payable, the function will reject any money sent.

Examples
This function can receive money when called.
Blockchain / Solidity
function deposit() public payable {
    // Accept money sent to this function
}
This function checks if enough money was sent before proceeding.
Blockchain / Solidity
function buyItem() external payable {
    require(msg.value >= itemPrice, "Not enough money");
    // Process purchase
}
A simple function to accept donations.
Blockchain / Solidity
function donate() public payable {
    // Just accept donations
}
Sample Program

This contract lets anyone send money using deposit. The owner can check the balance and withdraw money.

Blockchain / Solidity
pragma solidity ^0.8.0;

contract SimpleWallet {
    address public owner;

    constructor() {
        owner = msg.sender;
    }

    // Payable function to receive money
    function deposit() public payable {
        // Money sent is stored in contract balance
    }

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

    // Withdraw money by owner
    function withdraw(uint amount) public {
        require(msg.sender == owner, "Only owner can withdraw");
        require(amount <= address(this).balance, "Not enough balance");
        payable(owner).transfer(amount);
    }
}
OutputSuccess
Important Notes

Only functions marked payable can receive money.

Use msg.value to check how much money was sent.

Always check and handle money carefully to avoid mistakes or theft.

Summary

Payable functions let your program accept money safely.

Mark functions with payable to receive funds.

Use msg.value to know how much money was sent.