Skip to content
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
47 changes: 0 additions & 47 deletions src/data-layer/fetchers/fetchEthPrice.ts

This file was deleted.

43 changes: 0 additions & 43 deletions src/data-layer/fetchers/fetchEthereumMarketcap.ts

This file was deleted.

89 changes: 89 additions & 0 deletions src/data-layer/fetchers/fetchEthereumMetrics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import type { EthPriceData, MetricReturnData } from "@/lib/types"

import { fetchRetry } from "./fetchRetry"

type SuccessfulEthPriceData = Extract<EthPriceData, { value: number }>
type SuccessfulMetricReturnData = Extract<
MetricReturnData,
{ value: number }
>

interface CoinGeckoEthereumResponse {
ethereum?: {
usd?: number
usd_24h_change?: number | null
usd_market_cap?: number
}
}

export interface EthereumMetricsData {
ethPrice: SuccessfulEthPriceData
ethereumMarketcap: SuccessfulMetricReturnData
}

export function parseEthereumMetrics(
data: CoinGeckoEthereumResponse,
timestamp = Date.now()
): EthereumMetricsData {
const { usd, usd_24h_change, usd_market_cap } = data.ethereum ?? {}

if (typeof usd !== "number" || !Number.isFinite(usd)) {
throw new Error("Unable to fetch ETH price from CoinGecko")
}

if (
typeof usd_market_cap !== "number" ||
!Number.isFinite(usd_market_cap)
) {
throw new Error("Unable to fetch ETH market cap from CoinGecko")
}

const percentChange24h =
typeof usd_24h_change === "number" && Number.isFinite(usd_24h_change)
? usd_24h_change / 100
: undefined

return {
ethPrice: { value: usd, timestamp, percentChange24h },
ethereumMarketcap: { value: usd_market_cap, timestamp },
}
}

/**
* Fetch Ethereum price, 24-hour change, and market cap in one CoinGecko call.
*/
export async function fetchEthereumMetrics(): Promise<EthereumMetricsData> {
const apiKey = process.env.COINGECKO_API_KEY
const params = new URLSearchParams({
ids: "ethereum",
vs_currencies: "usd",
include_24hr_change: "true",
include_market_cap: "true",
})
const url = `https://api.coingecko.com/api/v3/simple/price?${params}`

console.log("Starting Ethereum metrics fetch")

const response = await fetchRetry(url, {
headers: apiKey ? { "x-cg-demo-api-key": apiKey } : undefined,
})

if (!response.ok) {
const { status } = response
console.warn("CoinGecko fetch non-OK", { status })
throw new Error(`CoinGecko responded with status ${status}`)
}

const metrics = parseEthereumMetrics(
(await response.json()) as CoinGeckoEthereumResponse
)

console.log("Successfully fetched Ethereum metrics", {
price: metrics.ethPrice.value,
percentChange24h: metrics.ethPrice.percentChange24h,
marketCap: metrics.ethereumMarketcap.value,
timestamp: metrics.ethPrice.timestamp,
})

return metrics
}
28 changes: 23 additions & 5 deletions src/data-layer/tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* Hourly tasks run every hour.
*/

import * as Sentry from "@sentry/nextjs"

Check failure on line 9 in src/data-layer/tasks.ts

View workflow job for this annotation

GitHub Actions / Lint, type-check & markdown

Run autofix to sort these imports!
import { logger, schedules, task, tasks } from "@trigger.dev/sdk/v3"

import { fetchDeveloperTools } from "./fetchers/developer-tools"
Expand All @@ -15,9 +15,8 @@
import { fetchBlobStats } from "./fetchers/fetchBlobStats"
import { fetchCalendarEvents } from "./fetchers/fetchCalendarEvents"
import { fetchCommunityPicks } from "./fetchers/fetchCommunityPicks"
import { fetchEthereumMarketcap } from "./fetchers/fetchEthereumMarketcap"
import { fetchEthereumStablecoinsMcap } from "./fetchers/fetchEthereumStablecoinsMcap"
import { fetchEthPrice } from "./fetchers/fetchEthPrice"
import { fetchEthereumMetrics } from "./fetchers/fetchEthereumMetrics"
import { fetchEvents } from "./fetchers/fetchEvents"
import { fetchGasPrice } from "./fetchers/fetchGasPrice"
import { fetchGFIs } from "./fetchers/fetchGFIs"
Expand Down Expand Up @@ -96,9 +95,7 @@
]

const HOURLY: TaskDef[] = [
[KEYS.ETHEREUM_MARKETCAP, fetchEthereumMarketcap],
[KEYS.ETHEREUM_STABLECOINS_MCAP, fetchEthereumStablecoinsMcap],
[KEYS.ETH_PRICE, fetchEthPrice],
[KEYS.GAS_PRICE, fetchGasPrice],
[KEYS.TOTAL_ETH_STAKED, fetchTotalEthStaked],
[KEYS.TOTAL_VALUE_LOCKED, fetchTotalValueLocked],
Expand All @@ -124,9 +121,30 @@
})
}

const ethereumMetricsFetchTask = task({
id: KEYS.ETH_PRICE,
retry: {
maxAttempts: 2,
},
catchError: async ({ error }) => {
logger.error(`[${KEYS.ETH_PRICE}] failed`, { error })
},
run: async () => {
const { ethPrice, ethereumMarketcap } = await fetchEthereumMetrics()

await Promise.all([
set(KEYS.ETH_PRICE, ethPrice),
set(KEYS.ETHEREUM_MARKETCAP, ethereumMarketcap),
])

logger.info(`Stored ${KEYS.ETH_PRICE} + ${KEYS.ETHEREUM_MARKETCAP}`)
return { keys: [KEYS.ETH_PRICE, KEYS.ETHEREUM_MARKETCAP] }
},
})

const weeklyFetchTasks = WEEKLY.map(createDataTask)
const dailyFetchTasks = DAILY.map(createDataTask)
const hourlyFetchTasks = HOURLY.map(createDataTask)
const hourlyFetchTasks = [ethereumMetricsFetchTask, ...HOURLY.map(createDataTask)]

// Must export for trigger.dev to discover
export const allFetchTasks = [
Expand Down
46 changes: 46 additions & 0 deletions tests/unit/data-layer/fetchEthereumMetrics.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { expect, test } from "@playwright/test"

import { parseEthereumMetrics } from "@/data-layer/fetchers/fetchEthereumMetrics"

test.describe("parseEthereumMetrics", () => {
test("maps one CoinGecko response to both stored metric formats", () => {
const timestamp = 1_700_000_000_000
const result = parseEthereumMetrics(
{
ethereum: {
usd: 3_500,
usd_24h_change: 2.5,
usd_market_cap: 420_000_000_000,
},
},
timestamp
)

expect(result.ethPrice).toEqual({
value: 3_500,
timestamp,
percentChange24h: 0.025,
})
expect(result.ethereumMarketcap).toEqual({
value: 420_000_000_000,
timestamp,
})
})

test("allows CoinGecko to omit the 24-hour change", () => {
const result = parseEthereumMetrics({
ethereum: { usd: 3_500, usd_market_cap: 420_000_000_000 },
})

expect(result.ethPrice.percentChange24h).toBeUndefined()
})

for (const [name, response] of [
["price", { ethereum: { usd_market_cap: 420_000_000_000 } }],
["market cap", { ethereum: { usd: 3_500 } }],
] as const) {
test(`rejects a response without a valid ${name}`, () => {
expect(() => parseEthereumMetrics(response)).toThrow()
})
}
})
Loading