0
contract MyContract {
  address payable public owner;
  address payable public withdrawAddress = 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2; 
  
  constructor() public {
    owner = msg.sender;
    ...
  }

  function totalBalance() external view returns(uint) {
    // CAST CONTRACT TO PAYABLE ADDRESS
    return payable(address(this)).balance;
  }

  function withdrawFunds() external withdrawAddressOnly() {
    msg.sender.transfer(this.totalBalance());
  }

  modifier withdrawAddressOnly() {
    require(msg.sender == withdrawAddress, 'only withdrawer can call this');
    _;
  }
  
  ...
contract MyContract {
  address payable public owner;
  address payable public withdrawAddress = 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2; 
  
  constructor() public {
    owner = msg.sender;
    ...
  }

  function totalBalance() external view returns(uint) {
    // PAYABLE ADDRESS SET ABOVE
    return owner.balance;
  }

  function withdrawFunds() external withdrawAddressOnly() {
    msg.sender.transfer(this.totalBalance());
  }

  modifier withdrawAddressOnly() {
    require(msg.sender == withdrawAddress, 'only withdrawer can call this');
    _;
  }
  
  ...

This first one's withdrawFunds works, but the second doesn't.

The only difference is the totalBalance function.

  • First example: casts the contract to payable address, and get's it balance
  • Second example: uses the owner state variable, and get's it balance

The owner variable is already a payable address, so I don't understand why the first one succeeds and the second one fails?

0

The value of payable(address(this)).balance is the amount of Ether held by the contract.

The value of owner.balance is the amount of Ether held by the contract's deployer.

Transferring the latter from the contract can work only if it is not larger than the former.

1
  • makes perfect sense!
    – GN.
    Dec 10 '20 at 20:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.