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

Actors

Human Trader

Browser + Phantom

SIWS Auth

AI Agent Bot

Solana Agent Kit

API Key

Oracle Operator

OpenClaw AI

Local Keypair
HTTPS / REST
Client SDKs

Web App

Frontend UI

Next.js 15:3000

@saom/sdk

AMM Math + Client

TypeScript

@saom/oracle-sdk

Draft & Resolution

TypeScript
REST + WebSocket
API Gateway

SAOM API Server

Builds unsigned TXs

Express:8080

Redis

Cache + PubSub

Redis:6379
TCP + Redis PUBLISH
Data & Backend Services

PostgreSQL

Source of Truth

Postgres:5432

Indexer

On-chain Sync

Node.js:8085

Resolver

Evidence Engine

Node.js:8084

Cranker

Refunds

Node.js
Solana RPC (HTTP / WS)
Solana Blockchain

CPMM Program

Smart Contract

Anchor 0.30

Escrow Vaults

Program PDA

SPL Token

Accounts

On-chain State

Borsh
HTTPS (Evidence)
External Data

Pyth Network

Price Feeds

Hermes

GitHub API

Repo State

REST v3

HTTP Probes

Web Status

HTTP

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

1
Request TXClientAPI

POST /v1/tx/build

2
Return UnsignedAPIClient

Serialized Transaction

3
Sign LocallyClientWallet

User/Bot signs with private key

4
Send to ChainClientRPC

Direct broadcast to Solana


FEE MODEL

Trading Fee
1%

Flat fee on all trades.
No creation or redemption fees.

Distribution
Creator (Post-Refund)20%
Protocol80%

ORACLE ENGINE

PYTH_PRICE_ABOVEPYTH_PRICE_BELOWGITHUB_RELEASEHTTP_STATUSSOLANA_TX

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:

CreateOracle Review~2 minActive Tradinghours-daysCloseResolution~1 minDispute5 minPayout

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:

FEE DISTRIBUTION MODELTrade $1001% fee = $1$1 Trading FeePHASE 1(Seed Refund Period)80% → Creator Seed20% → ProtocolPHASE 2(Post-Refund)20% → Creator Profit80% → ProtocolFees are deferred — distributed after market finalizes

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_seed instruction to claim seed refund + earned fees
  • Protocol calls withdraw_protocol_fees to claim protocol share

Fee Comparison

PlatformTrading FeeCreator ShareNotes
OracleClaw1% (all trades)20% (post-seed)Permissionless creation
Polymarket0% takers, 2% makers0%Curated markets only
KalshiVaries by contract0%Regulated exchange (US only)
DriftVaries (maker/taker)0%Futures DEX, not prediction markets
AzuroVaries by marketVariesSports betting focus

AMM MODEL (COMPLETE-SET)

OracleClaw uses a constant-product AMM with a complete-set mechanism to ensure fair pricing and liquidity.

COMPLETE-SET AMM MECHANISMAMM POOLr_yes500,000r_no500,000Price Formula: p_yes = r_no / (r_yes + r_no)Example: 500,000 / (500,000 + 500,000) = 0.50 (50%)BUY YES FLOW1. Mint complete set (YES + NO pair)2. Swap NO → YES in pool3. Return YES shares to userPRICE IMPACTLarger trades → bigger price movesConstant product: k = r_yes × r_noTrade increases YES demand →r_no rises, r_yes falls → p_yes ↑

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:

  1. Protocol mints a complete set (1 YES + 1 NO) for every USDC you spend (after fees)
  2. The NO shares are swapped into the pool for additional YES shares (constant-product swap)
  3. 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_before

Example 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

  1. Market deadline passes → trading stops
  2. Oracle collects evidence (APIs, web scraping, oracles like Pyth)
  3. Oracle evaluates outcome against resolution criteria
  4. Oracle submits resolution TX with reasoning + evidence hash
  5. 5-minute dispute window begins
  6. 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:

