Skip to content
MirakoolDevPublic

About

A daily $PFWA leaderboard game on a Uniswap v4 hook on Robinhood Chain. Every move is a buy: steal, rob the leader or flip for it, and the top 3 split the ETH pot.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

17 Commits

Folders and files

Repository files navigation

Sherwood

A PvP game on Robinhood Chain (chain ID 4663). This section is Season 1, the first version: a daily game on a Uniswap v4 hook. Every move is a buy of $PFWA in one ETH/$PFWA pool; the hook keeps the score, the pot and the payouts onchain. The whole game is one contract: src/Sherwood.sol.

Rules

  • Moves travel as hook data: abi.encode(uint256 move) or abi.encode(uint256 move, address referrer). 0 Buy, 1 Steal, 2 Robin Hood, 3 Flip. A swap with no hook data scores as Buy.
  • Points: 1 per 0.001 ETH of an exact-input ETH→$PFWA swap, at most 100 per buy (0.1 ETH). Buys under 0.001 ETH don't score. Points are int256 and can go negative. A buy must fill completely: one stopped early by a price limit reverts (PartialFill).
  • Steal: also moves 20% → 40% of the previous player's positive points to the buyer.
  • Robin Hood: moves 10% → 33% of the leader's positive points to the lowest of the last 10 players, which can be the player making the move.
  • Flip: requests randomness from Dice Protocol (a Pyth Entropy fork). Win: 2x → 3x the buy's points. Lose: the points are debited from the player and credited to the previous player. If Dice refuses the request or can't quote a fee, or the fee is above MAX_DICE_FEE (0.0005 ETH), the move scores as a Buy. An unrevealed flip can be expired after 10 minutes. A win's multiplier is fixed from the buy size when the flip is requested.
  • Steal, Robin Hood and the flip win scale linearly with the buy's base points (scaledBps).
  • Pot: 5% of the ETH side of every buy and sell in the pool. Anyone can add ETH with fundPot(day), and ETH sent to the hook from anywhere other than the PoolManager or Dice lands in today's pot.
  • Day: block.timestamp / 1 days. After 00:00 UTC + 15 minutes, anyone can settle(day, maxPlayers) in batches, once none of that day's flips is pending (pendingFlips; expire them first). Top 3 players with positive points take 50% / 20% / 10%; 10% goes to the buyback reserve (bought and burned through a separate holder pool by the operator); the rest rolls into the current day's pot.
  • Holding rules: the hook records the $PFWA each player buys per day (bought). A winner whose balance is below that day's buys at settlement keeps only prize * balance / bought and forfeits the rest into the next pot (sold 20%, lose 20%). The balance kept is recorded (heldToClaim), and claim reverts while the winner holds less than that. Holding all of yesterday's buys gives +25% points today (holderBonusActive).
  • Selling $PFWA in this pool wipes the seller's positive points for the day.
  • Referrals: a player's referrer is set once, on their very first play, from hook data. Not self, not mutual. A referred player gets +10% points on their first day. On days the referrer also played: +10% of the player's scored points to the referrer (minted, not taken), and 5% of the player's prize to referralEarnings (taken from the rollover, not the prize), withdrawn with claimReferral().
  • Claims: winners claim(day) until claimDeadline(day): 7 days from the day's end or from settlement, whichever is later. Anyone can sweepUnclaimed(day) back into the pot after that.

Roles and trust

Role Can Cannot
Owner setOwner (names the next owner, who takes over with acceptOwner), setOperator; create the game pool (once) Touch the pot, points, prizes, referral earnings or rules; choose or change the burn pools, which are fixed at deployment
Operator (and owner) buybackAndBurn(amount, minPfwaOut) from the buyback reserve; refundDiceRequest Send reserve ETH anywhere but the buyback swap in the pool set at launch; $PFWA bought goes to the dead address. minPfwaOut is the operator's choice (the upkeep job uses a live quote)
Anyone Trade, settle, sweepUnclaimed, fundPot, expireFlip (after 10 minutes), add liquidity —

Rules are constants; there is no upgrade path.

