LEARN SOLIDITY LESSON 11: Payable function. Withdraws Ether & Transfer ETH. Check Balance in SOLIDITY
LEARN SOLIDITY LESSON 11
Payable function. Withdraws Ether & Transfer ETH. Check Balance in SOLIDITY
Payable function
payable functions are part of what makes Solidity and Ethereum so cool — they are a special type of function that can receive Ether.
contract OnlineStore { function buySomething() external payable { // Check to make sure 0.001 ether was sent to the function call: require(msg.value == 0.001 ether); // If so, some logic to transfer the digital item to the caller of the function: transferThing(msg.sender); } }
Note: If a function is not marked payable and you try to send Ether to it as above, the function will reject your transaction.
Withdraws Ether. Get Balance ETH
You can write a function to withdraw Ether from the contract as follows:
contract GetPaid is Ownable {
function withdraw() external onlyOwner {
address payable _owner = address(uint160(owner()));
_owner.transfer(address(this).balance);
}
}
It is important to note that you cannot transfer Ether to an address unless that address is of type address payable.
Transfer ETH
You can use transfer to send funds to any Ethereum address. For example, you could have a function that transfers Ether back to the msg.sender if they overpaid for an item:
uint itemFee = 0.001 ether; msg.sender.transfer(msg.value - itemFee);
Comments