From a7065ee8d901535d1cbaca589da58ca34185d417 Mon Sep 17 00:00:00 2001 From: QHooks <352651120+qhooks@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:55:19 -0600 Subject: [PATCH 1/2] Fix expired raffle draws and fixed-end staking streams Apply the reviewed contract patch with regression tests and updated SHA256SUMS. Expired raffle rounds close without a reroll; timely draws earn a 1% bounty. Stake rewards use fixed-end tranches so syncs and dust cannot delay prior income. Document blockhash randomness, small-pot guidance and a future VRF upgrade. Pin forge-std v1.9.7 for reproducible local tests. No deployments. Co-Authored-By: Claude Opus 5.5 --- .gitmodules | 3 + README.md | 4 + contracts/README.md | 20 ++- contracts/SHA256SUMS.txt | 4 +- contracts/lib/forge-std | 1 + contracts/src/QRafflePot.sol | 51 ++++-- contracts/src/QStakeModule.sol | 100 ++++++++--- contracts/test/Fixed.t.sol | 310 +++++++++++++++++++++++++++++++++ contracts/test/Mocks.sol | 34 ++++ 9 files changed, 488 insertions(+), 39 deletions(-) create mode 100644 .gitmodules create mode 160000 contracts/lib/forge-std create mode 100644 contracts/test/Fixed.t.sol create mode 100644 contracts/test/Mocks.sol diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..bab06ca --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "contracts/lib/forge-std"] + path = contracts/lib/forge-std + url = https://github.com/foundry-rs/forge-std.git diff --git a/README.md b/README.md index 6caa02d..39b42ec 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,10 @@ This repository is the public toolkit for builders: The SDK never holds keys or sends transactions. It returns `{ to, data, value }` for the user's wallet to review and send. +## Reference modules + +`QRafflePot` uses blockhash randomness. Block producers or sequencers can predict or influence the result, so keep pots small. VRF is planned for a future version. See [`contracts/README.md`](contracts/README.md) for module behavior and tests. + ## Quick start ```js diff --git a/contracts/README.md b/contracts/README.md index 0ad781d..5dce791 100644 --- a/contracts/README.md +++ b/contracts/README.md @@ -3,8 +3,8 @@ | File | What it is | |---|---| | `src/QModuleBase.sol` | The base every marketplace module inherits, **unchanged**. Review checks its SHA-256 against `SHA256SUMS.txt`. | -| `src/QStakeModule.sol` | Reference module: holder staking, payouts streamed over a day. | -| `src/QRafflePot.sol` | Reference module: a raffle pot. | +| `src/QStakeModule.sol` | Reference module: holder staking with fixed-end 24–30-hour reward streams. | +| `src/QRafflePot.sol` | Reference module: a raffle pot with a 1% bounty for timely completed draws. | Build with [Foundry](https://book.getfoundry.sh): `forge build` (settings in `foundry.toml`: solc 0.8.26, `via_ir`, optimizer 200 runs, `cancun`, `bytecode_hash = none`). @@ -14,3 +14,19 @@ deterministic deployer `0x4e59b44847b379578588920ca78fbf26c0b4956c`, salt `kecca `init = creationCode ++ abi.encode(token, quote, builder, builderBps)`. Start with [`../docs/modules.md`](../docs/modules.md), then submit at . + +## Raffle randomness and expiry + +`QRafflePot` uses a future blockhash, not VRF. Block producers or sequencers can predict or influence the result: keep pots small; VRF is planned for a future version. Anyone completing a timely draw earns 1% of each pot currency; the winner receives the remainder. If the draw hash expires after its 256-block window, the round closes without a winner and its pot carries to the next entered round. The expired round cannot be re-armed; entrants can still withdraw their deposits. + +## Tests + +From the repository root, initialize the pinned test dependency, then run the local mock-only regressions: + +```sh +git submodule update --init --recursive +cd contracts +forge test +``` + +`forge-std` is pinned to v1.9.7 (`77041d2ce690e692d6e03cc812b57d1ddaa4d505`). Tests cover raffle expiry/carry-over/bounties, fixed-end staking streams, dust-sync resistance, just-in-time staking and reward conservation. They require no RPC or wallet. diff --git a/contracts/SHA256SUMS.txt b/contracts/SHA256SUMS.txt index a4108ad..f5efc7a 100644 --- a/contracts/SHA256SUMS.txt +++ b/contracts/SHA256SUMS.txt @@ -1,3 +1,3 @@ 84dafd9d69d240737fb53cac28bae51780b0447082c817254cc32ae272fae9c6 QModuleBase.sol -8aae62f02836960875c854a3a131e16485c515c48853dff2f07923318a1edcf6 QStakeModule.sol -6e4bddf11b17941cbf93229ae383773b6e1eea5a69f18fc0fa475ec641d07657 QRafflePot.sol +2e57efaf294ebe28542a186eea75a4dd8e2f2e16f2d6d336999d790e053ba85e QStakeModule.sol +c8c1057a52d57574c09582312401114579da311fe83027097beb46645a81aa7f QRafflePot.sol diff --git a/contracts/lib/forge-std b/contracts/lib/forge-std new file mode 160000 index 0000000..77041d2 --- /dev/null +++ b/contracts/lib/forge-std @@ -0,0 +1 @@ +Subproject commit 77041d2ce690e692d6e03cc812b57d1ddaa4d505 diff --git a/contracts/src/QRafflePot.sol b/contracts/src/QRafflePot.sol index dfbeb0e..daf63b1 100644 --- a/contracts/src/QRafflePot.sol +++ b/contracts/src/QRafflePot.sol @@ -8,13 +8,20 @@ import {QModuleBase} from "./QModuleBase.sol"; /// pot. Holders enter a daily round by depositing the token; tickets are tokens x seconds left in the round, so /// entering at the last minute buys almost nothing. After a round ends anyone draws it: the first call picks a draw /// block a few blocks ahead, the next call after that block uses its hash to pick one winner, weighted by tickets, -/// who wins the whole pot in the token and the pair currency. Every depositor takes their tokens back once the round -/// has ended, winner or not. Rounds nobody entered are skipped; their income waits for the next draw. -/// Randomness comes from a future block hash: good enough for a small pot, but the chain's block producer could -/// influence it, so pots are not meant to be large. No owner. +/// who wins the pot (less a small bounty for whoever completes the draw) in the token and the pair currency. Every +/// depositor takes their tokens back once the round has ended, winner or not. Rounds nobody entered are skipped; their +/// income waits for the next draw. +/// A draw block's hash is only readable for 256 blocks. If nobody completes the draw in that window the round closes +/// with no winner and its pot carries over to the next entered round: an armed round is never re-armed, so a loser who +/// has already seen the losing hash cannot roll again. The bounty pays anyone to complete draws on time. +/// Randomness comes from a future block hash: good enough for a small pot, but the chain's block producer (on Arbitrum +/// Orbit chains, the sequencer) could predict or influence it, so pots are not meant to be large; use VRF for more. +/// No owner. contract QRafflePot is QModuleBase { uint256 public constant ROUND = 1 days; uint256 public constant DRAW_DELAY = 2; // blocks between arming a draw and drawing it + /// @notice Share of the pot paid to whoever completes a draw, in basis points: 1%. + uint256 public constant DRAW_BOUNTY_BPS = 100; uint256 public immutable start; @@ -45,6 +52,9 @@ contract QRafflePot is QModuleBase { event Withdrawn(uint256 indexed round, address indexed who, uint256 amount); event Armed(uint256 indexed round, uint256 drawBlock); event Drawn(uint256 indexed round, address indexed winner, uint256 tokenPrize, uint256 quotePrize); + event Bounty(uint256 indexed round, address indexed drawer, uint256 tokenAmount, uint256 quoteAmount); + /// @notice Nobody drew round `round` while its draw block's hash was readable: no winner, the pot carries over. + event Expired(uint256 indexed round); event Claimed(address indexed who, uint256 tokenAmount, uint256 quoteAmount); constructor(address token_, address quote_, address builder_, uint16 builderBps_) @@ -96,36 +106,51 @@ contract QRafflePot is QModuleBase { } /// @notice Draws the next ended round with entries. The first call arms it (picks a draw block DRAW_DELAY - /// blocks ahead); a call after that block draws. If the draw block is too old for its hash, it re-arms. + /// blocks ahead); a call after that block draws, and the caller earns DRAW_BOUNTY_BPS of the pot. If the draw block + /// is too old for its hash, the round closes with no winner and its pot carries over; it is never re-armed. /// Returns true when a winner was drawn. function draw() external guarded returns (bool) { require(drawIndex < entered.length, "QRaffle: nothing to draw"); uint256 r = entered[drawIndex]; require(r < currentRound(), "QRaffle: round open"); Round storage rd = rounds[r]; - if (rd.drawBlock == 0 || (block.number > rd.drawBlock && blockhash(rd.drawBlock) == 0)) { + if (rd.drawBlock == 0) { rd.drawBlock = uint64(block.number + DRAW_DELAY); emit Armed(r, rd.drawBlock); return false; } require(block.number > rd.drawBlock, "QRaffle: too early"); + bytes32 h = blockhash(rd.drawBlock); + if (h == 0) { + rd.drawn = true; // winner stays address(0); deposits come back through withdraw as usual + drawIndex++; + emit Expired(r); + return false; + } _syncAll(); - uint256 seed = uint256(keccak256(abi.encode(blockhash(rd.drawBlock), r, address(this)))); + uint256 seed = uint256(keccak256(abi.encode(h, r, address(this)))); address w = _pick(r, seed % rd.weight); uint256 pt = pot[0]; uint256 pq = pot[1]; pot[0] = 0; pot[1] = 0; + uint256 bt = pt * DRAW_BOUNTY_BPS / BPS; + uint256 bq = pq * DRAW_BOUNTY_BPS / BPS; + pt -= bt; + pq -= bq; _won[w][0] += pt; _won[w][1] += pq; - _prizesOwed[0] += pt; - _prizesOwed[1] += pq; + _won[msg.sender][0] += bt; + _won[msg.sender][1] += bq; + _prizesOwed[0] += pt + bt; + _prizesOwed[1] += pq + bq; rd.drawn = true; rd.winner = w; rd.prizeToken = pt; rd.prizeQuote = pq; drawIndex++; emit Drawn(r, w, pt, pq); + if (bt != 0 || bq != 0) emit Bounty(r, msg.sender, bt, bq); return true; } @@ -153,11 +178,15 @@ contract QRafflePot is QModuleBase { return (_won[who][0], _won[who][1]); } - /// @notice The pot the next draw pays, counting income that has arrived but not been counted yet. + /// @notice The pot the next draw pays its winner (after the drawer's bounty), counting income that has arrived + /// but not been counted yet. function nextPrize() external view returns (uint256 tokenAmount, uint256 quoteAmount) { (uint256 t,) = _peek(0); (uint256 q,) = _peek(1); - return (pot[0] + t - t * builderBps / BPS, pot[1] + q - q * builderBps / BPS); + tokenAmount = pot[0] + t - t * builderBps / BPS; + quoteAmount = pot[1] + q - q * builderBps / BPS; + tokenAmount -= tokenAmount * DRAW_BOUNTY_BPS / BPS; + quoteAmount -= quoteAmount * DRAW_BOUNTY_BPS / BPS; } /// @notice Entries in round `r`. diff --git a/contracts/src/QStakeModule.sol b/contracts/src/QStakeModule.sol index cade516..c79c3ba 100644 --- a/contracts/src/QStakeModule.sol +++ b/contracts/src/QStakeModule.sol @@ -6,17 +6,29 @@ import {QModuleBase} from "./QModuleBase.sol"; /// @title QStakeModule /// @notice Holder staking as a marketplace module: QStakeVault's logic on QModuleBase. Stake the launch token, earn /// what the launch pays this module (less its builder's share, if any) in the token and its pair currency, streamed -/// over DURATION so staking for one block around a payout earns almost nothing. Funds that stream while nobody is -/// staked are kept and streamed again once someone is. Staked tokens are never counted as income. No lockup, no owner. -/// The same function names and selectors as QStakeVault, so one Staking panel drives both. +/// over at least DURATION so staking for one block around a payout earns almost nothing. Funds that stream while +/// nobody is staked are kept and streamed again once someone is. Staked tokens are never counted as income. No lockup, +/// no owner. The same function names and selectors as QStakeVault, so one Staking panel drives both. +/// +/// Streams: income is added to a tranche whose end is fixed on a clock grid (the end of the current EPOCH plus +/// DURATION, so every payout streams for between DURATION and DURATION + EPOCH). A later arrival in the same epoch only +/// raises that tranche's rate; it never moves the end of income that is already streaming, so a sync, or a dust +/// donation followed by a sync, cannot slow anyone's payout. A sync with no new income only moves the stream to now. contract QStakeModule is QModuleBase { uint256 public constant DURATION = 1 days; + /// @notice Width of the clock grid tranche ends sit on. + uint256 public constant EPOCH = 6 hours; + uint256 private constant SLOTS = DURATION / EPOCH + 1; // tranches that can be live at once uint256 private constant E18 = 1e18; uint256 private constant E36 = 1e36; - struct Stream { + struct Tranche { uint256 rate; // reward per second, scaled by 1e18 uint64 finish; + } + + struct Stream { + Tranche[SLOTS] tranches; uint64 last; uint256 acc; // reward per staked unit, scaled by 1e36 uint256 booked; // the module's share of income received so far and not yet paid out @@ -88,10 +100,18 @@ contract QStakeModule is QModuleBase { return (_earnedView(who, 0), _earnedView(who, 1)); } - /// @notice A currency's stream: reward per second (1e18-scaled), when it ends, and what it still holds. + /// @notice A currency's stream: reward per second now (1e18-scaled, all live tranches), when the last tranche + /// ends, and what it still holds. function stream(uint256 i) external view returns (uint256 rate, uint64 finish, uint256 booked, uint256 idle) { Stream storage s = _streams[i]; - return (s.rate, s.finish, s.booked, s.idle); + for (uint256 k; k < SLOTS; ++k) { + Tranche storage t = s.tranches[k]; + if (t.finish > block.timestamp) { + rate += t.rate; + if (t.finish > finish) finish = t.finish; + } + } + return (rate, finish, s.booked, s.idle); } function _reserved(uint256 i) internal view override returns (uint256) { @@ -113,45 +133,77 @@ contract QStakeModule is QModuleBase { } /// Moves the stream to now, counts new income (the builder's cut comes off first), then streams it plus - /// anything that streamed while nobody was staked. + /// anything that streamed while nobody was staked. With no new income and nothing idle this only accrues. function _sync(uint256 i) private { Stream storage s = _streams[i]; _accrue(s); _intake(i); // books and streams new income through _income - if (s.idle != 0) _start(i, 0); + uint256 idle = s.idle; + if (idle != 0) { + s.idle = 0; + _add(i, idle); + } } function _income(uint256 i, uint256 net) internal override { _streams[i].booked += net; - _start(i, net); + _add(i, net); } - function _start(uint256 i, uint256 incoming) private { + /// Adds `amount` to the tranche ending at the grid end for now. Other tranches, and what this tranche already + /// streams, keep their rate and end. Runs after `_accrue`, so a finished tranche has been fully counted. + function _add(uint256 i, uint256 amount) private { + if (amount == 0) return; Stream storage s = _streams[i]; - uint256 add = incoming + s.idle; - if (add == 0) return; - s.idle = 0; - uint256 left = block.timestamp < s.finish ? s.rate * (s.finish - block.timestamp) : 0; - s.rate = (left + add * E18) / DURATION; - s.finish = uint64(block.timestamp + DURATION); - s.last = uint64(block.timestamp); - emit Streamed(currency(i), add, s.rate, s.finish); + uint256 end = (block.timestamp / EPOCH + 1) * EPOCH + DURATION; + (Tranche storage t, bool live) = _tranche(s, end); + if (!live) { + t.rate = 0; + t.finish = uint64(end); + } + uint256 r = amount * E18 / (end - block.timestamp); + t.rate += r; + emit Streamed(currency(i), amount, r, uint64(end)); + } + + /// The tranche that ends at `end` (live = true), else a finished one to reuse. Only tranches opened in the last + /// SLOTS - 1 epochs can still be running and each epoch opens at most one, so a finished slot always exists. + function _tranche(Stream storage s, uint256 end) private view returns (Tranche storage t, bool live) { + uint256 freeK = SLOTS; + for (uint256 k; k < SLOTS; ++k) { + uint256 f = s.tranches[k].finish; + if (f == end) return (s.tranches[k], true); + if (freeK == SLOTS && f <= block.timestamp) freeK = k; + } + require(freeK < SLOTS, "QStake: tranches"); // unreachable + return (s.tranches[freeK], false); } + /// Credits everything every tranche streamed since `last`. Each tranche runs at a constant rate until its own end. function _accrue(Stream storage s) private { - uint256 t = block.timestamp < s.finish ? block.timestamp : s.finish; - if (t <= s.last) return; - uint256 amount = s.rate * (t - s.last); + uint256 last = s.last; + if (block.timestamp <= last) return; + uint256 amount = _streamed(s, last); + s.last = uint64(block.timestamp); + if (amount == 0) return; if (totalStaked != 0) s.acc += amount * E18 / totalStaked; else s.idle += amount / E18; - s.last = uint64(t); + } + + /// What the tranches streamed between `from` and now (1e18-scaled). + function _streamed(Stream storage s, uint256 from) private view returns (uint256 amount) { + for (uint256 k; k < SLOTS; ++k) { + Tranche storage t = s.tranches[k]; + uint256 f = t.finish; + if (f <= from) continue; + amount += t.rate * ((block.timestamp < f ? block.timestamp : f) - from); + } } function _earnedView(address who, uint256 i) private view returns (uint256) { Stream storage s = _streams[i]; uint256 acc = s.acc; - uint256 t = block.timestamp < s.finish ? block.timestamp : s.finish; - if (t > s.last && totalStaked != 0) acc += s.rate * (t - s.last) * E18 / totalStaked; + if (block.timestamp > s.last && totalStaked != 0) acc += _streamed(s, s.last) * E18 / totalStaked; return _owed[who][i] + staked[who] * (acc - _debt[who][i]) / E36; } diff --git a/contracts/test/Fixed.t.sol b/contracts/test/Fixed.t.sol new file mode 100644 index 0000000..40e935f --- /dev/null +++ b/contracts/test/Fixed.t.sol @@ -0,0 +1,310 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.26; + +// Regression tests for the patched QStakeModule and QRafflePot: the two reported attacks fail, and the +// accounting invariants hold. Run: forge test --match-path test/Fixed.t.sol + +import {Test, console2} from "forge-std/Test.sol"; +import {MockERC20} from "./Mocks.sol"; +import {QStakeModule} from "../src/QStakeModule.sol"; +import {QRafflePot} from "../src/QRafflePot.sol"; + +contract FixedStake is Test { + MockERC20 token; + MockERC20 quote; + QStakeModule m; + address alice = address(0xA11CE); + address bob = address(0xB0B); + address griefer = address(0xBAD); + + function setUp() public { + vm.warp(1_800_000_000); + token = new MockERC20("TKN"); + quote = new MockERC20("WETH"); + m = new QStakeModule(address(token), address(quote), address(0), 0); + address[2] memory who = [alice, bob]; + for (uint256 i; i < 2; ++i) { + token.mint(who[i], 1_000_000e18); + vm.prank(who[i]); + token.approve(address(m), type(uint256).max); + } + quote.mint(griefer, 1e18); + } + + function _now() internal view returns (uint256) { + return vm.getBlockTimestamp(); // via_ir can re-read block.timestamp after vm.warp + } + + function _stake(address who, uint256 a) internal { + vm.prank(who); + m.stake(a); + } + + function _pay(uint256 a) internal { + quote.mint(address(m), a); + m.sync(); + } + + // The reported attack: hourly 1-wei donations + sync. Fixed: the honest staker's 24 h earnings are unchanged. + function test_dustSyncsNoLongerSlowTheStream() public { + _stake(alice, 1000e18); + // Align to the grid so the payout's window is exactly DURATION + up to one EPOCH; compare against a twin. + QStakeModule twin = new QStakeModule(address(token), address(quote), address(0), 0); + vm.prank(alice); + token.approve(address(twin), type(uint256).max); + vm.prank(alice); + twin.stake(1000e18); + quote.mint(address(m), 900e18); + quote.mint(address(twin), 900e18); + m.sync(); + twin.sync(); + uint256 t0 = _now(); + for (uint256 h = 1; h <= 48; ++h) { + vm.warp(t0 + h * 1 hours); + vm.prank(griefer); + quote.transfer(address(m), 1); + m.sync(); + if (h == 24) { + (, uint256 a) = m.earned(alice); + (, uint256 b) = twin.earned(alice); + console2.log("24h earned, griefed module:", a); + console2.log("24h earned, untouched twin:", b); + assertGe(a, b, "dust syncs must not slow the payout"); + assertLe(a - b, 24, "only the dust itself is extra"); + assertGt(b, 900e18 * 24 / 30 - 1e18, "streams over DURATION..DURATION+EPOCH"); + } + } + (, uint256 fin) = m.earned(alice); + assertApproxEqAbs(fin, 900e18, 1e6, "everything paid within 30 h, dust aside"); + } + + // A sync with no new income changes nothing but the accrual clock. + function test_noIncomeSyncIsNoop() public { + _stake(alice, 1000e18); + _pay(500e18); + vm.warp(_now() + 3 hours); + (uint256 r0, uint64 f0, uint256 b0, uint256 i0) = m.stream(1); + (, uint256 e0) = m.earned(alice); + m.sync(); + m.sync(); + (uint256 r1, uint64 f1, uint256 b1, uint256 i1) = m.stream(1); + (, uint256 e1) = m.earned(alice); + assertEq(r0, r1); + assertEq(f0, f1); + assertEq(b0, b1); + assertEq(i0, i1); + assertEq(e0, e1); + } + + // New income never moves the end of income already streaming. + function test_laterIncomeDoesNotDelayEarlierIncome() public { + _stake(alice, 1000e18); + _pay(600e18); + (, uint64 f0,,) = m.stream(1); + vm.warp(_now() + 10 hours); // a later epoch: its own tranche + _pay(1); // dust + _pay(300e18); + vm.warp(f0); + // All of the first payout has streamed by its original end. + (, uint256 e) = m.earned(alice); + assertGe(e, 600e18 - 1e6); + } + + // Anti-JIT kept: income streams over at least DURATION, so one block around a payout earns ~nothing. + function test_justInTimeStakerEarnsAlmostNothing() public { + _stake(alice, 1000e18); + vm.warp(_now() + 5 hours + 59 minutes); // just before an epoch boundary: the shortest window (DURATION + 1 min) + _stake(bob, 1000e18); + _pay(1000e18); + vm.warp(_now() + 12); + vm.prank(bob); + m.exit(); + uint256 got = quote.balanceOf(bob); + assertLe(got, uint256(1000e18) * 12 / 1 days, "<= 12 s of a 1-day stream for half the stake"); + } + + // Conservation across random flows: nothing is created, the module stays solvent, all income ends up claimable. + function testFuzz_conservation(uint96[6] memory pays, uint32[6] memory gaps, uint96[6] memory stakes, bool[6] memory flips) + public + { + uint256 paid; + for (uint256 i; i < 6; ++i) { + address who = flips[i] ? alice : bob; + uint256 s = bound(stakes[i], 1, 100_000e18); + if (m.staked(who) >= s && flips[(i + 1) % 6]) { + vm.prank(who); + m.unstake(s); + } else { + _stake(who, s); + } + uint256 p = bound(pays[i], 0, 1_000_000e18); + paid += p; + _pay(p); + vm.warp(_now() + bound(gaps[i], 0, 2 days)); + assertGe(quote.balanceOf(address(m)), _bookedQuote(), "solvent"); + } + if (m.totalStaked() == 0) _stake(alice, 1e18); + vm.warp(_now() + 31 hours); + m.sync(); // idle re-streams for current stakers + vm.warp(_now() + 31 hours); + vm.prank(alice); + m.claim(); + vm.prank(bob); + m.claim(); + uint256 out = quote.balanceOf(alice) + quote.balanceOf(bob); + assertLe(out, paid, "never pays more than came in"); + assertApproxEqAbs(out, paid, 1e9, "everything but rounding dust paid out"); + assertGe(quote.balanceOf(address(m)), _bookedQuote()); + } + + function _bookedQuote() internal view returns (uint256 b) { + (,, b,) = m.stream(1); + } +} + +contract FixedRaffle is Test { + MockERC20 token; + MockERC20 quote; + QRafflePot pot; + address alice = address(0xA11CE); + address bob = address(0xB0B); + address keeper = address(0xC0FFEE); + + function setUp() public { + vm.warp(1_800_000_000); + vm.roll(1_000_000); + token = new MockERC20("TKN"); + quote = new MockERC20("WETH"); + pot = new QRafflePot(address(token), address(quote), address(0), 0); + address[2] memory who = [alice, bob]; + for (uint256 i; i < 2; ++i) { + token.mint(who[i], 1000e18); + vm.startPrank(who[i]); + token.approve(address(pot), type(uint256).max); + pot.enter(100e18); + vm.stopPrank(); + } + quote.mint(address(pot), 10e18); + pot.sync(); // count the pot + vm.warp(vm.getBlockTimestamp() + 1 days + 1); + } + + function _winnerFor(uint256 r, bytes32 h) internal view returns (address) { + (uint256 w,,,,,) = pot.rounds(r); + uint256 x = uint256(keccak256(abi.encode(h, r, address(pot)))) % w; + return x < w / 2 ? alice : bob; + } + + function _findHash(uint256 r, address want, uint256 salt) internal view returns (bytes32 h) { + for (uint256 i;; ++i) { + h = keccak256(abi.encode("h", salt, i)); + if (_winnerFor(r, h) == want) return h; + } + } + + function _solvent() internal view { + (uint256 t, uint256 q) = (token.balanceOf(address(pot)), quote.balanceOf(address(pot))); + (uint256 wa0, uint256 wa1) = pot.won(alice); + (uint256 wb0, uint256 wb1) = pot.won(bob); + (uint256 wk0, uint256 wk1) = pot.won(keeper); + assertGe(t, pot.totalDeposits() + pot.pot(0) + wa0 + wb0 + wk0); + assertGe(q, pot.pot(1) + wa1 + wb1 + wk1); + } + + // The reported attack: Bob saw a losing hash, let it expire, re-armed. Fixed: the round closes, no re-roll. + function test_expiredRoundCannotBeReArmed() public { + vm.prank(bob); + assertFalse(pot.draw()); // arm + (, uint64 db,,,,) = pot.rounds(0); + bytes32 h1 = _findHash(0, alice, 1); + vm.roll(db + 1); + vm.setBlockhash(db, h1); + // Bob stalls until the hash is gone. + vm.roll(db + 257); + vm.prank(bob); + assertFalse(pot.draw()); + (, uint64 db2, bool drawn, address w,,) = pot.rounds(0); + assertEq(db2, db, "not re-armed"); + assertTrue(drawn); + assertEq(w, address(0), "no winner"); + assertEq(pot.drawIndex(), 1); + assertEq(pot.pot(1), 10e18, "pot carries over untouched"); + vm.expectRevert(bytes("QRaffle: nothing to draw")); + vm.prank(bob); + pot.draw(); + vm.expectRevert(bytes("QRaffle: nothing won")); + vm.prank(bob); + pot.claim(); + // Deposits come back as usual. + vm.prank(alice); + pot.withdraw(0); + vm.prank(bob); + pot.withdraw(0); + assertEq(token.balanceOf(alice), 1000e18); + assertEq(token.balanceOf(bob), 1000e18); + _solvent(); + } + + // A timely draw pays the winner 99% and the drawer 1%, and nothing else changes. + function test_timelyDrawPaysWinnerAndBounty() public { + vm.prank(keeper); + pot.draw(); + (, uint64 db,,,,) = pot.rounds(0); + bytes32 h = _findHash(0, bob, 7); + vm.roll(db + 1); + vm.setBlockhash(db, h); + (, uint256 nq) = pot.nextPrize(); + assertEq(nq, 9.9e18); + vm.prank(keeper); + assertTrue(pot.draw()); + (,,, address w, uint256 pt, uint256 pq) = pot.rounds(0); + assertEq(w, bob); + assertEq(pt, 0); + assertEq(pq, 9.9e18); + _solvent(); + vm.prank(bob); + (, uint256 q) = pot.claim(); + vm.prank(keeper); + (, uint256 k) = pot.claim(); + assertEq(q, 9.9e18); + assertEq(k, 0.1e18); + assertEq(quote.balanceOf(address(pot)), 0); + } + + // The carried-over pot goes to the next entered round's winner; the expired round's entrants get no second roll + // inside the old round, only a normal entry in a new one alongside everyone else. + function test_carriedPotPaysNextRound() public { + vm.prank(bob); + pot.draw(); + (, uint64 db,,,,) = pot.rounds(0); + vm.roll(db + 300); + pot.draw(); // expires round 0 + uint256 r1 = pot.currentRound(); + vm.prank(alice); + pot.withdraw(0); + vm.prank(alice); + pot.enter(100e18); // round r1 + quote.mint(address(pot), 2e18); // new income + vm.warp(vm.getBlockTimestamp() + 1 days); + pot.draw(); // arm r1 + (, uint64 db1,,,,) = pot.rounds(r1); + vm.roll(db1 + 1); + vm.setBlockhash(db1, keccak256("any")); + vm.prank(keeper); + assertTrue(pot.draw()); + (,,, address w,, uint256 pq) = pot.rounds(r1); + assertEq(w, alice, "sole entrant"); + assertEq(pq, 12e18 - 12e18 / 100); + _solvent(); + } + + // Arming twice before the draw block is impossible to exploit: the second call just waits. + function test_cannotReArmBeforeDrawBlock() public { + pot.draw(); + (, uint64 db,,,,) = pot.rounds(0); + vm.expectRevert(bytes("QRaffle: too early")); + pot.draw(); + (, uint64 db2,,,,) = pot.rounds(0); + assertEq(db, db2); + } +} diff --git a/contracts/test/Mocks.sol b/contracts/test/Mocks.sol new file mode 100644 index 0000000..064eb59 --- /dev/null +++ b/contracts/test/Mocks.sol @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.26; + +contract MockERC20 { + string public symbol; + mapping(address => uint256) public balanceOf; + mapping(address => mapping(address => uint256)) public allowance; + + constructor(string memory s) { + symbol = s; + } + + function mint(address to, uint256 a) external { + balanceOf[to] += a; + } + + function approve(address s, uint256 a) external returns (bool) { + allowance[msg.sender][s] = a; + return true; + } + + function transfer(address to, uint256 a) external returns (bool) { + balanceOf[msg.sender] -= a; + balanceOf[to] += a; + return true; + } + + function transferFrom(address f, address to, uint256 a) external returns (bool) { + if (allowance[f][msg.sender] != type(uint256).max) allowance[f][msg.sender] -= a; + balanceOf[f] -= a; + balanceOf[to] += a; + return true; + } +} From b0bc5fab7eb852f7aca6630f3d51ceebf4e376b7 Mon Sep 17 00:00:00 2001 From: QHooks <352651120+qhooks@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:58:10 -0600 Subject: [PATCH 2/2] Test JIT staking at the intended epoch boundary --- contracts/test/Fixed.t.sol | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/contracts/test/Fixed.t.sol b/contracts/test/Fixed.t.sol index 40e935f..ea990f3 100644 --- a/contracts/test/Fixed.t.sol +++ b/contracts/test/Fixed.t.sol @@ -113,9 +113,11 @@ contract FixedStake is Test { // Anti-JIT kept: income streams over at least DURATION, so one block around a payout earns ~nothing. function test_justInTimeStakerEarnsAlmostNothing() public { _stake(alice, 1000e18); - vm.warp(_now() + 5 hours + 59 minutes); // just before an epoch boundary: the shortest window (DURATION + 1 min) + vm.warp((_now() / m.EPOCH() + 1) * m.EPOCH() - 1 minutes); // one minute before the next epoch boundary _stake(bob, 1000e18); _pay(1000e18); + (, uint64 finish,,) = m.stream(1); + assertEq(uint256(finish) - _now(), 1 days + 1 minutes, "exercise the shortest stream window"); vm.warp(_now() + 12); vm.prank(bob); m.exit();