External dependencies

  • Uniswap v4 PoolManager on Robinhood Chain 0x8366a39CC670B4001A1121B8F6A443A643e40951.
  • Dice Protocol entropy 0xd8A0680e7699526B57140ED4EAfdCc7219Dc0A0c, provider 0x8741b8a825644D9Ef18Faf2DAB5e9b47B900F2b6.
  • $PFWA 0xa934bA4F59070149d37A93F8A002Af79BAe35563 (standard ERC-20).
  • The burn pools, fixed in the hook at deployment (buybackPool() and hostBuybackPool()): the game token's burn goes through the existing ETH/token 1% pool (fee 10000, tick spacing 100, no hook), the host burn through the $PFWA holder pool, an existing ETH/$PFWA pool with Hookr's holder hook 0xb914f955294799de4b891bd2EA8AF628Fa1c68CC (dynamic fee, tick spacing 200). In $PFWA's own game the one burn goes through the holder pool. Nobody can point a reserve anywhere else; if a pool ever stops working, its reserve stays in the contract.

Deployment

The hook is deployed with CREATE2 to an address carrying its permission bits (beforeInitialize, beforeSwap, afterSwap, beforeSwapReturnDelta, afterSwapReturnDelta). Planned through Programmable's atomic executor: the constructor owner is the executor, which sets the buyback pool and operator, creates the pool and hands ownership to the admin wallet in one transaction. $PFWA liquidity is then added one-sided by the admin wallet.

Known design choices (accepted)

  • The player is tx.origin. Smart-account bundles credit the bundler.
  • Holding checks read balanceOf, so moving tokens between wallets can dodge them; they raise the cost of dumping, they don't make it impossible.
  • Referral by a second wallet you control is possible; it only earns the 10% bonus points on days you play and 5% of a prize from the rollover.
  • The leader is tracked incrementally. A rescan of up to MAX_LEADER_SCAN players runs inside the swap that debited #1; a bigger board is rescanned in resumable chunks by the swaps that follow (see King of the Hill under Sherwood v2).
  • Robin Hood can pay the player making the move when they're the lowest of the last 10: robbing the leader for yourself is allowed, so moves can be chained.
  • Liquidity is one-sided $PFWA, so the pool price can't fall below its starting price.

Audit

Audited by IMD at 1266778: 1 high, 3 medium, 4 low and 1 info. All fixed except one accepted design choice. See AUDIT.md.

Where we'd like the most scrutiny

  1. Delta accounting in beforeSwap / afterSwap (fee take, return deltas, exact-input only) and the unlockCallback buyback path.
  2. Pot and prize accounting across settle, claim, sweepUnclaimed, partial forfeits, referral shares and claimReferral: total ETH paid out can never exceed ETH received.
  3. Flip lifecycle: request, callback, expiry, refunds, and the Dice fee taken from the pot.
  4. Points bookkeeping with negative scores, leader tracking, the last-10 list and settlement batching.
  5. Anything a player, a griefer or the operator could use to block swaps, settlement or claims.

Build and test

Foundry with solc 0.8.26 (via IR, cancun). Dependencies are vendored in lib/.

forge build
forge test --no-match-contract Fork              # 67 unit tests
forge test --match-contract Fork                 # 3 tests against live Robinhood Chain state (needs the public RPC)

License

MIT

Sherwood v2

src/SherwoodV2.sol is the next version of the game, and it works with any token. Its first deployment is for $IMD, with $PFWA as the host token. The v1 game above keeps running unchanged.

