Skip to content

Commit

Permalink
Add Liquidity UI + Backend Progress
Browse files Browse the repository at this point in the history
Add Liquidity UI + Backend Progress
  • Loading branch information
noahlitvin authored Aug 5, 2024
2 parents 7f224c0 + 5b861f7 commit 6d6bf9c
Show file tree
Hide file tree
Showing 92 changed files with 2,311 additions and 541 deletions.
10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
"main": "index.js",
"scripts": {
"test": "pnpm run test --recursive",
"dev:protocol": "pnpm --filter protocol run update-abis && pnpm --filter protocol run dev",
"dev:app": "pnpm --filter protocol run update-abis && pnpm --filter app run dev",
"dev:docs": "pnpm --filter protocol run update-abis && pnpm --filter docs run dev",
"dev:website": "pnpm --filter protocol run update-abis && pnpm --filter website run dev",
"dev:data": "pnpm --filter protocol run update-abis && concurrently \"pnpm --filter data run start:api\" \"pnpm --filter data run start:market\" \"pnpm --filter data run start:chain\""
"dev:protocol": "pnpm --filter protocol run dev",
"dev:app": "pnpm --filter app run dev",
"dev:docs": "pnpm --filter docs run dev",
"dev:website": "pnpm --filter website run dev",
"dev:data": "concurrently \"pnpm --filter data run dev:service\" \"pnpm --filter data run dev:worker\""
},
"keywords": [],
"author": "",
Expand Down
42 changes: 36 additions & 6 deletions packages/app/src/lib/components/foil/addLiquidity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
RangeSliderMark,
Flex,
} from '@chakra-ui/react';
import { TickMath } from '@uniswap/v3-sdk';
import { useContext, useEffect, useState } from 'react';
import { formatUnits, parseUnits } from 'viem';
import {
Expand Down Expand Up @@ -149,6 +150,35 @@ const AddLiquidity = () => {
}
}, [allowanceData, collateralAssetDecimals]);

const {
data: tokenAmounts,
error,
status,
} = useReadContract({
address: foilData.address,
abi: foilData.abi,
functionName: 'getTokenAmounts',
args: [
parseUnits(depositAmount.toString(), collateralAssetDecimals), // uint256 collateralAmount
pool ? pool.sqrtRatioX96.toString() : '0', // uint160 sqrtPriceX96, // current price of pool
TickMath.getSqrtRatioAtTick(tickLower).toString(), // uint160 sqrtPriceAX96, // lower tick price in sqrtRatio
TickMath.getSqrtRatioAtTick(tickUpper).toString(), // uint160 sqrtPriceBX96 // upper tick price in sqrtRatio
],
chainId: chain?.id,
});

useEffect(() => {
if (tokenAmounts) {
const [amount0, amount1] = tokenAmounts as any[]; // there's some abitype project, i think
setBaseToken(parseFloat(formatUnits(amount0, 18)));
setQuoteToken(parseFloat(formatUnits(amount1, 18)));
}

if (error) {
console.error('Failed to fetch token amounts', error);
}
}, [tokenAmounts, error]);

const handleFormSubmit = (e: any) => {
e.preventDefault();

Expand Down Expand Up @@ -182,11 +212,11 @@ const AddLiquidity = () => {

useEffect(() => {
console.log('Deposit amount changed:', depositAmount);
const newBaseToken = depositAmount * 0.001;
const newQuoteToken = depositAmount * 0.001;
console.log('Base Token:', newBaseToken, 'Quote Token:', newQuoteToken);
setBaseToken(newBaseToken);
setQuoteToken(newQuoteToken);
// The following lines have been removed as they are redundant:
// const newBaseToken = depositAmount * 0.001;
// const newQuoteToken = depositAmount * 0.001;
// setBaseToken(newBaseToken);
// setQuoteToken(newQuoteToken);
}, [depositAmount]);

useEffect(() => {
Expand Down Expand Up @@ -358,7 +388,7 @@ const AddLiquidity = () => {
{minAmountTokenB.toFixed(2)})
</Text>
<Text fontSize="sm" color="gray.500" mb="0.5">
Net Position: {highPrice.toFixed(2)} Ggas
Net Position: X Ggas
</Text>
{isConnected &&
walletBalance !== null &&
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/lib/components/foil/positionsHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const PositionsHeader = () => {
let relativeTime = '';
let formattedTime = '';
if (endTime) {
const dateMilliseconds = Number(endTime * 1000);
const dateMilliseconds = Number(endTime) * 1000;
const date = new Date(dateMilliseconds);
relativeTime = formatDistanceToNow(date);
formattedTime = format(date, 'PPpp');
Expand Down
53 changes: 25 additions & 28 deletions packages/app/src/lib/context/MarketProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type React from 'react';
import { createContext, useEffect, useState } from 'react';
import * as Chains from 'viem/chains';
import type { Chain } from 'viem/chains';
import { useContractReads, useReadContract } from 'wagmi';
import { useReadContracts, useReadContract } from 'wagmi';

import useFoilDeployment from '../components/foil/useFoilDeployment';
import erc20ABI from '../erc20abi.json';
Expand Down Expand Up @@ -56,9 +56,7 @@ export const MarketContext = createContext<MarketContextType>({
export const useUniswapPool = (chainId: number, poolAddress: `0x${string}`) => {
const [pool, setPool] = useState<Pool | null>(null);

// TODO: Should this refetch on chainId change? Every X seconds?
// Remember token a and token b can switch btwn base and quote
const { data, isError, isLoading, error } = useContractReads({
const { data, isError, isLoading } = useReadContracts({
contracts: [
{
address: poolAddress,
Expand Down Expand Up @@ -94,48 +92,46 @@ export const useUniswapPool = (chainId: number, poolAddress: `0x${string}`) => {
});

useEffect(() => {
/*
if (data && data[0] && data[1] && data[2] && data[3] && data[4]) {
const token0Address = (data as any)[0].result;
const token1Address = (data as any)[1].result;
const fee = (data as any)[2].result;
const liquidity = (data as any)[3].result;
const slot0 = (data as any)[4].result as any[];
if (data) {
const token0Address = data[0].result;
const token1Address = data[1].result;
const fee = data[2].result;
const liquidity = data[3].result;
const slot0 = data[4].result as any[];

if (token0Address && token1Address) {
const [sqrtPriceX96, tick] = slot0;

const token0 = new Token(
1,
token0Address.toString(),
chainId,
token0Address as string,
18,
'TOKEN0',
'Token 0'
);
const token1 = new Token(
1,
token1Address.toString(),
chainId,
token1Address as string,
18,
'TOKEN1',
'Token 1'
);

const sqrtRatioX96 = slot0[0].toString();
const tickCurrent = slot0[1].toString();
const poolInstance = new Pool(
token0,
token1,
fee as FeeAmount, // todo confirm this is right
sqrtRatioX96,
Number(liquidity),
tickCurrent
fee as FeeAmount,
sqrtPriceX96.toString(),
(liquidity as any).toString(),
tick
);

setPool(poolInstance);
}
}
*/
}, [data]);
}, [data, chainId]);

return { pool, isError, isLoading, error };
return { pool, isError, isLoading };
};

export const MarketProvider: React.FC<MarketProviderProps> = ({
Expand Down Expand Up @@ -241,14 +237,15 @@ export const MarketProvider: React.FC<MarketProviderProps> = ({
if (epochViewFunctionResult.data !== undefined) {
setState((currentState) => ({
...currentState,
// should add start/endtime here
poolAddress: epochViewFunctionResult?.data[0],
startTime: epochViewFunctionResult?.data[0],
endTime: epochViewFunctionResult?.data[1],
poolAddress: epochViewFunctionResult?.data[2],
}));
}
}, [epochViewFunctionResult.data]);

// Fetch pool data when poolAddress is updated
const { pool, isError, isLoading, error } = useUniswapPool(
const { pool, isError, isLoading } = useUniswapPool(
chainId,
state.poolAddress
);
Expand Down
4 changes: 2 additions & 2 deletions packages/app/src/lib/layout/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ const Header = () => {
<Image src="/logo.svg" alt="Foil" height="28px" />
</Box>
<Flex marginLeft="auto" gap={9} align="center" fontWeight="600">
<Link href="/subscribe">Subscribe</Link>
<Link href="/earn">Earn</Link>
{/* <Link href="/subscribe">Subscribe</Link> */}
{/* <Link href="/earn">Earn</Link> */}
<Link href={`/markets/13370:${FoilLocal.address}`}>Local Market</Link>
<Link href={`/markets/11155111:${FoilTestnet.address}`}>
Testnet Market
Expand Down
10 changes: 7 additions & 3 deletions packages/data/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
"description": "",
"main": "index.js",
"scripts": {
"start:api": "ts-node-dev src/index.ts --port 3001",
"start:market": "ts-node-dev src/market.ts",
"start:chain": "ts-node-dev src/chain.ts",
"build": "tsc",
"dev:service": "ts-node-dev src/service.ts --port 3001",
"dev:worker": "ts-node-dev src/worker.ts",
"start:service": "ts-node src/service.ts",
"start:worker": "ts-node src/worker.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
Expand All @@ -15,9 +17,11 @@
"dependencies": {
"cors": "^2.8.5",
"express": "^4.19.2",
"pg": "^8.12.0",
"reflect-metadata": "^0.2.2",
"sqlite3": "^5.1.7",
"ts-node-dev": "^2.0.0",
"tsconfig-paths": "^4.2.0",
"typeorm": "^0.3.20",
"typescript": "^5.5.2",
"viem": "~2.9.20"
Expand Down
47 changes: 0 additions & 47 deletions packages/data/src/chain.ts

This file was deleted.

27 changes: 27 additions & 0 deletions packages/data/src/db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { ConnectionOptions } from "typeorm";
import { Position } from "./entity/Position";
import { Price } from "./entity/Price";
import { Transaction } from "./entity/Transaction";
import { Event } from "./entity/Event";

const isProduction = process.env.NODE_ENV === 'production';

const sqliteOptions: ConnectionOptions = {
type: "sqlite",
database: "./data/database.sqlite",
synchronize: true,
logging: true,
entities: [Price, Position, Transaction, Event],
};

const postgresOptions: ConnectionOptions = {
type: "postgres",
url: process.env.DATABASE_URL,
synchronize: true,
logging: true,
entities: [Price, Position, Transaction, Event],
};

const connectionOptions = isProduction ? postgresOptions : sqliteOptions;

export default connectionOptions;
2 changes: 1 addition & 1 deletion packages/data/src/entity/Transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export class Transaction {
nftId: number; // foreign key to NFT

@Column({
type: 'enum',
type: 'simple-enum',
enum: TransactionType,
})
type: TransactionType;
Expand Down
56 changes: 0 additions & 56 deletions packages/data/src/market.ts

This file was deleted.

Loading

0 comments on commit 6d6bf9c

Please sign in to comment.