Sub topic 12
Common pitfalls: decimals, double counting and prices
This chapter assumes you can write basic DuneSQL (SELECT, WHERE, GROUP BY, JOIN), know what an ERC-20 token and a DEX are, and have read the earlier chapters on decoded and curated tables and on TVL. Most wrong numbers on a dashboard come from three sources: raw token amounts that were never scaled, the same value counted more than once, and USD prices that do not mean what the author thought. Each one produces a number that looks plausible, so no error message warns you.
Pitfall 1: token decimals
Why amounts are integers
Smart contracts do not store fractions. An ERC-20 token stores whole integers and declares a decimals value that tells you where to put the decimal point. A balance of 1500000 in a token with 6 decimals means 1.5 tokens. The same integer in a token with 18 decimals means 0.0000000000015 tokens.
| Token | Decimals | Raw integer | Real amount |
|---|---|---|---|
| USDC | 6 | 1500000 | 1.5 |
| USDT | 6 | 2000000 | 2.0 |
| WETH | 18 | 1000000000000000000 | 1.0 |
| WBTC | 8 | 100000000 | 1.0 |
| DAI | 18 | 1000000000000000000 | 1.0 |
Decoded event tables such as erc20_ethereum.evt_Transfer give you the raw value. Curated tables such as dex.trades already supply a scaled token_bought_amount and a USD value in amount_usd.
Scaling in a query
The following query totals daily USDC transfers. It divides by 1e6 because USDC has 6 decimals, and it casts first because value is a 256-bit integer that can overflow ordinary arithmetic.
SELECT
date_trunc('day', evt_block_time) AS day,
SUM(CAST(value AS double) / 1e6) AS usdc_transferred
FROM erc20_ethereum.evt_Transfer
WHERE contract_address = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48
AND evt_block_date >= current_date - INTERVAL '7' DAY
GROUP BY 1
ORDER BY 1Three details matter here:
- The divisor must match the token. Reusing
1e6for a token with 18 decimals understates the amount by a factor of one trillion. - Casting to
doublekeeps about 15 significant digits. That is fine for charts. It is not fine for exact accounting, where you should keep the value asuint256ordecimaland scale at the end. - The filter on
evt_block_datelimits the scan to recent partitions, which also keeps the query cheap.
Looking decimals up instead of hard-coding them
Hard-coded divisors break when you extend a query to several tokens. Join to a token metadata table and use its decimals column. In Dune this is tokens.erc20.
SELECT
date_trunc('day', t.evt_block_time) AS day,
m.symbol,
SUM(CAST(t.value AS double) / power(10, m.decimals)) AS amount
FROM erc20_ethereum.evt_Transfer AS t
JOIN tokens.erc20 AS m
ON m.contract_address = t.contract_address
AND m.blockchain = 'ethereum'
WHERE t.contract_address IN (
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48,
0xdAC17F958D2ee523a2206206994597C13D831ec7
)
AND t.evt_block_date >= current_date - INTERVAL '7' DAY
GROUP BY 1, 2
ORDER BY 1, 2Check the join type. An inner join silently drops tokens that are missing from the metadata table. If a token you care about disappears from the result, switch to a LEFT JOIN and look for NULL decimals.
Sanity check: size of a number
A quick test catches most decimal mistakes. Ask whether the result is physically possible. Daily USDC transfers of 4 × 10¹⁵ dollars exceed the world's money supply, so the scaling is missing. Daily transfers of 0.004 dollars mean you divided by too much.
Pitfall 2: double counting
Double counting means the same economic value enters a total twice or more. It appears in three common forms.
Form 1: one transaction, many events
A single swap on a DEX aggregator can touch several pools. Each hop emits its own Swap event, and the aggregator may emit a summary event as well. If you add up every event, a $1,000 trade routed through three pools can count as $3,000 of volume.
Curated tables such as dex.trades record one row per pool-level swap. That is correct for pool volume. It is misleading if you wanted user-level trade size. Decide which one you are measuring and say so on the dashboard.
SELECT
tx_hash,
COUNT(*) AS swap_rows,
SUM(amount_usd) AS summed_usd
FROM dex.trades
WHERE blockchain = 'ethereum'
AND block_date >= current_date - INTERVAL '1' DAY
GROUP BY 1
HAVING COUNT(*) > 1
ORDER BY summed_usd DESC
LIMIT 20This query lists transactions that produced multiple rows, so you can see how routing inflates a naive sum.
Form 2: both sides of a transfer
Every transfer has a sender and a receiver. Summing value over all transfers measures gross movement. It does not measure unique money moved by users, because tokens often hop through routers, vaults and bridges. Similarly, dex.trades has a bought side and a sold side that represent the same value. Take amount_usd once, never the sum of both sides.
Form 3: TVL counted more than once
TVL has its own double counting problem. A user deposits ETH into a liquid staking protocol and receives a staked ETH token. They then deposit that token into a lending protocol. The same ETH now appears in the TVL of both protocols. The same chain of reuse can run deeper.
The diagram below shows how a single deposit is counted at each layer.
DefiLlama addresses this in two ways. Its chain-level totals can exclude "double counted" entries, and protocols can be flagged so their value is not added to the chain total again. Always check which setting a displayed number uses before you compare it with another source.
How to detect double counting
- Compare your sum against a known upper bound, such as total supply of a token or total value of a chain.
- Group by transaction hash and count rows. Many rows per hash suggests multi-hop activity.
- Pick one transaction by hand, open it in a block explorer, and trace its value through your query.
Pitfall 3: price assumptions
Where USD values come from
Chains record token amounts, not dollars. Every USD number is produced by someone joining amounts to a price. In Dune the main source is the prices.usd table, which gives per-minute prices for supported tokens. Curated tables like dex.trades use it to fill amount_usd.
This creates failure modes that do not exist for raw amounts:
- Missing prices. A new or illiquid token may have no price. Its
amount_usdisNULL, andSUMignoresNULLrows. Your volume is then understated without any warning. - Manipulable prices. A thinly traded token can be priced at a number nobody could actually sell at. One tiny trade on a pool with little liquidity can set the "price" for the whole day.
- Time mismatch. Using today's price for last year's amounts gives a very different chart from using the price at the time of each event.
- Stale or wrong mapping. Fake tokens that copy a real symbol can be matched to the real token's price if you join on symbol instead of contract address.
Checking for missing prices
Count how many rows have no USD value, and how large they are in token terms.
SELECT
COUNT(*) AS total_rows,
COUNT_IF(amount_usd IS NULL) AS rows_without_usd,
COUNT_IF(amount_usd IS NULL) * 100.0 / COUNT(*) AS pct_missing
FROM dex.trades
WHERE blockchain = 'ethereum'
AND block_date >= current_date - INTERVAL '30' DAYIf the percentage is not tiny, find the tokens behind it before you publish a USD volume.
Outliers
Filter or at least inspect extreme rows. A single trade of $9 billion on a day when the whole market traded $2 billion is almost always a price error.
SELECT
block_time,
project,
token_pair,
amount_usd,
tx_hash
FROM dex.trades
WHERE blockchain = 'ethereum'
AND block_date >= current_date - INTERVAL '30' DAY
AND amount_usd > 100000000
ORDER BY amount_usd DESC
LIMIT 20Do not delete outliers automatically. Some are real. Look at the transaction, then decide, and write down the rule you used.
Price effects in TVL
TVL is a dollar figure, so it moves with token prices even when nobody deposits or withdraws. If ETH falls 20%, the TVL of an ETH-heavy protocol falls about 20% with no user action. To separate flows from price, compare TVL in USD against TVL in the native token, which DefiLlama exposes for many protocols.
You can see the problem in the API data. This script fetches the protocol list and prints the top ten by TVL.
import requests
resp = requests.get("https://api.llama.fi/protocols", timeout=30)
resp.raise_for_status()
protocols = resp.json()
top = sorted(
(p for p in protocols if p.get("tvl")),
key=lambda p: p["tvl"],
reverse=True,
)[:10]
for p in top:
category = p.get("category") or "n/a"
print(f"{p['name']:<25} {category:<20} ${p['tvl'] / 1e9:,.2f}B")Run it on two different days and the ranking can shift purely because of prices. Treat the dollar value as a snapshot, not a measure of user growth.
A pre-publication checklist
| Check | Question to ask | Typical fix |
|---|---|---|
| Decimals | Did I scale each token by its own decimals? | Join to `tokens.erc20` and use `power(10, decimals)` |
| Casting | Could `value` overflow or lose precision? | Cast deliberately and scale last |
| Row grain | Is one row one swap, one hop, or one trade? | Group by `tx_hash` and inspect |
| Both sides | Am I adding bought and sold amounts together? | Use `amount_usd` once |
| Double counting | Is the total above the asset's supply? | Exclude re-used receipt tokens |
| Missing prices | What share of rows has `NULL` USD? | Report it or add a price source |
| Outliers | Are there single rows far above the daily total? | Inspect, then filter with a stated rule |
| Time basis | Which price date applies to each amount? | Use price at event time |
Putting it together
Suppose a colleague reports that Ethereum DEX volume was $40 billion yesterday, and DefiLlama shows $3 billion. Work through the pitfalls in order. First check decimals, since a missed scale factor on one token can add billions. Then group by tx_hash to see whether multi-hop routing inflated the count. Finally look for outliers and missing prices. The next chapter uses this same order when it compares Dune against DefiLlama directly.
Exercise
A query sums value / 1e6 for transfers of a token that has 18 decimals. Is the result too large or too small, and by what factor? Name one check that would have caught it.
Show answer
The result is too large, by a factor of 10^12 (1e18 divided by 1e6). The correct divisor is 1e18. A sanity check would catch it: the daily total would exceed the token's total supply, which is a hard ceiling. Joining to tokens.erc20 and using its decimals column would also have prevented it.
Exercise
A $1,000 swap is routed through three pools, so dex.trades has three rows for one tx_hash, each with amount_usd of about 1000. A dashboard sums all rows and reports $3,000. Is that wrong? Explain, and say what you would label the metric.
Show answer
It depends on the metric. As pool-level volume, $3,000 is correct, because each pool did $1,000 of swapping. As user trade volume, it is triple counted, because the user traded $1,000 once. Label the metric clearly, for example "DEX pool volume (per hop)" versus "trade volume by transaction". For user-level volume, deduplicate to one row per tx_hash using the first input and last output.
Exercise
A protocol's TVL in USD fell 25% in a week while its ETH-denominated TVL stayed flat. What most likely happened, and what does that tell you about using USD TVL as a measure of user activity?
Show answer
ETH most likely fell about 25% in price, and users neither deposited nor withdrew in any significant amount. USD TVL mixes price changes with real flows, so a falling USD number can hide stable or growing deposits. Compare USD TVL with token-denominated TVL before drawing conclusions about users.