Skip to content

edycutjong/nansen-polymarket-oracle

Repository files navigation

███╗   ██╗ █████╗ ███╗   ██╗███████╗███████╗███╗   ██╗
████╗  ██║██╔══██╗████╗  ██║██╔════╝██╔════╝████╗  ██║
██╔██╗ ██║███████║██╔██╗ ██║███████╗█████╗  ██╔██╗ ██║
██║╚██╗██║██╔══██║██║╚██╗██║╚════██║██╔══╝  ██║╚██╗██║
██║ ╚████║██║  ██║██║ ╚████║███████║███████╗██║ ╚████║
╚═╝  ╚═══╝╚═╝  ╚═╝╚═╝  ╚═══╝╚══════╝╚══════╝╚═╝  ╚═══╝

 ██████╗ ██████╗  █████╗  ██████╗██╗     ███████╗
██╔═══██╗██╔══██╗██╔══██╗██╔════╝██║     ██╔════╝
██║   ██║██████╔╝███████║██║     ██║     █████╗
██║   ██║██╔══██╗██╔══██║██║     ██║     ██╔══╝
╚██████╔╝██║  ██║██║  ██║╚██████╗███████╗███████╗
 ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝ ╚═════╝╚══════╝╚══════╝

🔮 Smart Money × Prediction Market Intelligence

License Node 20 Node 22 Node 24 Tests Coverage Suites Nansen CLI

"Don't bet against Smart Money. See what they see."

Cross-reference on-chain whale positions with prediction market odds to identify mispriced outcomes.

🏆 Built for Nansen CLI Build Challenge — Week 3Build Something Real

Nansen Oracle Demo


💡 The Problem

Prediction markets show crowd consensus. But the crowd is often wrong.

Smart Money — hedge funds, whale traders, and institutional wallets — frequently takes positions that diverge from the market. These hidden signals are buried in on-chain data that most traders never see.

⚡ The Solution

The Oracle surfaces one actionable insight: "Where is Smart Money silently betting against the crowd?"

Market Odds say:     12% YES on "Will Bitcoin hit $200K by June 2026?"
Smart Money says:    67% positioned on YES ($6.0M deployed)
Divergence:          🔥 +55 pts — SM is massively bullish vs. crowd

When Smart Money conviction diverges significantly from market odds, it signals a potential mispricing.


🎯 How It Works

Core Pipeline: scanenrichanalyzetrade

Core Pipeline Architecture

  1. Scan — Fetches active prediction markets from Nansen CLI research prediction-market endpoints
  2. Enrich — Cross-references holder addresses against Nansen's profiler labels to identify Smart Money wallets (Funds, Smart Traders, 90D Traders, etc.)
  3. Analyze — Calculates a capital-weighted SM Divergence Score (-100 to +100):
    • Positive = SM is more bullish than market odds
    • Negative = SM is more bearish than market odds
    • Markets with |score| ≥ 40 are flagged as 🔥 EXTREME alpha opportunities
  4. Trade (New in v2.0) — Automatically hedges identified Extreme divergence signals using 1inch integration (trade execute, trade quote) and on-chain infrastructure (wallet create, wallet status).

The SM Divergence Score

// SM Divergence Score: -100 to +100
// Positive = SM more bullish than market
// Negative = SM more bearish than market

function calculateDivergence(smHolders, allHolders, marketOdds):
  1. Capital-weight each SM holder's position (YES = +weight, NO = -weight)
  2. Normalize weighted conviction from [-1, 1] to [0, 1]
  3. Divergence = (SM_conviction - market_odds) × 100
Score Level Signal
±40+ 🔥 EXTREME SM strongly disagrees with market
±25+ ⚠️ HIGH Notable divergence worth monitoring
±10+ 📊 MODERATE Mild divergence
<±10 ✅ LOW/🤝 ALIGNED SM agrees with market consensus

🛡️ Cross-Chain Proxy Hedging

Polymarket is typically settled in USDC on Polygon. When the Oracle identifies an EXTREME bullish divergence (Smart Money strongly believes YES before the crowd), it can automatically execute a proxy hedge on Base L2.

  • Bullish Output: Borrows conviction from Smart Money to swap USDC → Target Asset (e.g., WETH for Crypto categories) to capture upside.
  • Bearish Output: Automatically scales out to stables (Target Asset → USDC) to protect capital.

