contractBalance after calling deposit with 1 ether?pragma solidity ^0.8.0;
contract Wallet {
uint public contractBalance;
function deposit() public payable {
contractBalance += msg.value;
}
}msg.value holds the amount of wei sent with the transaction.The deposit function is marked payable, so it can receive ether. The msg.value contains the amount sent in wei. Adding it to contractBalance updates the balance correctly.
withdraw and send 1 ether along with the call?pragma solidity ^0.8.0;
contract Bank {
function withdraw() public {
// withdraw logic
}
}Functions not marked payable reject any ether sent with the call. The transaction reverts with an error indicating the function cannot accept ether.
pragma solidity ^0.8.0;
contract Test {
fallback() external {
// fallback without payable
}
}Fallback functions must be marked payable to accept ether. Without payable, any ether sent causes the transaction to revert.
In Solidity, only functions marked payable can receive ether. Other functions reject ether and cause the transaction to revert.
address(this).balance after these calls?
1. Call deposit with 2 ether
2. Call withdraw with 1 ether
Assume withdraw sends ether back to the caller.pragma solidity ^0.8.0;
contract Vault {
function deposit() public payable {
// Accept ether
}
function withdraw(uint amount) public {
payable(msg.sender).transfer(amount);
}
}The contract receives 2 ether in deposit. Then it sends 1 ether back in withdraw. So the contract balance is 1 ether.
