Data access · 10 min read

How to index Uniswap v3 swaps on Base into Postgres with TypeScript

This guide builds a TypeScript indexer that reads Uniswap v3 Swap events on Base and writes one Postgres row per swap, using SQD's Pipes SDK and the keyless public Portal. The code, the terminal output and the psql results below are pasted from a run on December 1, 2026, over a pinned window of 3,000 Base blocks, so you can rerun it and compare. Two traps silently miscount Uniswap swaps on Base, and both are measured here.

Updated 2026-12-01 · By the SQD team

1. What you end up with

The finished indexer is one TypeScript file and one Postgres table. It asks SQD Portal for the Swap logs of three pools, decodes them with the pool ABI, and inserts them through a Drizzle target that also stores the stream cursor and undoes rows from blocks a reorg replaces. The pools are WETH/USDC on Uniswap v3, one per fee tier, which together had 839 swaps in the window, a third of all Uniswap v3 swaps on Base in those blocks.

Fee tier Pool Swaps
0.01% 0xb4cb800910b228ed3d0834cf79d697127bbb00e5 644
0.05% 0xd0b53d9277642d899df5c87a3966a349a798f224 152
0.30% 0x6c561b446416e1a00e8e93e221854d6ea4171372 43
Total 3 pools 839
WETH/USDC pools on Uniswap v3, Base: swaps in blocks 64,700,000 to 64,702,999 (2026-12-01, 13:06:15 to 13:16:15 UTC)

The 0.01% pool, 0xb4cb…00e5, was the busiest Uniswap v3 pool on Base in the window: its 644 swaps were 25.6% of the 2,515 Uniswap v3 swaps across 333 pools, and the next pool had 185. The window is 3,000 blocks, ten minutes of Base, because the public Portal is a rate-limited exploration endpoint. The same code runs over any range; a full-history backfill needs a paid plan (section 11).

2. Find the pools from the factory

Take pool addresses from the factory contract, not from a token list or a search result. Uniswap's Base deployments page lists UniswapV3Factory at 0x3312…FDfD, and its getPool(tokenA, tokenB, fee) returns the one canonical pool per pair and fee. The tokens are WETH (0x4200…0006) and USDC (0x8335…2913, from Circle's address list). For the 0.05% tier, fee 500:

your terminal
# getPool(address,address,uint24) = 0x1698ee82; args: WETH, USDC, fee 500 (0x1f4)
curl -s https://mainnet.base.org -H 'content-type: application/json' -d '{
"jsonrpc": "2.0", "id": 1, "method": "eth_call",
"params": [{
"to": "0x33128a8fC17869897dcE68Ed026d694621f6FDfD",
"data": "0x1698ee820000000000000000000000004200000000000000000000000000000000000006000000000000000000000000833589fcd6edb6e08f4c7c32d4f71b54bda0291300000000000000000000000000000000000000000000000000000000000001f4"
}, "latest"]
}'

Fee 100 (0x64) returns 0xb4cb…00e5 and fee 3000 (0xbb8) returns 0x6c56…1372. Those three addresses are the whole configuration of the indexer.

3. Set up Postgres and the project

Any Postgres works; a throwaway container is enough to follow along. The SDK version below is the npm latest tag on the day of the run, 1.0.0-beta.12 (MIT license). It is a beta and its export names have changed between releases, so pin it, and check the names against the installed package if you use a newer one. drizzle-orm and pg are pinned to the versions the SDK lists as peer dependencies. The run used Node 22.23.

your terminal
docker run -d --name uniswap-pg -e POSTGRES_PASSWORD=postgres \
-p 127.0.0.1:5432:5432 postgres:17
mkdir -p uniswap-v3-base/src && cd uniswap-v3-base
npm init -y && npm pkg set type=module
npm install @subsquid/pipes@1.0.0-beta.12 drizzle-orm@0.44.7 pg@8.16.3
npm install -D tsx typescript @types/pg

4. The indexer

The whole indexer is the file below, exactly as it ran. It has four parts: the Swap event ABI, the pool list, the Drizzle table, and the stream wired to the Postgres target.

