Payable in solidity is a very common modifier that you will see. In this post, we break down what it is and how to use it with code examples.
The Payable Modifier
In Solidity, the payable
modifier is used to indicate that a function can accept ether (the native cryptocurrency of the Ethereum platform) as a parameter. Functions that are marked as payable
can be called with a transaction that includes a value, which will be transferred to the contract and stored in the contract’s balance.
Here is an example of a payable function in Solidity:
pragma solidity ^0.5.0;
contract MyContract {
function myFunction() public payable {
// This function can accept ether as a parameter.
}
}
In this example, the myFunction
function is marked as payable
, which means that it can be called with a transaction that includes a value. The value will be transferred to the contract and stored in the contract’s balance.
It is important to note that only functions marked as payable
can accept ether as a parameter. If a function is not marked as payable
, it will not be able to accept ether and any attempt to call it with a value will result in an error.
Overall, the payable
keyword is an important part of the Solidity language and is used to enable contracts to accept and store ether.
Address Payable
In Solidity, the “address payable” type is a variant of the “address” type that includes additional functionality for sending and receiving Ether (the native cryptocurrency of the Ethereum blockchain).
An “address payable” variable is a state variable (a variable that is stored on the Ethereum blockchain and can be accessed by contract functions) that holds the address of an Ethereum account. It is similar to a regular “address” variable, but it includes additional functions for interacting with the account’s balance.
Here is an example of an “address payable” variable in Solidity:
pragma solidity ^0.6.12;
contract Example {
// Declare an address payable variable
address payable public beneficiary;
function setBeneficiary(address payable _beneficiary) public {
// Set the beneficiary variable to the provided address
beneficiary = _beneficiary;
}
function sendFunds() public {
// Send Ether to the beneficiary address
beneficiary.transfer(1 ether);
}
}
The “address payable” type is useful for interacting with Ethereum accounts and sending and receiving Ether within a smart contract. It is recommended for anyone working with Ethereum smart contracts.
0 Comments