Subscribe to get access to this video

and the whole library of videos, sample code, and tutorials.

The Pull Payment Pattern - Withdraw payments when outbid

Let’s get back to the million ether page contract. Now we that we have a grasp on how to send payments let’s issue refunds when a pixel is outbid.

Taking a look at our colorPixel function, the obvious solution would be, after we’ve verified that the new bid price is greater than the sold price, we should .send the funds back to the previous owner.

That code might look like this:

  function colorPixel(uint x, uint y, bytes3 color) payable {
    Pixel storage pixel = pixels[x][y];

    // pixel.soldPrice will initialize to 0
    require(msg.value > pixel.soldPrice);

    pixel.owner.transfer(pixel.soldPrice); // --> what do you think?

    pixel.owner = msg.sender;
    pixel.soldPrice = msg.value;
    pixel.color = color;

    PixelChanged(x, y, pixel.owner, pixel.soldPrice, pixel.color);
  }

That looks pretty clean! But wait a second. What do you think about this code? Are there any problems or potential attacks? I can think of one.

Remember that .transfer will revert all changes if sending the funds fails. So if an attacker could craft a contract which buys the pixel and then always deliberately fails when you try to send it value, the result would be that no one could ever buy that pixel again!

Every time someone outbids them, this contract would fail to instate the new higher bid, because the transfer would fail.

This problem shows up in Ethereum smart contracts all the time, so much so, that the solution has a name called the Pull-Payment pattern.

 

Subscribe to get the full text of this lesson

and the entire library of videos, sample code, and tutorials.