Overview: What You’re Building and Why It’s Hard
A great Web3 trading wallet doesn’t just show balances.
It needs:
- A complete wallet history across chains and token types
- Per‑trade trace views so users can drill into swaps and DeFi interactions
- Near real‑time updates with trading‑grade latency
The challenge: wallet history is a merge problem, not a single endpoint. You need to unify external transactions, internal calls, token transfers, NFT activity, prices, and metadata into one coherent timeline.
This tutorial walks you through a practical build using modern blockchain data APIs, with Codex as the reference implementation. It’s designed for product and engineering teams building high‑traffic trading wallets.
This article complements the pillar guide “Blockchain APIs for Trading: Wallet History, Trace Transaction and RPC Layers”. Use that for deep theory; follow this one for implementation.
Step 0: Prerequisites and Architecture Decisions
Before you start coding, lock in a few decisions.
Technical Prerequisites
You’ll need:
- A backend in Node.js, Python, Go, or similar
- A database for caching history (PostgreSQL, ClickHouse, MongoDB, etc.)
- Basic familiarity with GraphQL‑style APIs and JSON
- For production: a background worker / queue system (e.g., BullMQ, Sidekiq, Celery)
Key Architecture Choices
Decide early on:
- Primary data layer: pre‑indexed API vs stitching raw RPC yourself
- Supported networks: Ethereum L1, L2s, Solana, and any other chains you care about
- Real‑time model: subscriptions/webhooks vs polling
The industry has moved toward pre‑indexed, production‑ready APIs. Codex, Alchemy, QuickNode, Etherscan, and The Graph all now offer data products well beyond basic RPC. For a trading wallet, you’ll almost always want one of these as your core data layer.
Step 1: Choose Your Blockchain Data Provider (API and Blockchain Layer)
What to Look For in a Trading‑Grade Wallet Data API
For a high‑traffic trading wallet, the data layer must hit four requirements:
Coverage
- Multichain support: at least major EVM chains + key L2s
- Long‑tail tokens and launchpad assets
- Wallet and prediction market coverage if you plan those features
Performance and Reliability
- Sub‑second response times for wallet history and prices
- 99.99% uptime or close
- Streaming / subscription options for live UX
Data Richness
- Token prices and OHLC chart data
- Aggregated metrics (volume, liquidity, unique wallets)
- Holders, balances, and scam filtering
- Trace/transaction drill‑down for per‑trade views
Unified Access
- Single key across many chains
- Consistent schemas and normalized data
How Codex Fits These Requirements
Codex positions itself as “the fastest and most reliable blockchain data API” for trading‑adjacent applications. Relevant stats:
- 80+ networks, 70M+ tokens, 700M+ wallets, 27B+ historical events
- Data is queryable in less than 1 second, token search returns results in <500ms
- Growth tier supports 300 requests/sec, Free tier 5 requests/sec
This makes Codex well‑suited for:
- High‑traffic trading wallets
- Exchanges, DEX front‑ends, social trading apps
- Prediction‑market UIs needing Polymarket/Kalshi data
If you prefer a different provider (Alchemy, QuickNode, The Graph), follow the same criteria: coverage, performance, data richness, unified API.
Step 2: Design Your Wallet History Data Model
You cannot build a good wallet timeline by exposing raw transactions. You need an enriched, normalized model.
Core Entities for Wallet History
At minimum, design:
WalletActivity (timeline events)
idwalletAddresschainIdblockTimestampactivityType(e.g.,TRANSFER,SWAP,NFT_TRANSFER,LIQUIDITY_ADD)txHashfromAddresstoAddressvalueNativevalueUSDstatus(SUCCESS,FAILED,PENDING)
WalletActivityDetails (drill‑down payload)
txFeeNativetxFeeUSDtokenTransfers[](token, amount, direction)internalCalls[](contract calls, value transfers)decodedProtocols[](Uniswap, Aave, etc.)
TokenMetadata (shared across the app)
tokenAddresschainIdsymbolnamedecimalslogoUrlisScam/ risk flags
Why This Model Matters
- It lets you merge multiple data sources into one user‑friendly timeline.
- It decouples your front‑end from provider‑specific schemas.
- It makes it easy to swap providers later without breaking your UI.
Step 3: Fetch and Merge Wallet History (External, Internal, Tokens, NFTs)
This is the core of the problem.
Understand the “Merge Problem” First
Wallet history must combine:
Normal (external) transactions
- User‑initiated, on‑chain, with signatures
Internal transactions / contract calls
- Contract‑to‑contract or contract‑to‑user value transfers
- Not stored on‑chain as separate transactions
- Tricky: no direct signatures, require traces or specialized APIs
Token transfers (fungible)
- ERC‑20 and similar
- Often emitted as Transfer events
NFT transfers
- ERC‑721 / ERC‑1155
- Also event‑driven
Providers like Etherscan expose these via separate endpoints (e.g., txlist, txlistinternal, tokentx).
Alchemy’s Transfers API can return a more unified view in one request for supported networks.
Codex takes the approach of exposing normalized, enriched wallet and token data via a GraphQL‑style API.
Step‑by‑Step: Implementing Wallet History with a Pre‑Indexed API (Codex Example)
Define the request
- Decide on page size (e.g., 50 events)
- Choose chains (e.g., Ethereum, Arbitrum, Base)
- Decide which fields you need (to keep payload small)
Call the wallet history endpoint
- In Codex, you’d typically use a query like
filterWalletActivities(or similar, see docs) filtered bywalletAddressandchainId. - Request only needed fields: timestamps, type, value, txHash, token transfers.
- In Codex, you’d typically use a query like
Normalize responses into
WalletActivity- Map provider activity types to your internal
activityTypeenum. - Convert values to native + USD using Codex’s real‑time prices.
- Map provider activity types to your internal
Merge in missing internal transactions if needed
- If your provider separates internal transactions, fetch them by
addressandblock range. - For Codex, internal value transfers and contract interactions are typically already enriched into structured activity objects, reducing your merge logic.
- If your provider separates internal transactions, fetch them by
Join token metadata and prices
- For each token address encountered, look up metadata (symbol, decimals, logo, scam flags).
- Use Codex’s token metadata and pricing endpoints to populate
TokenMetadataandvalueUSD.
Paginate and sort
- Always sort by
blockTimestampdescending for timeline views. - Use cursor‑based pagination where your provider supports it.
- Always sort by
Example Pseudocode (Node.js‑like)
const activities = await codexClient.filterWalletActivities({
address: userAddress,
chains: ["ethereum", "arbitrum"],
limit: 50,
cursor: cursor || null,
fields: [
"blockTimestamp",
"activityType",
"txHash",
"fromAddress",
"toAddress",
"valueNative",
"tokenTransfers",
],
});
const normalized = activities.items.map(a => ({
id: a.txHash,
walletAddress: userAddress,
chainId: a.chainId,
blockTimestamp: a.blockTimestamp,
activityType: mapActivityType(a.activityType),
txHash: a.txHash,
fromAddress: a.fromAddress,
toAddress: a.toAddress,
valueNative: a.valueNative,
// valueUSD populated after price lookup
}));
// Batch token price lookup
const priceInputs = collectTokensFromActivities(normalized);
const prices = await codexClient.getTokenPrices(priceInputs);
attachUsdValues(normalized, prices);
Use this pattern with any provider: fetch, normalize, enrich, paginate.
Step 4: Implement Per‑Trade Trace Views (Swap‑Level Drill‑Down)
A trading wallet needs more than a timeline. Power users expect to click into a swap and see exactly what happened:
- Which pools were touched
- How much gas was used
- Which internal calls failed or reverted
Why You Need Trace APIs
Standard transaction receipts don’t expose full execution details. For Ethereum and EVM chains, you need trace APIs such as:
- Geth’s
debug_traceTransaction(native) - Provider equivalents:
trace_transaction, trace APIs with call trees
Geth’s docs note that debug_traceTransaction can emit opcode‑by‑opcode logs with stack, memory, storage, gas, depth, and errors.
That’s overkill for most UIs, but the same data powers simplified per‑trade views.
High‑Level Flow for a Per‑Trade View
- User clicks a transaction in the wallet history
- Backend fetches trace data for that
txHash - Decode call tree into:
- Contract interactions
- Internal ETH transfers
- Token transfers per protocol
- Attach protocol labels and summaries
- “Swapped 2 ETH for 5,000 USDC via Uniswap V3”
- “Added liquidity to Pool X”
- “Bridged assets to Arbitrum”
Implementation Options
You have two main strategies:
Use provider‑level trace APIs directly
- Many node providers (QuickNode, Alchemy, others) expose
trace_transaction. - You send a
txHash, get back a call tree, and decode it yourself.
- Many node providers (QuickNode, Alchemy, others) expose
Leverage an enriched data layer
- Some data APIs (Codex included) pre‑index trades and swaps.
- You can query for trades, events, aggregates, and often avoid raw opcode‑level tracing.
Example Flow with Codex (Trading‑Focused)
- From a wallet activity item (
activityType = SWAP), capturetxHashandchainId. - Query trade/market endpoints tied to that transaction:
- For on‑chain swaps, use Codex’s pair/trade data to reconstruct the swap.
- For prediction markets, use
filterPredictionMarketsandfilterPredictionEvents+ trader stats.
- Build a drill‑down response:
{
"txHash": "0x...",
"chainId": "ethereum",
"summary": "Swapped 1.24 ETH for 4,210 USDC on Uniswap V3",
"steps": [
{
"type": "swap",
"pool": "ETH/USDC 0.3%",
"amountIn": "1.24 ETH",
"amountOut": "4,210 USDC"
},
{
"type": "fee",
"gasUsed": "210k",
"feeNative": "0.004 ETH",
"feeUSD": "12.03"
}
]
}
For advanced debugging interfaces, layer in full trace output from a node provider. For consumer trading UX, enriched trade summaries from a data API are usually enough.
Step 5: Optimize Read Paths for Trading UX (Latency, Caching, Subscriptions)
The best trading UX uses a hybrid read path:
- Indexed queries for history and one‑time loads
- Subscriptions/webhooks for live updates
- Caching for repeat views and scrollback
Codex’s optimization guide explicitly recommends this model.
Principle 1: Use Queries for Bulk and Historical Reads
Queries are ideal for:
- Initial wallet history load
- Scrollback pagination
- On‑demand drill‑down views
Optimization tips:
- Batch queries where possible
- Fetch multiple wallets or chains in one request
- Request only needed fields
- Avoid loading full traces for list views
- Use server‑side caching
- Cache per‑wallet history pages for 5–30 seconds
Principle 2: Use Subscriptions/Webhooks for Near Real‑Time
Real‑time streaming is increasingly standard for trading wallets. Codex offers GraphQL subscriptions and webhooks, while QuickNode Streams and Alchemy webhooks do similar.
Use them for:
- New transactions affecting a wallet
- Price updates for currently viewed assets
- Live PnL and position changes
Implementation pattern:
- Subscribe to wallet address + chains
- When a new event comes in:
- Normalize it into
WalletActivity - Push it into the front‑end via WebSocket or SSE
- Normalize it into
Codex notes that very high‑frequency feeds can make subscriptions more expensive than polling. For hyper‑active wallets or heavy price streams, consider adaptive strategies (e.g., polling for prices, subscriptions for transactions).
Principle 3: Caching Strategies for Wallet History Performance
Good caching is the difference between a snappy wallet and a sluggish one.
Recommended patterns:
Per‑wallet timeline cache
- Key:
wallet:{address}:{chainId}:page:{n} - TTL: 15–60 seconds for active traders
- Key:
Token metadata and prices cache
- Metadata: TTL in hours (rarely changes)
- Prices: TTL in seconds (e.g., 5–15s) depending on your appetite for staleness
Trace drill‑down cache
- Cache trace results keyed by
txHash - TTL: days (trace results don’t change)
- Cache trace results keyed by
Combine caching with field selection so payloads stay small and response times low.
Step 6: Multichain and Prediction Markets (Unified Timeline)
Modern trading wallets are increasingly multichain and prediction‑market aware. Your architecture should support:
- One unified timeline across chains
- Seamless inclusion of prediction market trades
Multichain Timeline Pattern
- Store activities with
chainIdandtxHash. - For a wallet view, query activities across all supported chains.
- Merge and sort by
blockTimestampdesc. - Use chain‑aware badges in UI (e.g., ETH, ARB, BASE icons).
Provider consolidation is now common. Codex, Etherscan, QuickNode, and Alchemy all emphasize “single key, many chains”. Codex currently supports 80+ networks under one auth layer.
Prediction Market Integration with Codex
Codex is one of the few providers focused on prediction market data. Using its prediction endpoints, you can:
- Fetch markets and events from platforms like Polymarket and Kalshi
- Get trades and trader analytics for a wallet
- Fold these into the same
WalletActivitytimeline
Implementation flow:
- On wallet load, call
filterPredictionEventsandfilterPredictionMarketsfor the wallet. - Normalize trades into
activityType = PREDICTION_TRADE. - Attach event metadata (question, expiry, resolution state).
This lets you present all trading activity—DeFi, swaps, CEX‑like behavior, prediction markets—in one place.
Step 7: Hardening for Production (Monitoring, Fallbacks, Provider Risk)
Finally, you need to make sure this stack survives production:
Monitor Latency, Errors, and Coverage Gaps
Track:
- P95/P99 latency per endpoint
- Error rates and timeouts
- Chain‑specific issues (e.g., L2 congestion)
Benchmark providers during implementation. Engineers will often A/B endpoints and measure response times and correctness.
Plan for Provider Changes
The ecosystem evolves. Examples:
- Dune’s Sim API retired on August 1, 2026
- SimpleHash’s Token API shut down, prompting The Graph to launch its Token API beta
Avoid building on fragile, single‑source tooling. Abstract your data layer behind internal services so you can swap providers if needed.
Codex’s infrastructure‑grade positioning and track record powering Coinbase, TradingView, Uniswap, Magic Eden, Rainbow, MoonPay, Farcaster, pump.fun, and others makes it a strong candidate when long‑term stability matters.



