A TypeScript application that analyzes swap events from PostHog to calculate total swap volume in USD. Processes events chronologically (oldest β newest) with high precision using Decimal.js.
- Event-by-event processing: Chronological analysis from oldest to newest swap events
- Dual pricing sources: Internal Prices API + CoinGecko fallback for missing tokens
- 100% token coverage: Comprehensive token mapping for NEAR ecosystem and standard tokens
- High precision: Uses Decimal.js for accurate financial calculations
- Flexible configuration: Supports volume calculation on either
amount_inoramount_out - Account filtering: Exclude test/internal accounts from calculations
- Trading pair analytics: Track top Token A β Token B conversions with volume and count
- Data quality monitoring: Check data availability and identify gaps across date ranges
- Comprehensive diagnostics: Reports unmapped tokens, missing prices, and bad amounts
- All-Time: 2,951+ swaps, $684,166+ USD volume
- Last 24h: 121 swaps, $24,463 USD volume (-43.72% swaps, -39.97% volume vs previous day)
- Previous 24h: 215 swaps, $40,751 USD volume
- Last 7d: 1,081 swaps, $152,872 USD volume
- Last 30d: 2,712 swaps, $569,981 USD volume
- Top Trading Pair: Mystery Token β USDC ($215K volume, 66 swaps)
- Most Active Pair: NEAR β NEAR Native (1,136+ swaps combined)
- Token Coverage: 100% (all tokens mapped and priced)
- Processing Speed: ~3 seconds for full analysis
-
Clone and install dependencies:
git clone <repository-url> cd posthog-swaps-metrics npm install
-
Configure environment:
cp .env.sample .env # Edit .env with your PostHog credentials -
Run analysis:
npm run run
-
Check data quality:
npm run check-data
-
Debug events (optional):
npm run debug
# PostHog Configuration
POSTHOG_BASE_URL=https://eu.posthog.com
POSTHOG_PROJECT_ID=13814
POSTHOG_API_KEY=phc_your_api_key_here
# Event Schema
SWAP_EVENT_NAME=swap
NETWORK_FILTER=mainnet
# Volume Calculation
VOLUME_SIDE=in # "in" or "out"
VOLUME_PROP_IN=amount_in
VOLUME_PROP_OUT=amount_out
# Pricing
PRICES_API_URL=
# Performance
BATCH_SIZE=500 # Events per PostHog query
MAX_EVENTS=0 # 0 = unlimited, >0 for testing# Exclude accounts by pattern or exact match
EXCLUDE_ACCOUNT_ID_PATTERNS=test,internal
EXCLUDE_ACCOUNT_IDS=test.near,bot.nearsrc/index.ts: Main application logic and event processingsrc/posthog.ts: PostHog API integration and HogQL queriessrc/prices.ts: Price fetching from internal API + CoinGecko fallbacksrc/tokenMapping.ts: Token ID to price ID mapping systemsrc/config.ts: Environment configuration and validationsrc/checkDataAvailability.ts: Data quality monitoring and gap detection
The application handles multiple token ID formats:
- Standard format:
intents:usdcβusd-coin - NEAR ecosystem:
eth.bridge.nearβethereum - Contract addresses:
17208628...β17208628...(direct mapping) - Meme tokens:
gnear-229.meme-cooking.nearβnear
- Primary: Fetch all prices from internal Prices API
- Fallback: If specific tokens missing (e.g., Kaito), fetch from CoinGecko
- Mapping: Convert token IDs to price API IDs using comprehensive mapping table
{
"sideValued": "in",
"allTime": {
"totalSwaps": 2951,
"totalVolumeUSD": 683997.460131663
},
"last24h": {
"totalSwaps": 121,
"totalVolumeUSD": 24411.73271967872,
"swapGrowthPercent": -44.24,
"volumeGrowthPercent": -40.08
},
"previous24h": {
"totalSwaps": 217,
"totalVolumeUSD": 40738.48889244697
},
"last7d": {
"totalSwaps": 1081,
"totalVolumeUSD": 152777.93104626966
},
"last30d": {
"totalSwaps": 2712,
"totalVolumeUSD": 569813.4399897703
},
"notes": {
"unmappedIntentTokenIds": [],
"priceIdMissing": [],
"badAmounts": 0
}
}sideValued: Which leg was valued (inorout)allTime: Complete historical metricslast24h: Activity in the last 24 hours with growth metricsswapGrowthPercent: Day-over-day change in transaction count (%)volumeGrowthPercent: Day-over-day change in volume (%)
previous24h: Activity 24-48 hours ago (for growth comparison)last7d: Activity in the last 7 dayslast30d: Activity in the last 30 daystotalSwaps: Number of swap events in time periodtotalVolumeUSD: Total volume in USD (high precision)unmappedIntentTokenIds: Token IDs without mapping (should be empty)priceIdMissing: Mapped tokens without price databadAmounts: Events with unparseable amounts
The project includes a data availability checker that helps monitor data quality and identify gaps in your PostHog events.
npm run check-dataπ Checking PostHog data availability...
π Data Range Summary:
Earliest swap: 2025-07-18
Latest swap: 2025-08-27
Total events: 2,951
π
Daily Data Availability (40 days with data):
β
2025-07-18: 1 swaps
β 2025-07-19: No data
β
2025-07-20: 2 swaps
β
2025-07-21: 19 swaps
...
π Data Quality Summary:
Total days in range: 41
Days with data: 40
Days without data: 1
Data coverage: 97.6%
Longest gap: 1 consecutive days
π Recent Activity (Last 7 Days):
Recent coverage: 7/7 days (100.0%)
π‘ Recommendations:
β
Excellent data coverage with minimal gaps.
- Date range analysis: Identifies the full span of available data
- Daily breakdown: Shows swap count for each day or marks missing days
- Gap detection: Identifies periods without data and measures gap lengths
- Coverage metrics: Calculates overall data coverage percentage
- Recent activity focus: Special attention to the last 7 days of data
- Actionable recommendations: Suggests next steps based on data quality
npm start: Execute main swap analysisnpm run check-data: Check data availability and identify gapsnpm run debug: Debug PostHog events and schemanpm run dev: Watch mode for developmentnpm run build: Compile TypeScript
Edit src/tokenMapping.ts:
const baseMap: Record<string, string> = {
// Add new mappings here
"new-token-id": "coingecko-id",
"another.token.near": "another-coingecko-id"
};Set MAX_EVENTS in .env for quick testing:
MAX_EVENTS=100 # Process only first 100 events-
"Unable to resolve field: swap"
- Check
SWAP_EVENT_NAMEmatches your PostHog event name - Verify PostHog API key has correct permissions
- Check
-
Low volume numbers
- Check
unmappedIntentTokenIdsfor missing token mappings - Review
priceIdMissingfor tokens needing price data
- Check
-
API timeouts
- Reduce
BATCH_SIZEfor slower connections - Check network connectivity to PostHog and price APIs
- Reduce
Use the included debug script to inspect PostHog data:
npm run debugIf the data availability checker shows gaps:
- Check PostHog ingestion: Verify events are being sent correctly
- Review date filters: Ensure your event collection covers the expected period
- Validate event naming: Confirm
SWAP_EVENT_NAMEmatches your actual events - Monitor ongoing: Run
npm run check-dataregularly to catch new gaps
- Fork the repository
- Create a feature branch
- Add token mappings or improve functionality
- Test with
MAX_EVENTS=100 - Submit a pull request
- Node.js 18+
- TypeScript 5.5+
- PostHog API access
- Network access to pricing APIs
MIT License - see LICENSE file for details.