Skip to content

Conversation

@iuwqyir
Copy link
Contributor

@iuwqyir iuwqyir commented Jul 22, 2025

Add ClickHouse Projections and Token Transfers Table

TL;DR

Added projections to existing ClickHouse tables and created a new token_transfers table with materialized view to improve query performance.

What changed?

  • Added logs_chainid_topic0_address projection to the logs table to optimize queries filtering by chain_id, topic_0, and address
  • Added address_projection to the token_balances table to improve queries filtering by token_type, chain_id, and address
  • Created new token_transfers table with three projections (from_address, to_address, transaction_hash) to efficiently track token transfers
  • Added materialized view logs_to_token_transfers that transforms logs into token transfer records
  • Added projections to the transactions table for queries filtering by chain_id with from_address or to_address
  • Updated table settings to properly handle projections during mutations and deduplication

How to test?

  1. Apply the SQL changes to your ClickHouse instance
  2. Verify the new projections are created by running:
    SHOW PROJECTIONS FROM logs;
    SHOW PROJECTIONS FROM token_balances;
    SHOW PROJECTIONS FROM transactions;
  3. Verify the new token_transfers table and materialized view:
    SHOW TABLES LIKE '%token_transfers%';
  4. Run queries that filter by the projected columns and confirm improved performance

Why make this change?

ClickHouse projections provide pre-sorted data structures that significantly improve query performance for specific access patterns. The added projections optimize common query patterns like:

  • Finding logs by chain_id, topic_0 (event signature), and contract address
  • Querying token balances by token type, chain, and contract address
  • Retrieving transactions by sender or recipient address
  • Efficiently tracking token transfers with optimized access by sender, recipient, or transaction hash

These changes will reduce query latency and resource consumption for these common access patterns.

Summary by CodeRabbit

  • New Features

    • Introduced a new table for tracking token transfer events, enabling more efficient and comprehensive querying of token transfers.
    • Added a materialized view to automatically populate token transfer data from raw logs, supporting multiple token standards and batch transfers.
  • Performance Improvements

    • Added new projections to logs, token balances, and transactions tables to optimize query performance for common access patterns.
    • Updated table settings to enhance data deduplication and mutation efficiency.

@coderabbitai
Copy link

coderabbitai bot commented Jul 22, 2025

Walkthrough

Several ClickHouse SQL scripts were updated to enhance table definitions with new projections and table settings, optimizing data ordering and mutation handling. Additionally, a new token_transfers table and its associated materialized view were introduced to process and store token transfer events extracted from blockchain logs, including logic for parsing ERC-20, ERC-721, and ERC-1155 events.

Changes

File(s) Change Summary
internal/tools/clickhouse_create_logs_table.sql
internal/tools/clickhouse_create_transactions_table.sql
Added new projections to logs and transactions tables with specific ordering clauses. Updated table settings for deduplication and mutation handling. Reformatted PARTITION BY clauses.
internal/tools/clickhouse_create_token_balances_mv.sql Added a projection address_projection to the token_balances table with ordering on (token_type, chain_id, address, token_id). Set table settings for index_granularity and lightweight_mutation_projection_mode.
internal/tools/clickhouse_create_token_transfers_mv.sql Introduced a new token_transfers table with projections, and a materialized view logs_to_token_transfers that extracts and processes token transfer events (ERC-20, ERC-721, ERC-1155) from logs, including logic for parsing and expanding batch transfers.

Sequence Diagram(s)

sequenceDiagram
    participant LogsTable as logs
    participant TokenTransfersMV as logs_to_token_transfers (MV)
    participant TokenTransfersTable as token_transfers

    LogsTable->>TokenTransfersMV: Insert new log entry
    TokenTransfersMV->>TokenTransfersMV: Filter and parse log (ERC-20/721/1155)
    TokenTransfersMV->>TokenTransfersMV: Extract addresses, token ids, amounts
    TokenTransfersMV->>TokenTransfersTable: Insert parsed transfer event(s)
Loading

Estimated code review effort

4 (~90 minutes)


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor Author

iuwqyir commented Jul 22, 2025

This stack of pull requests is managed by Graphite. Learn more about stacking.

@iuwqyir iuwqyir marked this pull request as ready for review July 22, 2025 18:23
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
internal/tools/clickhouse_create_logs_table.sql (1)

25-35: Solid projection but consider swapping topic_0 and address if address-centric queries dominate

Current order: (chain_id, topic_0, address, block_number, …).
If the most frequent pattern is “all events for contract X on chain Y”, putting address before topic_0 will prune more quickly. Worth validating with real query stats; otherwise LGTM.

internal/tools/clickhouse_create_token_transfers_mv.sql (1)

69-91: Repeated sub-query logic duplicates effort – extract CTE or reuse

transfer_logs is defined twice (before and after UNION ALL). Duplicating the heavy logic doubles parse & compile time and makes maintenance error-prone.
Extract once and reuse, or perform the batch/regular split via a single SELECT with conditional array join.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 513dd51 and f4d13a5.

📒 Files selected for processing (4)
  • internal/tools/clickhouse_create_logs_table.sql (1 hunks)
  • internal/tools/clickhouse_create_token_balances_mv.sql (1 hunks)
  • internal/tools/clickhouse_create_token_transfers_mv.sql (1 hunks)
  • internal/tools/clickhouse_create_transactions_table.sql (1 hunks)
🔇 Additional comments (6)
internal/tools/clickhouse_create_transactions_table.sql (2)

50-58: Nice: second projection already contains hash – covers chain_id+to_address+hash look-ups.
No action needed here.


61-62: Double-check new table-level settings on prod volumes

deduplicate_merge_projection_mode='drop' + lightweight_mutation_projection_mode='rebuild' can noticeably increase merge-tree write amplification and mutation cost on tens-of-TB partitions. Make sure this was load-tested (at least on staging) or gate-keep behind a feature flag.

internal/tools/clickhouse_create_logs_table.sql (1)

38-40: Same caution on merge-tree settings as in transactions

Verify the write / compact performance with the new projection-aware mutation modes.

internal/tools/clickhouse_create_token_balances_mv.sql (1)

20-21: 👍 Explicit index_granularity + mutation mode – consistent with other tables

internal/tools/clickhouse_create_token_transfers_mv.sql (2)

3-15: Type mismatch: amount cannot store negatives but you rely on sign only

amount is declared UInt256; the MV never stores negative values, relying on sign for direction – that’s OK. Just confirm downstream consumers always multiply by sign when computing net flows.


16-45: Nice trio of projections – covers from / to / tx-hash predicates

@iuwqyir iuwqyir merged commit 6e554a8 into main Jul 22, 2025
6 checks passed
@iuwqyir iuwqyir deleted the 07-21-update_clickhouse_schemas_to_latest_state branch July 22, 2025 18:33
@coderabbitai coderabbitai bot mentioned this pull request Aug 28, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants