Subscribe to get access to this video

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

Payable color pixel function

To color a pixel, we are going to require that Ether is sent to buy the pixel.

That means our colorPixel function needs to be marked payable.

We have our Pixel struct already, and we also want our PixelChanged event to emit the new owner and soldPrice, along with the x, y, and color as before. This way our UI can keep track of how much each pixel costs.

Here’s how change colorPixel:

/// MillionEtherPage-003.sol
pragma solidity ^0.4.11;

contract MillionEtherPage {
  struct Pixel {
    address owner;
    uint soldPrice;
    bytes3 color;
  }
  Pixel[1000][1000] public pixels;

  event PixelChanged(
    uint x,
    uint y,
    address owner,
    uint soldPrice,
    bytes3 color
  );

  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 = msg.sender;
    pixel.soldPrice = msg.value;
    pixel.color = color;

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

First, we want to read the current pixel from our contract’s storage. Here we declare the type Pixel and we designate this variable as coming from storage. This is important because variables in storage cost a different amount of gas than variables in memory, we don’t want to copy data unnecessarily.

This syntax means that our pixel object will reference the same pixel in storage, so any changes to this struct will be written to storage as well.

 

Subscribe to get the full text of this lesson

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