Defi代幣質押持幣生息系統技術開發(原始碼部署搭建)

灰飛機JT9119發表於2023-05-05

隨著Defi生態的不斷髮展,越來越多的專案開始推出質押持幣生息的產品。這種產品通常是將代幣質押到智慧合約中,然後

持有一定時間後就可以獲得一定的收益,從而實現資產的增值。


使用者可以將代幣質押到合約中。 使用者可以隨時撤回其質押的代幣。 使用者可以查詢其當前質押的代幣數量以及可以獲得的收益。 使用者可以領取其當前的收益。為了實現這些功能,我們需要維護每個使用者的質押金額和質押時間,並在使用者領取收益時計算應得的收益。


下面是我們的Solidity程式碼:

typescriptCopy codepragma solidity ^0.8.0;import "@openzeppelin/contracts/token/ERC20/IERC20.sol";import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract StakingContract {
    using SafeMath for uint256;    
    IERC20 public token;  
      mapping(address => uint256) public balances;  
        mapping(address => uint256) public timestamps; 
           mapping(address => uint256) public earnings;    
    constructor(IERC20 _token) {
        token = _token;
    }    
    function stake(uint256 amount) public {   
         require(amount > 0, "Amount must be greater than 0");    
             require(token.transferFrom(msg.sender, address(this), amount), "Transfer failed");    
                 if (balances[msg.sender] == 0) {
            timestamps[msg.sender] = block.timestamp;
        }
        balances[msg.sender] = balances[msg.sender].add(amount);
    }    
    function withdraw() public {
        uint256 amount = balances[msg.sender];  
              require(amount > 0, "No balance to withdraw");    
                  require(token.transfer(msg.sender, amount), "Transfer failed");
        uint256 time = block.timestamp.sub(timestamps[msg.sender]);
        uint256 dailyRate = 100; // 1% per day
        uint256 interest = amount.mul(dailyRate).mul(time).div(86400 * 100);
        earnings[msg.sender] = earnings[msg.sender].add(interest);
        timestamps[msg.sender] = block.timestamp;
        balances[msg.sender] = 0;
    }    
    function claimEarnings() public {
        uint256 amount = earnings[msg.sender];  
              require(amount > 0, "No earnings to claim");    
                  require(token.transfer(msg.sender, amount), "Transfer failed");
        earnings[msg.sender] = 0;
    }
}


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/70028070/viewspace-2950069/,如需轉載,請註明出處,否則將追究法律責任。

相關文章