Contracts

Staking Vault

Yield engine — Synthetix-style per-second reward accounting

Contract
LayerSubStakingVault
Source
src/LayerSubStakingVault.sol
Pragma
0.8.24
Precision
1e18

Overview

Stakers deposit $SUB and accrue rewards per staked token per second, following the Synthetix StakingRewards accounting model with 1e18 fixed-point math.

Because LayerSub uses one token for both staking and rewards, the vault must never pay staked principal out as yield. Rewards therefore come from an explicit budget the owner funds, and emission stops the moment that budget would run out.

ReentrancyGuardOwnable

Constructor

constructor(address _stakingToken, address _rewardToken, address initialOwner)

Notes

  • Reverts with ZeroAddress if any of the three is the zero address.
  • `lastUpdateTime` and `periodFinish` are both initialised to the deployment timestamp, so no emission occurs until the owner funds a budget and sets a rate.
  • In the $SUB deployment `_stakingToken` and `_rewardToken` are the same address. Nothing in the contract requires that, but the solvency model is only interesting when they match.

State

  • PRECISIONuint256constant= 1e18

    Fixed-point scaling factor for the reward-per-token accumulator.

  • stakingTokenIERC20immutable

    Token accepted for staking. $SUB in this deployment.

  • rewardTokenIERC20immutable

    Token paid out as yield. Equal to stakingToken in this deployment.

  • rewardRateuint256public storage

    Reward tokens emitted per second, shared across all stakers.

  • periodFinishuint256public storage

    Timestamp at which emission stops because the funded budget would be exhausted.

  • lastUpdateTimeuint256public storage

    Last timestamp at which reward accounting was settled.

  • rewardPerTokenStoreduint256public storage

    Global accumulator of rewards owed per staked token, scaled by PRECISION.

  • rewardsAvailableuint256public storage

    Funded reward tokens not yet committed to stakers. The uncommitted budget.

  • userRewardPerTokenPaidmapping(address => uint256)public storage

    Snapshot of rewardPerTokenStored at each staker's last interaction.

  • rewardsmapping(address => uint256)public storage

    Rewards already settled for each staker, pending claim. Does not include unsettled accrual.

Functions

13 documented functions. Owner-gated calls are flagged in red.

stake

Permissionless
stake(uint256 amount) external nonReentrant

Stakes amount of stakingToken on behalf of the caller.

Settles the caller's accrued rewards first, then pulls the tokens. The credited amount is measured as the vault's balance delta rather than trusting the requested amount, so a transfer-taxing token cannot desynchronise accounting.

Parameters

  • amountuint256

    Amount to stake, in wei-denominated tokens.

Reverts

  • ZeroAmount

    when amount is zero, or the measured balance delta is zero

EmitsStaked

Notes

  • Requires an ERC-20 allowance for the vault, or a prior `permit`.
  • `Staked` carries the amount actually received, which for a standard token equals the amount requested.

withdraw

Permissionless
withdraw(uint256 amount) public nonReentrant

Withdraws part or all of the caller's staked principal.

Accrued rewards are settled before the balance changes, so withdrawing never forfeits yield already earned — it stays claimable via claimReward.

Parameters

  • amountuint256

    Amount to withdraw, in wei-denominated tokens.

Reverts

  • ZeroAmount

    when amount is zero

  • InsufficientStakedBalance

    when amount exceeds the caller's stake; carries requested and available

Notes

  • There is no lockup and no withdrawal fee. Principal is always withdrawable in full.

claimReward

Permissionless
claimReward() public nonReentrant

Transfers all of the caller's accrued rewards to them.

Notes

  • Claiming with nothing accrued is a silent no-op: the call succeeds, transfers nothing and emits no event. It does not revert.
  • Claiming does not touch the caller's stake, which keeps accruing.

exit

Permissionless
exit() external nonReentrant

Withdraws the caller's entire stake and claims all accrued rewards in one transaction.

Reverts

  • ZeroAmount

    when the caller has no stake — the withdrawal leg rejects a zero amount

Notes

  • A staker with rewards but no remaining stake cannot use exit; call claimReward directly instead.

fundRewards

Owner only
fundRewards(uint256 amount) external onlyOwner

Transfers reward tokens into the vault as distributable yield.

Adds to rewardsAvailable and pushes periodFinish out to the moment the whole budget would be emitted at the current rewardRate. Like stake, the credited amount is the measured balance delta.

Parameters

  • amountuint256

    Amount of reward tokens to add to the budget.

Reverts

  • ZeroAmount

    when amount is zero

Notes

  • This is the only way reward tokens enter the budget. A plain ERC-20 transfer to the vault does not increase rewardsAvailable — it silently becomes unaccounted surplus.

setRewardRate

Owner only
setRewardRate(uint256 _rewardRate) external onlyOwner

Sets the per-second emission rate shared across all stakers.

periodFinish is re-derived from the remaining budget, so raising the rate shortens the emission window rather than over-committing tokens the vault does not hold.

Parameters

  • _rewardRateuint256

    New emission rate in wei-denominated reward tokens per second.