src/index.ts
import { evmPortalStream, evmEventDecoder, defineAbi } from '@subsquid/pipes/evm'
import { drizzleTarget, chunkForInsert } from '@subsquid/pipes/targets/drizzle/node-postgres'
import { drizzle } from 'drizzle-orm/node-postgres'
import { sql } from 'drizzle-orm'
import { pgTable, text, integer, bigint, numeric, timestamp, primaryKey } from 'drizzle-orm/pg-core'
// Uniswap v3 pool ABI, Swap event only
const pool = defineAbi([
{
type: 'event',
name: 'Swap',
inputs: [
{ indexed: true, name: 'sender', type: 'address' },
{ indexed: true, name: 'recipient', type: 'address' },
{ indexed: false, name: 'amount0', type: 'int256' },
{ indexed: false, name: 'amount1', type: 'int256' },
{ indexed: false, name: 'sqrtPriceX96', type: 'uint160' },
{ indexed: false, name: 'liquidity', type: 'uint128' },
{ indexed: false, name: 'tick', type: 'int24' },
],
},
] as const)
// WETH/USDC on Uniswap v3 (Base), one pool per fee tier.
// Addresses from UniswapV3Factory.getPool(WETH, USDC, fee) on Base.
const POOLS: Record<string, number> = {
'0xb4cb800910b228ed3d0834cf79d697127bbb00e5': 100, // 0.01%
'0xd0b53d9277642d899df5c87a3966a349a798f224': 500, // 0.05%
'0x6c561b446416e1a00e8e93e221854d6ea4171372': 3000, // 0.30%
}
export const swaps = pgTable(
'uniswap_v3_swaps',
{
blockNumber: bigint('block_number', { mode: 'number' }).notNull(),
logIndex: integer('log_index').notNull(),
blockTime: timestamp('block_time', { withTimezone: true }).notNull(),
txHash: text('tx_hash').notNull(),
pool: text('pool').notNull(),
feeTier: integer('fee_tier').notNull(),
sender: text('sender').notNull(),
recipient: text('recipient').notNull(),
amount0: numeric('amount0').notNull(), // WETH, 18 decimals, signed
amount1: numeric('amount1').notNull(), // USDC, 6 decimals, signed
sqrtPriceX96: numeric('sqrt_price_x96').notNull(),
liquidity: numeric('liquidity').notNull(),
tick: integer('tick').notNull(),
},
(t) => [primaryKey({ columns: [t.blockNumber, t.logIndex] })],
)
const decoder = evmEventDecoder({
range: { from: 64_700_000, to: 64_702_999 },
contracts: Object.keys(POOLS),
events: { swap: pool.events.Swap },
}).pipe(({ swap }) =>
swap.map((s) => ({
blockNumber: s.block.number,
logIndex: s.rawEvent.logIndex,
blockTime: s.timestamp,
txHash: s.rawEvent.transactionHash,
pool: s.contract,
feeTier: POOLS[s.contract],
sender: s.event.sender,
recipient: s.event.recipient,
amount0: s.event.amount0.toString(),
amount1: s.event.amount1.toString(),
sqrtPriceX96: s.event.sqrtPriceX96.toString(),
liquidity: s.event.liquidity.toString(),
tick: s.event.tick,
})),
)
const db = drizzle(process.env.DB_URL ?? 'postgresql://postgres:postgres@localhost:5432/postgres')
await evmPortalStream({
id: 'uniswap-v3-base-weth-usdc', // cursor key; keep it stable across restarts
portal: 'https://portal.sqd.dev/datasets/base-mainnet',
outputs: { swaps: decoder },
}).pipeTo(
drizzleTarget({
db,
tables: [swaps],
onStart: async ({ db }) => {
await db.execute(sql`
CREATE TABLE IF NOT EXISTS uniswap_v3_swaps (
block_number bigint NOT NULL,
log_index integer NOT NULL,
block_time timestamptz NOT NULL,
tx_hash text NOT NULL,
pool text NOT NULL,
fee_tier integer NOT NULL,
sender text NOT NULL,
recipient text NOT NULL,
amount0 numeric NOT NULL,
amount1 numeric NOT NULL,
sqrt_price_x96 numeric NOT NULL,
liquidity numeric NOT NULL,
tick integer NOT NULL,
PRIMARY KEY (block_number, log_index)
)`)
},
onData: async ({ tx, data }) => {
for (const values of chunkForInsert(data.swaps)) {
await tx.insert(swaps).values(values)
}
},
}),
)
await db.$client.end() // close the pg pool; otherwise the process idles 10 s before exiting

Four details in it matter more than they look:

  • Amounts go in as numeric. amount0 and amount1 are int256 and sqrtPriceX96 is uint160; they decode to bigint and overflow bigint columns, so the transform turns them into strings for Postgres numeric.
  • The table needs a primary key. The target refuses a table without one, because it keys its reorg undo log on it. (block_number, log_index) identifies a log uniquely on one chain.
  • The id is the cursor key. The target saves its position in a sync table under this id, so a restart resumes instead of reinserting. Change the id and the pipe starts over.
  • The range is pinned. to: 64_702_999 makes the process exit after the window. Remove to and it keeps following the chain head (section 9).

5. Run it

On the public endpoint, the first request is often refused and retried. Four of the seven runs made for this guide on December 1, including one from a fresh directory, got a 529 overloaded on their first request; the SDK logs a warning, waits ten seconds and retries on its own. The run below, from a fresh directory on December 2, got no 529 and took 1.6 seconds end to end. Timestamps are the machine's local clock (UTC+1):

your terminal
npx tsx src/index.ts
[15:44:34.932] INFO: uniswap-v3-base-weth-usdc Start indexing from 64,700,000 block
[15:44:35.660] INFO: uniswap-v3-base-weth-usdc Cleaning up old offsets less than 64701999 block for uniswap-v3-base-weth-usdc row...

Running the same command again inserts nothing, because the cursor in sync already points at the end of the window:

your terminal
npx tsx src/index.ts
[15:44:36.488] INFO: uniswap-v3-base-weth-usdc Resuming indexing from 64,702,999 block

The row count stayed at 839 after the second run. The database now has three tables: uniswap_v3_swaps, the cursor table sync, and uniswap_v3_swaps__snapshots, the undo log the target creates for reorgs.

6. Query the swaps in Postgres

Swap counts and volume per fee tier are one GROUP BY. USDC has 6 decimals, so the USDC leg of each swap divided by 1e6 is its dollar size:

your terminal
docker exec uniswap-pg psql -U postgres -c "
SELECT fee_tier, count(*) AS swaps, round(sum(abs(amount1)) / 1e6) AS usdc_volume
FROM uniswap_v3_swaps GROUP BY fee_tier ORDER BY fee_tier;"
fee_tier | swaps | usdc_volume
----------+-------+-------------
100 | 644 | 103001
500 | 152 | 77914
3000 | 43 | 537277
(3 rows)

Swap count and dollar volume rank the tiers in opposite orders. The 0.30% pool had the fewest swaps and three quarters of the volume, $537.3k of about $718.2k, and most of that came from a handful of trades: the five largest swaps in the tier were $295.1k, 54.9% of it. The largest single one sold 62.30 WETH for 106,677.64 USDC in 0x2c92…bab1. In a ten-minute window, a few trades decide the volume ranking, so read the tier split as a property of this window, not of the pools.

Individual swaps read the same way. The first row in block order is the first swap of the window:

your terminal
docker exec uniswap-pg psql -U postgres -x -c "
SELECT block_number, block_time, fee_tier, tx_hash,
amount0 / 1e18 AS weth, amount1 / 1e6 AS usdc,
round(abs(amount1 / 1e6) / abs(amount0 / 1e18), 2) AS usdc_per_weth
FROM uniswap_v3_swaps ORDER BY block_number, log_index LIMIT 1;"
-[ RECORD 1 ]-+-------------------------------------------------------------------
block_number | 64700007
block_time | 2026-12-01 13:06:17+00
fee_tier | 100
tx_hash | 0xad0ea9a2acc22243d40c127139944bdabdc825200bd7bb52394f2d0bfbcc46ae
weth | -0.00327225451524297400
usdc | 5.6118880000000000
usdc_per_weth | 1714.99

The signs are from the pool's side. A positive amount entered the pool and a negative amount left it, so in 0xad0e…46ae at block 64,700,007 the trader paid 5.611888 USDC into the 0.01% pool and received 0.003272 WETH, a price of 1,714.99 USDC per WETH. Volume queries take abs() of one leg; buy and sell splits read the sign.

7. Trap 1: the Swap topic is not Uniswap

Filtering on the Swap event signature alone counts every fork of Uniswap v3 as Uniswap. Forks that kept the pool contract emit the same event, so they share its topic hash, 0xc42079f9…ca67. Over the same 3,000 blocks, the Portal returned 10,227 logs with that topic from 667 contracts. Checking each contract against Uniswap's factory left 2,515 swaps from 333 pools, 24.6% of the topic count:

Emitting contracts Contracts Swap logs
Pools deployed by UniswapV3Factory 333 2,515
Contracts reporting 15 other factories, plus 1 whose factory() reverts 334 7,712
All contracts emitting the topic 667 10,227
Logs with the Uniswap v3 Swap topic, Base blocks 64,700,000 to 64,702,999

A topic-only filter would have overstated Uniswap v3 swaps on Base about fourfold in this window. The check used two methods that agreed on every address: each contract's factory() return value, and the pool address recomputed with CREATE2 from the factory, the pool's token0, token1 and fee, and Uniswap's pool init code hash. Only the second is proof, because any contract can return any address from factory(). The indexer above avoids the trap by passing pool addresses in contracts, which the Portal applies as a log filter before anything is sent.

8. Trap 2: a factory registry needs history

To index every Uniswap v3 pool instead of a list, the SDK provides contractFactory, documented in the factory transformers guide. It reads the factory's PoolCreated events into a SQLite registry and keeps a Swap only when its emitter is in that registry. The registry only learns pools created inside the range you index, though. Here is the factory version run over the same window (contractFactorySqliteStore needs better-sqlite3, an optional peer dependency of the SDK: npm install better-sqlite3@12.4.5):

src/factory-trap.ts (excerpt)
const decoder = evmEventDecoder({
range: { from: 64_700_000, to: 64_702_999 },
contracts: contractFactory({
address: '0x33128a8fc17869897dce68ed026d694621f6fdfd', // UniswapV3Factory on Base
event: factoryAbi.events.PoolCreated,
childAddressField: 'pool',
database: contractFactorySqliteStore({ path: './pools.sqlite' }),
}),
events: { swap: poolAbi.events.Swap },
})
your terminal
npx tsx src/factory-trap.ts
[17:05:17.328] INFO: uniswap-v3-base-factory-window Start indexing from 64,700,000 block
[17:05:17.459] WARN: uniswap-v3-base-factory-window HTTP request id:2 will be retried in 10000 ms {"module":"http-client","retry_reason":"got 529 response status: server is overloaded", ...}
[17:05:27.540] WARN: uniswap-v3-base-factory-window HTTP request id:2 will be retried in 10000 ms {"module":"http-client","retry_reason":"got 529 response status: server is overloaded", ...}
[17:05:37.598] WARN: uniswap-v3-base-factory-window HTTP request id:2 will be retried in 10000 ms {"module":"http-client","retry_reason":"got 529 response status: server is overloaded", ...}
swaps decoded: 0

After three 529 retries, it decoded 0 of the window's 2,515 Uniswap v3 swaps, without an error. The factory created no pools in those 3,000 blocks, so the registry stayed empty and every swap was dropped as unknown. A registry is complete only when the range starts at the factory's first PoolCreated event, which on Base is block 2,009,446 (July 31, 2023, transaction 0x9a9b…8b08).

Starting there is a full-history backfill of 62.7 million blocks, and it costs more than the pool events. To find Uniswap's swaps, contractFactory asks the Portal for every log with the Swap topic and filters in your process, so it downloads the forks' swaps too, about four times the Uniswap volume if this window is typical. That is a job for a paid plan. For a free-tier exploration, a named pool list is the correct design.

10. Why this is harder over RPC

An RPC-based indexer reads the same logs with eth_getLogs, and the free endpoints cap it by range and by age. The same three-pool query for the 3,000-block window, sent to public Base endpoints on the same day, came back three different ways:

Public endpoint Response
base-rpc.publicnode.com 839 logs, matching the Portal
base.drpc.org "ranges over 100 blocks are not supported on free plan"
mainnet.base.org "request limit reached" (rate limit, after this session's earlier calls)
base-rpc.publicnode.com, same query at blocks 20,000,000 to 20,002,999 "Archive requests require a personal token"
eth_getLogs for the three WETH/USDC pools' Swap logs, blocks 64,700,000 to 64,702,999 (2026-12-01)

The endpoint that answered agrees with the Portal to the row, so the data is the same; the paging around it is not. At drpc's 100-block limit, the window takes 30 requests, and reading Base from genesis to this window takes about 647,000. The endpoint that accepted wide ranges refuses old blocks without an archive token. The Portal answered the 3,000-block window in one response, and the same request shape runs over any range of the chain without an archive node to provision. The eth_getLogs limits guide covers the caps in detail.

11. Limits of the free endpoint

The public Portal is sized for trying things, and this guide stays inside that. Its published allowance is about 50 MB a month at 0.1 MB/s. The response for this window was 877,677 bytes, so the allowance covers roughly 57 windows like it, under ten hours of WETH/USDC swaps at this window's rate, and it answered 529 to the first request of four of the seven runs on December 1.

A full-history backfill of these pools, or of every Uniswap v3 pool through contractFactory, needs a paid Portal plan; plans and their throughput are on the pricing page, and billing is not live yet. One measurement shows the gap: a factory-only PoolCreated scan from genesis, retrying 529s on the public endpoint, covered blocks 0 to 2,893,225, under 5% of the chain, in about ten minutes. The decoder and the target do not change between plans. Only the range changes, and the portal option, which takes the plan's endpoint and an API key sent as an x-api-key header.

Frequently asked questions

How do I index Uniswap v3 swaps on Base into Postgres with TypeScript?
Install @subsquid/pipes with drizzle-orm and pg, define the pool Swap event with defineAbi, and decode it with evmEventDecoder over the pools you care about. Point evmPortalStream at https://portal.sqd.dev/datasets/base-mainnet and write the rows with drizzleTarget. The full script on this page is about 110 lines and indexed 839 WETH/USDC swaps from a 3,000-block window into Postgres in under two seconds on the public endpoint; when the endpoint is busy, a 529 adds a 10-second retry.
What is the Uniswap v3 factory address on Base?
UniswapV3Factory on Base is 0x33128a8fC17869897dcE68Ed026d694621f6FDfD, as listed on Uniswap's own Base deployments page. Call getPool(tokenA, tokenB, fee) on it to resolve a pool address; for WETH/USDC it returns 0xb4cb800910b228ed3d0834cf79d697127bbb00e5 (0.01%), 0xd0b53d9277642d899df5c87a3966a349a798f224 (0.05%) and 0x6c561b446416e1a00e8e93e221854d6ea4171372 (0.30%).
Why does filtering on the Uniswap v3 Swap topic return too many swaps?
Every Uniswap v3 fork that kept the pool code emits the same Swap event, so the topic hash alone matches all of them. In blocks 64,700,000 to 64,702,999 on Base, 10,227 logs had the Uniswap v3 Swap topic, and only 2,515 of them (24.6%) came from pools deployed by Uniswap's factory. Filter by pool address, or by a registry of the factory's PoolCreated events, never by topic alone.
Can I index every Uniswap v3 pool on Base, not only WETH/USDC?
Yes, with contractFactory from @subsquid/pipes/evm, which reads the factory's PoolCreated events and keeps only swaps from pools it has seen. The catch is the start block: the registry only knows pools created inside the indexed range, so the range has to begin at the factory's first PoolCreated event (block 2,009,446 on Base). Started at block 64,700,000 instead, it decoded 0 of the window's 2,515 Uniswap v3 swaps. Indexing from block 2,009,446 is a full-history backfill, which needs a paid Portal plan.
Can the free public Portal backfill all Uniswap v3 history on Base?
No. The public Portal at portal.sqd.dev is for exploration: it is rate-limited, answered 529 overloaded to the first request of four of the seven runs made for this guide on December 1, and its published allowance is about 50 MB a month. The 3,000-block window here was 877,677 bytes, so the allowance covers roughly 57 windows like it, under ten hours of WETH/USDC swaps. A backfill across years of Base history needs a paid plan; see sqd.dev/pricing. Billing is not live yet.
How does this compare to Ponder or Envio?
All three are TypeScript indexers that can write Uniswap swaps to Postgres. The difference is where the data comes from: Ponder reads from RPC endpoints you supply, Envio reads from its HyperSync service, and the Pipes SDK reads from SQD Portal. The comparison pages cover setup, licensing and pricing in detail: sqd.dev/compare/sqd-vs-ponder and sqd.dev/compare/sqd-vs-envio.

Index your own pools

The Pipes SDK quickstart scaffolds the same Postgres setup for any contract on any of the Portal's EVM networks.