Skip to main content

Building a Coin Flip Contract

Let's build a coin flip game where players guess "heads" or "tails" and earn points for correct guesses.

Obtaining the Project

You have two options to start with the Coin Flip tutorial:

GitHub CodespacesClone Locally
Open in GitHub Codespaces🌐 https://github.com/near-examples/coin-flip-examples

Click the "Open in GitHub Codespaces" button above to get a fully configured development environment in your browser.

Contract Structure

Our contract needs:

  • A method to flip the coin using randomness
  • Storage for player points
  • View methods to check scores

Implementing the Coin Flip

The core logic generates a random outcome and compares it with the player's guess:

Key Implementation Details

1. Random Seed Usage

We use only the first byte of the 32-byte seed for simplicity:

randomSeed[0] % 2 === 0 ? 'heads' : 'tails'

2. State Management

Points are stored in an UnorderedMap for efficient access:

  • JavaScript: UnorderedMap<number>
  • Rust: UnorderedMap<AccountId, u8>

3. Input Validation

Always validate user input:

if (!['heads', 'tails'].includes(player_guess)) {
throw new Error('Invalid guess');
}

View Methods

Add methods to check player scores:

Building the Contract

# Install dependencies
npm install

# Build the contract
npm run build

# The compiled contract will be in build/coin_flip.wasm

Now that we have a working contract, let's test it to ensure the randomness behaves correctly.