0

The function withdraw() is not working, it can not transfer. But the function withdraw2() is working. What's wrong with my code?

pragma solidity ^0.4.18;

contract SupportPay4 {

    function() public payable {

    }

    function deposit() public payable {

    }

    function withdraw() public {
        msg.sender.transfer(getBalance());
    }

    function withdraw2(address addr) public {
        addr.transfer(getBalance());
    }

    function getBalance() public constant returns(uint256) {
        return address(this).balance;
    }
}
9
  • 2
    Works for me. Are you sure you deposited ether again after calling Withdraw2? Aug 6, 2018 at 9:01
  • yes, I deposited 0.3 ether. I could withdraw all ether by function withdraw2(). But it's not working with function withdraw().
    – Shane
    Aug 6, 2018 at 9:05
  • Yes, but did you deposit it again after withdrawing it the first time? I can withdraw from both. Aug 6, 2018 at 9:07
  • 1
    It works fine for me in remix. There is likely something wrong in the way you are testing. Aug 6, 2018 at 9:17
  • 1
    It got me crazy
    – Shane
    Aug 6, 2018 at 9:21

2 Answers 2

2

If you are using v0.8 you need to change this to

payable(msg.sender).transfer(address(this).balance);

Hope this helps

1
  • Yeah I'm doing the Solidity, Blockchain, and Smart Contract Course and he's working with v0.6 and the casting that you did solved it, thank you so much
    – M090009
    Apr 6, 2022 at 12:26
0

Try like this:

pragma solidity ^0.4.18;

contract SupportPay4 {

    function() public payable {

    }

    function deposit() public payable {

    }

    function withdraw() public {
        msg.sender.transfer(getBalance());
    }

    function withdraw2() public {
        msg.sender.transfer(address(this).balance);
    }

    function getBalance() public constant returns(uint256) {
        return address(this).balance;
    }
}

Hope it helps.

2
  • I tried, but still not working.
    – Shane
    Aug 7, 2018 at 3:08
  • 1
    The contract works in Remix. You might want to test it there to see for yourself, then turn your attention to the client side, which may not be interacting with the contract properly. Aug 7, 2018 at 5:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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