Sample staking contract

prem yekkali

1) Staking Contract - Fully functional and secure.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IERC20 {
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
}

contract Staking {
// Token used for staking
IERC20 public stakingToken;

// Token used for rewards
IERC20 public rewardToken;

// Mapping of user addresses to their stakes
mapping(address => uint256) public stakes;

// Mapping of user addresses to their accumulated reward points
mapping(address => uint256) public rewardPoints;

// Mapping of user addresses to the last time they staked
mapping(address => uint256) public lastStakeTime;

// Reward rate per second (adjustable)
uint256 public rewardRate = 100; // reward rate per second

// Total amount of tokens staked in the contract
uint256 public totalStaked;

// Events to log staking actions
event Staked(address indexed user, uint256 amount);
event Unstaked(address indexed user, uint256 amount);
event RewardsClaimed(address indexed user, uint256 reward);

// Constructor to set the staking and reward tokens
constructor(IERC20 _stakingToken, IERC20 _rewardToken) {
stakingToken = _stakingToken;
rewardToken = _rewardToken;
}

// Function to stake tokens
function stake(uint256 amount) external {
require(amount > 0, "Amount must be greater than zero");

// Update rewards for previous stake before new staking
_updateRewards(msg.sender);

// Transfer tokens from the user to the contract
stakingToken.transferFrom(msg.sender, address(this), amount);

// Increase user's stake and total staked amount
stakes[msg.sender] += amount;
totalStaked += amount;

// Record the current time as the last stake time
lastStakeTime[msg.sender] = block.timestamp;

emit Staked(msg.sender, amount);
}

// Function to unstake tokens
function unstake(uint256 amount) external {
require(amount > 0 && amount <= stakes[msg.sender], "Invalid amount");

// Update rewards before unstaking
_updateRewards(msg.sender);

// Decrease user's stake and total staked amount
stakes[msg.sender] -= amount;
totalStaked -= amount;

// Transfer tokens back to the user
stakingToken.transfer(msg.sender, amount);

emit Unstaked(msg.sender, amount);
}

// Function to claim rewards
function claimRewards() external {
_updateRewards(msg.sender);
uint256 reward = rewardPoints[msg.sender];
require(reward > 0, "No rewards available");

// Reset reward points after claiming
rewardPoints[msg.sender] = 0;

// Transfer reward tokens to the user
rewardToken.transfer(msg.sender, reward);
emit RewardsClaimed(msg.sender, reward);
}

// Internal function to update rewards for a user
function _updateRewards(address user) internal {
// Calculate the time the user has staked
uint256 stakedTime = block.timestamp - lastStakeTime[user];

// Calculate rewards based on the staked amount and time
uint256 rewards = stakedTime * rewardRate * stakes[user] / 1e18;

// Add calculated rewards to user's reward points
rewardPoints[user] += rewards;

// Update the last stake time to the current time
lastStakeTime[user] = block.timestamp;
}

// Function to get the total rewards for a user
function getRewards(address user) external view returns (uint256) {
uint256 stakedTime = block.timestamp - lastStakeTime[user];
uint256 rewards = stakedTime * rewardRate * stakes[user] / 1e18;
return rewardPoints[user] + rewards;
}
}

2) Documentation for Staking Contract

Overview
The Staking Contract allows users to stake a specified ERC20 token (staking token) and earn rewards in a different ERC20 token (reward token). This contract is designed for secure and efficient staking operations, ideal for DeFi projects.

Technical Documentation

Contract Structure
Staking Token: The token users stake to earn rewards (ERC20 compliant).
Reward Token: The token users receive as rewards (ERC20 compliant).
Key Components
Interfaces:
IERC20: Interactions for token transfers and balance checks.
State Variables:
stakingToken: Reference to the staking token contract.
rewardToken: Reference to the reward token contract.
stakes: Mapping of user addresses to their staked amounts.
rewardPoints: Mapping of user addresses to accumulated rewards.
lastStakeTime: Tracks the last time a user staked tokens.
rewardRate: Rate at which rewards are calculated (adjustable).
totalStaked: Total amount of tokens currently staked.
Events:
Staked: Emitted when tokens are staked.
Unstaked: Emitted when tokens are unstaked.
RewardsClaimed: Emitted when rewards are claimed.
Key Functions
Constructor: Initializes the staking and reward tokens.
Stake Function:
Allows users to stake a specified amount of tokens.
Parameters: amount (the number of tokens to stake).
Unstake Function:
Allows users to withdraw their staked tokens.
Parameters: amount (the number of tokens to withdraw).
Claim Rewards Function:
Allows users to claim their accumulated rewards.
Get Rewards Function:
Returns the total rewards available for a specified user.
Parameters: user (the address of the user).
Internal Function to Update Rewards:
Calculates and updates the rewards for a user based on the staking duration and amount.

User Guide

Staking Process
Prerequisites:
Ensure you have the required staking tokens in your wallet.
Approve the staking contract to spend your tokens.
Staking Tokens:
Call the stake function with the desired amount.
Unstaking Tokens:
Call the unstake function with the amount you wish to withdraw.
Claiming Rewards:
Call the claimRewards function to receive your rewards.
Checking Rewards:
Use the getRewards function by providing your address.

3) Deployment Instructions - Steps for deploying on the blockchain.

Set Up Environment:
Install Node.js and npm.
Install Truffle or Hardhat.
Create Project Directory:
Use mkdir StakingContract and cd into it.
Install Dependencies:
For Truffle: npm install -g truffle.
For Hardhat: npm install --save-dev hardhat.
Create Contract File:
In the contracts directory, create Staking.sol.
Configure Deployment Script:
Create a migration file in the migrations directory.
Compile the Contract:
Run truffle compile.
Deploy to Local Network:
Start Ganache and run truffle migrate --network development.
Deploy to Testnet/Mainnet:
Configure truffle-config.js for deployment to a testnet or mainnet.
Run Deployment Command:
Use truffle migrate --network <network_name>.
Verify Deployment:
Check deployment status on Etherscan.
Like this project

Posted Oct 25, 2024

The Staking Contract enables users to stake a specified ERC20 token and earn rewards in a different ERC20 token. Designed for security and efficiency, it featur

Demo Decentralized Exchange (DEX) Implementation
Demo Decentralized Exchange (DEX) Implementation
Sample Audit service
Sample Audit service

Join 50k+ companies and 1M+ independents

Contra Logo

© 2025 Contra.Work Inc