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.
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
Permissionlessstake(uint256 amount) external nonReentrantStakes 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
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
Permissionlesswithdraw(uint256 amount) public nonReentrantWithdraws 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
PermissionlessclaimReward() public nonReentrantTransfers 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
Permissionlessexit() external nonReentrantWithdraws 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 onlyfundRewards(uint256 amount) external onlyOwnerTransfers 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 onlysetRewardRate(uint256 _rewardRate) external onlyOwnerSets 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 onlyrecoverUnallocatedRewards(address to, uint256 amount) external onlyOwner nonReentrantRecovers 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
ViewtotalSupply() external view returns (uint256)Total stakingToken currently staked in the vault — the protocol's TVL.
balanceOf
ViewbalanceOf(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
Viewearned(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
ViewrewardPerToken() 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
ViewlastTimeRewardApplicable() public view returns (uint256)The current timestamp, capped at periodFinish. Accrual stops beyond it.
rewardForDuration
ViewrewardForDuration(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.
- userindexedaddress
The staker.
- amountuint256
Amount credited, in wei.
Withdrawn
Withdrawn(address indexed user, uint256 amount)A staker withdrew principal.
- userindexedaddress
The staker.
- amountuint256
Amount withdrawn, in wei.
RewardClaimed
RewardClaimed(address indexed user, uint256 reward)A staker claimed accrued yield. Not emitted when the claim would be zero.
- userindexedaddress
The staker.
- rewarduint256
Amount paid out, in wei.
RewardRateUpdated
RewardRateUpdated(uint256 newRate, uint256 periodFinish)The owner changed the emission rate. Carries the re-derived window end.
- newRateuint256
New per-second emission rate.
- periodFinishuint256
Recomputed emission end timestamp.
RewardsFunded
RewardsFunded(address indexed funder, uint256 amount, uint256 periodFinish)The owner added to the reward budget.
- funderindexedaddress
Who funded — always the owner.
- amountuint256
Amount added to the budget, as measured.
- periodFinishuint256
Extended emission end timestamp.
UnallocatedRewardsRecovered
UnallocatedRewardsRecovered(address indexed to, uint256 amount)The owner withdrew uncommitted budget.
- toindexedaddress
Recipient of the recovered tokens.
- amountuint256
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.
rewardPerToken() = rewardPerTokenStored + (elapsed × rewardRate × 1e18) / totalStakedelapsed = lastTimeRewardApplicable() − lastUpdateTime. Returns the stored value unchanged while totalStaked is zero.
earned(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.
periodFinish = rewardRate == 0 ? now : now + (rewardsAvailable / rewardRate)Integer division, so the window is truncated downward — never extended past what the budget covers.
APR = rewardRate × 31,536,000 / totalStakedUndefined while nothing is staked. Recomputed on every read, so it moves as stake enters and leaves.