How to Create Staking CRC20 Token with Reward Features – Coinex Smart Chain


Staking crypto is a method of staking coins or tokens, with the aim of getting a reward or passive income, if in the real world it is “interest” from the money we save in the bank. But staking is different from bank interest, staking runs on the blockchain, permission is less and anyone can contribute to the staking platform.

Staking allows you to earn passive income in the form of tokens or stable coins, which you can withdraw at any time to a crypto wallet. Crypto staking usually provides large returns or interest, there is even staking that has interest above 100%, this is an attraction that makes users want to stake. The greater the interest, the greater the risk, and vice versa, we must be careful in choosing a staking platform so as not to suffer losses.

In this article we will provide education, how to staking crc20 tokens with the reward feature. Later you can use this staking dapps to develop the project to make it more developed.

The staking that we will make is: staking crc20 tokens to a smart contract, and the user will get a crc20 token reward (the amount of the prize corresponds to the reward value in the smart contract and the number of tokens at stake)

What is needed ?
#1 Wallet

Coinex smart chain is a blockchain that supports EVM, so you can use the same wallet as ethereum, only need to change the rpc network to the rpc coinex smart chain. I recommend that you use the EVM metamask wallet (browser version) because it is easier and faster to use.

RPC URL : https://rpc.coinex.net
Network Name : Coinex Smart Chain
ChainID : 52
Symbol : CET
Block Explorer : https://www.coinex.net

 

2# Coin Native CET (coinex smart chain)

CET is the native coin of the coinex smart chain blockchain, coin cet is used to pay for all transactions such as swap, send, deploy, etc. To get CET coins you can buy on Coinex Exchange, for now one CET coin is priced at $ 0.048 . If you have bought CET coin immediately send it to the wallet that will be used to deploy

 

3# CRC20 Smart Contract

This is the solidity smart contract code to create a crc-20 coinex smart chain token, I used the code from openzepplin. You can change the details “Token Name”, “Symbol”, “Amount of Supply”

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract MySakingToken1 is ERC20 {
    constructor() ERC20("MySakingToken1", "MTT1") {
        _mint(msg.sender, 1000000 * 10 ** decimals());
    }
}

 

4# StakingSmart Contract & Reward Features

This is a solidity code to create a staking function + reward feature in coinex smart chain, you can change some features such as contract name, reward amount when user staking

uint256 public constant REWARD_RATE = 10000000000000000;

Because tokens use decimal 18, then for 1 token value, you have to add 18 numbers 0. This token uses a reward system per second.

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.6;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

error Staking__TransferFailed();
error Withdraw__TransferFailed();
error Staking__NeedsMoreThanZero();

contract Staking is ReentrancyGuard {
    IERC20 public s_stakingToken;
    IERC20 public s_rewardToken;

    uint256 public constant REWARD_RATE = 10000000000000000;
    uint256 public s_totalSupply;
    uint256 public s_rewardPerTokenStored;
    uint256 public s_lastUpdateTime;

    /** @dev Mapping from address to the amount the user has staked */
    mapping(address => uint256) public s_balances;

    /** @dev Mapping from address to the amount the user has been rewarded */
    mapping(address => uint256) public s_userRewardPerTokenPaid;

    /** @dev Mapping from address to the rewards claimable for user */
    mapping(address => uint256) public s_rewards;

    modifier updateReward(address account) {
        s_rewardPerTokenStored = rewardPerToken();
        s_lastUpdateTime = block.timestamp;
        s_rewards[account] = earned(account);
        s_userRewardPerTokenPaid[account] = s_rewardPerTokenStored;

        _;
    }

    modifier moreThanZero(uint256 amount) {
        if (amount == 0) {
            revert Staking__NeedsMoreThanZero();
        }
        _;
    }

    constructor(address stakingToken, address rewardToken) {
        s_stakingToken = IERC20(stakingToken);
        s_rewardToken = IERC20(rewardToken);
    }

    function earned(address account) public view returns (uint256) {
        uint256 currentBalance = s_balances[account];
        // how much they were paid already
        uint256 amountPaid = s_userRewardPerTokenPaid[account];
        uint256 currentRewardPerToken = rewardPerToken();
        uint256 pastRewards = s_rewards[account];
        uint256 _earned = ((currentBalance * (currentRewardPerToken - amountPaid)) / 1e18) +
            pastRewards;

        return _earned;
    }

    /** @dev Basis of how long it's been during the most recent snapshot/block */
    function rewardPerToken() public view returns (uint256) {
        if (s_totalSupply == 0) {
            return s_rewardPerTokenStored;
        } else {
            return
                s_rewardPerTokenStored +
                (((block.timestamp - s_lastUpdateTime) * REWARD_RATE * 1e18) / s_totalSupply);
        }
    }

    function stake(uint256 amount) external updateReward(msg.sender) moreThanZero(amount) {
        s_balances[msg.sender] += amount;
        s_totalSupply += amount;
        //emit event
        bool success = s_stakingToken.transferFrom(msg.sender, address(this), amount);
        // require(success, "Failed"); Save gas fees here
        if (!success) {
            revert Staking__TransferFailed();
        }
    }

    function withdraw(uint256 amount) external updateReward(msg.sender) moreThanZero(amount) {
        s_balances[msg.sender] -= amount;
        s_totalSupply -= amount;
        // emit event
        bool success = s_stakingToken.transfer(msg.sender, amount);
        if (!success) {
            revert Withdraw__TransferFailed();
        }
    }

    function claimReward() external updateReward(msg.sender) {
        uint256 reward = s_rewards[msg.sender];
        bool success = s_rewardToken.transfer(msg.sender, reward);
        if (!success) {
            revert Staking__TransferFailed();
        }

    }

    // Getter for UI
    function getStaked(address account) public view returns (uint256) {
        return s_balances[account];
    }
}

 

