Lesson 13: Build an On-Chain Space Shooter
Embark on your journey to building production grade apps.
A spaceship. Asteroids falling from the top. A laser button. Score goes up, ship explodes, game over. Standard arcade stuff. The twist: your best score lives on Monad, not on our server.
Games are one of the places where chain performance actually shows up in the user experience. On slower chains you couldn't put much of a game on-chain without ruining the feel, which is why this whole space is still young. Monad's sub-second finality opens it up. For this capstone, we're going to start at the simplest on-chain layer, the leaderboard, because it's the cleanest way to teach the most important idea in on-chain gaming: figuring out which parts of a game belong on-chain and which don't. The loop itself runs at 60fps inside your browser, that's where it belongs. The public record of who's best lives on Monad, where nobody can edit it. Everything else in this lesson follows from that split.
Capstone rules. One prompt at a time. If your agent drifts off-spec, stop it, paste the prompt again, narrower. The building blocks (auth, signing, wallets, contracts) all came from earlier lessons. If you're fuzzy on one, scroll back.
What We're Building
The game:
- A spaceship the player controls with arrow keys.
- Asteroids falling from the top of the screen at increasing speed.
- Space bar fires a laser that destroys asteroids.
- Destroying an asteroid scores points.
- Getting hit ends the run.
The on-chain piece:
- A leaderboard smart contract on Monad testnet that stores each player's best score.
- When a run ends, the client sends the score to a small signing API.
- The API signs the score with a server-held key and returns the signature.
- The client submits
{score, signature}to the contract from the player's wallet. - The contract verifies the signature came from the trusted signer and updates the player's best score.
Every skill from the sophomore track is doing something:
- Wallets and on-chain payments (payments lesson): the player calls the contract from their wallet.
- Security (implementing security): the server-signed score pattern exists because you cannot trust the client.
- Performance (optimizing performance): the game loop has to hit 60fps, that's why it stays off-chain.
- How the EVM works (EVM lesson): the contract uses
ecrecoverto verify signatures.
Why doesn't the game loop itself go on-chain?
Why does the server sign the score before the client submits it on-chain?
Set Up the Project
Open your Repl and paste into the AI panel:
I'm building an on-chain space shooter. Scaffold a Next.js
project with:
- A single page / route. No auth, no database.
- Wallet connection via RainbowKit + wagmi + viem:
* Install @rainbow-me/rainbowkit, wagmi, viem,
@tanstack/react-query.
* Define a monadTestnet chain object (id 10143, name
"Monad Testnet", RPC https://testnet-rpc.monad.xyz,
native currency MON, 18 decimals).
* Create app/providers.tsx with 'use client' that exports
a <Providers> component wrapping children in:
<WagmiProvider config={config}>
<QueryClientProvider client={new QueryClient()}>
<RainbowKitProvider>
where config is built via getDefaultConfig({
appName: 'Space Shooter',
projectId: 'demo',
chains: [monadTestnet],
}).
* In app/layout.tsx, import '@rainbow-me/rainbowkit/styles.css'
and wrap {children} with <Providers>.
* Render <ConnectButton /> from @rainbow-me/rainbowkit fixed
in the top-right of the page (position: fixed; top: 16px;
right: 16px). Do NOT roll your own connect button. Any
page or component using wagmi hooks needs 'use client' at
the top.
- Environment variables read directly from process.env:
* NEXT_PUBLIC_CONTRACT_ADDRESS (empty for now)
* SIGNER_PRIVATE_KEY (empty for now, server-only)
- A <main> area that will hold the game canvas. Nothing in it
yet.
- Minimal UI. Black background, white text, monospace font.
This is a space game.
Before you say you're done, open the browser and verify that
clicking the Connect button opens the RainbowKit modal. If it
doesn't, the provider wrapping or 'use client' is wrong, fix
it before handing back to me.
Once the scaffold runs and you can connect a wallet, move on.
Build the Game Loop
This is the pure browser part. No chain, no backend.
> Build the space shooter inside an HTML canvas that fills the
<main> area.
Mechanics:
- Player ship at the bottom, moves left/right with arrow keys.
- Space bar fires a laser that travels straight up.
- Asteroids spawn at random x positions at the top, fall at
increasing speed over time.
- Laser hitting an asteroid destroys both and adds 10 points.
- Asteroid hitting the ship ends the game.
- Render current score in the top-left.
State machine:
- "idle": shows "Press space to start"
- "playing": game loop is running
- "over": shows final score + a "Submit to leaderboard" button
(disabled until a wallet is connected)
Keep the canvas at 800x600. Pure canvas 2D, no external game
libraries. Use requestAnimationFrame.
Test it end-to-end before moving on. If the game isn't fun to play, nothing downstream matters.
Why requestAnimationFrame
A game loop is a function that updates state (ship position, asteroids, collisions), redraws the canvas, and schedules itself to run again. How it schedules itself is the thing to get right.
Two options exist. setInterval(loop, 16) fires every 16ms (roughly 60 times per second). requestAnimationFrame(loop) asks the browser to call your function right before its next paint.
Use requestAnimationFrame. It syncs your updates with the browser's render cycle, pauses automatically in hidden tabs (saving CPU and battery), and matches the display's refresh rate (60Hz, 120Hz) without any code change. setInterval does none of those things.
The pattern:
function loop() {
update()
draw()
requestAnimationFrame(loop)
}
requestAnimationFrame(loop)
Every browser game uses this.
Why use requestAnimationFrame instead of setInterval for the game loop?
Deploy the Leaderboard Contract
This is the smallest useful on-chain piece.
> Write a Solidity contract called Leaderboard.sol with this
behavior:
- Owner is set to the deployer. Owner can change the authorized
signer address.
- Public mapping bestScore(address player) -> uint256.
- Function submitScore(uint256 score, bytes signature):
* The message signed is keccak256(abi.encodePacked(msg.sender, score)).
* Use ECDSA (OpenZeppelin is fine) to recover the signer.
* Require the recovered address == authorizedSigner.
* If score > bestScore[msg.sender], update it and emit
NewBestScore(player, score).
- A view function topN(uint256 n) is NOT required on-chain;
we'll compute it off-chain from NewBestScore events.
Then deploy it to Monad testnet. Use Hardhat or Foundry, your
pick. Print out the deployed address and save it. Set the
authorizedSigner at deploy time to the address that derives from
SIGNER_PRIVATE_KEY.
Paste the deployed address into NEXT_PUBLIC_CONTRACT_ADDRESS. Generate a fresh signing keypair (the agent can do this with viem's privateKeyToAccount) and paste the private key into SIGNER_PRIVATE_KEY. Confirm both are in the shell before continuing.
Security. The signer key is a server secret.
SIGNER_PRIVATE_KEYmust never land in a.envfile the agent commits, or in client-side code. It lives in the server environment only. If it leaks, anyone can mint any score for any player, and the leaderboard is worthless.
Sign Scores on the Server
The pattern: the client tells the server its score, the server decides whether it's plausible, signs it, and hands the signature back.
> Add a POST /api/sign-score Next.js route that:
- Accepts { player: address, score: uint256 } in the body.
- Validates:
* score is a positive integer below a plausibility cap
(for now, 100000; a real game would fingerprint the run).
* player is a valid 0x address.
- Signs keccak256(abi.encodePacked(player, score)) with
SIGNER_PRIVATE_KEY using viem's signMessage for raw hashes.
- Returns { signature }.
Never expose SIGNER_PRIVATE_KEY to the client. The key is read
from process.env on the server only.
Security. Plausibility, not trust. A naive signer signs any score, which defeats the whole pattern. In a real game you'd fingerprint the run (inputs per second, entropy, replay tokens). For this lesson we just cap the score, but understand that anything below the cap can still be faked, your real defense is the run fingerprint you didn't write yet.
What's the weakness of 'trust any score under a cap'?
Submit Scores On-Chain
Now wire the game's "Submit to leaderboard" button to the contract.
> When the "over" state renders and the user clicks "Submit to
leaderboard":
- POST { player: userAddress, score } to /api/sign-score.
- Take the returned signature and call
contract.submitScore(score, signature) from the user's wallet.
- While pending, show "Submitting..." on the button.
- On confirmation, replace the button with "Submitted!" and
refresh the leaderboard below.
- On any error, show a clear message and keep the button
enabled for retry.
Show the Top 10
Because the contract emits NewBestScore, you can build the leaderboard off-chain by querying events.
> Below the game canvas, render a "Top 10" leaderboard.
- Use viem's getLogs with the Leaderboard contract and the
NewBestScore event, fromBlock 0n.
- For each player, keep only the highest score they've ever
posted.
- Sort descending, take the top 10.
- Render as a numbered list: "1. 0xabc…def 420".
- Re-fetch the list on successful submission.
- Cache the list for 5 seconds so the UI doesn't hammer the
RPC.
Why compute the top 10 from events off-chain instead of adding an on-chain topN function?
Try It End-to-End
- Connect your wallet, play a run, die, hit Submit to leaderboard. Your wallet pops a signature request. Sign, wait for confirmation, see your score on the list.
- Open a different browser (or incognito) with a different wallet. Play, submit, confirm the list updates and is sorted correctly.
- Try cheating: in the devtools console, POST directly to
/api/sign-scorewith{ player: yourAddress, score: 99999 }. Under the current plausibility rule (just a cap), the server will sign it. The fact that it works is the lesson.
Security Recap
- Signer key lives only on the server. Never in a committed
.env, never bundled into client JS. - Plausibility checks on the server are the real defense. The cap we wrote is the minimum; a real game would fingerprint inputs.
- Contract verifies the signer with
ecrecover, not the score content. If the signer key leaks, the entire leaderboard is compromised. - Rate-limit the sign-score route so a leaked key window stays small.
- Monitor the
NewBestScoreevent for anomalies (scores just below the cap, rapid submissions from one address).
What You Just Built
A real on-chain game:
- The loop runs at 60fps in the browser, where it belongs.
- The record of who's best lives on Monad, where no company can edit it.
- Scores are gated by a server-held key, so players can't self-promote to the top.
- The leaderboard is built from events, the cheapest way to read a sorted list on-chain.
This is the template for almost every "on-chain game" worth building. The interactive part stays client-side. The thing players care about long-term (ownership, ranking, rewards) lives on-chain.
0/5 correct
0% — get all correct to complete