Introduction
Payable functions let a program receive money when someone uses them. This is important to handle payments safely and clearly.
Payable functions let a program receive money when someone uses them. This is important to handle payments safely and clearly.
function functionName() public payable {
// function code
}The keyword payable marks the function to accept money.
Without payable, the function will reject any money sent.
function deposit() public payable {
// Accept money sent to this function
}function buyItem() external payable {
require(msg.value >= itemPrice, "Not enough money");
// Process purchase
}function donate() public payable {
// Just accept donations
}This contract lets anyone send money using deposit. The owner can check the balance and withdraw money.
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); } }
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.
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.
payable function in a blockchain smart contract?payablepayable keyword marks a function that can accept cryptocurrency (like Ether) when called.payable.public) comes before payable keyword.function deposit() public payable {}. Options A, B, and D have incorrect keyword order or syntax.contract Test {
uint public balance;
function deposit() public payable {
balance = msg.value;
}
}msg.value in Soliditymsg.value holds the amount of wei (smallest Ether unit) sent with the transaction. 2 Ether equals 2 * 10^18 wei = 2000000000000000000 wei.balancebalance = msg.value, so balance stores the wei amount sent, which is 2000000000000000000.function receiveFunds() public {
require(msg.value > 0, "Send some Ether");
}payable keyword. This function lacks it.msg.value is accessible in payable functions.payable and uses require(msg.value >= 1 ether) to enforce minimum Ether sent.balances[msg.sender] by adding msg.value. Other options either miss payable, use wrong comparison, or incorrect balance update.Pass the test and this pattern moves unknown