Skip to content

About

Synthetix-style staking rewards + factory: checkpoint-before-balance accumulator, solvency-checked notify, per-pool fee

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Staking Rewards

Synthetix-style liquidity mining in Solidity: a StakingRewards pool plus a StakingRewardsFactory that deploys and indexes them. Stake an ERC20 (e.g. an LP token), earn a different reward ERC20 streamed linearly over a fixed duration. O(1) accrual — no per-staker loops.

The reward accumulator is the canonical Synthetix design. What this implementation adds is a set of safety properties enforced in code and checked by tests, not just asserted in comments:

What makes it different

  • Solvency-checked notify — rewards can never exceed funding. notifyRewardAmount refuses any rate the pool cannot cover from its actual reward-token balance: it requires rewardRate * rewardsDuration <= rewardsToken.balanceOf(this). Since the pool never streams faster than rewardRate or longer than rewardsDuration, the most it can ever pay out is capped at the tokens actually held. No infinite mint, no under-collateralised promise. A stateful invariant asserts this holds across random action sequences (see invariant_neverDistributeMoreThanFunded: sum(earned) + paid <= funded).

  • Checkpoint-before-balance accumulator. Every state-changing entry point runs updateReward(account) before it mutates any balance, so an account's accrual is always settled against the balance it actually held while the reward was streaming. Checkpointing after a balance change would credit fresh stake with rewards it never earned (or strip a leaver of rewards it did). The ordering is the correctness-critical part of the pattern, and it is applied on every path — including recoverERC20.

  • Pause never traps stakers. pause() blocks new stake calls only. withdraw, getReward and exit are never pausable, so an emergency stop can never prevent a staker from retrieving principal or claiming accrued rewards.

  • Pull-funded notify closes the fund-then-notify race. notifyRewardAmountFrom(reward) pulls the reward tokens via transferFrom and notifies in the same call. A plain fund-then-notifyRewardAmount sequence passes its balance check against whatever tokens happen to be in the contract — including tokens only transiently present (e.g. flash-loaned). The pulling variant can only ever back its stream with tokens it actually moved, and an under-funded caller reverts at the transfer with no state change (atomic).

  • recoverERC20 can't touch principal. It sweeps stray tokens but reverts on the staking token (stakers' principal) and caps reward-token recovery at the unallocated surplus — balance minus everything accrued-but-unclaimed and the remaining future stream. recoverableRewardSurplus() returns that exact cap, folding in accrual that has streamed since the last checkpoint so a cold read never overstates it.

Contracts

  • StakingRewards.sol — the pool.
    • Staker: stake / withdraw / getReward / exit.
    • Owner: notifyRewardAmount or notifyRewardAmountFrom to fund a period, setRewardsDuration (only while no period is active), pause / unpause, recoverERC20.
    • Views: earned, rewardPerToken, getRewardForDuration, reservedRewards, recoverableRewardSurplus.
  • StakingRewardsFactory.sol — deploys and indexes pools, charging a bounded flat creation fee (msg.value, capped by an immutable feeCap) forwarded to feeRecipient.

How accrual works

rewardPerToken = rewardPerTokenStored + elapsed * rewardRate * 1e18 / totalSupply
earned(a)      = balanceOf(a) * (rewardPerToken - userPaid[a]) / 1e18 + rewards[a]

notifyRewardAmount sets rewardRate = reward / rewardsDuration for a fresh period, or folds the leftover of an active period into the new rate when topping up. The staking and reward token are required to differ, so the balance-based solvency check is never confused by staked principal.

Usage

Create a pool through the factory (signatures are exact):

// createPool(stakingToken, rewardToken, rewardsDuration, poolOwner) payable
address pool = factory.createPool{value: factory.creationFee()}(
    address(stakingToken),
    address(rewardToken),
    7 days,
    poolOwner
);

Fund and run it (as the pool owner):

StakingRewards sr = StakingRewards(pool);

// Option A: send reward tokens to the pool, then notify.
rewardToken.transfer(pool, 700 ether);
sr.notifyRewardAmount(700 ether);

// Option B (recommended): approve the pool and pull-fund atomically.
rewardToken.approve(pool, 700 ether);
sr.notifyRewardAmountFrom(700 ether);

Stake and claim (as a user):

stakingToken.approve(pool, amount);
sr.stake(amount);
// ... time passes ...
sr.getReward();   // claim rewards, keep stake
sr.exit();        // withdraw all stake + claim in one call

Tests

forge test

47 tests, all passing: 35 unit tests for the pool (single/multi-staker pro-rata accrual, mid-period stake/withdraw checkpointing, claim/exit, notify fresh-rate / leftover-fold / solvency-revert / zero-rate guards, duration and recover guards, pause behaviour, the pulling notify, and the surplus view), 9 factory tests, and 3 stateful invariants:

  • invariant_neverDistributeMoreThanFunded — sum(earned) + paid <= funded
  • invariant_earnedBackedByBalance — outstanding claimable ≤ reward balance
  • invariant_totalSupplyEqualsSumBalances — accounting matches staker balances

The invariant handler drives random stake/withdraw/claim/notify/notifyFrom/warp sequences (64 runs × 200 depth) against a ghost total of everything ever funded.

Gas

Per-action gas from forge test --gas-report (mean over the test suite, which mixes cold/warm and first-time storage paths — reproduce with the command below). A committed .gas-snapshot (forge snapshot) tracks per-test gas.

Action mean gas
stake ~109k
withdraw ~148k
getReward ~141k
exit ~157k
notifyRewardAmount ~94k
forge test --gas-report
forge snapshot     # regenerate .gas-snapshot

Build

solc 0.8.26, via_ir, cancun, optimizer 200 runs (see foundry.toml). Dependencies: OpenZeppelin (Ownable, Pausable, ReentrancyGuard, SafeERC20, Math).

Deploy

See DEPLOY.md — env vars, the exact forge script command, testnet-first guidance, and pool creation via the factory.

Status

Unaudited. Clean-room MIT implementation, tested but not reviewed by a third party. Do not use in production without an independent audit. If you deploy, verify the deployed address and its constructor arguments yourself.

License

MIT

About

Synthetix-style staking rewards + factory: checkpoint-before-balance accumulator, solvency-checked notify, per-pool fee

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages