All projects
Dec 2024

FairPlay: Secure Two-Player Smart Contract on Ethereum

A two-player guessing game that runs entirely in an Ethereum smart contract, designed so that neither player can cheat, even though every transaction on the blockchain is public.

SolidityEthereumBlockchainSmart Contracts

Game lifecycle

01

Pay

Each player pays a 200 wei entry fee

02

Commit

Players submit a hash of their number, guess and a secret salt

03

Reveal

Players disclose their values; the contract checks them against the hashes

04

Decide

The closest guess to the opponent's number wins; a draw refunds both

05

Collect

The winner withdraws the prize; refunds are claimed the same way

The problem

On a public blockchain, every transaction is visible before it is confirmed. In a naive game, the second player can simply read the first player's move and respond to it. This is known as front-running.

How commit-reveal solves it

Players first commit to a hash of their move combined with a secret salt, which reveals nothing about the move. Only once both commitments are locked in do players reveal their values, and the contract verifies each one against its hash. Changing a move after seeing the opponent's is impossible without breaking the hash.

Security measures

  • ▸Explicit game states with function modifiers, so each action is only allowed at the right stage
  • ▸Timeouts that abort stalled games and refund deposits, so a player can't lock funds by walking away
  • ▸Pull-payment pattern: winners and refunds are withdrawn rather than pushed, protecting against re-entrancy
  • ▸Input validation (numbers and guesses limited to 1–100) and a separate HashHelper contract for creating commitments
  • ▸Gas-efficient storage and testing of the full game cycle on the Sepolia test network