Dune Analytics API
A skill for querying and analyzing blockchain data via the Dune Analytics API.
Local Query Registry Integration (dq)
Some machines maintain a local Dune Query Registry — a git repo of query
assets managed by the dq CLI, recognizable by a registry.yaml plus a
queries/ directory (the root may also be pointed to by the DQ_ROOT env
var).
If such a registry exists, query WRITE operations are hard-constrained to
go through dq so local and online copies never drift:
| Never do this |
Do this instead |
client.create_query(...) / POST /query |
dq create --title t --sql-file f.sql (creates on Dune + registers locally, one atomic op) |
dune_query.py update_sql / client.update_query / PATCH /query/{id} |
dq save --query-id N --sql-file f.sql --push, or dq push <id> |
dq push keeps a per-query sync fingerprint and refuses non-fast-forward
pushes (remote edited on dune.com since the last sync) — run dq pull <id>
to reconcile first. Audit drift anytime with dq sync --all. After running
a query and drawing conclusions, record them: dq note <query_id> "...".
READ operations (execute, get_latest, get_sql, table discovery, data
uploads) are unrestricted. If no dq registry exists on the machine, this
section does not apply.
Setup
pip install dune-client
Set DUNE_API_KEY via environment variable, .env file, or agent config.
Best Practices
Read references first — The reference files contain critical table names, anti-patterns, and chain-specific gotchas that aren't obvious from table names alone. Reading the right reference before writing SQL prevents common mistakes like using dex.trades for wallet analysis (which inflates volume ~30%) or missing Solana's dedup requirement.
Prefer private queries — Creating queries with is_private=True keeps the user's workspace clean and avoids polluting the public Dune namespace. Fall back to public if it fails (free plan limitation), and let the user know.
Reuse before creating — Dune charges credits per execution. Reusing or updating an existing query avoids unnecessary duplicates and makes credit tracking easier. Only create new queries when the user explicitly asks.
Confirm before updating — Modifying an existing query's SQL is destructive (previous version isn't saved by default). A quick confirmation avoids overwriting work the user might want to keep.
Track credits — Each execution costs credits depending on the performance tier and data scanned. Reporting credits consumed helps the user manage their budget. See query-execution.md.
Scripts — Common Operations
For common operations, use the scripts in scripts/ to avoid writing boilerplate code every time. All scripts read DUNE_API_KEY from the environment automatically.
| Script |
Command |
What it does |
dune_query.py |
execute --query-id ID |
Execute a saved query (supports --params, --performance, --format) |
dune_query.py |
get_latest --query-id ID |
Get cached result without re-execution |
dune_query.py |
get_sql --query-id ID |
Print query SQL |
dune_query.py |
update_sql --query-id ID --sql "..." |
Update query SQL |
dune_discover.py |
search --keyword "uniswap" |
Search tables by keyword |
dune_discover.py |
schema --table "dex.trades" |
Show table columns and types |
dune_discover.py |
list_schemas --namespace "uniswap_v3" |
List tables in a namespace |
dune_discover.py |
contract --address "0x..." |
Find decoded tables by contract address |
dune_discover.py |
docs --keyword "dex" |
Search Dune documentation |
dune_upload.py |
upload_csv --file data.csv --table-name tbl |
Quick CSV upload (overwrites) |
dune_upload.py |
create_table --table-name tbl --namespace ns --schema '[...]' |
Create table with explicit schema |
dune_upload.py |
insert --file data.csv --table-name tbl --namespace ns |
Append data to existing table |
Example:
# Execute query with parameters
python scripts/dune_query.py execute --query-id 123456 --params '{"token":"ETH"}' --format table
# Upload a CSV privately
python scripts/dune_upload.py upload_csv --file wallets.csv --table-name my_wallets --private
Reference Selection
Before writing any SQL, route to the correct reference file(s) based on your task:
| Task involves... |
Read this reference |
| Finding tables / inspecting schema / discovering protocols |
table-discovery.md |
| Finding decoded tables by contract address |
table-discovery.md |
| Searching Dune documentation / guides / examples |
table-discovery.md |
| Wallet / address tracking / router identification |
wallet-analysis.md |
| Table selection / common table names |
common-tables.md |
| SQL performance / complex joins / array ops |
sql-optimization.md |
| API calls / execution / caching / parameters |
query-execution.md |
| Uploading CSV/NDJSON data to Dune |
data-upload.md |
If your task spans multiple categories, read all relevant files. The references contain critical details (e.g., specialized tables, anti-patterns) that aren't covered in this overview — guessing table names or query patterns leads to subtle bugs.
Quick Start
from dune_client.client import DuneClient
from dune_client.query import QueryBase
import os
client = DuneClient(api_key=os.environ['DUNE_API_KEY'])
# Execute a query
result = client.run_query(query=QueryBase(query_id=123456), performance='medium', ping_frequency=5)
print(f"Rows: {len(result.result.rows)}")
# Get cached result (no re-execution)
result = client.get_latest_result(query_id=123456)
# Get/update SQL
sql = client.get_query(123456).sql
client.update_query(query_id=123456, query_sql="SELECT ...")
# Upload CSV data (quick, overwrites existing)
client.upload_csv(
data="col1,col2\nval1,val2",
description="My data",
table_name="my_table",
is_private=True
)
# Create table + insert (supports append)
client.create_table(
namespace="my_user",
table_name="my_table",
schema=[{"name": "col1", "type": "varchar"}, {"name": "col2", "type": "double"}],
is_private=True
)
import io
client.insert_data(
namespace="my_user",
table_name="my_table",
data=io.BytesIO(b"col1,col2\nabc,1.5"),
content_type="text/csv"
)
Subscription Tiers
| Method |
Description |
Plan |
run_query |
Execute saved query (supports {{param}}) |
Free |
run_sql |
Execute SQL directly (no params) |
Plus |
Key Concepts
dex.trades vs dex_aggregator.trades
| Table |
Use Case |
Volume |
dex.trades |
Per-pool analysis |
⚠️ Inflated ~30% (multi-hop counted multiple times) |
dex_aggregator.trades |
User/wallet analysis |
Accurate |
Why this matters: If you're analyzing a specific wallet's trading activity and use dex.trades, you'll see inflated volume because a single swap through an aggregator gets split into multiple pool-level trades. dex_aggregator.trades captures the user-level intent — one row per user swap. See wallet-analysis.md for full patterns.
Solana has no dex_aggregator_solana.trades. Dedupe by tx_id:
SELECT tx_id, MAX(amount_usd) as amount_usd
FROM dex_solana.trades
GROUP BY tx_id
Data Freshness
| Layer |
Delay |
Example |
| Raw |
< 1 min |
ethereum.transactions, solana.transactions |
| Decoded |
15-60 sec |
uniswap_v3_ethereum.evt_Swap |
| Curated |
~1 hour+ |
dex.trades, dex_solana.trades |
Query previous day's data after UTC 12:00 for completeness.
References
Detailed documentation is organized in the references/ directory:
| File |
Description |
| table-discovery.md |
Table discovery: search tables by name, inspect schema/columns, list schemas and uploads |
| query-execution.md |
API patterns: execute, update, cache, multi-day fetch, credits tracking, subqueries |
| common-tables.md |
Quick reference of commonly used tables: raw, decoded, curated, community data |
| sql-optimization.md |
SQL optimization: CTE, JOIN strategies, array ops, partition pruning |
| wallet-analysis.md |
Wallet tracking: Solana/EVM queries, multi-chain aggregation, fee analysis |
| data-upload.md |
Data upload: CSV/NDJSON upload, create table, insert data, manage tables, credits |
1---2name: dune-analytics-api3description: Dune Analytics API skill for querying, analyzing, and uploading blockchain data. Use this skill whenever the user mentions Dune, on-chain data, blockchain analytics, token trading volume, DEX activity, wallet tracking, Solana/EVM transaction analysis, or wants to explore crypto data — even if they don't explicitly say 'Dune'. Also use for: running or creating Dune queries, finding blockchain tables and schemas, uploading CSV/NDJSON data to Dune, optimizing SQL for DuneSQL (Trino), checking token prices or trading pairs, analyzing wallet behavior, or any task involving dex.trades, decoded event logs, or raw blockchain transactions. Triggers on: Dune, blockchain data, on-chain, DEX trades, token volume, Solana transactions, wallet analysis, query optimization, data upload, table discovery, contract address lookup, crypto analytics, DuneSQL.4---56# Dune Analytics API78A skill for querying and analyzing blockchain data via the [Dune Analytics](https://dune.com) API.910## Local Query Registry Integration (dq)1112Some machines maintain a local **Dune Query Registry** — a git repo of query13assets managed by the `dq` CLI, recognizable by a `registry.yaml` plus a14`queries/` directory (the root may also be pointed to by the `DQ_ROOT` env15var).1617**If such a registry exists, query WRITE operations are hard-constrained to18go through dq** so local and online copies never drift:1920| Never do this | Do this instead |21|---|---|22| `client.create_query(...)` / `POST /query` | `dq create --title t --sql-file f.sql` (creates on Dune + registers locally, one atomic op) |23| `dune_query.py update_sql` / `client.update_query` / `PATCH /query/{id}` | `dq save --query-id N --sql-file f.sql --push`, or `dq push <id>` |2425`dq push` keeps a per-query sync fingerprint and refuses non-fast-forward26pushes (remote edited on dune.com since the last sync) — run `dq pull <id>`27to reconcile first. Audit drift anytime with `dq sync --all`. After running28a query and drawing conclusions, record them: `dq note <query_id> "..."`.2930READ operations (`execute`, `get_latest`, `get_sql`, table discovery, data31uploads) are unrestricted. If no dq registry exists on the machine, this32section does not apply.3334## Setup3536```bash37pip install dune-client38```3940Set `DUNE_API_KEY` via environment variable, `.env` file, or agent config.4142## Best Practices43441. **Read references first** — The reference files contain critical table names, anti-patterns, and chain-specific gotchas that aren't obvious from table names alone. Reading the right reference before writing SQL prevents common mistakes like using `dex.trades` for wallet analysis (which inflates volume ~30%) or missing Solana's dedup requirement.45462. **Prefer private queries** — Creating queries with `is_private=True` keeps the user's workspace clean and avoids polluting the public Dune namespace. Fall back to public if it fails (free plan limitation), and let the user know.47483. **Reuse before creating** — Dune charges credits per execution. Reusing or updating an existing query avoids unnecessary duplicates and makes credit tracking easier. Only create new queries when the user explicitly asks.49504. **Confirm before updating** — Modifying an existing query's SQL is destructive (previous version isn't saved by default). A quick confirmation avoids overwriting work the user might want to keep.51525. **Track credits** — Each execution costs credits depending on the performance tier and data scanned. Reporting credits consumed helps the user manage their budget. See [query-execution.md](references/query-execution.md#credits-tracking).5354## Scripts — Common Operations5556For common operations, use the scripts in `scripts/` to avoid writing boilerplate code every time. All scripts read `DUNE_API_KEY` from the environment automatically.5758| Script | Command | What it does |59|--------|---------|-------------|60| `dune_query.py` | `execute --query-id ID` | Execute a saved query (supports `--params`, `--performance`, `--format`) |61| `dune_query.py` | `get_latest --query-id ID` | Get cached result without re-execution |62| `dune_query.py` | `get_sql --query-id ID` | Print query SQL |63| `dune_query.py` | `update_sql --query-id ID --sql "..."` | Update query SQL |64| `dune_discover.py` | `search --keyword "uniswap"` | Search tables by keyword |65| `dune_discover.py` | `schema --table "dex.trades"` | Show table columns and types |66| `dune_discover.py` | `list_schemas --namespace "uniswap_v3"` | List tables in a namespace |67| `dune_discover.py` | `contract --address "0x..."` | Find decoded tables by contract address |68| `dune_discover.py` | `docs --keyword "dex"` | Search Dune documentation |69| `dune_upload.py` | `upload_csv --file data.csv --table-name tbl` | Quick CSV upload (overwrites) |70| `dune_upload.py` | `create_table --table-name tbl --namespace ns --schema '[...]'` | Create table with explicit schema |71| `dune_upload.py` | `insert --file data.csv --table-name tbl --namespace ns` | Append data to existing table |7273**Example:**74```bash75# Execute query with parameters76python scripts/dune_query.py execute --query-id 123456 --params '{"token":"ETH"}' --format table7778# Upload a CSV privately79python scripts/dune_upload.py upload_csv --file wallets.csv --table-name my_wallets --private80```8182## Reference Selection8384**Before writing any SQL, route to the correct reference file(s) based on your task:**8586| Task involves... | Read this reference |87|-----------------|-------------------|88| Finding tables / inspecting schema / discovering protocols | [table-discovery.md](references/table-discovery.md) |89| Finding decoded tables by contract address | [table-discovery.md](references/table-discovery.md#search-tables-by-contract-address) |90| Searching Dune documentation / guides / examples | [table-discovery.md](references/table-discovery.md#search-dune-documentation) |91| Wallet / address tracking / router identification | [wallet-analysis.md](references/wallet-analysis.md) |92| Table selection / common table names | [common-tables.md](references/common-tables.md) |93| SQL performance / complex joins / array ops | [sql-optimization.md](references/sql-optimization.md) |94| API calls / execution / caching / parameters | [query-execution.md](references/query-execution.md) |95| Uploading CSV/NDJSON data to Dune | [data-upload.md](references/data-upload.md) |9697If your task spans multiple categories, read **all** relevant files. The references contain critical details (e.g., specialized tables, anti-patterns) that aren't covered in this overview — guessing table names or query patterns leads to subtle bugs.9899## Quick Start100101```python102from dune_client.client import DuneClient103from dune_client.query import QueryBase104import os105106client = DuneClient(api_key=os.environ['DUNE_API_KEY'])107108# Execute a query109result = client.run_query(query=QueryBase(query_id=123456), performance='medium', ping_frequency=5)110print(f"Rows: {len(result.result.rows)}")111112# Get cached result (no re-execution)113result = client.get_latest_result(query_id=123456)114115# Get/update SQL116sql = client.get_query(123456).sql117client.update_query(query_id=123456, query_sql="SELECT ...")118119# Upload CSV data (quick, overwrites existing)120client.upload_csv(121 data="col1,col2\nval1,val2",122 description="My data",123 table_name="my_table",124 is_private=True125)126127# Create table + insert (supports append)128client.create_table(129 namespace="my_user",130 table_name="my_table",131 schema=[{"name": "col1", "type": "varchar"}, {"name": "col2", "type": "double"}],132 is_private=True133)134import io135client.insert_data(136 namespace="my_user",137 table_name="my_table",138 data=io.BytesIO(b"col1,col2\nabc,1.5"),139 content_type="text/csv"140)141```142143## Subscription Tiers144145| Method | Description | Plan |146|--------|-------------|------|147| `run_query` | Execute saved query (supports `{{param}}`) | Free |148| `run_sql` | Execute SQL directly (no params) | Plus |149150## Key Concepts151152### dex.trades vs dex_aggregator.trades153154| Table | Use Case | Volume |155|-------|----------|--------|156| `dex.trades` | Per-pool analysis | ⚠️ Inflated ~30% (multi-hop counted multiple times) |157| `dex_aggregator.trades` | User/wallet analysis | Accurate |158159> **Why this matters:** If you're analyzing a specific wallet's trading activity and use `dex.trades`, you'll see inflated volume because a single swap through an aggregator gets split into multiple pool-level trades. `dex_aggregator.trades` captures the user-level intent — one row per user swap. See [wallet-analysis.md](references/wallet-analysis.md) for full patterns.160161Solana has no `dex_aggregator_solana.trades`. Dedupe by `tx_id`:162```sql163SELECT tx_id, MAX(amount_usd) as amount_usd164FROM dex_solana.trades165GROUP BY tx_id166```167168### Data Freshness169170| Layer | Delay | Example |171|-------|-------|---------|172| Raw | < 1 min | `ethereum.transactions`, `solana.transactions` |173| Decoded | 15-60 sec | `uniswap_v3_ethereum.evt_Swap` |174| Curated | ~1 hour+ | `dex.trades`, `dex_solana.trades` |175176Query previous day's data after **UTC 12:00** for completeness.177178## References179180Detailed documentation is organized in the `references/` directory:181182| File | Description |183|------|-------------|184| [table-discovery.md](references/table-discovery.md) | Table discovery: search tables by name, inspect schema/columns, list schemas and uploads |185| [query-execution.md](references/query-execution.md) | API patterns: execute, update, cache, multi-day fetch, credits tracking, subqueries |186| [common-tables.md](references/common-tables.md) | Quick reference of commonly used tables: raw, decoded, curated, community data |187| [sql-optimization.md](references/sql-optimization.md) | SQL optimization: CTE, JOIN strategies, array ops, partition pruning |188| [wallet-analysis.md](references/wallet-analysis.md) | Wallet tracking: Solana/EVM queries, multi-chain aggregation, fee analysis |189| [data-upload.md](references/data-upload.md) | Data upload: CSV/NDJSON upload, create table, insert data, manage tables, credits |