Skip to content

Commit

Permalink
feat: replace coingecko with lunarcrush
Browse files Browse the repository at this point in the history
  • Loading branch information
He1DAr committed Mar 8, 2024
1 parent 193dbe6 commit 76f225d
Show file tree
Hide file tree
Showing 21 changed files with 191 additions and 220 deletions.
45 changes: 15 additions & 30 deletions src/__tests__/pages/token/[tokenId].test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ import '@testing-library/jest-dom';
import '@testing-library/jest-dom/extend-expect';

import { getTokenInfo } from '../../../app/token/[tokenId]/getTokenInfo';
import { apiClients as apiClientsActual } from '../../../common/api/client';

global.fetch = jest.fn();
const apiClients = apiClientsActual as jest.MockedFunction<any>;
const fetch = global.fetch as jest.MockedFunction<any>;

jest.mock('../../../common/api/client', () => ({
Expand Down Expand Up @@ -59,30 +57,7 @@ describe('getTokenInfo', () => {
expect(console.error).toBeCalledWith(new Error('token not found'));
});

it('returns basic token info if CoinGecko does not have the token', async () => {
const tokenId = 'token1';
const chain = 'mainnet';

fetch
.mockResolvedValueOnce({
json: jest.fn().mockResolvedValueOnce({ name: 'NAME', symbol: 'SYMBOL' }),
})
.mockResolvedValueOnce({
json: jest.fn().mockResolvedValueOnce({ coins: [] }),
});

const result = await getTokenInfo(tokenId, chain);

expect(result).toEqual({
basic: {
name: 'NAME',
symbol: 'SYMBOL',
totalSupply: null,
},
});
});

it('returns token info if CoinGecko has token', async () => {
it('returns token info', async () => {
const tokenId = 'token1';
const chain = 'mainnet';

Expand Down Expand Up @@ -110,7 +85,6 @@ describe('getTokenInfo', () => {
circulatingSupply: null,
currentPrice: null,
currentPriceInBtc: null,
fullyDilutedValuation: null,
links: {
announcements: [],
blockchain: [],
Expand All @@ -122,11 +96,22 @@ describe('getTokenInfo', () => {
},
marketCap: null,
priceChangePercentage24h: null,
priceInBtcChangePercentage24h: null,
tradingVolume24h: null,
tradingVolumeChangePercentage24h: null,
tvl: null,
developerData: {},
marketCapRank: null,
priceInBtcChangePercentage24h: null,
developerData: {
closed_issues: null,
code_additions_deletions_4_weeks: null,
commit_count_4_weeks: null,
forks: null,
last_4_weeks_commit_activity_series: null,
pull_request_contributors: null,
pull_requests_merged: null,
stars: null,
subscribers: null,
total_issues: null,
},
},
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ exports[`BlockListWithControls renders correctly 1`] = `
class="css-16e8ooo"
>
<div
class="css-1rdddxq"
class="css-1b9enxg"
>
<span
class="chakra-text css-hnwgpl"
Expand Down
4 changes: 2 additions & 2 deletions src/app/_components/BlockList/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ function BlocksListBase({
return (
<Section
title="Recent Blocks"
gridColumnStart={['1', '1', '2']}
gridColumnEnd={['2', '2', '3']}
gridColumnStart={['1', '1', '1', '2']}
gridColumnEnd={['2', '2', '2', '3']}
minWidth={0}
flexGrow={0}
flexShrink={1}
Expand Down
4 changes: 2 additions & 2 deletions src/app/_components/Footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,11 @@ export const Footer: FC = () => {
</Flex>
<Box>
<FooterLink
href="https://www.coingecko.com/"
href="https://lunarcrush.com/"
target="_blank"
rel="noopener noreferrer nofollow"
>
Market data provided by CoinGecko
Market data provided by LunarCrush
</FooterLink>
</Box>
</Flex>
Expand Down
5 changes: 2 additions & 3 deletions src/app/address/[principal]/StxBalance/BalanceItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,18 @@

import * as React from 'react';

import { useSuspenseCurrentStxPrice } from '../../../../common/queries/useCurrentPrices';
import { useSuspenseStxPrice } from '../../../../common/queries/useCurrentPrices';
import {
formatStacksAmount,
getLocaleDecimalSeparator,
getUsdValue,
} from '../../../../common/utils/utils';
import { Box } from '../../../../ui/Box';
import { Flex, FlexProps } from '../../../../ui/Flex';
import { Text } from '../../../../ui/Text';
import { ExplorerErrorBoundary } from '../../../_components/ErrorBoundary';

function UsdBalanceBase({ balance }: { balance: number }) {
const { data: stxPrice } = useSuspenseCurrentStxPrice();
const { data: stxPrice } = useSuspenseStxPrice();
const usdBalance = getUsdValue(balance, stxPrice);

if (!usdBalance) {
Expand Down
12 changes: 11 additions & 1 deletion src/app/block/[hash]/tx-lists/BlockTxsList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ import { useSuspenseBlockTxsInfinite } from '../../../../common/queries/useBlock
import { FilteredTxs } from '../../../../features/txs-list/FilteredTxs';
import { TxListItem } from '../../../../features/txs-list/ListItem/TxListItem';
import { FilterButton } from '../../../../features/txsFilterAndSort/FilterButton';
import { ShowValueMenu } from '../../../../features/txsFilterAndSort/ShowValueMenu';
import { Box } from '../../../../ui/Box';
import { Flex } from '../../../../ui/Flex';
import { ExplorerErrorBoundary } from '../../../_components/ErrorBoundary';

interface BlockTxsListProps {
Expand All @@ -29,7 +31,15 @@ function BlockTxsListBase({ blockHash, limit }: BlockTxsListProps) {
}

return (
<Section title={'Transactions'} topRight={<FilterButton />}>
<Section
title={'Transactions'}
topRight={
<Flex gap={4} direction={['column', 'row']}>
<ShowValueMenu />
<FilterButton />
</Flex>
}
>
<Box flexGrow={1}>
<Box position={'relative'}>
<FilteredTxs txs={txs} TxListItem={TxListItem} />
Expand Down
24 changes: 17 additions & 7 deletions src/app/getTokenPriceInfo.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
import { LUNAR_CRUSH_API_KEY } from '../common/constants/env';
import { LunarCrushCoin } from '../common/types/lunarCrush';
import { TokenPrice } from '../common/types/tokenPrice';
import { getCacheClient } from '../common/utils/cache-client';

const TOKEN_PRICE_CACHE_KEY = 'token-price';

export const getCurrentBtcPrice = async () =>
fetch('https://api.coingecko.com/api/v3/exchange_rates')
export const getCurrentBtcPrice = async (): Promise<number> =>
fetch('https://lunarcrush.com/api4/public/coins/btc/v1', {
headers: {
Authorization: `Bearer ${LUNAR_CRUSH_API_KEY}`,
},
})
.then(res => res.json())
.then(data => data?.rates?.usd?.value || 0);

export const getCurrentStxPrice = async () =>
fetch('https://api.coingecko.com/api/v3/simple/price?ids=blockstack,bitcoin&vs_currencies=usd')
.then(data => data?.data?.price || 0);

export const getCurrentStxPrice = async (): Promise<number> =>
fetch('https://lunarcrush.com/api4/public/coins/stx/v1', {
headers: {
Authorization: `Bearer ${LUNAR_CRUSH_API_KEY}`,
},
})
.then(res => res.json())
.then(data => data?.blockstack?.usd || 0);
.then(data => data?.data?.price || 0);

async function getCachedTokenPrice() {
try {
Expand Down
40 changes: 40 additions & 0 deletions src/app/stxPrice/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { NextRequest } from 'next/server';

import { LUNAR_CRUSH_API_KEY } from '../../common/constants/env';

export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const blockBurnTime = searchParams.get('blockBurnTime');

console.log('blockBurnTime', blockBurnTime);
if (!blockBurnTime || blockBurnTime === 'current') {
console.log(11);
const response = await fetch('https://lunarcrush.com/api4/public/coins/stx/v1', {
headers: {
Authorization: `Bearer ${LUNAR_CRUSH_API_KEY}`,
},
});
const data = await response.json();
console.log(data);
return Response.json({ price: data?.data?.price || 0 });
}

const to = new Date(blockBurnTime);
const from = new Date(blockBurnTime);
from.setDate(from.getDate() - 1);
const response = await fetch(
`https://lunarcrush.com/api4/public/coins/stx/time-series/v2?bucket=day&interval=1d&start=${
from.getTime() / 1000
}&end=${to.getTime() / 1000}`,
{
next: { revalidate: 10 * 60 }, // Revalidate every 10 minutes
headers: {
Authorization: `Bearer ${LUNAR_CRUSH_API_KEY}`,
},
}
);

const data = await response.json();

return Response.json({ price: data?.data?.[0]?.open || 0 });
}
2 changes: 1 addition & 1 deletion src/app/token/[tokenId]/PageClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export default function PageClient({
{name} ({symbol})
</PageTitle>
)}
{!!tokenInfo.extended?.links && <LinksMenu links={tokenInfo.extended.links} />}
{/*{!!tokenInfo.extended?.links && <LinksMenu links={tokenInfo.extended.links} />}*/}
</Flex>
<TokenInfo tokenInfo={tokenInfo} txId={tokenId} />
<Tabs
Expand Down
12 changes: 1 addition & 11 deletions src/app/token/[tokenId]/TokenInfo/Price.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,8 @@ export const Price: FC<
currentPrice: number | null | undefined;
priceChangePercentage24h: number | null | undefined;
currentPriceInBtc: number | null | undefined;
priceInBtcChangePercentage24h: number | null | undefined;
}
> = ({
currentPrice,
priceChangePercentage24h,
currentPriceInBtc,
priceInBtcChangePercentage24h,
...gridProps
}) => {
> = ({ currentPrice, priceChangePercentage24h, currentPriceInBtc, ...gridProps }) => {
const colorMode = useColorMode().colorMode;
return (
<StatSection
Expand All @@ -33,9 +26,6 @@ export const Price: FC<
caption={
<Flex fontSize={'12px'} fontWeight="500" alignItems={'center'} gap={'6px'}>
{currentPriceInBtc ? `${currentPriceInBtc.toFixed(8)} BTC` : 'N/A'}
{priceInBtcChangePercentage24h ? (
<TrendArrow change={priceInBtcChangePercentage24h} size={'11px'} />
) : null}
</Flex>
}
{...gridProps}
Expand Down
12 changes: 5 additions & 7 deletions src/app/token/[tokenId]/TokenInfo/Transaction.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,13 @@ import { Flex } from '../../../../ui/Flex';
import { GridProps } from '../../../../ui/Grid';
import { StatSection } from '../../../_components/Stats/StatSection';

export const Transaction: FC<GridProps & { txId: string; tvl: number | null | undefined }> = ({
tvl,
txId,
...gridProps
}) => {
export const Transaction: FC<
GridProps & { txId: string; marketCapRank: number | null | undefined }
> = ({ marketCapRank, txId, ...gridProps }) => {
const colorMode = useColorMode().colorMode;
return (
<StatSection
title="Contract transaction"
title="Contract Transaction"
bodyMainText={
<Box
textOverflow={'ellipsis'}
Expand All @@ -31,7 +29,7 @@ export const Transaction: FC<GridProps & { txId: string; tvl: number | null | un
bodySecondaryText={null}
caption={
<Flex fontSize={'12px'} fontWeight="500">
TVL: {tvl ? `$${numberToString(tvl)}` : 'N/A'}
Market Cap Rank: {marketCapRank || 'N/A'}
</Flex>
}
{...gridProps}
Expand Down
3 changes: 1 addition & 2 deletions src/app/token/[tokenId]/TokenInfo/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ export const TokenInfo: FC<{ tokenInfo: TokenInfoProps; txId: string }> = ({ tok
currentPrice={tokenInfo.extended?.currentPrice}
priceChangePercentage24h={tokenInfo.extended?.priceChangePercentage24h}
currentPriceInBtc={tokenInfo.extended?.currentPriceInBtc}
priceInBtcChangePercentage24h={tokenInfo.extended?.priceInBtcChangePercentage24h}
borderRightWidth={['0px', '0px', '0px', '1px']}
/>
<MarketCap
Expand All @@ -32,7 +31,7 @@ export const TokenInfo: FC<{ tokenInfo: TokenInfoProps; txId: string }> = ({ tok
tradingVolumeChangePercentage24h={tokenInfo.extended?.tradingVolumeChangePercentage24h}
borderRightWidth={['0px', '0px', '1px', '1px']}
/>
<Transaction txId={txId} tvl={tokenInfo.extended?.tvl} />
<Transaction txId={txId} marketCapRank={tokenInfo.extended?.marketCapRank} />
</Wrapper>
</ErrorBoundary>
);
Expand Down

0 comments on commit 76f225d

Please sign in to comment.