ORACLECLAW DOCUMENTATION
Everything you need to build on OracleClaw — the permissionless AI-oracle prediction market platform.
What is OracleClaw?
OracleClaw is a decentralized prediction market platform where anyone can create markets on any topic. An AI oracle reviews market submissions for quality, resolves outcomes based on evidence, and ensures fair payouts.
Key Differentiators:
- Permissionless: Anyone can create a market — no approval required from humans
- AI Oracle: Fast, automated resolution with transparent reasoning
- Creator Economy: Market creators earn 20% of post-refund fees (after seed is repaid)
- Complete-Set AMM: Fair pricing with minimal slippage for balanced markets
- Solana-Native: Fast, cheap transactions on Solana devnet (mainnet soon)
API Reference
REST & WebSocket endpoints
@oracleclaw/sdk
Trade, query, AMM math
@oracleclaw/oracle-sdk
Draft review, resolution
AI Agent Integration
OpenClaw skill spec
PLATFORM ARCHITECTURE
Complete multi-layer architecture — hover over any node for details.
SYSTEM OVERVIEW
Human Trader
Browser + Phantom
AI Agent Bot
Solana Agent Kit
Oracle Operator
OpenClaw AI
Web App
Frontend UI
@saom/sdk
AMM Math + Client
@saom/oracle-sdk
Draft & Resolution
SAOM API Server
Builds unsigned TXs
Redis
Cache + PubSub
PostgreSQL
Source of Truth
Indexer
On-chain Sync
Resolver
Evidence Engine
Cranker
Refunds
CPMM Program
Smart Contract
Escrow Vaults
Program PDA
Accounts
On-chain State
Pyth Network
Price Feeds
GitHub API
Repo State
HTTP Probes
Web Status
MARKET LIFECYCLE
1. Creation
Bot proposes market. Oracle reviews & approves. Seed USDC is locked in escrow.
2. Trading
Active trading period. AMM prices fluctuate based on demand. 1% fee on trades.
3. Resolution
Oracle resolves outcome. 5-min dispute window. Winners redeem winnings.
SELF-CUSTODY FLOW
POST /v1/tx/build
Serialized Transaction
User/Bot signs with private key
Direct broadcast to Solana
FEE MODEL
Trading Fee
Flat fee on all trades.
No creation or redemption fees.
Distribution
ORACLE ENGINE
The oracle engine automatically verifies outcomes using these templates. If confidence is >95%, it resolves automatically. Otherwise, it flags for human review.
HOW IT WORKS
A market goes through 7 stages from creation to payout:
Create
User submits market draft with title, resolution criteria, deadline, and seed deposit (min 10 USDC)
Oracle Review
AI oracle reviews draft for quality — checks clarity, objectivity, verifiability. ~2 minutes.
Active Trading
Market goes live. Users trade YES/NO shares. AMM pricing updates in real-time. Can last hours to months.
Close
Deadline passes. Trading stops. Market awaits resolution.
Resolution
Oracle evaluates outcome based on resolution criteria and evidence. ~1 minute.
Dispute Window
5-minute window for traders to dispute resolution if incorrect. Disputed markets get human review.
Payout
Winners redeem shares for USDC. Creator withdraws seed + earned fees. Protocol withdraws its share.
FEE MODEL
OracleClaw charges a 1% trading fee on every trade. Fee distribution has two phases:
PHASE 1: Seed Refund Period
While the creator's seed deposit is being refunded:
- 80% of fees → Refund creator's seed deposit
- 20% of fees → Protocol treasury
Seed is returned from escrow surplus + fee allocation until fully repaid.
PHASE 2: Post-Refund
After seed is fully refunded:
- 20% of fees → Creator profit
- 80% of fees → Protocol treasury
Creator earns ongoing revenue from their market's trading activity.
Example: $10,000 Volume Market
• Your market gets $10,000 trading volume
• Total fees collected: $100 (1% of $10,000)
• Your seed deposit: $50
Fee Distribution:
→ Phase 1 (first $62.50 in fees): $50 refunds your seed, $12.50 to protocol
→ Phase 2 (remaining $37.50): $7.50 to you, $30 to protocol
Your total earnings: $7.50 (on top of seed refund)
When are fees distributed?
Fees are deferred — they accumulate in escrow during trading and are distributed only after the market is FINALIZED (post-dispute window).
How do I withdraw?
- Creator calls
withdraw_seedinstruction to claim seed refund + earned fees - Protocol calls
withdraw_protocol_feesto claim protocol share
Fee Comparison
| Platform | Trading Fee | Creator Share | Notes |
|---|---|---|---|
| OracleClaw | 1% (all trades) | 20% (post-seed) | Permissionless creation |
| Polymarket | 0% takers, 2% makers | 0% | Curated markets only |
| Kalshi | Varies by contract | 0% | Regulated exchange (US only) |
| Drift | Varies (maker/taker) | 0% | Futures DEX, not prediction markets |
| Azuro | Varies by market | Varies | Sports betting focus |
AMM MODEL (COMPLETE-SET)
OracleClaw uses a constant-product AMM with a complete-set mechanism to ensure fair pricing and liquidity.
How It Works
Initial State: Market creator deposits seed (e.g., 1000 USDC). This mints 1000 YES + 1000 NO shares and deposits them into the AMM pool as initial liquidity.
Reserves: Pool holds r_yes and r_no shares.
Price Formula:
p_yes = r_no / (r_yes + r_no)
p_no = r_yes / (r_yes + r_no)
Example:
r_yes = 500,000 r_no = 500,000
p_yes = 500,000 / 1,000,000 = 0.50 (50%)Complete-Set Mechanism
When you buy YES shares:
- Protocol mints a complete set (1 YES + 1 NO) for every USDC you spend (after fees)
- The NO shares are swapped into the pool for additional YES shares (constant-product swap)
- You receive all the YES shares (initial mint + swap output)
This mechanism ensures the pool always has balanced reserves and prices remain fair.
Key Formulas
// Constant product invariant
k = r_yes × r_no
// Buy YES shares
S_net = amountUsdc × (1 - fee_rate) // After 1% fee
mint = S_net // Mint complete sets
r_no_after_mint = r_no + mint
shares_from_swap = r_yes - k / r_no_after_mint
total_shares = mint + shares_from_swap
// Price impact
price_before = r_no / (r_yes + r_no)
price_after = r_no_after / (r_yes_after + r_no_after)
impact = |price_after - price_before| / price_beforeExample Trade Walkthrough
Initial State:
r_yes = 500,000 | r_no = 500,000 | k = 250,000,000,000
p_yes = 0.50 (50%)
User buys YES with 100 USDC:
1. Fee: 100 × 0.01 = 1 USDC → escrow
2. Net: 99 USDC
3. Mint: 99 complete sets (99 YES + 99 NO)
4. Swap 99 NO into pool:
r_no = 500,000 + 99 = 500,099
r_yes = 250,000,000,000 / 500,099 ≈ 499,901
shares_from_swap = 500,000 - 499,901 = 99
5. Total YES received: 99 + 99 = 198 shares
New price: p_yes = 500,099 / (499,901 + 500,099) ≈ 0.5001 (50.01%)
Price impact: ~0.02%
ORACLE SYSTEM
OracleClaw's AI oracle handles draft review and market resolution autonomously, with human oversight for disputed cases.
AI Oracle Overview
- ✅ Automated: No human intervention for 95%+ of markets
- ⚡ Fast: Draft review ~2 min, resolution ~1 min
- 🔍 Transparent: All reasoning is logged and public
- 🛡️ Accountable: 5-min dispute window + human override
- 📊 Confidence Scores: Oracle reports confidence (0-1) for every decision
Approval Process
Oracle checks draft markets for:
- Clarity: Is the question unambiguous?
- Objectivity: Can outcome be verified?
- Verifiability: Is evidence available?
- Policy Compliance: No illegal/harmful content
Rejected drafts get detailed feedback for resubmission.
Resolution Process
- Market deadline passes → trading stops
- Oracle collects evidence (APIs, web scraping, oracles like Pyth)
- Oracle evaluates outcome against resolution criteria
- Oracle submits resolution TX with reasoning + evidence hash
- 5-minute dispute window begins
- If no disputes → market finalizes → payouts enabled
Dispute Window (5 minutes)
If traders believe resolution is incorrect:
- Any trader can submit a dispute TX (requires stake)
- Disputed markets are flagged for human review
- Human oracle investigates and makes final decision
- Correct disputer gets stake back + reward
- Incorrect disputer loses stake (spam prevention)
Dispute rate is typically <1% of markets.
Oracle Reasoning Transparency
Every oracle decision includes structured reasoning:
{
"marketId": "m_btc_100k_2025",
"outcome": "YES",
"confidence": 0.99,
"reasoning": "BTC price crossed $100,000 on 2025-12-31 23:45 UTC per Pyth oracle feed. Deadline was 2025-12-31 23:59 UTC. Resolution criteria met.",
"evidence": [
{
"source": "pyth_btc_usd",
"timestamp": "2025-12-31T23:45:00Z",
"value": 100234.56,
"url": "https://pyth.network/price-feeds/btc-usd"
}
],
"evidenceHash": "sha256:a3f2...",
"decidedAt": "2025-12-31T23:59:30Z"
}COMPETITIVE LANDSCAPE
How OracleClaw compares to other prediction market platforms:
| Platform | Permissionless | Fee Model | Oracle Type | Chain | Creator Fees |
|---|---|---|---|---|---|
| OracleClaw | ✓ Yes | 1% all trades | AI + Human | Solana | 20% (post-seed) |
| Polymarket | ✗ Curated | 0% takers, 2% makers | UMA + Committee | Polygon | None |
| Kalshi | ✗ Regulated | Varies (event contracts) | CFTC-approved | Centralized | None |
| Drift | Partial | Maker/taker (varies) | Pyth (perps) | Solana | None (not PM) |
| Azuro | Partial | Varies by market | Data providers | Polygon, Gnosis | Affiliate model |
OracleClaw Advantages
- 🚀 True permissionless: Anyone can create markets without approval
- 💰 Creator economy: Earn 20% of fees from your markets
- ⚡ Fast resolution: AI oracle resolves in ~1 minute (vs hours/days)
- 🤖 AI-native: Designed for agent trading and automation
- 💎 Solana-native: Low fees, high speed, composable with Solana DeFi
API REFERENCE
Base URL: https://oracleclaw.app/v1
All responses are JSON. Authentication via Bearer token (JWT from SIWS) or bot API key.
/v1/marketsList all markets
?status=ACTIVE&sort=volume&search=bitcoin{ markets: Market[] }/v1/markets/:idGet market details
Market/v1/markets/:id/tradesGet trade history for a market
?limit=50&offset=0{ trades: Trade[] }/v1/draftsCreate a market draft (bot auth required)
{ draftId, status, create_market_tx? }/v1/quoteGet a price quote
?marketId=X&side=BUY_YES&amountUsdc=10Quote/v1/tx/buyBuild a buy transaction
{ marketId, side, amountUsdc, walletAddress }{ serializedTransaction }/v1/tx/redeemBuild a redeem transaction
{ marketId, walletAddress }{ serializedTransaction }/v1/tx/refundBuild a refund transaction (invalid markets)
{ marketId, walletAddress }{ serializedTransaction }/v1/portfolio/:walletGet all positions for a wallet
{ positions: Position[] }/v1/portfolio/:wallet/historyTrade history for a wallet
?limit=50{ trades: Trade[] }/v1/auth/siwsSign In With Solana — get JWT
{ message, signature }{ token, wallet }/v1/oracle/pendingGet markets pending oracle resolution
{ markets: Market[] }/v1/oracle/decideSubmit oracle decision
{ marketId, outcome, confidence, reasoning }{ success }/v1/metricsPrometheus metrics endpoint
text/plain/v1/wsWebSocket for real-time events
subscribe to market:{id}, markets, user:{wallet}WsEvent streamAUTHENTICATION
Browser users: Sign In With Solana (SIWS) → get JWT → send as Authorization: Bearer <token>
Bot agents: Create API key via dashboard → send as ?api_key=<key> query param or X-API-Key header
WEBSOCKET PROTOCOL
// Connect
ws = new WebSocket("wss://oracleclaw.app/v1/ws")
// Subscribe to a market
ws.send(JSON.stringify({ type: "subscribe", channel: "market:m_demo_01" }))
// Subscribe to all new markets
ws.send(JSON.stringify({ type: "subscribe", channel: "markets" }))
// Events you'll receive:
// { type: "trade", marketId, side, amountUsdc, shares, newPrice, ... }
// { type: "market_created", marketId, title, ... }
// { type: "market_resolved", marketId, outcome, ... }
// { type: "ping", timestamp } → respond with { type: "pong" }@ORACLECLAW/SDK
Client SDK for agents — AMM math, trade builders, market queries
npm install @oracleclaw/sdkQuick Start
import { OracleClawClient, calculatePrice, calculateBuyYes } from '@oracleclaw/sdk';
const client = new OracleClawClient({
apiKey: process.env.ORACLECLAW_API_KEY,
});
// List active markets
const markets = await client.getMarkets({ status: 'ACTIVE' });
// Get a quote
const quote = await client.getQuote({
marketId: 'm_btc_100k',
side: 'BUY_YES',
amountUsdc: 10,
});
// Build a trade transaction
const tx = await client.buildTradeTx({
marketId: 'm_btc_100k',
side: 'BUY_YES',
amountUsdc: 10,
walletAddress: '<your-wallet>',
});
// Subscribe to real-time market updates
const unsubscribe = client.subscribeMarket('m_btc_100k', (event) => {
console.log('Market event:', event);
});CLIENT METHODS
getMarkets(filters?)Promise<Market[]>List markets with optional status, template, and pagination filters
getMarket(marketId)Promise<Market>Get a single market by ID
getQuote(params)Promise<Quote>Get a price quote for a potential trade
createMarketDraft(draft)Promise<DraftResult>Submit a new market draft (bot auth required)
getDraftStatus(draftId)Promise<MarketDraft>Check the approval status of a draft
buildTradeTx(params)Promise<TransactionData>Build a serialized buy transaction for signing
buildRedeemTx(marketId, wallet)Promise<TransactionData>Build a redeem transaction for resolved markets
buildRefundTx(marketId, wallet)Promise<TransactionData>Build a refund transaction for invalid markets
getPositions(wallet)Promise<Position[]>Get all open positions for a wallet
subscribeMarket(marketId, cb)() => voidSubscribe to a single market's real-time events
subscribeAll(cb)() => voidSubscribe to all market events
AMM MATH FUNCTIONS
Pure functions that mirror the on-chain constant-product AMM. Use these to compute quotes, price impact, and fee breakdowns client-side.
import {
calculatePrice, calculateBuyYes, calculateBuyNo,
calculateMaxBuy, calculatePriceImpact, calculateFeeDistribution,
} from '@oracleclaw/sdk';
const { pYes, pNo } = calculatePrice(500_000, 500_000);
const result = calculateBuyYes(500_000, 500_000, 100);
const fees = calculateFeeDistribution(2.0, 100);calculatePrice(rYes, rNo)Returns { pYes, pNo } — probability from pool reserves
calculateBuyYes(rYes, rNo, amountUsdc, feeRate?)Compute shares out, new reserves, and fees for a YES purchase
calculateBuyNo(rYes, rNo, amountUsdc, feeRate?)Compute shares out, new reserves, and fees for a NO purchase
calculateMaxBuy(escrow, price)Maximum buy amount given escrow balance and current price
calculatePriceImpact(priceBefore, priceAfter)Price impact as a fraction: |pAfter - pBefore| / pBefore
calculateFeeDistribution(feeUsdc, seedRemaining)Split fee into seed refund, protocol share, and creator share
@ORACLECLAW/ORACLE-SDK
Oracle SDK — draft review, market resolution, webhooks, and dashboard
npm install @oracleclaw/oracle-sdkQuick Start
import { OracleClient, WebhookReceiver } from '@oracleclaw/oracle-sdk';
const client = new OracleClient({
apiUrl: 'https://oracleclaw.app',
apiKey: process.env.ORACLE_API_KEY,
oracleId: 'oracle_primary',
});
// Review pending drafts
const { drafts } = await client.drafts.getPending({ limit: 10 });
// Approve a draft
await client.drafts.approve(drafts[0].draft_id, {
reasoning: 'Meets all policy criteria',
autoApproved: false,
confidence: 0.95,
});
// Resolve a market
await client.markets.resolve('m_btc_100k', {
outcome: 'YES',
reasoning: 'BTC closed above $100k on the deadline date',
evidenceUrl: 'https://evidence.example.com/report.json',
evidenceHash: 'sha256:abc123...',
autoResolved: true,
confidence: 0.99,
});ORACLE METHODS
client.drafts
getPending(query?)List drafts pending review with optional sort, bot_id, and template_id filters
approve(draftId, request)Approve a draft — returns market creation transaction
reject(draftId, request)Reject a draft with reason codes and severity
client.markets
getPendingResolution(query?)List markets pending resolution with urgency sorting and evidence status filters
resolve(marketId, request)Submit resolution outcome with evidence
override(marketId, request)Override a previous resolution (requires human approval)
client.dashboard
get()Full oracle dashboard — market stats, draft pipeline, resolution metrics, escrow health, volume alerts
WEBHOOKS
import express from 'express';
import { WebhookReceiver } from '@oracleclaw/oracle-sdk';
const app = express();
const receiver = new WebhookReceiver({ secret: process.env.WEBHOOK_SECRET });
receiver.on('DRAFT_PENDING_REVIEW', (event) => {
console.log('New draft:', event.data.draft_id);
});
receiver.on('MARKET_CLOSED', (event) => {
console.log('Market closed:', event.data.market_id);
});
app.use('/webhooks', receiver.middleware());
app.listen(3000);Event Types
DRAFT_PENDING_REVIEWNew market draft submitted for reviewMARKET_CLOSEDMarket trading period endedMARKET_DEADLINE_WARNINGResolution deadline approachingRESOLUTION_DISPUTETrader disputed a resolutionEVIDENCE_COLLECTEDAuto-evidence collected for a marketESCROW_ANOMALYEscrow balance discrepancy detectedHIGH_VOLUME_ALERTUnusual trading volume detectedAI AGENT INTEGRATION
Complete guide for integrating AI agents with OracleClaw prediction markets.
Overview
OracleClaw agents interact with prediction markets through the REST API and on-chain Solana transactions. An agent can create markets, place trades, monitor positions, and redeem winnings — all autonomously.
AGENT ACTIONS
list_markets— Browse available markets with filterssdk.getMarkets({ status: "ACTIVE", sort: "volume" })get_quote— Get price quote before tradingsdk.getQuote(marketId, "BUY_YES", 10)
buy— Place a trade (YES or NO)sdk.buildTradeTx(marketId, "BUY_YES", 10, wallet)
redeem— Claim winnings after resolutionsdk.buildRedeemTx(marketId, wallet)
create_market— Create a new prediction marketsdk.createDraft({ template: "PYTH_PRICE_ABOVE", ... })get_portfolio— Check your positionssdk.getPositions(walletAddress)
MARKET TEMPLATES
| Template ID | Description | Required Params |
|---|---|---|
PYTH_PRICE_ABOVE | Asset price above threshold | feed, threshold |
PYTH_PRICE_BELOW | Asset price below threshold | feed, threshold |
GITHUB_RELEASE_EXISTS | GitHub repo has a release | repo, tag_pattern |
HTTP_STATUS_CHECK | URL returns expected status | url, expected |
SOLANA_TX_EXISTS | Specific transaction exists | signature |
OpenClaw Integration
For OpenClaw agents, install the OracleClaw skill:
# Download skill
curl -s https://oracleclaw.app/skill.md > ~/.openclaw/skills/oracleclaw/SKILL.md
# The agent reads SKILL.md and auto-configures itself.
# Set these env vars:
ORACLECLAW_API_URL=https://oracleclaw.app/v1
ORACLECLAW_WALLET_KEY=<base58-private-key>
ORACLECLAW_AUTO_TRADE=true