Skip to content

Commit

Permalink
fan deposit and withdraw successfully tested on kovan. contract creat…
Browse files Browse the repository at this point in the history
…ion is inefficient
  • Loading branch information
nick committed Feb 6, 2021
1 parent 2158fb1 commit b0178aa
Show file tree
Hide file tree
Showing 8 changed files with 169 additions and 36 deletions.
59 changes: 41 additions & 18 deletions contracts/Pool.sol
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ contract Pool {
address public UNISWAP_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;

// kovan aave lending pool
address public LENDING_POOL = 0x9FE532197ad76c5a68961439604C037EB79681F0;
address public LENDING_POOL = 0xE0fBa4Fc209b4948668006B2bE61711b7f465bAe;

// store addres -> account mapping
mapping(address => uint256) balances;
Expand Down Expand Up @@ -146,19 +146,7 @@ contract Pool {

// setup token to be swapped
IERC20 token = IERC20(_token);
// console.log("");
// console.log("sender: ", msg.sender);

// approval is called outside of contract
// token.approve(address(msg.sender), _amountIn);

// console.log("contract: ", address(this));
// console.log("token balance before transfer:", token.balanceOf(msg.sender));

// console.log("amountIn: ", _amountIn);
// console.log("amountOutMin: ", _amountOutMin);

// require(_amountIn >= _amountOutMin, 'Unisw!apV2Router: INSUFFICIENT_OUTPUT_AMOUNT');

// transfer tokens to smart contract
// require(token.transferFrom(msg.sender, address(this), _amountIn), 'transferFrom failed.');
Expand All @@ -182,7 +170,7 @@ contract Pool {
// execute swap through uniswap and return ETH to user
uniswap.swapExactTokensForETH(
_amountIn,
_amountOutMin,
amountOutMin,
path,
_to,
block.timestamp
Expand Down Expand Up @@ -253,17 +241,52 @@ contract Pool {
// setup stablecoin
IERC20 stable = IERC20(DAI);

// setup aToken reference
IERC20 aToken = IERC20(aDAI);

//
uint aTokenAmount = aToken.balanceOf(address(this));

require(aToken.approve(LENDING_POOL, aTokenAmount), "aToken approval failed");

require(aToken.allowance(address(this), LENDING_POOL) > 0, "allowance too low");


// ensure balance is high enough
require(stable.balanceOf(address(this)) == 0, "There shouldn't be stablecoins");

// withdraw tokens from the lending pool
aave.withdraw(address(stable), amount, address(this));
// -1 for all
require(aave.withdraw(address(stable), aTokenAmount, address(this)) > 0, "withdraw failed");

// ensure balance is high enough
require(stable.balanceOf(address(this)) > 0, "There should be stablecoins");


// get amount of stablecoins to swapped with eth
uint amountStable = stable.balanceOf(address(this));

require(amountStable > 0, "no stablecoins!");

// swap tokens back to ETH and send to user
swapExactTokensForETH(address(stable), msg.sender, amount, 0);
swapExactTokensForETH(address(stable), msg.sender, amountStable, 0);

// ensure balance is high enough
require(stable.balanceOf(address(this)) == 0, "There shouldn't be stablecoins again");

// update mapping
balances[msg.sender] -= amount;
if (balances[msg.sender] - amountStable < 0) {
balances[msg.sender] = 0;
} else {
balances[msg.sender] -= amountStable;
}

// update pool balance
totalBalance -= amount;
if (totalBalance - amountStable < 0) {
totalBalance = 0;
} else {
totalBalance -= amountStable;
}

}

Expand Down
1 change: 1 addition & 0 deletions contracts/UniswapV2Interfaces.sol
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ interface IUniswapV2Factory {
interface IUniswap {

function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);

function swapExactTokensForTokens(
uint amountIn,
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/contracts/Pool.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions frontend/src/contracts/PoolFactory.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion frontend/src/contracts/contract-address.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"PoolFactory": "0x3FCD53ea0334f57a08F0f20a8Ae99e2F1E8D0974"
"PoolFactory": "0x3C3af302c49BAcf3F55f91f2437E12c3CC7dB4eC"
}
4 changes: 2 additions & 2 deletions frontend/src/pages/Creator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ function Creator(props: {poolFactory: ethers.Contract,
const gasPrice = await getGasPrice();

// deposit amount
await poolContract.deposit({value: value, gasLimit:8000000, gasPrice: gasPrice * 1e9});
await poolContract.deposit({value: value, gasLimit:900000, gasPrice: gasPrice * 1e9});

}

Expand All @@ -220,7 +220,7 @@ function Creator(props: {poolFactory: ethers.Contract,
const gasPrice = await getGasPrice();

// deposit amount
await poolContract.withdraw(userBalance, {gasLimit:8000000, gasPrice: gasPrice * 1e9});
await poolContract.withdraw(userBalance, {gasLimit:900000, gasPrice: gasPrice * 1e9});

}

Expand Down
21 changes: 20 additions & 1 deletion frontend/src/pages/NewCreator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import db from '../components/firestore';
import Loading from '../components/Loading';
import { useHistory } from "react-router-dom";
import { ethers } from 'ethers';
import axios from 'axios';

/**
* Form for creating new creator pages
Expand All @@ -17,16 +18,34 @@ function NewCreator(props: {poolFactory: ethers.Contract, connectedAddress: stri
const[links, setLinks] = useState<string[]>([]);
const history = useHistory();

// get latest gas prices
async function getGasPrice(speed?: string) {

// make request w/ axios
const price = await axios.get('https://ethgasstation.info/api/ethgasAPI.json?api-key=' + process.env.DEFI_PULSE_KEY)

if (speed === "fastest")
return(parseInt(price.data.fastest)/10);
else if (speed === "fast")
return(parseInt(price.data.fast)/10);
else
return(parseInt(price.data.average)/10);

}

// handle form submission
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {

// prevent refresh
e.preventDefault();


// get current gas prices
const gasPrice = await getGasPrice();

// create a new pool
try {
const tx = await props.poolFactory.newPool(props.connectedAddress);
const tx = await props.poolFactory.newPool(props.connectedAddress,{gasLimit:900000, gasPrice: gasPrice * 1e9});
await tx.wait();
} catch (err) {
console.log(err);
Expand Down
110 changes: 100 additions & 10 deletions test/Kovan.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ describe("Pools", function () {
// mined.
// poolFactoryContract = await poolFactory.deploy();
poolFactoryContract = new ethers.Contract(
"0xfd0b6580bFc9DD1d45E21aDab7c651449B82D54B",
"0x3C3af302c49BAcf3F55f91f2437E12c3CC7dB4eC",
poolFactory.interface,
owner.provider
);
Expand All @@ -140,12 +140,29 @@ describe("Pools", function () {

this.timeout(50000);

it("Should get my deposited balance", async function() {
it("Should create a new pool", async function () {

return;

pools = await poolFactoryContract.connect(owner).getPools();

let numPoolsBefore = pools.length;

await poolFactoryContract.connect(owner).newPool(owner.address);

pools = await poolFactoryContract.connect(owner).getPools();

let numPoolsAfter = pools.length;

let targetPool = pools[0];
expect(numPoolsAfter).to.be.gt(numPoolsBefore);

});

it("Should get my deposited balance", async function() {

return;

let targetPool = pools[pools.length - 1];

// get the last pool
const pool1 = new ethers.Contract(targetPool, pool.interface, owner);
Expand All @@ -159,22 +176,96 @@ describe("Pools", function () {
expect(userBalance).to.be.gt(0);


});

it("Should do a round trip", async function () {

///////// CREATE

pools = await poolFactoryContract.connect(owner).getPools();
console.log(pools);

let numPoolsBefore = pools.length;
console.log(pools.length);

await poolFactoryContract.connect(owner).newPool(owner.address);

pools = await poolFactoryContract.connect(owner).getPools();

let numPoolsAfter = pools.length;
console.log(pools.length);

expect(numPoolsAfter).to.be.gt(numPoolsBefore)

console.log("creation successful")

///////// DEPSOIT

// get pool
let targetPool = pools[pools.length - 1];
console.log(targetPool);

// get the last pool
let pool1 = new ethers.Contract(targetPool, pool.interface, owner);

let stake = 0.03;

// let bal = await pool1.connect(owner).getTotalBalance();
// console.log(bal.toString());

let value = ethers.utils.parseEther(stake.toString());

await pool1.connect(owner).deposit({value: value, gasLimit: 900000,gasPrice:1000000000});
// await pool1.connect(owner).withdraw({value: "5000000000000000000"});

let userBalance = await pool1.balanceOf(owner.address);
userBalance = parseFloat(userBalance.toString());

expect(userBalance).to.be.gt(0);

console.log("deposit successful")

///////// WITHDRAW

// targetPool = pools[pools.length - 1] ;

// get the last pool
// let pool1 = new ethers.Contract(targetPool, pool.interface, owner);

// get balance
userBalance = await pool1.balanceOf(owner.address);

// let bal = await pool1.connect(owner).getTotalBalance();
// console.log(bal.toString());

// withdraw balance
await pool1.withdraw(userBalance, {gasLimit:8000000, gasPrice:1000000000});

userBalance = await pool1.balanceOf(owner.address);

expect(userBalance).to.be.eq(0);

console.log("withdraw successful")


});

it("Should withdraw from Kovan pool", async function() {

let targetPool = pools[0];
return;


let targetPool = pools[pools.length - 1] ;

// get the last pool
const pool1 = new ethers.Contract(targetPool, pool.interface, owner);

// get balance
let userBalance = await pool1.balanceOf(owner.address);
let amount = "11802015251953149519669";

// let amount = "11802015251953149519669";

// withdraw balance
await pool1.withdraw(amount, {gasLimit:8000000, gasPrice:1000000000});
await pool1.withdraw(userBalance, {gasLimit:8000000, gasPrice:1000000000});

userBalance = await pool1.balanceOf(owner.address);

Expand All @@ -187,9 +278,8 @@ describe("Pools", function () {

return;


// get pool
let targetPool = pools[0];
let targetPool = pools[pools.length - 1];

// get the last pool
const pool1 = new ethers.Contract(targetPool, pool.interface, owner);
Expand All @@ -209,7 +299,7 @@ describe("Pools", function () {

let value = ethers.utils.parseEther(stake.toString());

await pool1.connect(owner).deposit({value: value, gasLimit:8000000, gasPrice:1000000000});
await pool1.connect(owner).deposit({value: value, gasLimit: 900000,gasPrice:1000000000});
// await pool1.connect(owner).withdraw({value: "5000000000000000000"});

let userBalance = await pool1.balanceOf(owner.address);
Expand Down

0 comments on commit b0178aa

Please sign in to comment.