query-onchain-data

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Query Onchain Data on Base

查询Base链上数据

Use the CDP SQL API to query onchain data (events, transactions, blocks, transfers) on Base. Queries are executed via x402 and are charged per query.
使用CDP SQL API查询Base链上的链上数据(事件、交易、区块、转账)。查询通过x402执行,按次收费。

Confirm wallet is initialized and authed

确认钱包已初始化并完成认证

bash
npx awal@latest status
If the wallet is not authenticated, refer to the
authenticate-wallet
skill.
bash
npx awal@latest status
如果钱包未完成认证,请参考
authenticate-wallet
技能。

Executing a Query

执行查询

bash
npx awal@latest x402 pay https://x402.cdp.coinbase.com/platform/v2/data/query/run -X POST -d '{"sql": "<YOUR_QUERY>"}' --json
IMPORTANT: Always single-quote the
-d
JSON string to prevent bash variable expansion.
bash
npx awal@latest x402 pay https://x402.cdp.coinbase.com/platform/v2/data/query/run -X POST -d '{"sql": "<YOUR_QUERY>"}' --json
重要提示:始终对
-d
后的JSON字符串使用单引号,以避免bash变量展开。

CRITICAL: Indexed Fields

关键注意事项:索引字段

Queries against
base.events
MUST filter on indexed fields to avoid full table scans. The indexed fields are:
Indexed FieldUse For
event_signature
Filter by event type. Use this instead of
event_name
for performance.
address
Filter by contract address.
block_timestamp
Filter by time range.
Always include at least one indexed field in your WHERE clause. Combining all three gives the best performance.
针对
base.events
的查询必须过滤索引字段,以避免全表扫描。索引字段如下:
索引字段用途
event_signature
按事件类型过滤。为提升性能,请使用此字段而非
event_name
address
按合约地址过滤。
block_timestamp
按时间范围过滤。
请始终在WHERE子句中包含至少一个索引字段。同时使用三个字段可获得最佳性能。

CoinbaseQL Syntax

CoinbaseQL语法

CoinbaseQL is a SQL dialect based on ClickHouse. Supported features:
  • Clauses: SELECT (DISTINCT), FROM, WHERE, GROUP BY, ORDER BY (ASC/DESC), LIMIT, WITH (CTEs), UNION (ALL/DISTINCT)
  • Joins: INNER, LEFT, RIGHT, FULL with ON
  • Operators:
    =
    ,
    !=
    ,
    <>
    ,
    <
    ,
    >
    ,
    <=
    ,
    >=
    ,
    +
    ,
    -
    ,
    *
    ,
    /
    ,
    %
    , AND, OR, NOT, BETWEEN, IN, IS NULL, LIKE
  • Expressions: CASE/WHEN/THEN/ELSE, CAST (both
    CAST()
    and
    ::
    syntax), subqueries, array/map indexing with
    []
    , dot notation
  • Literals: Array
    [...]
    , Map
    {...}
    , Tuple
    (...)
  • Functions: Standard SQL functions, lambda functions with
    ->
    syntax
CoinbaseQL是基于ClickHouse的SQL方言。支持的特性包括:
  • 子句:SELECT(DISTINCT)、FROM、WHERE、GROUP BY、ORDER BY(ASC/DESC)、LIMIT、WITH(CTE)、UNION(ALL/DISTINCT)
  • 连接:INNER、LEFT、RIGHT、FULL JOIN(带ON条件)
  • 运算符
    =
    ,
    !=
    ,
    <>
    ,
    <
    ,
    >
    ,
    <=
    ,
    >=
    ,
    +
    ,
    -
    ,
    *
    ,
    /
    ,
    %
    , AND, OR, NOT, BETWEEN, IN, IS NULL, LIKE
  • 表达式:CASE/WHEN/THEN/ELSE、CAST(支持
    CAST()
    ::
    语法)、子查询、使用
    []
    的数组/映射索引、点表示法
  • 字面量:数组
    [...]
    、映射
    {...}
    、元组
    (...)
  • 函数:标准SQL函数、使用
    ->
    语法的Lambda函数