Powered by Nansen CLI: The Oracle natively integrates Nansen's wallet status/wallet create, research token info, trade quote, and trade execute endpoints to perform these actions entirely autonomously upon your approval.


📸 Screenshots

Scan — Market Discovery & Divergence Table

Scan Results

Analyze — Deep Market Intel

Deep Analysis

Report — Alpha Export

Report Output

Trade — Autonomous Agent Execution

Trade Agent

Telemetry — Provable API Usage

Telemetry - Deep Analysis
Every decision is provable. The Oracle tracks and displays every Nansen CLI call made during the analysis session.

Telemetry - Full Report


🚀 Quick Start

1. Installation & Setup

# Install local dependencies
npm install

# Build and link the CLI globally
npm run build
npm link

# Install and configure Nansen CLI
npm install -g nansen-cli
nansen auth login

2. Run the Oracle

🎬 Quick Demo (No API Key Required):

bash demo.sh

Nansen Oracle Splash

Data Modes

Mode Command Description
🔁 Replay (default) bash demo.sh Real recorded API data — no API key needed
🧪 Mock bash demo.sh mock Synthetic data for development
🔴 Live bash demo.sh live Live Nansen API (requires nansen auth login)
# Replay mode — real recorded data, zero API calls
NANSEN_REPLAY=true nansen-oracle scan --limit 10

# Mock mode — synthetic test data
NANSEN_MOCK=true nansen-oracle scan --limit 8

# Live mode — real-time API (default when no env var is set)
nansen-oracle scan

# Record mode — capture live API responses for replay
NANSEN_RECORD=true nansen-oracle scan --limit 5

💡 nansen-record.log contains captured responses from a real Nansen API session — real markets, real whale addresses — without consuming API credits. Generate your own with NANSEN_RECORD=true.


🛠️ Commands

Command Description
scan Discover prediction markets ranked by SM divergence
analyze <id> Deep analysis of a specific market: holders, trades, PnL
report Full alpha report exported as Markdown or JSON
trade Autonomous agent that trades EXTREME mispricings via proxy hedge
watch <id> Live monitoring with Smart Money position change alerts
address <addr> Wallet-level SM lookup: labels, PnL, recent trades
CLI Options
scan:
  -c, --category <cat>     Filter by market category
  -v, --min-volume <usd>   Minimum volume (default: 10000)
  -l, --limit <n>          Markets to scan (default: 20)
  --chain <chain>          Chain for profiler (default: ethereum)

analyze:
  --chain <chain>          Chain for profiler (default: ethereum)

report:
  -f, --format <fmt>       Output: md, json, table (default: md)
  -o, --output <path>      File path for report
  -l, --limit <n>          Markets to include (default: 20)

trade:
  -a, --amount <usd>       Amount to trade per signal (USDC)
  -m, --max-usd <usd>      Maximum total trade size limit (default 100)
  -t, --threshold <score>  Minimum divergence score (default 40)
  --live                   Execute live trades (default is dry-run)

watch:
  -i, --interval <secs>    Refresh interval in seconds (default: 60)
  --chain <chain>          Chain for profiler (default: ethereum)

🏗️ Architecture

src/
├── index.ts              # CLI entrypoint (Commander.js)
├── commands/
│   ├── scan.ts           # Market discovery + enrichment
│   ├── analyze.ts        # Single market deep-dive
│   ├── report.ts         # Full report generation
│   ├── trade.ts          # Autonomous proxy-hedge trading agent
│   ├── watch.ts          # Real-time monitoring
│   └── address.ts        # Wallet-level SM lookup
├── lib/
│   ├── nansen.ts         # CLI wrapper (exec → JSON) with debug logging
│   ├── enricher.ts       # SM label cross-referencing + rate limiting
│   ├── analyzer.ts       # Divergence score algorithm
│   ├── trading.ts        # Proxy-hedge signal mapping + execution
│   ├── cache.ts          # TTL cache for label lookups
│   ├── formatter.ts      # Terminal + Markdown output
│   ├── telemetry.ts      # Provable API usage tracking
│   ├── known-wallets.ts  # Known SM wallet registry
│   ├── mock.ts           # Mock data generator (12 markets, 8 SM wallets)
│   └── replay.ts         # API response replay engine
└── types/
    ├── market.ts          # Prediction market types
    ├── smartmoney.ts      # SM labels + enriched holders
    ├── trading.ts         # Trade signal + execution types
    └── report.ts          # Analysis output types

