Note
Learn game theory and smart contract development on Arbitrum using Stylus (Rust). Build and deploy a multiplayer, iterated Prisoner's Dilemma game with strategic decision-making, token staking, and multiple rounds per match. All in a preconfigured Codespace!
| Learning Outcomes |
|---|
| Understand game theory and the Prisoner's Dilemma |
| Deploy and interact with Stylus (Rust) smart contracts on Arbitrum |
| Implement strategic multiplayer games with token staking and multiple rounds |
| Use cargo stylus, foundry (cast), and viem + wagmi |
| Connect game contracts to a React + Vite + TypeScript frontend with real-time state updates |
| Practice contract interaction patterns, state management, and iterative game logic |
The Iterated Prisoner's Dilemma is a classic game theory scenario where two players repeatedly choose between cooperation and defection over multiple rounds, without knowing the other's choice in each round. This version introduces strategic depth, as players can adapt their choices based on previous outcomes.
- Join a Cell: Players stake ETH to create or join a cell (game instance). Each cell is assigned a random number of rounds (between 2 and 5) for iterated play.
- Play Rounds: In each round, both players secretly choose to Cooperate (0) or Defect (1). Choices are revealed simultaneously.
- Continue or Exit: After each round, both players must independently decide whether to continue to the next round or exit. The game continues only if both agree and the maximum rounds for the cell have not been reached.
- Payouts & Results: After the final round or if a player exits, payouts are distributed based on the cumulative results of all rounds played in the cell.
| Your Move | Opponent's Move | Your Payout | Opponent's Payout |
|---|---|---|---|
| 🤝 Cooperate | 🤝 Cooperate | 1.0x stake | 1.0x stake |
| 🤝 Cooperate | 💀 Defect | 0.5x stake | 1.5x stake |
| 💀 Defect | 🤝 Cooperate | 1.5x stake | 0.5x stake |
| 💀 Defect | 💀 Defect | 0.5x stake | 0.5x stake |
- Memory & Adaptation: Players can adjust their strategy based on previous rounds (e.g., tit-for-tat, always defect, always cooperate).
- Continuation Decisions: After each round, both players must opt-in to continue. If either declines, the cell ends and payouts are distributed.
- Randomized Rounds: Each cell has a random number of rounds (2-5), so players cannot always predict when the game will end, increasing strategic uncertainty.
- Mutual Cooperation: Both players get a fair return (1.0x per round)
- Mutual Defection: Both players lose (0.5x per round) - the "tragedy" of the dilemma
- Mixed Strategies: The defector wins big (1.5x per round), but the cooperator loses (0.5x per round)
The Dilemma: While mutual cooperation yields the best collective outcome, individual incentives push toward defection—especially in the final round!
Run the workshop in a preconfigured Codespace — no setup required!
Steps:
- Click the button above.
- Wait for initialization.
- Open a terminal (Terminal → New Terminal).
- Follow the workshop steps below.
- ✅ Set up a local Arbitrum Nitro Devnode
- ✅ Deploy and interact with a Stylus (Rust) Prisoner's Dilemma contract
- ✅ Use cargo stylus and foundry (cast) for contract deployment
- ✅ Connect the game contract to a React + Vite + TypeScript frontend
- ✅ Implement strategic gameplay with local testnet ETH staking
- ✅ Practice game theory concepts in a blockchain environment
For running locally:
contracts/
└── prisoners-dilemma/ # Stylus (Rust) Prisoner's Dilemma contract
├── src/
│ ├── lib.rs # Main contract implementation
│ └── main.rs # (if present, entry point for bin)
├── Cargo.toml # Rust dependencies
├── rust-toolchain.toml # Rust toolchain config
├── package.json # Build and deploy scripts
└── target/ # Build output
frontend/ # React + Vite + TS frontend
├── public/
└── src/
├── abi/ # Contract ABI
│ └── PrisonersDilemmaContract.json
├── components/ # Game UI components (CellView, GameLobby, MoveButtons, etc.)
├── contexts/ # Web3 context and state
├── hooks/ # Custom hooks for cell/game state
├── lib/ # Contract interaction logic (contract.ts)
├── types/ # TypeScript types
├── utils/ # CellManager and helpers for round/cell logic
├── App.tsx
nitro-devnode/ # Local Arbitrum node
scripts/
├── funds.sh # Fund test accounts
└── package.json # Script utilitiespnpm install -rNote
Codespaces users: This is mostly handled for you, but you still need to manually start the devnode.
cd nitro-devnode
./run-dev-node.sh- The Stylus contract is implemented in
contracts/prisoners-dilemma/src/lib.rs. - Build and deploy locally:
pnpm --filter prisoners-dilemma-contract deploy:local- Important: Copy the deployed contract address from the output for later use.
- Use cargo stylus to export the ABI for frontend integration:
cd contracts/prisoners-dilemma
cargo stylus export-abi --json > ../../frontend/src/abi/PrisonersDilemma.json- Open the exported ABI file and ensure it contains only the ABI in JSON format.
- The frontend is in
frontend/. - Update the contract address in your
contract.tsfile:
// frontend/src/lib/contract.ts
const CONTRACT_ADDRESS = '0x...' as `0x${string}`;Tip
Main Learning Focus: The contract is complete! Your task is to study and understand the iterated game theory implementation, continuation logic, and Web3 integration patterns.
- Master strategic game interactions on blockchain
- Understand ETH staking and payout mechanisms
- Learn game state management and real-time updates
- Practice advanced contract interaction patterns
- Explore game theory concepts in practice
The frontend demonstrates advanced game mechanics:
1. Iterated Strategic Decision Making
- 📋 Task 1: Explore the cooperate vs defect choice interface for each round
- � Task 2: Study how continuation decisions are handled after each round
- � Task 3: Learn how the frontend and contract keep all players in sync across rounds
2. Iterated Payout Distribution
- 📖 Task 1: Understand cumulative ETH payout calculations across multiple rounds
- ✍️ Task 2: Study the payoff matrix implementation per round and for the final cell
- 🎯 Task 3: Learn transaction confirmation and state update patterns for multi-round games
Nash Equilibrium (Iterated)
- Both players defecting in every round is the Nash equilibrium, but strategies like tit-for-tat can outperform in repeated play.
Pareto Efficiency
- Mutual cooperation in every round is Pareto optimal (best collective outcome), but individual incentives and uncertainty about the final round often prevent this outcome.
Risk vs Reward
- Cooperation: Safe but vulnerable to exploitation, especially if the other player defects late.
- Defection: Aggressive but may lose out on long-term gains if the other player retaliates.
- Play the Game: Create games and test different strategies
- Analyze Outcomes: Track your wins/losses with different approaches
- Study Incentives: Understand why players might choose each strategy
- Test Edge Cases: What happens with different stake amounts?
- Explore Psychology: How does knowing your opponent affect decisions?
pnpm --filter frontend devDeployer Account:
- Address:
0x3f1Eae7D46d88F08fc2F8ed27FCb2AB183EB2d0E - Private Key:
0xb6b15c8cb491557369f3c7d2c287b053eb229daa9c22138887752191c9520659
Test Users:
| Index | Address | Private Key |
|---|---|---|
| 0 | 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 | 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 |
| 1 | 0x70997970C51812dc3A010C7d01b50e0d17dc79C8 | 0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d |
| 2 | 0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC | 0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a |
| 3 | 0x90F79bf6EB2c4f870365E785982E1f101E93b906 | 0x7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6 |
| 4 | 0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65 | 0x47e179ec197488593b187f80a00eb0da91f1b9d0b13f8733639f19c30a34926a |
| 5 | 0x9965507D1a55bcC2695C58ba16FB37d819B0A4dc | 0x8b3a350cf5c34c9194ca85829a2df0ec3153be0318b5e2d3348e872092edffba |
| 6 | 0x976EA74026E726554dB657fA54763abd0C3a0aa9 | 0x92db14e403b83dfe3df233f83dfa3a0d7096f21ca9b0d6d6b8d88b2b4ec1564e |
| 7 | 0x14dC79964da2C08b23698B3D3cc7Ca32193d9955 | 0x4bbbf85ce3377467afe5d46f804f221813b2bb87f24d81f60f1fcdbf7cbf4356 |
| 8 | 0x23618e81E3f5cdF7f54C3d65f7FBc0aBf5B21E8f | 0xdbda1821b80551c9d65939329250298aa3472ba22feea921c0cf5d620ea67b97 |
| 9 | 0xa0Ee7A142d267C1f36714E4a8F75612F20a79720 | 0x2a871d0798f97d79848a013d4936a73bf4cc922c825d33c1cf7073dff6d409c6 |
Fund User Wallets:
./scripts/funds.shTo check if the contract compiles and is valid, run:
pnpm --filter prisoners-dilemma-contract checkTo estimate gas for deployment, run:
pnpm --filter prisoners-dilemma-contract estimate-gasTo test the contract, run:
pnpm --filter prisoners-dilemma-contract testLocal Network:
- Name: Localhost-Nitro
- RPC: http://localhost:8547
- Chain ID: 412346
Codespaces RPC:
- Use the forwarded port URL from the "Ports" tab (e.g.,
https://your-codespace-8547.app.github.dev)
The Prisoner's Dilemma illustrates fundamental concepts in:
- Economics: Market competition and cooperation
- Politics: International relations and treaties
- Biology: Evolution of cooperation
- Blockchain: Protocol design and validator behavior
- Always Cooperate: Optimistic but vulnerable
- Always Defect: Pessimistic but safe
- Tit-for-Tat: Start cooperative, then mirror opponent's previous move
- Random: Unpredictable mixed strategy
- DeFi Protocols: Validator staking and slashing
- DAOs: Governance participation vs free-riding
- MEV: Cooperation vs competition among searchers
- Layer 2s: Honest vs malicious operator behavior
- Use different accounts to simulate real multiplayer scenarios
- Try various stake amounts and see how the number of rounds affects decision-making
- Experiment with different strategies and track outcomes across multiple rounds
- Consider the psychological aspects: How does anonymity and round uncertainty affect choices?
- Think about mechanism design: How could the game be modified to encourage cooperation or longer play?
Happy strategizing! 🎯