How to Staking Token CRC20 With Reward Features
1# Deploy Smart Contract CRC20

To create a crc20 token, you have to deploy the solidity smart contract code to the coinex smart chain blockchain, to deploy you can use “remix idea”

  • Open remix ide
  • Create a new file
  • Paste the code for the smart contract token crc20
  • Edit : token name, symbol, total supply
  • Select “Solidity Compiler” Compile the smart contract code with the appropriate compiler version

  • Select “Deploy & Run Transaction”, in the Environment section select the wallet you will use
  • Deploy

2# Deploy Smart Contract Staking
  • Open remix & Create new file
  • Paste the smart contract staking code
  • Edit : contract name, number of reward tokens per second : example= uint256 public constant REWARD_RATE = 10000000000000000;
  • Select “Solidity Compiler” Compile the smart contract code
  • Select “Deploy & Run Transaction”, in the Environment section select the wallet you will use
  • Before deploying you must enter the crc20 token smart contract
  • StakingToken = is the token that is staked in the smart contract
  • RewardToken = is token reward, which is given to staker, you can use the same token as token staking or use a different token
  • Deploy

 

3# Smart Contract Verification

In order for users to interact with smart contracts via explorer & open code, you must verify the smart contract. Once verified, anyone can see the code from the crc20 smart contract or staking.

  • In remixIDE select “Plugins”, search flattener, and install the plugin
  • In the flattener menu, flat file solidity
  • Save the file, and copy it to the explorer verification form

  • Enter the coinex smart chain explorer, enter the smart contract
  • Select “Contract Info”
  • Select “Verify and Publish”
  • Fill in all the required forms, must match the compiler in the remix

 

4# Approve Address

In order to be able to do staking, we need to approve the wallet address and smart contract staking to the crc20 smart contract, if this is not done, it will appear failed when staking.

  • Go to explorer coinex smart chain
  • Sign in to the crc20 smart contract
  • Connect your wallet
  • Select “Contract Info”, Select “Write Contract”
  • Select “Approve”
  • spender(address) = enter your wallet address / smart contract staking
  • amount(uint256) = input the number of tokens, don’t forget to add 18 numbers 0
  • Click “Write”

 

5# Send Token to Address (Smart Contract Staking)

You need to send a token to the smart contract staking address, this token will later be allocated for staker rewards.

 

5# Test Staking

Because this is just a smart contract and doesn’t have a website yet, to stake you have to interact with the smart contract in the Coinex Smart Chain explorer.

  • Go to explorer coinex smart chain, enter smart contract staking, or you can interact on RemixIDE
  • Connect your wallet, and select “write contract”

How to Staking

  • Select “Stake”, enter the number of tokens you want to stake (don’t forget to add 18 digits 0), Click write/transact.
  • Tokens in your wallet will be automatically deducted (enter the smart contract staking)

How to Claim Reward

  • Select “Claim Rewards”
  • Click write/transact . after the transaction is complete you will receive a token reward

How to UnStake

  • Select “Withdraw”
  • Enter the number of tokens you want to Unstake, Click Write/Transact
  • After the transaction is complete, the token you stake will be returned to the wallet

 

Kesimpulan

You can use this smart contract for your crypto project, so that your project is more preferred. With the staking system, users will be more interested in buying and holding tokens, this will increase the token price. If you are proficient in making Reactjs web, you can incorporate the smart contract into the website, so that users can interact using the website. This is education, if there are mistakes, please correct and criticize, thank you


Alif Fahmi

hi , I'm Alif, I'm a blockchain & cryptocurrency lover, I love writing & learning, my job is web developer & crypto trader