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

Addl info #65

Open
wants to merge 28 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
210 changes: 210 additions & 0 deletions components/ChainInfo/Chart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
import React, { useEffect, useRef, useMemo } from 'react';
import { createChart } from 'lightweight-charts';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import { toK } from '../../utils/utils';

dayjs.extend(utc);

export const CHART_TYPES = {
BAR: 'BAR',
AREA: 'AREA',
};

const formattedNum = (value, units) => `${units + toK(value)}`;

// constant height for charts
const HEIGHT = 300;

const TradingViewChart = ({
type = CHART_TYPES.BAR,
data = [],
base,
baseChange,
field,
title,
width,
units = '$',
chainId = 1,
useWeekly = false,
}) => {
// reference for DOM element to create with chart
const ref = useRef();

// parse the data and format for tardingview consumption
const formattedData = useMemo(() => {
return data.map((entry) => {
return {
time: dayjs.unix(entry[0]).utc().format('YYYY-MM-DD'),
value: parseFloat(entry[field]),
};
});
}, [data, field]);

// adjust the scale based on the type of chart
const topScale = type === CHART_TYPES.AREA ? 0.32 : 0.2;

const darkMode = window.localStorage.getItem('yearn.finance-dark-mode') === 'dark';

useEffect(() => {
const textColor = darkMode ? 'white' : 'black';
const crossHairColor = darkMode ? 'rgba(255, 255, 255, 0.1)' : 'rgba(32, 38, 46, 0.1)';

const chart = createChart(ref.current, {
width: width,
height: HEIGHT,
layout: {
backgroundColor: 'transparent',
textColor: textColor,
},
rightPriceScale: {
scaleMargins: {
top: topScale,
bottom: 0,
},
borderVisible: false,
},
timeScale: {
borderVisible: false,
},
grid: {
horzLines: {
color: 'rgba(197, 203, 206, 0.5)',
visible: false,
},
vertLines: {
color: 'rgba(197, 203, 206, 0.5)',
visible: false,
},
},
crosshair: {
horzLine: {
visible: false,
labelVisible: false,
},
vertLine: {
visible: true,
style: 0,
width: 2,
color: crossHairColor,
labelVisible: false,
},
},
localization: {
priceFormatter: (val) => formattedNum(val, units),
},
});

const series =
type === CHART_TYPES.BAR
? chart.addHistogramSeries({
color: '#394990',
priceFormat: {
type: 'volume',
},
scaleMargins: {
top: 0.32,
bottom: 0,
},
lineColor: '#394990',
lineWidth: 3,
})
: chart.addAreaSeries({
topColor: '#394990',
bottomColor: 'rgba(112, 82, 64, 0)',
lineColor: '#394990',
lineWidth: 3,
});

series.setData(formattedData);

const prevTooltip = document.getElementById('tooltip-id' + chainId + type);
const node = document.getElementById('test-id' + chainId + type);

if (prevTooltip && node) {
node.removeChild(prevTooltip);
}

const toolTip = document.createElement('div');
toolTip.setAttribute('id', 'tooltip-id' + chainId + type);
toolTip.className = darkMode ? 'three-line-legend-dark' : 'three-line-legend';

ref.current.appendChild(toolTip);

toolTip.style.display = 'block';
toolTip.style.fontWeight = '500';
toolTip.style.left = 0;
toolTip.style.top = '-6px';
toolTip.style.backgroundColor = 'transparent';
toolTip.style.position = 'absolute';

// format numbers
let percentChange = baseChange?.toFixed(2);
let formattedPercentChange = (percentChange > 0 ? '+' : '') + percentChange + '%';
let color = percentChange >= 0 ? 'green' : 'red';

// get the title of the chart
function setLastBarText() {
toolTip.innerHTML =
`<div style="font-size: 16px; margin: 4px 0px; color: ${textColor};">${title} ${
type === CHART_TYPES.BAR && !useWeekly ? '(24hr)' : ''
}</div>` +
`<div style="font-size: 22px; margin: 4px 0px; color:${textColor}" >` +
formattedNum(base ?? 0, units) +
(baseChange
? `<span style="margin-left: 10px; font-size: 16px; color: ${color};">${formattedPercentChange}</span>`
: '') +
'</div>';
}
setLastBarText();

// update the title when hovering on the chart
chart.subscribeCrosshairMove(function (param) {
if (
param === undefined ||
param.time === undefined ||
param.point.x < 0 ||
param.point.x > width ||
param.point.y < 0 ||
param.point.y > HEIGHT
) {
setLastBarText();
} else {
let dateStr = useWeekly
? dayjs(param.time.year + '-' + param.time.month + '-' + param.time.day)
.startOf('week')
.format('MMMM D, YYYY') +
'-' +
dayjs(param.time.year + '-' + param.time.month + '-' + param.time.day)
.endOf('week')
.format('MMMM D, YYYY')
: dayjs(param.time.year + '-' + param.time.month + '-' + param.time.day).format('MMMM D, YYYY');

const price = param.seriesPrices.get(series);

toolTip.innerHTML =
`<div style="font-size: 16px; margin: 4px 0px; color: ${textColor};">${title}</div>` +
`<div style="font-size: 22px; margin: 4px 0px; color: ${textColor}">` +
formattedNum(price, units) +
'</div>' +
'<div>' +
dateStr +
'</div>';
}
});

chart.timeScale().fitContent();

return () => {
chart.remove();
};
}, [base, baseChange, title, topScale, type, useWeekly, width, units, formattedData, darkMode]);

return (
<div style={{ position: 'relative' }}>
<div ref={ref} id={'test-id' + chainId + type} />
</div>
);
};

export default TradingViewChart;
46 changes: 46 additions & 0 deletions components/ChainInfo/RPCList.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { useEffect } from 'react';
import { useRPCData } from '../../utils/utils';
import classes from './index.module.css';

export default function RPCList({ chain }) {
const { data } = useRPCData(chain.rpc);
const darkMode = window.localStorage.getItem('yearn.finance-dark-mode') === 'dark';

useEffect(() => {
// clear network resources list for better performance to find latency of each rpc url
window.performance.clearResourceTimings();

const interval = setInterval(() => {
window.performance.clearResourceTimings();
}, 15000);

return () => clearInterval(interval);
}, []);

return (
<table
className={classes.table}
style={{ '--border-color': darkMode ? 'hsl(0deg 0% 39% / 33%)' : 'hsl(0deg 0% 17% / 4%)' }}
>
<caption>{`${chain.name} RPC URL List`}</caption>
<thead>
<tr>
<th>S.No</th>
<th>RPC Server Address</th>
<th>Height</th>
<th>Latency</th>
</tr>
</thead>
<tbody>
{data?.map((item, index) => (
<tr key={index}>
<td>{index + 1}</td>
<td>{item.url}</td>
<td>{item.height}</td>
<td>{item.latency ? (item.latency / 1000).toFixed(3) + 's' : null}</td>
</tr>
))}
</tbody>
</table>
);
}
64 changes: 64 additions & 0 deletions components/ChainInfo/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { useMemo } from 'react';
import { Paper } from '@material-ui/core';
import { getPercentChange, getPrevTvlFromChart, useChain } from '../../utils/utils';
import classes from './index.module.css';
import ParentSize from '@visx/responsive/lib/components/ParentSize';
import dynamic from 'next/dynamic';
import Loader from 'react-spinners/BeatLoader';
import RPCList from './RPCList';

const Chart = dynamic(() => import('./Chart'), { ssr: false });

export default function ChainInfo({ chain }) {
const { data, isLoading, isError } = useChain(chain.chainSlug);

const { tvl, volumeChange, chart } = useMemo(() => {
let chart = [];
let tvl = null;
let volumeChange = null;

if (!isLoading && !isError && data?.length > 0) {
chart = data.map(({ date, totalLiquidityUSD }) => [date, Math.trunc(totalLiquidityUSD)]);

tvl = getPrevTvlFromChart(chart, 0);
const tvlPrevDay = getPrevTvlFromChart(chart, 1);
const volumeChangeUSD = getPercentChange(tvl, tvlPrevDay);

const percentChange = volumeChangeUSD?.toFixed(2);
volumeChange = (percentChange > 0 ? '+' : '') + percentChange + '%';
}

return { tvl, volumeChange: volumeChangeUSD, chart };
}, [data]);

const darkMode = window.localStorage.getItem('yearn.finance-dark-mode') === 'dark';

return (
<Paper elevation={1} className={classes.disclosure}>
<RPCList chain={chain} />
{chain.tvl && (
<div className={classes.chartContainer}>
{isLoading ? (
<Loader size={8} color={darkMode ? 'white' : 'black'} />
) : (
<ParentSize>
{({ width }) => (
<Chart
data={chart}
base={tvl}
baseChange={volumeChange}
title={chain.name + ' TVL'}
field="1"
width={width}
type="AREA"
units="$"
chainId={chain.chainId}
/>
)}
</ParentSize>
)}
</div>
)}
</Paper>
);
}
36 changes: 36 additions & 0 deletions components/ChainInfo/index.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
.disclosure {
grid-column: 1 / -1;
position: relative;
padding: 16px;
}

.chartContainer {
height: 300px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin-top: 24px;
}

.table {
border-collapse: collapse;
margin: 0 auto;
}

.table caption,
.table th,
.table td {
padding: 2px 12px;
border: 1px solid var(--border-color);
}

.table caption {
font-size: 1rem;
font-weight: 500;
border-bottom: 0;
}

.table th {
font-weight: 500;
}
Loading