Available Tables

可用表

base.events

base.events

Decoded event logs from smart contract interactions. This is the primary table for most queries.
ColumnTypeDescription
log_idStringUnique log identifier
block_numberUInt64Block number
block_hashFixedString(66)Block hash
block_timestampDateTime64(3, 'UTC')Block timestamp (INDEXED)
transaction_hashFixedString(66)Transaction hash
transaction_toFixedString(42)Transaction recipient
transaction_fromFixedString(42)Transaction sender
log_indexUInt32Log index within block
addressFixedString(42)Contract address (INDEXED)
topicsArray(FixedString(66))Event topics
event_nameLowCardinality(String)Decoded event name
event_signatureLowCardinality(String)Event signature (INDEXED - prefer over event_name)
parametersMap(String, Variant(Bool, Int256, String, UInt256))Decoded event parameters
parameter_typesMap(String, String)ABI types for parameters
actionEnum8('removed' = -1, 'added' = 1)Added or removed (reorg)
智能合约交互的已解析事件日志。这是大多数查询的主表
列名类型描述
log_idString唯一日志标识符
block_numberUInt64区块编号
block_hashFixedString(66)区块哈希
block_timestampDateTime64(3, 'UTC')区块时间戳(已索引
transaction_hashFixedString(66)交易哈希
transaction_toFixedString(42)交易接收方
transaction_fromFixedString(42)交易发送方
log_indexUInt32区块内的日志索引
addressFixedString(42)合约地址(已索引
topicsArray(FixedString(66))事件主题
event_nameLowCardinality(String)已解析的事件名称
event_signatureLowCardinality(String)事件签名(已索引 - 优先于event_name使用)
parametersMap(String, Variant(Bool, Int256, String, UInt256))已解析的事件参数
parameter_typesMap(String, String)参数的ABI类型
actionEnum8('removed' = -1, 'added' = 1)新增或移除(重组)

base.transactions

base.transactions

Complete transaction data.
ColumnTypeDescription
block_numberUInt64Block number
block_hashStringBlock hash
transaction_hashStringTransaction hash
transaction_indexUInt64Index in block
from_addressStringSender address
to_addressStringRecipient address
valueStringValue transferred (wei)
gasUInt64Gas limit
gas_priceUInt64Gas price
inputStringInput data
nonceUInt64Sender nonce
typeUInt64Transaction type
max_fee_per_gasUInt64EIP-1559 max fee
max_priority_fee_per_gasUInt64EIP-1559 priority fee
chain_idUInt64Chain ID
vStringSignature v
rStringSignature r
sStringSignature s
is_system_txBoolSystem transaction flag
max_fee_per_blob_gasStringBlob gas fee
blob_versioned_hashesArray(String)Blob hashes
timestampDateTimeBlock timestamp
actionInt8Added (1) or removed (-1)
完整的交易数据。
列名类型描述
block_numberUInt64区块编号
block_hashString区块哈希
transaction_hashString交易哈希
transaction_indexUInt64区块内的索引
from_addressString发送方地址
to_addressString接收方地址
valueString转账金额(wei)
gasUInt64燃气限额
gas_priceUInt64燃气价格
inputString输入数据
nonceUInt64发送方随机数
typeUInt64交易类型
max_fee_per_gasUInt64EIP-1559最高燃气费
max_priority_fee_per_gasUInt64EIP-1559优先燃气费
chain_idUInt64链ID
vString签名v值
rString签名r值
sString签名s值
is_system_txBool系统交易标记
max_fee_per_blob_gasStringBlob燃气费
blob_versioned_hashesArray(String)Blob哈希
timestampDateTime区块时间戳
actionInt8新增(1)或移除(-1)

base.blocks

base.blocks

Block-level metadata.
ColumnTypeDescription
block_numberUInt64Block number
block_hashStringBlock hash
parent_hashStringParent block hash
timestampDateTimeBlock timestamp
minerStringBlock producer
nonceUInt64Block nonce
sha3_unclesStringUncles hash
transactions_rootStringTransactions merkle root
state_rootStringState merkle root
receipts_rootStringReceipts merkle root
logs_bloomStringBloom filter
gas_limitUInt64Block gas limit
gas_usedUInt64Gas used in block
base_fee_per_gasUInt64Base fee per gas
total_difficultyStringTotal chain difficulty
sizeUInt64Block size in bytes
extra_dataStringExtra data field
mix_hashStringMix hash
withdrawals_rootStringWithdrawals root
parent_beacon_block_rootStringBeacon chain parent root
blob_gas_usedUInt64Blob gas used
excess_blob_gasUInt64Excess blob gas
transaction_countUInt64Number of transactions
actionInt8Added (1) or removed (-1)
区块级元数据。
列名类型描述
block_numberUInt64区块编号
block_hashString区块哈希
parent_hashString父区块哈希
timestampDateTime区块时间戳
minerString区块生产者
nonceUInt64区块随机数
sha3_unclesString叔块哈希
transactions_rootString交易默克尔根
state_rootString状态默克尔根
receipts_rootString收据默克尔根
logs_bloomString布隆过滤器
gas_limitUInt64区块燃气限额
gas_usedUInt64区块内已使用燃气
base_fee_per_gasUInt64基础燃气费
total_difficultyString链总难度
sizeUInt64区块大小(字节)
extra_dataString额外数据字段
mix_hashString混合哈希
withdrawals_rootString提款根
parent_beacon_block_rootString信标链父根
blob_gas_usedUInt64已使用Blob燃气
excess_blob_gasUInt64剩余Blob燃气
transaction_countUInt64交易数量
actionInt8新增(1)或移除(-1)

Example Queries

查询示例

Get recent USDC Transfer events with decoded parameters

获取最近7天带解析参数的USDC转账事件

sql
SELECT
  parameters['from'] AS sender,
  parameters['to'] AS to,
  parameters['value'] AS amount,
  address AS token_address
FROM base.events
WHERE
  event_signature = 'Transfer(address,address,uint256)'
  AND address = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'
  AND block_timestamp >= now() - INTERVAL 7 DAY
LIMIT 10
sql
SELECT
  parameters['from'] AS sender,
  parameters['to'] AS to,
  parameters['value'] AS amount,
  address AS token_address
FROM base.events
WHERE
  event_signature = 'Transfer(address,address,uint256)'
  AND address = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'
  AND block_timestamp >= now() - INTERVAL 7 DAY
LIMIT 10

Get transactions from a specific address

获取特定地址的交易记录

bash
npx awal@latest x402 pay https://x402.cdp.coinbase.com/platform/v2/data/query/run -X POST -d '{"sql": "SELECT transaction_hash, to_address, value, gas, timestamp FROM base.transactions WHERE from_address = lower('\''0xYOUR_ADDRESS'\'') AND timestamp >= now() - INTERVAL 1 DAY LIMIT 10"}' --json
bash
npx awal@latest x402 pay https://x402.cdp.coinbase.com/platform/v2/data/query/run -X POST -d '{"sql": "SELECT transaction_hash, to_address, value, gas, timestamp FROM base.transactions WHERE from_address = lower('\''0xYOUR_ADDRESS'\'') AND timestamp >= now() - INTERVAL 1 DAY LIMIT 10"}' --json

Count events by type for a contract in the last hour

统计最近1小时内某合约的事件类型数量

bash
npx awal@latest x402 pay https://x402.cdp.coinbase.com/platform/v2/data/query/run -X POST -d '{"sql": "SELECT event_signature, count(*) as cnt FROM base.events WHERE address = lower('\''0xCONTRACT_ADDRESS'\'') AND block_timestamp >= now() - INTERVAL 1 HOUR GROUP BY event_signature ORDER BY cnt DESC LIMIT 20"}' --json
bash
npx awal@latest x402 pay https://x402.cdp.coinbase.com/platform/v2/data/query/run -X POST -d '{"sql": "SELECT event_signature, count(*) as cnt FROM base.events WHERE address = lower('\''0xCONTRACT_ADDRESS'\'') AND block_timestamp >= now() - INTERVAL 1 HOUR GROUP BY event_signature ORDER BY cnt DESC LIMIT 20"}' --json

Get latest block info

获取最新区块信息

bash
npx awal@latest x402 pay https://x402.cdp.coinbase.com/platform/v2/data/query/run -X POST -d '{"sql": "SELECT block_number, timestamp, transaction_count, gas_used FROM base.blocks ORDER BY block_number DESC LIMIT 1"}' --json
bash
npx awal@latest x402 pay https://x402.cdp.coinbase.com/platform/v2/data/query/run -X POST -d '{"sql": "SELECT block_number, timestamp, transaction_count, gas_used FROM base.blocks ORDER BY block_number DESC LIMIT 1"}' --json

Common Contract Addresses (Base)

Base链常用合约地址

TokenAddress
USDC
0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
WETH
0x4200000000000000000000000000000000000006
代币地址
USDC
0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
WETH
0x4200000000000000000000000000000000000006

Best Practices

最佳实践

  1. Always filter on indexed fields (
    event_signature
    ,
    address
    ,
    block_timestamp
    ) in
    base.events
    queries.
  2. Never use
    SELECT *
    - specify only the columns you need.
  3. Always include a
    LIMIT
    clause to bound result size.
  4. Use
    event_signature
    instead of
    event_name
    for filtering - it is indexed and much faster.
  5. Use time-bounded queries with
    block_timestamp
    to narrow the scan range.
  6. Always wrap address values in
    lower()
    - the database stores lowercase addresses but users may provide checksummed (mixed-case) addresses. Use
    address = lower('0xAbC...')
    not
    address = '0xAbC...'
    .
  7. Common event signatures:
    Transfer(address,address,uint256)
    ,
    Approval(address,address,uint256)
    ,
    Swap(address,uint256,uint256,uint256,uint256,address)
    .
  1. 始终过滤索引字段:在
    base.events
    查询中使用
    event_signature
    address
    block_timestamp
  2. 切勿使用
    SELECT *
    :仅指定你需要的列
  3. 始终包含
    LIMIT
    子句
    :限制结果集大小
  4. 优先使用
    event_signature
    而非
    event_name
    过滤
    :它已被索引,速度更快
  5. 使用时间范围查询:通过
    block_timestamp
    缩小扫描范围
  6. 始终用
    lower()
    包裹地址值
    :数据库存储小写地址,但用户可能提供校验和格式(大小写混合)的地址。请使用
    address = lower('0xAbC...')
    而非
    address = '0xAbC...'
  7. 常见事件签名
    Transfer(address,address,uint256)
    Approval(address,address,uint256)
    Swap(address,uint256,uint256,uint256,uint256,address)

Prerequisites

前置条件

  • Must be authenticated (
    npx awal@latest status
    to check, see
    authenticate-wallet
    skill)
  • Wallet must have sufficient USDC balance (
    npx awal@latest balance
    to check)
  • Each query costs $0.10 (100000 USDC atomic units)
  • 必须完成认证(使用
    npx awal@latest status
    检查,参考
    authenticate-wallet
    技能)
  • 钱包必须有足够的USDC余额(使用
    npx awal@latest balance
    检查)
  • 每次查询费用为0.10美元(100000 USDC最小单位)

Error Handling

错误处理

  • "Not authenticated" - Run
    awal auth login <email>
    first, or see
    authenticate-wallet
    skill
  • "Insufficient balance" - Fund wallet with USDC; see
    fund
    skill
  • Query timeout or error - Ensure you are filtering on indexed fields and using a LIMIT
  • "Not authenticated"(未认证):先运行
    awal auth login <email>
    ,或参考
    authenticate-wallet
    技能
  • "Insufficient balance"(余额不足):为钱包充值USDC;参考
    fund
    技能
  • 查询超时或出错:确保你正在过滤索引字段并使用了LIMIT子句