What changed from v1

  • Rounds: rolling 20-hour rounds from GENESIS replace fixed UTC days, so the end of each round falls at a different hour every day.

  • Moves: 0 Buy, 1 Steal, 2 Robin Hood, 3 Flip, 4 Shield. Steal, Robin Hood and Flip use charges that stack:

    Move Earn rate Most you can bank
    Steal 1 every 10 minutes 18
    Robin Hood 1 every hour 3
    Flip 1 every 6h40m (3 a round) 6

    Banks are kept per wallet and carry across rounds. A new wallet starts with a full bank. A move with no charge left plays as a Buy.

  • Shield: every 0.025 ETH played in a round earns one charge, and a player holds at most one. Playing Shield raises a 30-minute shield. The next Steal or Robin Hood aimed at the shielded player is reflected, and the attacker pays the whole cut the move would have taken, below zero if need be (like a lost flip). A move that would have taken nothing reflects nothing and leaves the shield up.

  • King of the Hill: the player who held #1 for the longest in a round wins 8%. When #1 loses points the board is rescanned for the new #1:

    • Up to MAX_LEADER_SCAN (1,500) players, the move that debited #1 rescans the whole board at once (about 4.7k gas per player with cold storage: up to about 7.1M).
    • On a bigger board, or when #1 loses a flip (Dice's reveal only has FLIP_CALLBACK_GAS, 200k, enough to rescan 12 players), #1 is unknown until the next play, sell or flip expiry rescans the board. Such a transaction rescans at least LEADER_SCAN_CHUNK (200) players, about 950k gas, and as many more as its gas allows while keeping LEADER_SCAN_RESERVE (1M) for the rest of the swap, so a caller who gives the swap gas to spare finishes a big board in one go; otherwise the following transactions carry on from where it stopped.
    • While #1 is unknown nobody's clock runs and Robin Hood scores as a Buy and keeps its charge. Every point change restarts the unknown spell, so when the rescan completes the #1 it finds has held #1 for the whole spell and is credited back to its start. Seconds nobody is credited for go to nobody; the King is decided only by seconds actually observed at #1.
  • Steal and Robin Hood with nothing to take: a Steal with no previous player, or a Robin Hood with no leader or no other recent player, plays as a Buy and keeps its charge. A Steal or Robin Hood whose target exists but has no points above zero spends its charge and moves nothing: the move was made, there was just nothing to take.

  • Split:

    Share Goes to
    40% / 20% / 10% Top 3
    8% King of the Hill
    10% Game token burn, through buybackPool
    7% Host token burn, through hostBuybackPool
    5% Rollover

    Empty prize slots roll over. Referral cuts come out of the rollover: at most 5% × 78% = 3.9% < 5%.

  • Host token: a game for another token buys and burns the host token ($PFWA) with its 7%. Holding at least hostHolderMin of the host token gives +10% points. When the host token is the game token, both features are off and the 7% joins the game token burn.

  • Claims: prizes are claimed within 7 days. sweepUnclaimed moves anything left into the pot of the live round.

  • Hook data: abi.encode(uint256 move) or abi.encode(uint256 move, address referrer). A move above 4 plays as a Buy; a referrer word that isn't a clean address is ignored. A swap never reverts over its hook data.

  • Flips and the Dice fee: the fee comes out of the pot. A flip only goes to Dice when the fee is at most MAX_DICE_FEE and at most the 5% its own buy paid in (so a flip never costs the pot more than the buy brought); otherwise the move scores as a Buy and keeps its charge.

  • Seeding: fundPot(round) takes the current round and up to 365 rounds ahead, so every seed can be settled out.

Deploying without a salt

A v4 hook needs its permission flags (0x20CC) in the low bits of its address. src/SherwoodV2Launcher.sol is for factories that can't pass a CREATE2 salt. In its constructor it searches salts onchain and deploys the hook with CREATE2. That takes about 16k tries on average, and the whole deploy costs about 10M gas. Read the result from launcher.hook().

test/SherwoodV2LauncherFork.t.sol rehearses the whole $IMD launch on a Robinhood Chain fork: deploy, owner setup, a play, settlement and both burns.

The changes made for the $IMD launch, and the audit findings behind them, are listed in ADAPTATION.md.

Owner setup after deploy

script/SetupSherwoodV2.s.sol runs these steps as the owner:

  1. Create the ETH/$IMD game pool: fee 9000, tick spacing 180, hooks set to the hook, at the 1% pool's price.
  2. setOperator(bot).

The two burn pools (ETH/$IMD 1% and the ETH/$PFWA holder pool) are fixed in the hook at deployment; the script only checks that both exist. A later owner handover is setOwner(next) by the owner, then acceptOwner() by next; nothing changes until they accept, and setOwner(0) cancels.

Keeping the game pool on the market price

Until a game pool has liquidity, nobody can trade it, so its price stays where it was created while the market moves. src/PoolPriceAlign.sol walks an empty pool's price to a reference pool's live price with a 1-wei swap limited to the target price. Across a stretch with no liquidity the swap moves the price and exchanges nothing; if any liquidity is in the way, tokens would change hands and the call reverts with WouldTrade. It holds no funds and has no owner.

Deployed on Robinhood Chain at 0xbdA0Bc2461c2f0706573878F2932F87526b43D63. The site's upkeep job calls align(gamePool, refPool) when the $IMD game pool drifts 50 or more ticks from the 1% ETH/$IMD pool. script/AlignImdGamePool.s.sol does the same by hand, and test/PoolPriceAlignFork.t.sol checks it on a Robinhood Chain fork, including the revert when liquidity is in range.

Where we would like the most scrutiny (v2)

  • The two buyback swaps: they share one unlockCallback, with a flag saying which burn it is. Slippage protection relies only on the operator's minOut.
  • Pot accounting: settlement must never revert, and ETH out can never exceed ETH in, across prizes, referral cuts, claims and sweeps.
  • Charge clocks: _charges, _spend and _nextCharge.
  • King of the Hill reign tracking: _updateReign and the bounded leader rescan.
  • Host bonus: it reads the balance at play time, so a player could borrow 100k $PFWA for one transaction. We first thought the swap fees of buying and selling made that cost more than the 10% edge; a Uniswap v4 flash take borrows for free, so it doesn't (reported by Hey Research Lab, Nov 2026; see the arena's security review below). The same applies to v2's settlement and claim checks.

Sherwood v2.1

src/SherwoodV21.sol is Sherwood v2 with two changes, made for the $WIF game (PFWA's entry to the World is Flat hackathon). Everything else, from the moves and the split to settlement and claims, is the v2 code.

  1. Shields hold blocks. Every 0.01 ETH a player plays in a round (any move) banks one shield block, up to 5. A SHIELD move loads every banked block into a 30-minute shield (topping up one that is still up, to at most 5, and restarting its 30 minutes). Each Steal or Robin Hood the shield turns around uses one block, and the shield drops with its last block. A move that would take nothing reflects nothing and uses no block. New views: shieldBlocks(player); shieldStats(round, player) now returns uint8 charges (blocks banked) instead of bool charge.
  2. The token burns through the game pool itself. buybackPool() returns the game pool (fee and tick spacing recorded when it is created), so the buyback buys the token where the game trades. The hook's own swap skips its callbacks (v4's noSelfCall), so the burn pays no pot fee and scores nothing. There is no separate burn pool to create or fund.

Deployed on Robinhood Chain at 0x45aC5C394f4fD8194fC4868c63A75d606a8A20CC for $WIF (0x5173b8eA6923c2d40267890D45C46a3480954773), with $PFWA as the host token. Rounds started at GENESIS 1793008800 (2026-10-26 10:00 UTC). Play at sherwood.pfwa.fun/wif; the guide is at sherwood.pfwa.fun/wif/docs.

script/PlanSherwoodV21.s.sol plans the three transactions the owner signs (deploy through the CREATE2 deployer with a mined salt, create the game pool, name the operator). The tests are the v2 suites carried over to v2.1, with the shield and burn tests rewritten: forge test --match-contract SherwoodV21 (188 tests).

The arena on Hookr ($PFWA)

src/SherwoodArena.sol brings the $PFWA game back as a plain contract instead of a hook. The market is an ETH/$PFWA pool on Hookr's root hook (arb recapture on, a 6.25% buy tax); the game is ours. Each move is play(move, minOut, referrer): the arena buys $PFWA with all the ETH sent, through Hookr's router, keeps it for the player (their holdings) and scores the move with v2.1's rules (charges, shield blocks, King of the Hill).

What changed from v2.1

  • The player is msg.sender, not tx.origin, so a wallet, an agent or another contract can play.

  • Only arena moves score. Buys made anywhere else score nothing, but they still pay the buy tax into the pot.

  • Holdings instead of wallet balances. The $PFWA a move buys stays in the arena under the player's address until they call withdraw(amount). The settlement sell rule, the claim check and the +25% holder bonus all read holdings(player), which only grows through play() (there is no deposit). So tokens borrowed for one transaction, such as a free Uniswap v4 flash take, can't pass them.

  • Selling starts with a withdraw, which doesn't wipe points. It costs at settlement instead: a winner whose holdings are below what the round's moves bought keeps only that share of the prize (withdrew 20%, lose 20%), and the rest rolls into the live pot. To claim, a winner must still have what they had at settlement.

  • Rounds are 20 hours at launch, as on v2.1. The owner can set any whole number of minutes from 5 min to 7 days (setRoundLength), from the next round boundary on (before round 1, at once), no new contract needed; the round being played keeps its end.

  • Flip uses HoodRand and can be switched off by the owner (a FLIP then plays as a BUY). A HoodRand result is public about 15 seconds after the request and anyone can submit it, so an unanswered flip only expires (as a plain buy) after a day, HoodRand's refund window. Until then the round it belongs to waits to settle; later rounds settle as usual.

  • The pot is fed by the buy tax (paid to the pot vault, which forwards it to the arena), the trader share of arb recapture (credited to the router adapter, which passes it on), ETH anyone sends, and half of $PFWA's Pons creator-fee ETH through the fee splitter. There is no play fee (playFeeBps is 0).

  • Split, fixed in the contract:

    Share Goes to
    40% / 20% / 10% Top 3
    8% King of the Hill
    17% Buys $PFWA through Hookr's router (BUYBACK_BPS, buybackAndBurn). 10% of the pot's worth goes to 0x…dEaD (BURN_BPS); the other 7% (KEEP_BPS) stays in the arena as spare tokens for the PFWA treasury
    5% Rollover
  • Spare tokens: anything the arena holds beyond everyone's holdings (spareTokens()): the kept part of each buyback, and tokens sent straight to the arena. Only the owner can send them on (sendSpareTokens(to, amount)), and never more than the spare, so holdings can't be touched.

Contracts (Robinhood Chain)

Redeployed on 2026-11-02 with the fixes from the security review below, all verified (Sourcify, shown on Blockscout); round 1 starts on 2026-11-03 at 15:00 UTC (GENESIS 1793718000), in 20-hour rounds:

Contract Address Role
SherwoodArena 0x817063839b465823180BedC11601681A42E7d92f The game
SherwoodPotVault 0xE0bF87424bBdBCBABf1d9A30B34671C3282eff1B The pool's buy-tax recipient; forwards every wei to the arena
HookrRouterAdapter 0x2507Fe3b9D792B63F10B96B617916ce611a2d48d The arena's one swap, through Hookr's router; bound to the arena once
SherwoodArenaDeployer 0x8Cbe9083cb12C316eBe96a005D0C9e17A7BF1961 Deploys the three above, wired together, in one transaction
PonsFeeSplitter 0x9C5d8E94343D51bB3656b068E4a91A7c3c50606e Collects $PFWA's Pons fees; once a day sends a share of the ETH (half to start) to the pot vault and the rest, with all the $PFWA, to the treasury

Retired before launch, never played: arena 0x097AcFfB2B247d9492983b3eb1F4a57820D1BAD1, vault 0x77BC34F3669Ff7dd41C9C2Ca8F0201022f3Cbc68, adapter 0x195554e3ec0678bF34e37b0E9aBdc5C0b5d89D52 and deployer 0xF178379a521bCc695c3896FD01bCD65b18239D9d (GENESIS 1793631600); and a build from before the 10% burn, deployed from a stale launch page and never wired to a pool: arena 0xd87248001fD0732d1a56d6f69fcfDb58E2Df2d62, vault 0x9621693D1bbdef13b9bc3CEF0F4Bb882fa0824d5.

Security review (Nov 2026)

