-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Add Clickhouse Client #4602
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
Open
0xpeluche
wants to merge
6
commits into
DefiLlama:master
Choose a base branch
from
0xpeluche:add_clickhouse_client
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+206
−4,406
Open
Add Clickhouse Client #4602
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
c994c96
add clickhouse client
0xpeluche 33aab8a
Merge branch 'master' into add_clickhouse_client
0xpeluche 5d1abd6
.
0xpeluche 98160b2
Merge branch 'add_clickhouse_client' of https://github.com/0xpeluche/…
0xpeluche e428bd7
fix
0xpeluche 926c661
Delete package-lock.json
0xpeluche File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| import { Row } from "@clickhouse/client" | ||
| import { FetchOptions, ProtocolType, Adapter } from "../../adapters/types"; | ||
| import { METRIC } from "../../helpers/metrics"; | ||
| import { queryClickhouse } from "../../helpers/clickhouse"; | ||
| import { CHAIN } from "../../helpers/chains"; | ||
|
|
||
| type FeesRow = Row & { | ||
| total_fees_wei: string; | ||
| base_burn_wei: string; | ||
| }; | ||
|
|
||
| export const SQL_BLOCK_RANGE = ` | ||
| SELECT | ||
| CAST( | ||
| sum(toDecimal256(effective_gas_price, 0) * toDecimal256(gas_used, 0)) | ||
| AS String | ||
| ) AS total_fees_wei, | ||
| CAST( | ||
| sum(toDecimal256(base_fee_per_gas, 0) * toDecimal256(gas_used, 0)) | ||
| AS String | ||
| ) AS base_burn_wei | ||
| FROM evm_indexer.transactions | ||
| WHERE | ||
| chain = {chain:UInt64} | ||
| AND block_number >= {fromBlock:UInt32} | ||
| AND block_number < {toBlock:UInt32} | ||
| `; | ||
|
|
||
| export const fetch = async (options: FetchOptions) => { | ||
| const chainId = options.api.chainId | ||
| const fromBlock = await options.getFromBlock() | ||
| const _toBlock = await options.getToBlock() | ||
| const safeBlock = _toBlock - 150 | ||
|
|
||
| if (safeBlock <= fromBlock) { | ||
| const dailyFees = options.createBalances(); | ||
| const dailyRevenue = options.createBalances(); | ||
| return { dailyFees, dailyRevenue, dailyHoldersRevenue: dailyRevenue }; | ||
| } | ||
|
|
||
| const rows = await queryClickhouse<FeesRow>(SQL_BLOCK_RANGE, { | ||
| chain: chainId, | ||
| fromBlock, | ||
| toBlock: safeBlock, | ||
| }); | ||
|
|
||
| const totalFeesWei = BigInt(rows?.[0]?.total_fees_wei ?? "0"); | ||
| const baseFeesWei = BigInt(rows?.[0]?.base_burn_wei ?? "0"); | ||
| const priorityWei = totalFeesWei - baseFeesWei; | ||
|
|
||
| const dailyFees = options.createBalances(); | ||
| const dailyRevenue = options.createBalances(); | ||
|
|
||
| dailyFees.addGasToken(baseFeesWei, METRIC.TRANSACTION_BASE_FEES); | ||
| dailyFees.addGasToken(priorityWei, METRIC.TRANSACTION_PRIORITY_FEES); | ||
| dailyRevenue.addGasToken(baseFeesWei, METRIC.TRANSACTION_BASE_FEES); | ||
|
|
||
| return { dailyFees, dailyRevenue, dailyHoldersRevenue: dailyRevenue }; | ||
| } | ||
|
|
||
| const adapter: Adapter = { | ||
| version: 2, | ||
| adapter: { | ||
| [CHAIN.ETHEREUM]: { | ||
| fetch, | ||
| start: '2015-07-30', | ||
| }, | ||
| }, | ||
| protocolType: ProtocolType.CHAIN, | ||
| methodology: { | ||
| Fees: 'Total ETH gas fees (including base fees and priority fees) paid by users', | ||
| Revenue: 'Amount of ETH base fees that were burned', | ||
| HoldersRevenue: 'Amount of ETH base fees that were burned', | ||
| }, | ||
| breakdownMethodology: { | ||
| Fees: { | ||
| [METRIC.TRANSACTION_BASE_FEES]: 'Total ETH base fees paid by users', | ||
| [METRIC.TRANSACTION_PRIORITY_FEES]: 'Total ETH priority fees paid by users', | ||
| }, | ||
| Revenue: { | ||
| [METRIC.TRANSACTION_BASE_FEES]: 'Total ETH base fees will be burned', | ||
| }, | ||
| HoldersRevenue: { | ||
| [METRIC.TRANSACTION_BASE_FEES]: 'Total ETH base fees will be burned', | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| export default adapter; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import { ClickHouseClient, createClient, Row } from "@clickhouse/client"; | ||
|
|
||
| let client: ClickHouseClient | null = null; | ||
| let connectionPromise: Promise<ClickHouseClient> | null = null; | ||
| let hooksInstalled = false; | ||
|
|
||
| type ClickhouseConfig = { | ||
| host: string; | ||
| port: number | string; | ||
| database: string; | ||
| username: string; | ||
| password: string; | ||
| }; | ||
|
|
||
| const DEFAULT_TIMEOUT = 180_000; | ||
| const DEFAULT_MAX_CONN = 10; | ||
| const DEFAULT_KEEPALIVE_TTL = 180_000; | ||
|
|
||
| function readConfig(): ClickhouseConfig { | ||
| const raw = process.env.CLICKHOUSE_CONFIG; | ||
| if (!raw) throw new Error("Missing CLICKHOUSE_CONFIG."); | ||
|
|
||
| const cfg = JSON.parse(raw) as Partial<ClickhouseConfig>; | ||
|
|
||
| if (!cfg.host || !cfg.port || !cfg.database || !cfg.username || !cfg.password) { | ||
| throw new Error('CLICKHOUSE_CONFIG must include "host","port","database","username","password".'); | ||
| } | ||
|
|
||
| return { | ||
| host: cfg.host, | ||
| port: cfg.port, | ||
| database: cfg.database, | ||
| username: cfg.username, | ||
| password: cfg.password, | ||
| }; | ||
| } | ||
|
|
||
| function buildUrl(cfg: ClickhouseConfig): string { | ||
| return `http://${cfg.host}:${cfg.port}`; | ||
| } | ||
|
|
||
|
|
||
| function installShutdownHooks() { | ||
| if (hooksInstalled) return; | ||
| hooksInstalled = true; | ||
|
|
||
| const cleanup = async () => { try { await disconnectClickhouse(); } catch {} }; | ||
|
|
||
| ["SIGINT", "SIGTERM", "SIGHUP"].forEach((sig) => process.once(sig, () => { void cleanup().then(() => process.exit(0)) })); | ||
| process.once("beforeExit", () => { void cleanup() }); | ||
| process.once("uncaughtException", () => { void cleanup().then(() => process.exit(1)) }); | ||
| process.once("unhandledRejection", () => { void cleanup().then(() => process.exit(1)) }); | ||
| } | ||
|
|
||
| export async function connectClickhouse(): Promise<ClickHouseClient> { | ||
| if (client) return client; | ||
| if (connectionPromise) return connectionPromise; | ||
|
|
||
| installShutdownHooks(); | ||
|
|
||
| connectionPromise = (async () => { | ||
| const cfg = readConfig(); | ||
| const url = buildUrl(cfg); | ||
|
|
||
| const _client = createClient({ | ||
| url, | ||
| username: cfg.username, | ||
| password: cfg.password, | ||
| database: cfg.database, | ||
| request_timeout: DEFAULT_TIMEOUT, | ||
| max_open_connections: DEFAULT_MAX_CONN, | ||
| keep_alive: { enabled: true, idle_socket_ttl: DEFAULT_KEEPALIVE_TTL }, | ||
| compression: { response: true, request: false }, | ||
| }); | ||
|
|
||
| await _client.ping(); | ||
| client = _client; | ||
| return _client; | ||
| })(); | ||
|
|
||
| return connectionPromise; | ||
| } | ||
|
|
||
| export async function queryClickhouse<T extends Row>(sql: string, params?: Record<string, unknown>): Promise<T[]> { | ||
| const c = await connectClickhouse(); | ||
| const rs = await c.query({ query: sql, query_params: params, format: "JSONEachRow" }); | ||
| return rs.json<T>(); | ||
| } | ||
|
|
||
| export async function disconnectClickhouse() { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. please add auto disconnect on exit event |
||
| if (!client) return; | ||
| try { await client.close(); } | ||
| finally { client = null; connectionPromise = null; } | ||
| } | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -69,6 +69,11 @@ export const ENV_KEYS = new Set([ | |
| 'DUNE_BULK_MODE', | ||
| 'DUNE_BULK_MODE_BATCH_TIME', | ||
| 'LLAMA_HL_INDEXER', | ||
| 'CLICKHOUSE_HOST', | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I prefer a single env var, can be a json string, check what we are doing in server repo |
||
| 'CLICKHOUSE_PORT', | ||
| 'CLICKHOUSE_USERNAME', | ||
| 'CLICKHOUSE_PASSWORD', | ||
| 'CLICKHOUSE_DATABASE' | ||
| ]) | ||
|
|
||
| // This is done to support both ZEROx_API_KEY and ZEROX_API_KEY | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
wondering if should move this to @defillama/sdk repo
this way, code is not repeated