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 Codespaces | Clone Locally |
|---|---|
🌐 https://github.com/near-examples/coin-flip-examples |
- GitHub Codespaces
- Local Setup
Click the "Open in GitHub Codespaces" button above to get a fully configured development environment in your browser.
# Clone the repository
git clone https://github.com/near-examples/coin-flip-examples
cd coin-flip-examples
# Choose your preferred language
cd contract-ts # for TypeScript
# or
cd contract-rs # for Rust
Contract Structure
Our contract needs:
- A method to flip the coin using randomness
- Storage for player points
- View methods to check scores
- JavaScript
- Rust
Loading...
Loading...
Implementing the Coin Flip
The core logic generates a random outcome and compares it with the player's guess:
- JavaScript
- Rust
Loading...
Loading...
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:
- JavaScript
- Rust
Loading...
Loading...
Building the Contract
- JavaScript
- Rust
# Install dependencies
npm install
# Build the contract
npm run build
# The compiled contract will be in build/coin_flip.wasm
# Build the contract
cargo near build
# The compiled contract will be in target/wasm32-unknown-unknown/release/
Now that we have a working contract, let's test it to ensure the randomness behaves correctly.