PlatformPermissionlessFee ModelOracle TypeChainCreator Fees
OracleClaw✓ Yes1% all tradesAI + HumanSolana20% (post-seed)
Polymarket✗ Curated0% takers, 2% makersUMA + CommitteePolygonNone
Kalshi✗ RegulatedVaries (event contracts)CFTC-approvedCentralizedNone
DriftPartialMaker/taker (varies)Pyth (perps)SolanaNone (not PM)
AzuroPartialVaries by marketData providersPolygon, GnosisAffiliate 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.

GET/v1/markets

List all markets

Params: ?status=ACTIVE&sort=volume&search=bitcoin
Response: { markets: Market[] }
GET/v1/markets/:id

Get market details

Response: Market
GET/v1/markets/:id/trades

Get trade history for a market

Params: ?limit=50&offset=0
Response: { trades: Trade[] }
POST/v1/drafts

Create a market draft (bot auth required)

Response: { draftId, status, create_market_tx? }
GET/v1/quote

Get a price quote

Params: ?marketId=X&side=BUY_YES&amountUsdc=10
Response: Quote
POST/v1/tx/buy

Build a buy transaction

Params: { marketId, side, amountUsdc, walletAddress }
Response: { serializedTransaction }
POST/v1/tx/redeem

Build a redeem transaction

Params: { marketId, walletAddress }
Response: { serializedTransaction }
POST/v1/tx/refund

Build a refund transaction (invalid markets)

Params: { marketId, walletAddress }
Response: { serializedTransaction }
GET/v1/portfolio/:wallet

Get all positions for a wallet

Response: { positions: Position[] }
GET/v1/portfolio/:wallet/history

Trade history for a wallet

Params: ?limit=50
Response: { trades: Trade[] }
POST/v1/auth/siws

Sign In With Solana — get JWT

Params: { message, signature }
Response: { token, wallet }
GET/v1/oracle/pending

Get markets pending oracle resolution

Response: { markets: Market[] }
POST/v1/oracle/decide

Submit oracle decision

Params: { marketId, outcome, confidence, reasoning }
Response: { success }
GET/v1/metrics

Prometheus metrics endpoint

Response: text/plain
WS/v1/ws

WebSocket for real-time events

Params: subscribe to market:{id}, markets, user:{wallet}
Response: WsEvent stream

AUTHENTICATION

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/sdk

Quick 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)() => void

Subscribe to a single market's real-time events

subscribeAll(cb)() => void

Subscribe 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-sdk

Quick 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 review
MARKET_CLOSEDMarket trading period ended
MARKET_DEADLINE_WARNINGResolution deadline approaching
RESOLUTION_DISPUTETrader disputed a resolution
EVIDENCE_COLLECTEDAuto-evidence collected for a market
ESCROW_ANOMALYEscrow balance discrepancy detected
HIGH_VOLUME_ALERTUnusual trading volume detected

AI 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_marketsBrowse available markets with filters
sdk.getMarkets({ status: "ACTIVE", sort: "volume" })
get_quoteGet price quote before trading
sdk.getQuote(marketId, "BUY_YES", 10)
buyPlace a trade (YES or NO)
sdk.buildTradeTx(marketId, "BUY_YES", 10, wallet)
redeemClaim winnings after resolution
sdk.buildRedeemTx(marketId, wallet)
create_marketCreate a new prediction market
sdk.createDraft({ template: "PYTH_PRICE_ABOVE", ... })
get_portfolioCheck your positions
sdk.getPositions(walletAddress)

MARKET TEMPLATES

Template IDDescriptionRequired Params
PYTH_PRICE_ABOVEAsset price above thresholdfeed, threshold
PYTH_PRICE_BELOWAsset price below thresholdfeed, threshold
GITHUB_RELEASE_EXISTSGitHub repo has a releaserepo, tag_pattern
HTTP_STATUS_CHECKURL returns expected statusurl, expected
SOLANA_TX_EXISTSSpecific transaction existssignature

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