Notes

  • Setting the rate to zero halts emission immediately and sets periodFinish to the current block timestamp.
  • Already-accrued rewards are settled before the change, so a rate change never retroactively alters what stakers have earned.

recoverUnallocatedRewards

Owner only
recoverUnallocatedRewards(address to, uint256 amount) external onlyOwner nonReentrant

Recovers reward tokens that have not yet been committed to stakers.

Draws only from rewardsAvailable, so it cannot touch staked principal or rewards already accrued. Accounting is settled before the check, which means the owner cannot front-run pending accrual by calling this first.

Parameters

  • toaddress

    Recipient of the recovered tokens. Cannot be the zero address.

  • amountuint256

    Amount to recover. Cannot exceed rewardsAvailable.

Reverts

  • ZeroAddress

    when to is the zero address

  • ZeroAmount

    when amount is zero

  • InsufficientRewardBudget

    when amount exceeds rewardsAvailable; carries requested and available

totalSupply

View
totalSupply() external view returns (uint256)

Total stakingToken currently staked in the vault — the protocol's TVL.

balanceOf

View
balanceOf(address account) external view returns (uint256)

Amount of stakingToken staked by account.

Notes

  • The vault is not itself a token; this mirrors the ERC-20 name for convenience only.

earned

View
earned(address account) public view returns (uint256)

Total rewards claimable by account, including accrual not yet settled to storage.

This is the authoritative figure for a staker's claimable yield, and the number the dApp displays. The `rewards` mapping alone is stale between interactions.

rewardPerToken

View
rewardPerToken() public view returns (uint256)

Current value of the global reward-per-staked-token accumulator, scaled by PRECISION.

Notes

  • Returns the stored value unchanged while nothing is staked, since there is nothing to divide across.

lastTimeRewardApplicable

View
lastTimeRewardApplicable() public view returns (uint256)

The current timestamp, capped at periodFinish. Accrual stops beyond it.

rewardForDuration

View
rewardForDuration(uint256 duration) external view returns (uint256)

Rewards that would be emitted over duration seconds at the current rate.

Notes

  • A plain `rewardRate * duration`. It does not cap at periodFinish or check the budget, so for a duration beyond the window it overstates what will actually be emitted.

Events

Staked

Staked(address indexed user, uint256 amount)

A staker deposited principal. The amount is what the vault actually received.

  • userindexed
    address

    The staker.

  • amount
    uint256

    Amount credited, in wei.

Withdrawn

Withdrawn(address indexed user, uint256 amount)

A staker withdrew principal.

  • userindexed
    address

    The staker.

  • amount
    uint256

    Amount withdrawn, in wei.

RewardClaimed

RewardClaimed(address indexed user, uint256 reward)

A staker claimed accrued yield. Not emitted when the claim would be zero.

  • userindexed
    address

    The staker.

  • reward
    uint256

    Amount paid out, in wei.

RewardRateUpdated

RewardRateUpdated(uint256 newRate, uint256 periodFinish)

The owner changed the emission rate. Carries the re-derived window end.

  • newRate
    uint256

    New per-second emission rate.

  • periodFinish
    uint256

    Recomputed emission end timestamp.

RewardsFunded

RewardsFunded(address indexed funder, uint256 amount, uint256 periodFinish)

The owner added to the reward budget.

  • funderindexed
    address

    Who funded — always the owner.

  • amount
    uint256

    Amount added to the budget, as measured.

  • periodFinish
    uint256

    Extended emission end timestamp.

UnallocatedRewardsRecovered

UnallocatedRewardsRecovered(address indexed to, uint256 amount)

The owner withdrew uncommitted budget.

  • toindexed
    address

    Recipient of the recovered tokens.

  • amount
    uint256

    Amount recovered, in wei.

Custom errors

  • ZeroAddress()

    A zero address was supplied where one is not allowed.

  • ZeroAmount()

    A zero amount was supplied, or a measured transfer credited nothing.

  • InsufficientStakedBalance(uint256 requested, uint256 available)

    A withdrawal exceeded the caller's stake. Carries both amounts.

  • InsufficientRewardBudget(uint256 requested, uint256 available)

    A recovery exceeded the uncommitted budget. Carries both amounts.

Accrual maths

Every figure the vault reports derives from these four expressions. The two floor divisions in earned() are the origin of the rounding surplus described on the solvency page.

Reward per tokenrewardPerToken() = rewardPerTokenStored + (elapsed × rewardRate × 1e18) / totalStaked

elapsed = lastTimeRewardApplicable() − lastUpdateTime. Returns the stored value unchanged while totalStaked is zero.

Earned by a stakerearned(a) = balanceOf(a) × (rewardPerToken() − userRewardPerTokenPaid[a]) / 1e18 + rewards[a]

Two floor divisions sit between the budget and the payout, which is where the vault's rounding surplus comes from.

Emission windowperiodFinish = rewardRate == 0 ? now : now + (rewardsAvailable / rewardRate)

Integer division, so the window is truncated downward — never extended past what the budget covers.

APRAPR = rewardRate × 31,536,000 / totalStaked

Undefined while nothing is staked. Recomputed on every read, so it moves as stake enters and leaves.