[Ethereum] Sending entire contract balance to address

address.transferremixsolidity

I am trying to establish a basic reversed auction in solidity using the Remix IDE.

In the last function i want to pay back the whole contract balance to a certain address.

My approach with .transfer(address(this).balance); does not work. Compiling is fine but after deploying the contract this line is not working.

Is there another way i can "empty" the contract balance. Or do i use the wrong syntax?

Help would be much appreciated 😉
Thanks

complete contract:

pragma solidity ^0.5.11;

contract ReverseAuction {

address payable public auctioneer;
address payable public lowestBidder;
uint public auctionEndTime;
uint public WTP;
uint public lowestBid;
bool ended;

mapping(address => uint) pendingReturns;

constructor(uint biddingTime) public payable {
    auctioneer = msg.sender;
    auctionEndTime = now + biddingTime;
    WTP = msg.value;
    lowestBid = WTP;
    ended = false;
}

function bid() public payable {                                         ///insurance deposit (linking with tracking contract!)
    require(now <= auctionEndTime,"Auction already ended.");
    require(msg.value < WTP,"Bid exceeds willingness to pay.");
    require(msg.value < lowestBid,"There already is a lower bid.");
    if (lowestBid != 0) {
        lowestBidder.transfer(lowestBid);
        pendingReturns[lowestBidder] += lowestBid;
        lowestBidder = msg.sender;
        lowestBid = msg.value;
    }
}

function AuctionEnd() public {
    require(msg.sender == auctioneer,"Insufficient permission.");
    require(now >= auctionEndTime, "Auction not yet ended.");
    require(ended == false, "AuctionEnd has already been called.");
    lowestBidder.transfer(lowestBid*2); ///paying back safety deposit + actual payment (so 2 times lowest bid)
    auctioneer.transfer(address(this).balance);  ///rest of the contract balance (WTP-lowest bid) should go back to the auctioneer
    ended = true;
}

}


Error message:

transact to ReverseAuction.AuctionEnd errored: VM error: revert.
revert The Transaction has been reverted to the initial state.
Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.

Best Answer

If you are sending the money to a contract, and not an account address, then the recipient contract must have a "fallback" function to be able to receive ETH.

Fallback functions tend to look as follows:

    function() external payable {}

though you can add logic within the fallback function if you wish.

Using recipient.transfer(...) limits the transfer to 2300 gas. This means, if you put complex logic within the fallback function, that would cost more than 2300 gas, the transferal will revert. In this case to transfer the ETH to the contract you must use .call.value(address(this).balance)() instead of .transfer.

Related Topic