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

Refactor and Enhance Ethereum API Routes #156

Open
wants to merge 2 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
29 changes: 24 additions & 5 deletions app/api/ethereum-data/route.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { NextResponse } from 'next/server';

const CACHE_EXPIRATION_MS = 10000; // 10 seconds cache
// Cache expiration time in milliseconds (10 seconds)
const CACHE_EXPIRATION_MS = 10000;

interface ICache {
interface ICache {
blockNumber: number | null;
gasPrice: number | null;
ethPrice: number | null;
Expand Down Expand Up @@ -42,15 +43,33 @@ export async function GET() {
console.log("Fetching new data from Etherscan");

const [blockResponse, gasResponse, priceResponse] = await Promise.all([
fetch(`${etherscanAddress}?module=proxy&action=eth_blockNumber&apikey=${apiKey}`, {cache: "no-store"}),
fetch(`${etherscanAddress}?module=proxy&action=eth_gasPrice&apikey=${apiKey}`, {cache: "no-store"}),
fetch(`${etherscanAddress}?module=stats&action=ethprice&apikey=${apiKey}`, {cache: "no-store"})
fetch(`${etherscanAddress}?module=proxy&action=eth_blockNumber&apikey=${apiKey}`, { cache: "no-store" }),
fetch(`${etherscanAddress}?module=proxy&action=eth_gasPrice&apikey=${apiKey}`, { cache: "no-store" }),
fetch(`${etherscanAddress}?module=stats&action=ethprice&apikey=${apiKey}`, { cache: "no-store" })
]);

// Check response statuses
if (!blockResponse.ok || !gasResponse.ok || !priceResponse.ok) {
console.error('One or more API requests failed');
return NextResponse.json(
cache || { error: 'Failed to fetch Ethereum data' },
{ status: 502 }
);
}

const blockData = await blockResponse.json();
const gasData = await gasResponse.json();
const priceData = await priceResponse.json();

// Check for API response errors
if (blockData.error || gasData.error || priceData.error) {
console.error('API returned error:', { blockData, gasData, priceData });
return NextResponse.json(
cache || { error: 'Etherscan API returned error' },
{ status: 502 }
);
}

const newBlockNumber = parseInt(blockData.result, 16);
const newGasPrice = Math.round((parseInt(gasData.result, 16) / 1e9) * 100) / 100;
const newEthPrice = Math.round(parseFloat(priceData.result.ethusd) * 100) / 100;
Expand Down
57 changes: 38 additions & 19 deletions app/api/get-transactions/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,49 @@ import { NextResponse } from 'next/server';

const BRIDGE_CONTRACT_ADDRESS = process.env.NEXT_PUBLIC_BRIDGE_CONTRACT || '';
const API_KEY = process.env.ETHERSCAN_API_KEY || '';
// Starting block to search for transactions
const START_BLOCK = 21126289;

// Define an interface for a transaction
interface Transaction {
to: string;
from: string;
hash: string;
blockNumber: string;
// Add other necessary fields as needed
}

export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const address = searchParams.get('address');
const { searchParams } = new URL(request.url);
const address = searchParams.get('address');

if (!address || typeof address !== 'string') {
return NextResponse.json({ message: 'Address is required' }, { status: 400 });
}
if (!address || typeof address !== 'string') {
return NextResponse.json({ message: 'Address is required' }, { status: 400 });
}

try {
const apiUrl = `${process.env.NEXT_PUBLIC_ETHERSCAN_ADDRESS}?module=account&action=txlist&address=${address}&startblock=21126289&endblock=99999999&page=1&offset=1000&sort=asc&apikey=${API_KEY}`;
const response = await fetch(apiUrl);
const data = await response.json();
try {
const apiUrl = `${process.env.NEXT_PUBLIC_ETHERSCAN_ADDRESS}?module=account&action=txlist&address=${address}&startblock=${START_BLOCK}&endblock=99999999&page=1&offset=1000&sort=asc&apikey=${API_KEY}`;
const response = await fetch(apiUrl);

if (data.status !== '1') {
throw new Error(data.message || 'Failed to fetch data from Etherscan');
}
if (!response.ok) {
throw new Error('Failed to fetch data from Etherscan API');
}

const deposits = data.result
.filter((tx: any) => tx.to.toLowerCase() === BRIDGE_CONTRACT_ADDRESS.toLowerCase());
const data = await response.json();

return NextResponse.json(deposits);
} catch (error) {
console.error('Error fetching last deposits:', error);
return NextResponse.json({ message: 'Internal Server Error' }, { status: 500 });
}
if (data.status !== '1') {
throw new Error(data.message || 'Failed to fetch data from Etherscan');
}

const deposits = data.result
.filter((tx: Transaction) => tx.to.toLowerCase() === BRIDGE_CONTRACT_ADDRESS.toLowerCase());

return NextResponse.json(deposits);
} catch (error) {
console.error('Error fetching last deposits:', error);
return NextResponse.json(
{ message: error instanceof Error ? error.message : 'Internal Server Error' },
{ status: 500 }
);
}
}