Skip to content

Commit

Permalink
Make readable the Protocols + hide the subgraph api key
Browse files Browse the repository at this point in the history
  • Loading branch information
Koplo committed Nov 23, 2024
1 parent 8a47126 commit 8c9053a
Show file tree
Hide file tree
Showing 8 changed files with 1,484 additions and 45 deletions.
1,377 changes: 1,373 additions & 4 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"start": "next start"
},
"dependencies": {
"@airswap/utils": "^5.0.2",
"chart.js": "^4.4.0",
"graphql": "^16.8.1",
"graphql-request": "^6.1.0",
Expand Down
28 changes: 28 additions & 0 deletions src/app/api/graphql/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

export const API_KEY = process.env.NEXT_PUBLIC_GRAPH_API_KEY;
export const SUBGRAPH_URL = `https://gateway.thegraph.com/api/${API_KEY}/subgraphs/id/7ruo9nxQ3LUqnKkbLgmETDQ27j6A2DFx5L5eV6MS2TAz`;

export async function request<T>(query: string, variables?: Record<string, any>): Promise<T> {
const response = await fetch('/api/subgraph', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query,
variables,
}),
});

if (!response.ok) {
throw new Error('Failed to fetch data');
}

const { data, errors } = await response.json();
if (errors) {
throw new Error(errors[0].message);
}

return data;
}

Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { gql } from 'graphql-request';

export const DAILY_VOLUME_QUERY = gql`
query GetDailyData($fromTimestamp: Int!) {
query GetDailyData($timestamp: Int!) {
dailies(
where: { date_gte: $fromTimestamp }
where: { date_gte: $timestamp }
orderBy: date
orderDirection: desc
) {
Expand All @@ -13,6 +13,7 @@ export const DAILY_VOLUME_QUERY = gql`
}
}
`;

export const BIGGEST_SWAPS_QUERY = gql`
query GetBigSwaps($timestamp24h: Int!, $timestamp7d: Int!, $timestamp30d: Int!, $minAmount: String!) {
last24h: swapERC20S(
Expand Down Expand Up @@ -62,6 +63,7 @@ export const BIGGEST_SWAPS_QUERY = gql`
}
}
`;

export const SERVERS_QUERY = gql`
query GetServers {
servers(first: 100) {
Expand Down
27 changes: 27 additions & 0 deletions src/app/api/subgraph/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { NextRequest, NextResponse } from 'next/server';

const API_KEY = process.env.NEXT_PUBLIC_GRAPH_API_KEY;
const SUBGRAPH_URL = `https://gateway.thegraph.com/api/${API_KEY}/subgraphs/id/7ruo9nxQ3LUqnKkbLgmETDQ27j6A2DFx5L5eV6MS2TAz`;

export async function POST(req: NextRequest) {
try {
const { query, variables } = await req.json();

const response = await fetch(SUBGRAPH_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query,
variables,
}),
});

const data = await response.json();
return NextResponse.json(data);
} catch (error) {
console.error('Subgraph query error:', error);
return NextResponse.json({ error: 'Failed to fetch data' }, { status: 500 });
}
}
73 changes: 41 additions & 32 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,37 @@
'use client';

import { useState, useEffect } from 'react';
import { request } from 'graphql-request';
import { SUBGRAPH_URL } from '@/lib/api/graphql/client';
import { DAILY_VOLUME_QUERY, BIGGEST_SWAPS_QUERY, SERVERS_QUERY } from '@/lib/api/graphql/queries';
import { DAORevenue } from '@/components/revenue/DAORevenue';
import { VolumeStats } from '@/components/volume/VolumeStats';
import { DailyVolume } from '@/components/volume/DailyVolume';

import { BiggestSwaps } from '@/components/swaps/BiggestSwaps';
import { MarketMakers } from '@/components/market-makers/MarketMakers';
import { SwapData } from '@/components/swaps/type';
import { ServerData } from '@/components/market-makers/types';
import { DailyData } from '@/components/revenue/types';
import { VolumeData } from '@/components/volume/type';
import { DAILY_VOLUME_QUERY, BIGGEST_SWAPS_QUERY, SERVERS_QUERY } from '@/app/api/graphql/queries';



async function secureRequest<T>(query: string, variables?: any): Promise<{ data: T }> {
const response = await fetch('/api/subgraph', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query,
variables,
}),
});

if (!response.ok) {
throw new Error('Failed to fetch data');
}

return response.json();
}

export default function Home() {
const [selectedTimeframe, setSelectedTimeframe] = useState<'24h' | '7d' | '30d'>('24h');
Expand All @@ -30,34 +48,25 @@ export default function Home() {

useEffect(() => {
const fetchData = async () => {
if (!process.env.NEXT_PUBLIC_GRAPH_API_KEY) {
setError('API key not found');
setLoading(false);
return;
}

try {
const now = Math.floor(Date.now() / 1000);
const timestamp24h = now - (24 * 60 * 60);
const timestamp7d = now - (7 * 24 * 60 * 60);
const timestamp30d = now - (30 * 24 * 60 * 60);
// Get data for 4 years to cover all possible timeframes
const timestamp4y = now - (4 * 365 * 24 * 60 * 60);

const [dailyResponse, bigSwapsResponse, serversResponse] = await Promise.all([
request<{ dailies: DailyData[] }>(
SUBGRAPH_URL,
const [dailyResponse, swapsResponse, serversResponse] = await Promise.all([
secureRequest<{ dailies: DailyData[] }>(
DAILY_VOLUME_QUERY,
{
fromTimestamp: timestamp4y // Use 4y timestamp to get all needed data
timestamp: timestamp4y
}
),
request<{
secureRequest<{
last24h: SwapData[];
last7d: SwapData[];
last30d: SwapData[];
}>(
SUBGRAPH_URL,
BIGGEST_SWAPS_QUERY,
{
timestamp24h,
Expand All @@ -66,14 +75,16 @@ export default function Home() {
minAmount: "50000"
}
),
request<{ servers: ServerData[] }>(
SUBGRAPH_URL,
secureRequest<{ servers: ServerData[] }>(
SERVERS_QUERY
),
]);

// Store the daily data
setDailyData(dailyResponse.dailies);
if (!dailyResponse.data || !swapsResponse.data || !serversResponse.data) {
throw new Error('Invalid response data');
}

setDailyData(dailyResponse.data.dailies);

// Calculate volumes for the cards
const calculateRollingVolume = (data: DailyData[], fromTimestamp: number) => {
Expand All @@ -99,19 +110,19 @@ export default function Home() {
return totalVolume;
};

const volumes = {
'24h': calculateRollingVolume(dailyResponse.dailies, timestamp24h),
'7d': calculateRollingVolume(dailyResponse.dailies, timestamp7d),
'30d': calculateRollingVolume(dailyResponse.dailies, timestamp30d)
const volumeData = {
'24h': calculateRollingVolume(dailyResponse.data.dailies, timestamp24h),
'7d': calculateRollingVolume(dailyResponse.data.dailies, timestamp7d),
'30d': calculateRollingVolume(dailyResponse.data.dailies, timestamp30d)
};

setVolumes(volumes);
setVolumes(volumeData);
setBiggestSwaps({
'24h': bigSwapsResponse.last24h,
'7d': bigSwapsResponse.last7d,
'30d': bigSwapsResponse.last30d
'24h': swapsResponse.data.last24h,
'7d': swapsResponse.data.last7d,
'30d': swapsResponse.data.last30d
});
setServers(serversResponse.servers);
setServers(serversResponse.data.servers);
setLoading(false);

} catch (err) {
Expand Down Expand Up @@ -146,6 +157,4 @@ export default function Home() {
</div>
</main>
);


}
13 changes: 10 additions & 3 deletions src/components/market-makers/MarketMakers.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { ServerData } from './types';
import { ProtocolIds } from '@airswap/utils';

export function MarketMakers({ servers }: { servers: ServerData[] }) {
const getProtocolName = (protocolId: string) => {
const normalizedId = protocolId.toLowerCase();
const protocolName = Object.entries(ProtocolIds).find(
([_, value]) => value.toLowerCase() === normalizedId
)?.[0];
return protocolName || protocolId;
};

return (
<div className="bg-white rounded-lg">
<h2 className="px-4 py-3 text-xl font-bold border-b">Market Makers</h2>
Expand All @@ -11,7 +20,6 @@ export function MarketMakers({ servers }: { servers: ServerData[] }) {
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500">URL</th>
<th className="px-4 py-3 text-center text-xs font-medium text-gray-500">Tokens</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500">Protocols</th>

</tr>
</thead>
<tbody className="divide-y divide-gray-200">
Expand Down Expand Up @@ -39,12 +47,11 @@ export function MarketMakers({ servers }: { servers: ServerData[] }) {
key={`${server.id}-${protocol}-${index}`}
className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800"
>
{protocol}
{getProtocolName(protocol)}
</span>
))}
</div>
</td>

</tr>
))}
</tbody>
Expand Down
4 changes: 0 additions & 4 deletions src/lib/api/graphql/client.ts

This file was deleted.

0 comments on commit 8c9053a

Please sign in to comment.