📡 Nansen CLI Endpoints Used (20)

Nansen API Usage Analytics

# Endpoint Purpose
1 research prediction-market market-screener Discover active markets
2 research prediction-market event-screener Event-level overview
3 research prediction-market top-holders Who holds positions
4 research prediction-market trades-by-market Trading activity
5 research prediction-market pnl-by-market PnL leaderboard
6 research prediction-market ohlcv Price history
7 research prediction-market orderbook Liquidity depth
8 research prediction-market pnl-by-address SM prediction accuracy
9 research prediction-market trades-by-address SM trading patterns
10 research prediction-market categories Market categorization
11 research prediction-market position-detail Position breakdown
12 research profiler labels Wallet classification
13 research profiler pnl-summary Wallet performance
14 research profiler batch Batch wallet labeling
15 research smart-money netflow Cross-chain flow context
16 research smart-money holdings SM portfolio analysis
17 research token info Token price/metadata
18 trade quote DEX swap quoting via 1inch
19 trade execute On-chain trade execution
20 wallet status / wallet create Wallet infrastructure

✅ Testing

223 unit tests · 16 suites · 100% coverage · all thresholds enforced

# Full CI pipeline (typecheck + lint + test:coverage)
npm run ci

# Run tests only
npm test

# Run with coverage enforcement (100% threshold)
npm run test:coverage
 Test Files  16 passed (16)
      Tests  223 passed (223)

 % Coverage report from v8
-------------------|---------|----------|---------|---------
File               | % Stmts | % Branch | % Funcs | % Lines
-------------------|---------|----------|---------|---------
All files          |     100 |      100 |     100 |     100
 commands (6)      |     100 |      100 |     100 |     100
 lib (10)          |     100 |      100 |     100 |     100
-------------------|---------|----------|---------|---------
What's tested (16 source files, 16 test suites)
Area Tests Coverage
Divergence algorithm Capital-weighting, edge cases, score bounds analyzer.ts 100%
SM enrichment Label matching, batch processing, rate limiting enricher.ts 100%
TTL cache Expiry, invalidation, getOrFetch cache.ts 100%
Mock data system 20 command routes, all branch paths mock.ts 100%
API replay engine Record, replay, fallback replay.ts 100%
Nansen wrapper Exec, error handling, debug logging nansen.ts 100%
Trading engine Signal mapping, proxy hedging, dry-run trading.ts 100%
Telemetry Receipt rendering, call tracking telemetry.ts 100%
All 6 CLI commands scan, analyze, report, trade, watch, address commands/* 100%
Formatter Terminal tables, markdown export formatter.ts 100%
Error handling Network failures, malformed data, graceful degradation All files

🏆 Hackathon Criteria

Criteria How Oracle Delivers Evidence
Creativity First prediction market × Smart Money cross-reference tool No existing tool combines Nansen profiler labels with Polymarket positions
Usefulness Directly actionable: "SM bets $7.9M that BTC hits $200K — but the market says 12%" Real divergence signals from live Nansen data
Technical Depth 20 endpoints, cross-referencing, divergence algorithm, autonomous trade agent 223 tests, 100% coverage, 16 source files, 4 data modes
Presentation Output IS the pitch — rich terminal UI with telemetry receipts Every API call is provable and displayed

Why This Wins

  1. Most Endpoints — 20 distinct Nansen CLI endpoints orchestrated in a single pipeline
  2. Production Quality — 223 tests, 100% coverage (statements, branches, functions, lines), enforced CI
  3. Real Alpha — Not a dashboard. Not a wrapper. A system that finds what Smart Money knows and the crowd doesn't
  4. Full Autonomyscan → enrich → analyze → trade runs end-to-end without human intervention
  5. Provable Usage — Built-in telemetry receipt proves every Nansen API call made during execution

📄 License

MIT © edycutjong


📊 Data by Nansen · #NansenCLI · @nansen_ai

About

Smart Money × Prediction Market Intelligence. Find mispriced Polymarket odds using on-chain conviction.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors