Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementa Staking Rewards #2

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions contracts/Exchange.sol
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "hardhat/console.sol";


interface IRegistry {
function getExchange(address _tokenAddress) external returns (address);
Expand Down
125 changes: 125 additions & 0 deletions contracts/StakingRewards.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "hardhat/console.sol";

contract StakingRewards {
IERC20 public rewardsToken;
IERC20 public stakingToken;

uint public rewardRate = 100;
uint public lastUpdateTime;
uint public rewardPerTokenStored;

mapping(address => uint) public userRewardPerTokenPaid;
mapping(address => uint) public rewards;

uint private _totalSupply;
mapping(address => uint) private _balances;

/* ========== CONSTRUCTOR ========== */
constructor(address _stakingToken, address _rewardsToken) {
stakingToken = IERC20(_stakingToken);
rewardsToken = IERC20(_rewardsToken);
}

/* ========== VIEWS ========== */
function totalSupply() external view returns (uint256) {
return _totalSupply;
}

function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}

function rewardPerToken() public view returns (uint) {
//console.log("RewardsPerToken total supply: %s rewardPerTokenStored %s",_totalSupply,rewardPerTokenStored);
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored +
(((block.timestamp - lastUpdateTime) * rewardRate * 1e18) / _totalSupply);
}

function earned(address account) public view returns (uint) {
return
((_balances[account] *
(rewardPerToken() - userRewardPerTokenPaid[account])) / 1e18) +
rewards[account];
}

/* ========== MUTATIVE FUNCTIONS ========== */

function stake(uint _amount) external updateReward(msg.sender) {
require(_amount > 0, "Cannot stake 0");
_totalSupply += _amount;
_balances[msg.sender] += _amount;
stakingToken.transferFrom(msg.sender, address(this), _amount);

//console.log("Stake %s tokens", _amount);
}

function withdraw(uint _amount) public updateReward(msg.sender) {
require(_amount > 0, "Cannot withdraw 0");
_totalSupply -= _amount;
_balances[msg.sender] -= _amount;
stakingToken.transfer(msg.sender, _amount);

//console.log("withdraw %s tokens \ntotal supply %s", _amount,_totalSupply);

}

function getReward() public updateReward(msg.sender) {
//console.log("Rewards on get", rewards[msg.sender],rewardPerTokenStored);
uint reward = rewards[msg.sender];
if (reward > 0) {
rewards[msg.sender] = 0;
rewardsToken.transferFrom(address(this), msg.sender, reward);
}

}

function exit() external {
withdraw(_balances[msg.sender]);
getReward();
}

/// @notice add the tokens to be distributed as rewards
/// @param _amount token amount (token address is the one on constructor)
function depositRewardsTokens(uint256 _amount) external {
rewardsToken.transferFrom(msg.sender, address(this), _amount);
rewardsToken.approve(address(this), _amount);
}

/* ========== MODIFIERS ========== */
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = block.timestamp;

rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
_;
}

}

