Payable modifier in Solidity smart contracts

Payable function modifiers provide a mechanism to receive funds in your smart contract. These functions are annotated with the payable keyword.

Keep the following in mind

  • Use the keyword payable in a function or state variable to send and receive Ether.
  • Include the payable keyword in the state variable in order to withdraw from the contract
  • Include the payable keyword in the constructor to be able to deposit into the contract when the contract is created/deployed
    • constructor() public payable;
    • the deploy button in remix will be red because we can add ether when we deploy
  • Include the payable keyword in a function to allow deposits into the contract
    • function deposit() public payable {}

Below is a simple example of a contract that has a function set to payable. Having this function set to payable will allow another contract to call it and send it Ether. Test this out in Remix.

pragma solidity ^0.7.0;

//sample contract is called payableSample
contract  payableSample {
    
    uint amount =0;
    

    //payable is added to this function so another contract can call it and send ether to this contract
    function payMeMoney() public payable{
        amount += msg.value;
    }
}

Try it in Remix

In the example below we set variables and functions to payable. If we did not make the address payable the to.transfer would not work. Try testing this contract in Remix

pragma solidity ^0.7.0;

contract  payableSample {

    //add the keyword payable to the state variable
    address payable public Owner;
    

    //set the owner to the msg.sender
    constructor () public {
        Owner = msg.sender; 
    }
    

    //create a modifier that the msg.sender must be the owner
    modifier onlyOwner() {
        require(msg.sender == Owner, 'Not owner');
        _;
    }
    

    //the owner can withdraw from the contract because payable was added to the state variable above
    function withdraw (uint _amount) public onlyOwner {
        Owner.transfer(_amount); 
    }
    

    //to.transfer works because we made the address above payable.
    function transfer(address payable _to, uint _amount) public onlyOwner {
        _to.transfer(_amount); //to.transfer works because we made the address above payable.
    }
}

Try it in Remix

For more information read the docs.

This code is for learning and entertainment purposes only. The code has not been audited and use at your own risk. Remember smart contracts are experimental and could contain bugs.

Click here for more information about how to use the Ethereum test network and how to obtain test ETH.

Next Review – Import into a Solidity smart contract

Leave a Reply