A production-grade ERC-721 staking vault that streams ERC-20 rewards per second, using the
canonical Synthetix StakingRewards
reward-per-token accounting adapted so that the accounting "token" is one staked NFT of uniform
weight.
Stake one or more ERC-721 tokenIds, earn a per-second stream of ERC-20 rewards split evenly across every staked NFT, claim any time, and withdraw your exact NFTs whenever you like.
Rewards accrue with the classic reward-per-token accumulator, where each staked NFT counts as one unit of uniform weight (so a user staking 3 NFTs earns 3x a user staking 1 over the same window):
rewardRate— reward tokens emitted per second across the whole vault.rewardPerTokenStored— cumulative reward per staked NFT, scaled by1e18.lastUpdateTime— last timestamp the accumulator was refreshed.userRewardPerTokenPaid[a]— the accumulator value snapshotted for accountaat its last touch.rewards[a]— rewards already credited toabut not yet claimed.
rewardPerToken() = rewardPerTokenStored
+ (min(now, periodFinish) - lastUpdateTime) * rewardRate * 1e18 / totalStaked
earned(a) = stakedCount[a] * (rewardPerToken() - userRewardPerTokenPaid[a]) / 1e18 + rewards[a]
An updateReward(account) modifier settles the global accumulator and the caller's credited
rewards before any staking-weight change or payout, on every stake / unstake / claim /
notifyRewardAmount. This is what makes the accounting exact and order-independent.
The owner funds a reward period with notifyRewardAmount(reward) over rewardsDuration:
- If the previous period has ended,
rewardRate = reward / rewardsDuration. - Mid-period, the unspent remainder is rolled in:
rewardRate = (reward + remaining * rewardRate) / rewardsDuration. - The contract must already hold the reward tokens. The Synthetix solvency check
rewardRate <= balance / rewardsDurationguarantees the rate can never exceed what the funded balance can pay for the full period, so the vault can always cover what it owes.
rewardsDuration can only be changed when no period is active, so an in-flight stream's rate is
never silently rescaled.
While nothing is staked there is no divisor for the accumulator, so rewardPerToken() returns the
stored value unchanged and time does not distribute rewards to anyone. Reward tokens that would have
streamed during an empty period simply stay in the contract; the next notifyRewardAmount rolls the
unspent rate into the following period as leftover. This mirrors Synthetix exactly and is the
documented, intended behavior — rewards for an empty gap are not distributed.
The solvency check assumes the reward token credits the contract the full transferred amount. A
fee-on-transfer (FoT) reward token under-funds the vault relative to the notified amount, so
notifyRewardAmount(fullAmount) is rejected by the solvency check (the rate derived from the
notified amount exceeds what the under-funded balance can pay). This is the safe outcome: the vault
never starts a period it cannot pay. A funder who insists on such a token must notify only the
amount actually received, which then stays fully solvent. Do not use a FoT reward token expecting to
distribute the full notified amount. (Fee-on-transfer / rebasing does not exist for ERC-721, so the
staking side is unaffected.)
- Each staked NFT is escrowed against its staker; only the original staker can withdraw it.
- The owner can only fund rewards and set the reward duration. There is no admin path to withdraw staked NFTs and no path to touch users' accrued rewards.
onERC721Receivedaccepts safe transfers only from the configured staking collection, so foreign NFTs cannot be locked in a vault that has no way to return them.stake/unstake/claimarenonReentrant; a hostile reward token or hostile ERC-721 cannot re-enter to double-pay or corrupt custody (both are tested).
The stateful suite (test/NftStaking.invariant.t.sol, run with fail-on-revert = true pinned
inline, ~12,800 calls) proves:
- Reward solvency — total unclaimed accrued rewards across all users never exceeds the reward tokens the vault holds.
- NFT custody — Σ per-user staked counts ==
totalStaked== the vault's NFT balance; every staked tokenId is owned by the vault and mapped to exactly its staker. - Monotonicity —
rewardPerTokenis non-decreasing across the whole run.
Per-user monotonic accrual, proportional splits (by NFT count × time), claim resets, and the
totalStaked == 0 gap are covered by the unit tests.
37 tests total: 34 unit tests + 3 stateful invariants, all green. Toolchain: Foundry, solc 0.8.26,
via_ir, cancun, OpenZeppelin v5.0.2.
forge test # 37 passing
forge build --sizes # NftStaking runtime well under the EIP-170 24,576-byte limit
forge fmt --checkscript/Deploy.s.sol reads STAKING_TOKEN, REWARDS_TOKEN, STAKING_OWNER (optional, defaults to
broadcaster) and REWARDS_DURATION (optional, defaults to 7 days) from the environment.
A second adversarial audit pass (test/NftStaking.deepdive.t.sol, +5 tests) hammered reward
solvency, rounding, and the accounting boundaries. Findings, honestly:
- No untrusted-exploitable bug. The Synthetix reward accounting is sound as adapted: a funded
top-up chain (mid-period tops, empty gaps, partial claims) keeps total owed
<=tokens held; many small notifies never over-distribute (truncation leaves dust in the vault, it never over-pays); unstake→restake neither drops nor double-counts credited rewards; a mid-periodtotalStaked==0gap leaves the empty-window stream undistributed and resumes cleanly. - Documented trust boundary (owner footgun), not a vulnerability. The canonical Synthetix
solvency check compares
rewardRateto the whole balance, which already includes rewards owed to stakers from a prior period. If the (trusted,onlyOwner) owner callsnotifyRewardAmountfor a new period without first funding it, the check can pass while total owed then exceeds tokens held, and a laterclaim()reverts. This is inherent to the canonical pattern and is why the trust model / NatSpec require the owner to fund every notify.test_nonFundedNotifyIsAnOwnerFootgunpins the boundary so the assumption is explicit rather than incidental; no untrusted party can trigger it. - Mutation check: deleting the
rewardRate <= balance/durationsolvency guard is caught bytest_notifyRewardInsufficientBalanceRevertsandtest_feeOnTransferRewardIsRejectedBySolvencyCheck. - Test hygiene: time is advanced with
skip(); two consecutivevm.warp(block.timestamp + x)calls are common-subexpression-eliminated undervia_ir(the second reads a staleblock.timestamp) and would silently no-op.
Invariants unchanged and still non-hollow: 3 invariants, 12,800 calls each, 0 reverts,
fail_on_revert = true.
MIT