interface IERC20 {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mejor utilizar la de OpenZepelling acá.

function totalSupply() external view returns (uint);

function balanceOf(address account) external view returns (uint);

function transfer(address recipient, uint amount) external returns (bool);

function allowance(address owner, address spender) external view returns (uint);

function approve(address spender, uint amount) external returns (bool);

function transferFrom(
address sender,
address recipient,
uint amount
) external returns (bool);

event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
10 changes: 7 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

67 changes: 66 additions & 1 deletion test/exchange-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@ const { provider } = waffle;
const totalSupply = ethers.utils.parseEther("10000");
const amountA = ethers.utils.parseEther("2000");
const amountB = ethers.utils.parseEther("1000");

let token;
let exchange;
let rewardsToken;
let rewards;

let deployer, bob, alice;

let tx;

let deployer, bob, alice;

describe("Exchange", function () {
beforeEach(async function () {
Expand All @@ -21,6 +25,20 @@ describe("Exchange", function () {

const Exchange = await ethers.getContractFactory("Exchange");
exchange = await Exchange.deploy(token.address)

// Deploy otro ERC-20 para dar rewards
rewardsToken = await Token.deploy("FreeMoney", "F$$", totalSupply);
await rewardsToken.deployed();

// Deploy el contrato de rewards
const Rewards = await ethers.getContractFactory("StakingRewards");
rewards = await Rewards.deploy(exchange.address, rewardsToken.address)

// Manda todos los rewardsToken al contrato de rewards
const deployerRewardsTokens = await rewardsToken.balanceOf(deployer.address)
await rewardsToken.approve(rewards.address, deployerRewardsTokens)
await rewards.depositRewardsTokens(deployerRewardsTokens)

});

it("add liquidity", async function () {
Expand All @@ -29,10 +47,55 @@ describe("Exchange", function () {
await expect(tx).to.emit(exchange, "AddLiquidity")
.withArgs(deployer.address, amountB, amountA);

expect(await exchange.balanceOf(deployer.address)).to.equal(ethers.utils.parseUnits("1000"));
expect(await provider.getBalance(exchange.address)).to.equal(amountB);
expect(await exchange.getReserve()).to.equal(amountA);
});

it("Verificar StakingRewards.sol (rewards) fue deployed correctamente", async function () {

expect(await rewards.stakingToken()).to.equal(exchange.address);
expect(await rewards.rewardsToken()).to.equal(rewardsToken.address);
expect(await rewardsToken.balanceOf(deployer.address)).to.equal(0);
expect(await rewardsToken.balanceOf(rewards.address)).to.equal(ethers.utils.parseUnits("10000"));

});

it("Stake exchange tokens (LP) y recibir rewards", async () => {
await token.approve(exchange.address, amountA);
await exchange.addLiquidity(amountA, { value: amountB });

let tokens_to_be_staked = await exchange.balanceOf(deployer.address)
await exchange.approve(rewards.address, tokens_to_be_staked);
await rewards.stake(tokens_to_be_staked)

expect(await exchange.balanceOf(rewards.address)).to.equal(tokens_to_be_staked);
expect(parseInt(await rewards.rewardPerToken())).to.equal(0);

// simular 20 bloques
let numberOfBlocks = 20
for (let i = 0; i < numberOfBlocks; i++) {
await ethers.provider.send("evm_increaseTime", [60]); // 60 segunods
await ethers.provider.send("evm_mine", []); // add 60 secs
}

// ver staking rewards
console.log(` STAKING REWARDS (${numberOfBlocks} bloques):\n > rewardsPerToken: ${parseInt(await rewards.rewardPerToken())}\n > earned: ${parseInt(await rewards.earned(deployer.address))}`)


expect(parseInt(await rewards.rewardPerToken())).to.equal(120);
expect(parseInt(await rewards.earned(deployer.address))).equal(120000);

await rewards.withdraw(tokens_to_be_staked)
expect(await exchange.balanceOf(rewards.address)).to.equal(0);

await rewards.getReward()
expect(await rewardsToken.balanceOf(deployer.address)).to.equal(120000);

// by Kayaba_Attribution

Kayaba-Attribution marked this conversation as resolved.
Show resolved Hide resolved
});

it("returns correct token price", async () => {
// await token.approve(exchange.address, amountA);
// await exchange.addLiquidity(amountA, { value: amountB });
Expand Down Expand Up @@ -87,6 +150,7 @@ describe("Exchange", function () {

bar = await exchange.getEthAmount(ethers.utils.parseEther("2000"));
expect(ethers.utils.formatEther(bar)).to.eq("497.487437185929648241");

});

it("swap eth into token", async () => {
Expand All @@ -109,5 +173,6 @@ describe("Exchange", function () {
await expect(tx).to.emit(exchange, "TokenPurchase");
// // revisar estos valores
// expect(await token.balanceOf(alice.address)).to.eq(expectedOutputForAlice);

});
});