Skip to content

Commit

Permalink
merge main
Browse files Browse the repository at this point in the history
  • Loading branch information
jnastaskin committed Aug 15, 2024
2 parents a4a4a8b + 5a8bda1 commit 3ab1e5e
Show file tree
Hide file tree
Showing 20 changed files with 806 additions and 371 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@
In `/packages/protcol`:
* Increment the version number in the cannonfiles
* Run `pnpm simulate-deploy:sepolia` to verify there are no issues
* Run `CANNON_PRIVATE_KEY=x CANNON_PROVIDER_URL=y pnpm deploy sepolia` (or set those values in a `.env` file)
* Run `CANNON_PRIVATE_KEY=x CANNON_PROVIDER_URL=y pnpm deploy:sepolia` (or set those values in a `.env` file)
111 changes: 77 additions & 34 deletions packages/app/src/lib/components/chart.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import type React from 'react';
import { useContext } from 'react';
import { useContext, useEffect, useRef, useState } from 'react';
import {
ResponsiveContainer,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ComposedChart,
Bar,
ReferenceLine,
Expand All @@ -16,38 +15,51 @@ import { colors } from '~/lib/styles/theme/colors';

const CustomBarShape = ({
x,
y,
width,
payload,
yAxis,
yAxisDomain,
chartHeight,
gridOffsetFromParent,
}: {
x: any;
y: any;
width: any;
x: number;
width: number;
payload: any;
yAxis: any;
yAxisDomain: any;
chartHeight: number;
gridOffsetFromParent: number;
}) => {
const candleColor =
colors.green &&
colors.red &&
(payload.open < payload.close ? colors.green[400] : colors.red[500]);
const barHeight = Math.abs(yAxis(payload.open) - yAxis(payload.close));
const wickHeight = Math.abs(yAxis(payload.low) - yAxis(payload.high));
const wickY = Math.min(yAxis(payload.low), yAxis(payload.high));
const barY = Math.min(yAxis(payload.open), yAxis(payload.close));
payload.open < payload.close
? colors.green?.[400] ?? '#00FF00'
: colors.red?.[500] ?? '#FF0000';

const scaleY = (value: number) => {
const scaled = (value - yAxisDomain[0]) / (yAxisDomain[1] - yAxisDomain[0]);
return chartHeight - scaled * chartHeight + gridOffsetFromParent;
};

const lowY = scaleY(payload.low);
const highY = scaleY(payload.high);
const openY = scaleY(payload.open);
const closeY = scaleY(payload.close);

const barHeight = Math.abs(openY - closeY);
const wickHeight = Math.abs(lowY - highY);

return (
<>
{/* Wick */}
<rect
x={x + width / 2 - 0.5}
y={wickY}
y={highY}
width={1}
height={wickHeight}
fill={candleColor}
/>
{/* Body */}
<rect
x={x}
y={barY}
y={Math.min(openY, closeY)}
width={width}
height={barHeight}
fill={candleColor}
Expand All @@ -57,33 +69,64 @@ const CustomBarShape = ({
};

const CandlestickChart: React.FC = () => {
const grayColor = colors.gray?.[800] ?? '#808080';

const { averagePrice, prices } = useContext(MarketContext);
console.log('prices:', prices);

const yAxisDomain = [
Math.min(...prices.map((p) => p.low)),
Math.max(...prices.map((p) => p.high)),
];

const chartRef = useRef(null);
const [gridHeight, setGridHeight] = useState(0);
const [gridOffsetFromParent, setGridOffsetFromParent] = useState(0);

useEffect(() => {
if (chartRef.current) {
// Access the parent container and the CartesianGrid's bounding boxes
const parentElement = (chartRef.current as any).container;
const gridElement = parentElement.querySelector(
'.recharts-cartesian-grid'
);

if (gridElement && parentElement) {
const gridRect = gridElement.getBoundingClientRect();
const parentRect = parentElement.getBoundingClientRect();

// Calculate the height of the CartesianGrid
setGridHeight(gridRect.height);

// Calculate the offset from the top of the parent container
setGridOffsetFromParent(gridRect.top - parentRect.top);
}
}
}, [prices]);

return (
<ResponsiveContainer>
<ComposedChart data={prices}>
<ResponsiveContainer height="100%" width="100%">
<ComposedChart data={prices} ref={chartRef}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="date" />
<YAxis
domain={[0, Math.max(...prices.map((p) => p.high))]}
tickFormatter={(value) => (value / 10e8).toFixed(2)}
/>
<Tooltip formatter={(value) => ((value as number) / 10e8).toFixed(2)} />
<YAxis domain={yAxisDomain} />
<Bar
dataKey="high"
// eslint-disable-next-line react/no-unstable-nested-components
shape={(props: any) => (
<CustomBarShape
{...props}
yAxis={(d: any) => (d / 10e8) * (400 / 15)}
/>
)}
dataKey="candles"
// eslint-disable-next-line @typescript-eslint/no-explicit-any, react/no-unstable-nested-components
shape={(props: any) => {
return (
<CustomBarShape
{...props}
yAxisDomain={yAxisDomain}
chartHeight={gridHeight}
gridOffsetFromParent={gridOffsetFromParent}
/>
);
}}
/>
<ReferenceLine
y={averagePrice}
label="Average Price"
stroke={colors?.gray && colors.gray[800]}
stroke={grayColor}
strokeDasharray="3 3"
/>
</ComposedChart>
Expand Down
13 changes: 8 additions & 5 deletions packages/app/src/lib/layout/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@

import { Box, Flex, Image } from '@chakra-ui/react';
import Link from 'next/link';
import FoilTestnet from '@/protocol/deployments/11155111/Foil.json';
import FoilLocal from '@/protocol/deployments/13370/Foil.json';

import ConnectButton from '../components/ConnectButton';

import FoilTestnet from '@/protocol/deployments/11155111/Foil.json';
import FoilLocal from '@/protocol/deployments/13370/Foil.json';

const Header = () => {
return (
<Box
Expand All @@ -25,9 +26,11 @@ const Header = () => {
<Flex marginLeft="auto" gap={9} align="center" fontWeight="600">
{/* <Link href="/subscribe">Subscribe</Link> */}
{/* <Link href="/earn">Earn</Link> */}
<Link href={`/markets/13370:${FoilLocal.address}/1`}>
Local Market
</Link>
{process.env.NODE_ENV === 'development' && (
<Link href={`/markets/13370:${FoilLocal.address}/1`}>
Local Market
</Link>
)}
<Link href={`/markets/11155111:${FoilTestnet.address}/1`}>
Testnet Market
</Link>
Expand Down
2 changes: 2 additions & 0 deletions packages/data/src/processes/market.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export const indexMarketEvents = async (publicClient: PublicClient, Foil: { addr
const processLogs = async (logs: Log[]) => {
for (const log of logs) {
const serializedLog = JSON.stringify(log, bigintReplacer);
// TODO: Make this upsert!
const event = eventRepository.create({
logData: JSON.parse(serializedLog), // Parse back to JSON object
contractId: `${chainId}:${Foil.address}`,
Expand Down Expand Up @@ -60,6 +61,7 @@ export const indexMarketEventsRange = async (publicClient: PublicClient, start:
topics: log.topics,
});
const serializedLog = JSON.stringify(decodedLog, bigintReplacer);
// TODO: Make this upsert!
const event = eventRepository.create({
logData: JSON.parse(serializedLog), // Parse back to JSON object
contractId: `${await publicClient.getChainId()}:${contractAddress}`,
Expand Down
3 changes: 2 additions & 1 deletion packages/data/src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ createConnection(connectionOptions).then(async connection => {
});

// Get average price over a specified time period filtered by contractId
app.get('/prices/average', async (req, res) => {
app.get('/prices/average', async (req, res) => {
const { startTimestamp, endTimestamp, contractId } = req.query;
const where: any = {};

Expand Down Expand Up @@ -160,6 +160,7 @@ createConnection(connectionOptions).then(async connection => {

res.json(chartData);
});

app.get('/positions', async (req, res) => {
const { contractId, isLP } = req.query;
const where: any = {};
Expand Down
30 changes: 10 additions & 20 deletions packages/data/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,15 @@ async function createViemPublicClient(providerUrl: string) {
}

async function indexBaseFeePerGasRangeCommand(startBlock: number, endBlock: number, rpcUrl: string, contractAddress: string) {
console.log(`Indexing base fee per gas from block ${startBlock} to ${endBlock} for contract ${contractAddress} using ${rpcUrl}`);
const client = await createViemPublicClient(rpcUrl);
await indexBaseFeePerGasRange(client, startBlock, endBlock, contractAddress);
console.log(`Indexing base fee per gas from block ${startBlock} to ${endBlock} for contract ${contractAddress} using ${rpcUrl}`);
const client = await createViemPublicClient(rpcUrl);
await indexBaseFeePerGasRange(client, startBlock, endBlock, contractAddress);
}

async function indexMarketEventsRangeCommand(startBlock: number, endBlock: number, rpcUrl: string, contractAddress: string, contractAbi: Abi) {
console.log(`Indexing market events from block ${startBlock} to ${endBlock} for contract ${contractAddress} using ${rpcUrl}`);
const client = await createViemPublicClient(rpcUrl);
await indexMarketEventsRange(client, startBlock, endBlock, contractAddress, contractAbi);
console.log(`Indexing market events from block ${startBlock} to ${endBlock} for contract ${contractAddress} using ${rpcUrl}`);
const client = await createViemPublicClient(rpcUrl);
await indexMarketEventsRange(client, startBlock, endBlock, contractAddress, contractAbi);
}

if(process.argv.length < 3) {
Expand All @@ -80,19 +80,9 @@ if(process.argv.length < 3) {
} else {
const args = process.argv.slice(2);
if (args[0] === 'index-sepolia') {
// Index mainnet gas to sepolia contract
indexBaseFeePerGasRangeCommand(20413376, 20428947, 'https://ethereum-rpc.publicnode.com', `${sepolia.id}:${FoilSepolia.address}`)
//indexMarketEventsRangeCommand(1722270000, 1722458027, 'https://ethereum-rpc.publicnode.com', FoilSepolia.address, FoilSepolia.abi as Abi)
} else if (args[0] === 'index-base-fee-per-gas') {
const [start, end, rpcUrl, contractAddress] = args.slice(1);
indexBaseFeePerGasRangeCommand(Number(start), Number(end), rpcUrl, contractAddress)
.then(() => console.log('Indexing completed successfully'))
.catch(error => console.error('Error indexing base fee per gas range:', error));
} else if (args[0] === 'index-market-events') {
const [start, end, rpcUrl, contractAddress, contractAbiPath] = args.slice(1);
const contractAbi = require(contractAbiPath) as Abi; // Assuming the ABI is provided as a JSON file path
indexMarketEventsRangeCommand(Number(start), Number(end), rpcUrl, contractAddress, contractAbi)
.then(() => console.log('Indexing completed successfully'))
.catch(error => console.error('Error indexing market events range:', error));
Promise.all([
indexBaseFeePerGasRangeCommand(20413376, 20428947, 'https://ethereum-rpc.publicnode.com', `${sepolia.id}:${FoilSepolia.address}`),
indexMarketEventsRangeCommand(1722270000, 1722458027, 'https://ethereum-sepolia-rpc.publicnode.com', FoilSepolia.address, FoilSepolia.abi as Abi)
])
}
}
4 changes: 2 additions & 2 deletions packages/protocol/cannonfile.sepolia.toml
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
name="foil"
version="0.5"
version="0.6"

[var.settings]
owner="0xE006B58cA5aB7ba53863012dc3067A14b965C1da"
startTime = "1722270000" # Mon Jul 29 2024 16:20:00 GMT+0000
endTime = "1722458027" # Wed Jul 31 2024 20:33:47 GMT+0000
endTime = "1725195600" # Sunday, September 1, 2024 9:00:00 AM GMT-04:00
baseAssetMinPriceTick = "5200" # 1.709
baseAssetMaxPriceTick = "28200" # 17.09
feeRate = "10000" # 1%
Expand Down
4 changes: 2 additions & 2 deletions packages/protocol/cannonfile.toml
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
name="foil"
version="0.5"
version="0.6"

[var.settings]
owner = "0xEB045D78d273107348b0300c01D29B7552D622ab"
startTime = "1722270000" # Mon Jul 29 2024 16:20:00 GMT+0000
endTime = "1725900163" # Fri, 09 Sep 2024 16:42:43 GMT+0000
endTime = "1725195600" # Sunday, September 1, 2024 9:00:00 AM GMT-04:00
baseAssetMinPriceTick = "5200" # 1.709
baseAssetMaxPriceTick = "28200" # 17.09
feeRate = "10000" # 1%
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"address": "0x233Fdf7aeD41DADcf21E684048649e84769807C5",
"address": "0x35f49BA660F4A65A3e411D6Ee9C97332b9Fb5Ac9",
"abi": [
{
"type": "function",
Expand Down Expand Up @@ -233,12 +233,12 @@
],
"constructorArgs": [],
"linkedLibraries": {},
"deployTxnHash": "0x8c5d6ed2010e2a75000260198e7cb0b009bd1cf3770097874ba764674d995f2b",
"deployTxnBlockNumber": "6474235",
"deployTimestamp": "1723307100",
"deployTxnHash": "0x784d70f38d9e76198c86767878647a4b7d7aeff268cbce8cb810bafe1d867ed1",
"deployTxnBlockNumber": "6506105",
"deployTimestamp": "1723741740",
"sourceName": "src/contracts/modules/EpochConfigurationModule.sol",
"contractName": "EpochConfigurationModule",
"deployedOn": "deploy.EpochConfigurationModule",
"gasUsed": 2016847,
"gasCost": "1001154682"
"gasCost": "27304630816"
}
12 changes: 6 additions & 6 deletions packages/protocol/deployments/11155111/EpochLiquidityModule.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"address": "0x4AB67EE0d21fE2816EBDCD2286c21e0728BF5a0A",
"address": "0xBFA7450ef1EE0De783d212F7d5566C8Db4C15F72",
"abi": [
{
"type": "function",
Expand Down Expand Up @@ -486,12 +486,12 @@
],
"constructorArgs": [],
"linkedLibraries": {},
"deployTxnHash": "0x4dbcd6e7c95fe5ed1720baf9be28161605470f785c05c0a9484235b276a39bfa",
"deployTxnBlockNumber": "6474229",
"deployTimestamp": "1723307028",
"deployTxnHash": "0x49f297cafe18548d5c0431de649a9d9220750eb9390d876626bc040a27a6aa58",
"deployTxnBlockNumber": "6506098",
"deployTimestamp": "1723741644",
"sourceName": "src/contracts/modules/EpochLiquidityModule.sol",
"contractName": "EpochLiquidityModule",
"deployedOn": "deploy.EpochLiquidityModule",
"gasUsed": 2082120,
"gasCost": "1071720725"
"gasUsed": 2068518,
"gasCost": "37401849570"
}
10 changes: 5 additions & 5 deletions packages/protocol/deployments/11155111/EpochNftModule.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"address": "0xde6d24F43752BA9C4bd63fc9942d4384f3af00ac",
"address": "0xF1358121F4e1869821839ec04B50624077d4b6D7",
"abi": [
{
"type": "constructor",
Expand Down Expand Up @@ -463,12 +463,12 @@
],
"constructorArgs": [],
"linkedLibraries": {},
"deployTxnHash": "0x7ac01cc6cc6101a034d757bc8a521aa3c2b4e401f8f295cf14b5cb70770b6382",
"deployTxnBlockNumber": "6474230",
"deployTimestamp": "1723307040",
"deployTxnHash": "0xc3bca3b335b4e296a71644c6072d3f914d87c41d0ea12dffe7f3c60dc885f615",
"deployTxnBlockNumber": "6506099",
"deployTimestamp": "1723741656",
"sourceName": "src/contracts/modules/EpochNftModule.sol",
"contractName": "EpochNftModule",
"deployedOn": "deploy.EpochNftModule",
"gasUsed": 1190314,
"gasCost": "1046361736"
"gasCost": "35710715745"
}
Loading

0 comments on commit 3ab1e5e

Please sign in to comment.