Before launch, Hey Research Lab (r00k) reviewed this repo at 84c9830 and reported two low-severity issues in the arena, both fixed here:

  1. Borrowed tokens passed the holding checks. The sell rule at settlement, the claim check and the holder bonus read balanceOf(player) at one instant, and anyone can borrow tokens from the Uniswap v4 PoolManager for one transaction at no cost (flash accounting). A contract player could sell its bag, then borrow, settle, claim and repay in one call and keep the full prize. Fixed with holdings: the checks read what the arena keeps for the player, which only play() adds to.
  2. A HoodRand flip could be expired selectively. A HoodRand result is public once drand publishes the round, and an unanswered flip expired as a plain buy after 10 minutes, so during a relayer outage a player could reveal their winning flips and let the losing ones expire. Fixed by expiring only after a day (HoodRand's refund window); anyone can reveal before that.

Their report also covered v2 and v2.1 (the $IMD and $WIF games' hooks): they read balances the same way (with tx.origin as the player, which an EIP-7702 delegated EOA can still use), so the same borrowing works there. Those hooks can't be changed; their pots are small, and the fix carries into their next seasons.

Roles and trust

Role Can Cannot
Arena owner setOwner/acceptOwner, setOperator, setFlipsEnabled, setRoundLength (from the next round), setTaxQueue (once), sendSpareTokens (only tokens beyond everyone's holdings) Touch pots, points, prizes, referral earnings, players' holdings or the split
Operator buybackAndBurn(amount, minOut) from the buyback reserve; refundDiceRequest Send reserve ETH anywhere but a $PFWA buy (10/17 of it to 0x…dEaD, the rest kept as spare tokens)
Vault owner proposeArena(next), cancelSwitch() Switch the arena before SWITCH_DELAY (2 days) has passed, or send the tax anywhere but the current arena
Anyone play, withdraw (their own holdings), settle, claim, sweepUnclaimed, fundPot, pullTax, flush on the vault, switchArena() once a proposal is due —

The pool's tax recipient is fixed by Hookr at launch, so it is the vault, not the arena. A fixed or upgraded arena replaces this one without a new pool: the owner proposes it on the vault, and after 2 days anyone completes the switch, so players see it coming.

Holdings assume nothing the player controls runs during the arena's own swap (a token with transfer hooks, or a router that calls back): then borrowed tokens could be sent in mid-swap and be credited. $PFWA is a plain OpenZeppelin ERC20 and Hookr's router makes no such call.

Tests

forge test --match-contract "SherwoodArena|SherwoodPotVault|PonsFeeSplitter": the v2.1 suites carried over to the arena, plus the router, tax, slippage, re-entry, contract-player, round-length and vault tests, the escrow tests (test/SherwoodArenaEscrow.t.sol: flash-borrow attacks at settlement, at claim and inside play(), withdrawals, spare tokens), invariants that the arena's tokens equal everyone's holdings plus the kept buybacks, and fork tests against Hookr's router and the Pons locker (the Pons fork test skips when no fees are owed at the latest block).

Pons fee splitter factory

src/PonsFeeSplitterFactory.sol lets any token launched on Pons get its own PonsFeeSplitter, the contract that sends half of $PFWA's Pons creator fees into the Sherwood pot every day. Every copy is the same contract, so each one verifies against the same source.

  • Who: only the wallet that launched the token on Pons (the token's deployer()), once per token, so nobody else can take a project's slot. Only tokens made by Pons' launch factory and paired with WETH.
  • Where: a CREATE2 address that depends only on the token, owner and treasury; predict(token, owner, treasury) gives it before it exists.
  • After create: the launcher points the token's fees at the splitter on Pons (setFeeRedirect on the locker), and the owner sets the pot (setPot) and its share (setPotShare, half to start). Once a day anyone can run distribute(): the pot's share of the ETH to the pot, the rest of the ETH and all the token to the treasury.
  • The factory takes no fee and owns nothing it makes. Lookups: splitterOf(token), count(), page(start, n).

Tests: forge test --match-contract PonsFeeSplitterFactory (plus a fork test that makes a splitter for $PFWA's real launch when ROBINHOOD_RPC_URL is set). Deploying to Robinhood Chain next; the address goes here once it's live.

HoodRand: verifiable randomness for Robinhood Chain

hoodrand/ is HoodRand, live at 0xbE5105faf1Cb76733876959d5802448d066D734F. It turns drand's evmnet beacon (the League of Entropy, a new BLS signature every 3 seconds) into random numbers checked onchain with Robinhood Chain's BN254 pairing precompile, so nobody, PFWA included, can predict or bias a result. It has the same interface as Dice Protocol and Pyth Entropy, so contracts built for them work unchanged. Fee: 0.00002 ETH a request. See hoodrand/README.md.

About

A daily $PFWA leaderboard game on a Uniswap v4 hook on Robinhood Chain. Every move is a buy: steal, rob the leader or flip for it, and the top 3 split the ETH pot.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages