DEV Community

Cover image for staking: per-second token rewards on Solana with a reward-per-token accumulator
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

staking: per-second token rewards on Solana with a reward-per-token accumulator

A staking pool sounds like a loop. Every second, a fixed amount of reward tokens is released. Each staker gets a slice in proportion to their share of the pool. So: every second, go through all stakers and add to their balance.

That loop cannot run on a blockchain. Nothing executes on its own every second, and a transaction that touches every staker gets more expensive with every new one. The pool needs a way to know what each staker has earned without ever visiting them all.

There is a well-known trick for this, the reward-per-token accumulator, and staking is the project where I implemented it: stake an SPL token and earn another one, paid per second, in proportion to your share of the pool. It is built with Anchor 1.2 and token_interface, so it works with SPL Token or Token-2022.

The warning from the README first: not audited, devnet / localnet only. This is a learning project. Do not deploy it to mainnet or use it with real funds.

What it does

The program has five instructions: init_pool(reward_rate), fund(amount) (admin only), stake(amount), unstake(amount) and claim().

Its accounts:

account address
Pool PDA ["pool", stake_mint]: admin, mints, reward_rate, total_staked, last_update, reward_per_token
stake vault / reward vault ATAs of the pool PDA
Staker PDA ["staker", pool, owner]: amount, reward_per_token_paid, pending

There is one pool per stake mint. The pool PDA owns two vaults: one holding the staked tokens and one holding the rewards the admin has funded. Each user has one Staker account per pool.

How to use it

Clone the repository, build, and run the tests:

git clone https://github.com/AbdeldjalilChougui/staking.git
cd staking
anchor build    # or: anchor build --tools-version v1.58
cargo test      # math unit tests + LiteSVM integration tests, no validator
Enter fullscreen mode Exit fullscreen mode

There is no front end. The tests are the usage example: they create the mints, init a pool, fund it, stake from two wallets, move the clock, and check the numbers.

The reward-per-token accumulator

Paying every staker every second would be O(n). Instead, the pool keeps one number that only grows: the rewards earned so far by one staked unit.

on every stake / unstake / claim, at time `now`:
    pool.rpt  += (now - pool.last_update) * reward_rate * 1e12 / pool.total_staked
    pool.last_update = now
    user.pending += user.amount * (pool.rpt - user.rpt_paid) / 1e12
    user.rpt_paid = pool.rpt
Enter fullscreen mode Exit fullscreen mode

Read it in two halves.

The first two lines bring the pool up to date. Since the last update, now - last_update seconds have passed, each releasing reward_rate tokens, shared among total_staked units. So each staked unit earned that much more, and rpt grows by it.

The last two lines settle one user. user.rpt_paid remembers what rpt was the last time this user was settled. The difference is what one unit earned since then, and the user holds user.amount units. That goes into pending, and the marker moves forward.

Why is this exact? Between two checkpoints a user's stake is constant, so amount × Δrpt is exactly what they earned over that interval. And every action that changes a stake is itself a checkpoint. Every instruction is O(1) whatever the number of stakers.

A worked example

This one comes from the tests. The rate is 100 tokens per second. Alice stakes 1,000 at t=0 and Bob stakes 3,000 at t=10.

  • From t=0 to t=10, Alice is alone. She earns 10 s × 100 = 1,000.
  • From t=10 to t=20, the pool holds 4,000. Alice has a quarter of it and Bob three quarters. Alice earns 10 s × 100 × ¼ = 250 and Bob earns 10 s × 100 × ¾ = 750.

At t=20, Alice has earned 1,250 and Bob 750. The test rewards_split_by_stake_and_time checks those numbers on chain.

What I learned

Turn a loop over users into one number per pool. This pattern is the lesson. Instead of pushing rewards to everyone, the pool records a global rate of earning, and each user pulls their share when they next act. The work moves from "every second, for everyone" to "once, for the person who is already paying for a transaction".

Precision is a design decision. rpt is a u128 scaled by PRECISION = 1e12, so small stakes against large pools do not round to zero. With integer math and no scaling, a small reward_rate divided by a large total_staked would be 0 every time, and nobody would earn anything.

Decide what happens when nobody is staked. Dividing by total_staked when it is zero is not an option. Here, when nothing is staked, rpt does not move, so those rewards are simply not distributed. It is a choice, and the README states it rather than hiding it.

Unstaking must not erase history. Because the user is settled before their amount changes, rewards earned so far survive an unstake, and nothing accrues while unstaked. The test unstake_keeps_earned_rewards checks both, and also that claiming twice fails with NothingToClaim.

Separate pure math from on-chain plumbing. Unit tests in src/lib.rs cover the accumulator math on its own, including the proportional split and overflow detection. The LiteSVM tests in programs/staking/tests/staking.rs then cover the program:

  • rewards_split_by_stake_and_time: the 1,250 / 750 example, on chain
  • unstake_keeps_earned_rewards: described above
  • cannot_unstake_more_than_staked (InsufficientStake), and zero amounts
  • claim_fails_when_reward_vault_is_short: insufficient funding (RewardVaultEmpty)
  • cannot_unstake_someone_elses_position: wrong signer / wrong owner, both by passing the victim's staker account and by redirecting the destination
  • only_admin_can_fund: wrong signer (has_one = admin)

Time is driven through the LiteSVM Clock sysvar, which also covers the per-second boundaries.

Promised rewards and funded rewards are different things. The accumulator computes what users are owed. Whether the reward vault holds that much is a separate question. When it does not, claim fails cleanly with RewardVaultEmpty and the rewards stay pending. Accounting that never checks the vault would promise tokens that do not exist.

Things to know

  • Not audited. Devnet / localnet only. Do not deploy to mainnet or use with real funds.
  • There is no reward end date. The admin must keep the reward vault funded. Claims fail cleanly when it runs dry, and the rewards stay pending.
  • There are no lockups or early-unstake penalties.
  • The reward rate is fixed at init_pool.
  • Rewards that would have been released while nothing is staked are not distributed.
  • The tests run in LiteSVM with no validator. The README describes no devnet deployment.

Why I built it

Proportional, time-based rewards are a recurring problem in on-chain programs, and the naive solution, a loop over all participants, is exactly the one a blockchain does not allow. The accumulator is the standard way around it, and it is short enough to fit in four lines of pseudocode. But four lines hide the hard parts: integer precision, the empty pool, the order of settling and changing a stake, and an underfunded vault. I wanted to implement it once, completely, with a worked example I could verify by hand and then verify again on chain.

Get the code

The program, the math unit tests and the LiteSVM tests are on GitHub: https://github.com/AbdeldjalilChougui/staking. It is MIT licensed. Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.

Top comments (0)