How to Build a Staking and Unstaking Smart Contract
A staking smart contract locks tokens, tracks rewards and lets users unstake safely. Learn the functions, the reward math and the security checks it needs.
On this page
Short answer
A staking and unstaking smart contract is a program that holds user tokens, records each staker's share, accrues rewards over time and releases tokens when a user unstakes. It needs stake, unstake, claim and emergency functions, plus checks against reentrancy, reward manipulation and owner abuse.
What is a staking and unstaking smart contract?
A staking and unstaking smart contract is a program that accepts tokens from users, locks them for a set period, tracks who staked how much and for how long, and returns the tokens plus rewards when a user unstakes. It is the core of most DeFi staking platforms, and it runs without a central operator once deployed.
The contract holds three kinds of state: each user's staked balance, the total amount staked, and the reward rate per token. Every stake, unstake or claim updates those numbers. If the numbers are wrong, users are paid too much or too little, so the accounting is the part that matters most.
Staking contracts differ from staking platforms. A platform adds a website, wallets, dashboards and support around the contract. The contract itself is only the on-chain rules: who can stake, how rewards accrue, when tokens can leave, and what happens in an emergency.
How do staking rewards work?
Staking rewards pay users for locking tokens and taking the risk that the price falls while they cannot sell. The contract usually tracks a single number, reward per token, which grows over time at a fixed rate while tokens are staked.
When a user stakes, the contract records the current reward per token. When the user claims or unstakes, it pays the difference between the current value and the recorded value, multiplied by the user's staked balance. This pattern means the contract never loops over users, which keeps gas costs flat no matter how many people stake.
| Reward model | How it pays | Main risk |
|---|---|---|
| Fixed rate | Set tokens per second | Rewards run out |
| Share of fees | Share of protocol income | Income varies |
| Inflation | New tokens minted | Token price dilutes |
| Boosted lock | More for longer locks | Users cannot exit fast |
Rewards must come from somewhere: a fixed reward pool, protocol fees or new token issuance. A contract that promises rewards with no funded source will run dry, and users who staked late will be paid last or not at all.
What functions does the contract need?
A staking contract needs a small set of functions, each with a clear job. Extra functions add attack surface, so keep the list short.
| Function | What it does |
|---|---|
| stake | Takes tokens and records the user's share |
| unstake | Starts or completes the withdrawal |
| claim | Pays out accrued rewards |
| exit | Claims rewards and unstakes in one call |
| pause | Stops deposits in an emergency |
| setRewardRate | Changes the reward rate, owner only |
The stake function should check that the amount is above zero, pull the tokens from the user, update the reward accounting first and then record the new balance. Updating rewards before changing the balance is the key ordering rule: if the balance changes first, the user earns rewards on tokens they only just deposited.
The unstake function should either return tokens at once or start a waiting period. A waiting period, often called an unbonding period, protects the protocol from sudden mass withdrawals. Whatever you choose, the rule must be visible in the interface before a user stakes.
How do lock periods and unstaking delays work?
A lock period is the minimum time a stake must stay in the contract before it can be withdrawn. An unstaking delay is the waiting time after a user asks to unstake before the tokens are released. The two are different, and a contract can use either or both.
Lock periods suit protocols that need stable deposits, such as a new chain that needs validators to stay online. The trade-off is that users cannot react to price falls, so lock periods should be short at first and lengthen only when users trust the system.
Unstaking delays suit protocols that need time to unwind positions or process withdrawals in order. A delay of a few days is common. Longer delays need a clear reason, because users compare your delay with other staking options before they deposit. Show the remaining wait time in the interface, and never change the delay for stakes that are already locked.
How to build the contract in 6 steps
Build the contract in order, testing each step on a testnet before moving on. A staking contract handles real money, so each step needs its own test.
- Define the rules first. Write down the reward source, the rate, the lock period, the unstaking delay and the emergency rules before writing any code.
- Write the accounting. Build the reward-per-token tracking, the per-user balances and the total staked amount, with tests that check rewards after many small deposits.
- Add stake and unstake. Implement deposits and withdrawals, with the reward update happening before any balance change.
- Add claim and exit. Let users take rewards without unstaking, and combine claim plus unstake into one exit call.
- Add owner controls. Add pause, reward-rate changes and emergency withdrawal, each behind access control and a timelock where possible.
- Test, audit, then deploy small. Run unit tests, invariant tests and a testnet trial, get an external audit, fix the findings and launch with a reward cap.
What security checks does the contract need?
Staking contracts are a frequent target because they hold large token balances and pay out on a schedule. The checks below are the minimum before any real funds are accepted.
- Reentrancy guards. Every function that sends tokens out must update balances before the transfer, or use a reentrancy guard. An attacker who re-enters during a payout can drain the pool.
- Reward manipulation. Test what happens when one user stakes a huge amount for one block, or when the reward rate changes mid-period. Rewards must accrue fairly.
- Access control. Only the owner should change the reward rate or pause the contract, and ownership should sit behind a multi-signature wallet or timelock, not a single key.
- Token handling. Some tokens charge fees on transfer or return false instead of reverting. Use safe transfer helpers and test with the exact token you will accept.
- External audit. Get an independent audit and publish the report. Fix every high-severity finding before launch, and re-audit after any change to the reward logic.
Example (hypothetical): a small staking pool
Example (hypothetical): a team launches a staking contract for its own token with a reward pool of 100,000 tokens and a rate of 1 token per second. The pool runs for about 28 hours at that rate, so the team tops it up weekly.
Four users stake 10,000 tokens each, so the total staked is 40,000. After one day, 86,400 reward tokens have accrued, which is 2.16 tokens per staked token. Each user who claims receives 21,600 tokens, because 10,000 times 2.16 equals 21,600.
One user unstakes after a 3-day delay and receives the original 10,000 tokens plus the rewards earned up to the claim. The team notices the reward pool is draining faster than expected, so it lowers the rate to 0.5 tokens per second through the timelock and tells users a day before the change takes effect.
What are the common mistakes?
The most common staking contract mistakes are wrong reward accounting, missing reentrancy protection, unfunded reward promises and owner keys with too much power.
- Updating balances before rewards. If the balance changes first, users earn rewards on tokens they just deposited. Update rewards first, always.
- No reentrancy guard. Any function that sends tokens out is a drain risk without one.
- Promising rewards with no source. Rewards need a funded pool, fee income or a clear minting rule. An empty pool pays nobody.
- Changing rules mid-stake. Raising the lock period or cutting the rate for existing stakes breaks trust. Apply changes only to new stakes.
- One owner key. A single key that can change the rate, pause the contract and withdraw funds is a single point of failure. Use a multi-signature wallet.
Key takeaways
- A staking contract holds tokens, tracks each user's share and pays rewards over time
- Reward per token is the standard accounting pattern because it keeps gas costs flat
- Update rewards before changing any balance, or users earn on tokens they just deposited
- Lock periods and unstaking delays are different tools with different trade-offs
- Reentrancy guards, access control and an external audit are the minimum before launch
Frequently asked questions
What is the difference between staking and unstaking?
Staking locks tokens in a contract to earn rewards, while unstaking releases them. Unstaking often involves a waiting period, called an unbonding period, before the tokens return to the user's wallet.
How are staking rewards calculated?
Most contracts track reward per token, a number that grows over time at the reward rate. A user's payout is the difference between the current value and the value when they last updated, multiplied by their staked balance.
Can users unstake at any time?
It depends on the contract. Some allow instant unstaking, while others enforce a lock period or a waiting delay. The rules must be shown before a user stakes, and they should not change for stakes that are already locked.
What is a reentrancy attack on a staking contract?
It is an attack where a malicious contract calls back into the staking contract during a payout, before balances are updated, and withdraws funds repeatedly. Updating balances before sending tokens, or using a reentrancy guard, stops it.
Do staking contracts need an audit?
Yes. A staking contract holds user funds and pays out on a schedule, so an independent audit is the minimum before launch. Fix every high-severity finding first, and re-audit after any change to the reward logic.
Where do staking rewards come from?
Rewards come from a funded pool, a share of protocol fees or new token issuance. A contract that promises rewards with no funded source will run dry, and users who stake late may be paid last or not at all.