Sway is in public testnet beta on Base Sepolia — gasless, non-custodial, auto-resolving. Start building →
Sway the odds.

Sway Documentation

Build on a gasless, non-custodial prediction market with transparent, automatic on-chain resolution — for people, wallets, and AI agents alike.

Get Started →
// No SDK required — Sway is a plain REST API.
const SWAY = 'https://api.swaytrade.xyz';

// 1. Read the live deployment (chain + fee policy)
const dep = await fetch(`${SWAY}/deployment`).then(r => r.json());
console.log(dep.chain_id, dep.fee_bps); // 84532 150

// 2. Browse open markets
const markets = await fetch(`${SWAY}/markets`).then(r => r.json());
const m = markets[0];
console.log(m.question, m.resolver, m.voided);
# No SDK required — Sway is a plain REST API.
import requests
SWAY = "https://api.swaytrade.xyz"

# 1. Read the live deployment (chain + fee policy)
dep = requests.get(f"{SWAY}/deployment").json()
print(dep["chain_id"], dep["fee_bps"])  # 84532 150

# 2. Browse open markets
markets = requests.get(f"{SWAY}/markets").json()
m = markets[0]
print(m["question"], m["resolver"], m["voided"])

Get familiar with Sway

Learn the fundamentals, explore the API, and start building on a prediction market designed to be transparent and verifiable end-to-end.


Getting Started

Quickstart

Fetch market data, read the fee policy, and stream live prices — in a few requests, with nothing to install.

Base URL

Every REST call hits a single host. The beta runs on Base Sepolia.

https://api.swaytrade.xyztestnet beta · Base Sepolia (84532)

1 · Read the deployment

/deployment is the source of truth for the active chain, the contract addresses, and the live fee policy. Read it once at startup and cache it.

const dep = await fetch('https://api.swaytrade.xyz/deployment').then(r => r.json());
// { chain_id: 84532, fee_bps: 150, fee_mode: 'flat',
//   resolver, reportable_resolver, escrow, exchange, relayer_ready: true }
dep = requests.get("https://api.swaytrade.xyz/deployment").json()
# {'chain_id': 84532, 'fee_bps': 150, 'fee_mode': 'flat',
#  'escrow': '0x…', 'exchange': '0x…', 'relayer_ready': True}

2 · List & read markets

GET /markets returns every live market; GET /markets/{'{'}id{'}'} returns one. Each row carries its question, the bound resolver, and status flags (resolved, voided, archived).

const markets = await fetch('https://api.swaytrade.xyz/markets').then(r => r.json());
const m = markets.find(x => !x.resolved && !x.archived);
const market = await fetch(`https://api.swaytrade.xyz/markets/${m.market_id}`).then(r => r.json());
markets = requests.get("https://api.swaytrade.xyz/markets").json()
m = next(x for x in markets if not x["resolved"] and not x["archived"])
market = requests.get(f"https://api.swaytrade.xyz/markets/{m['market_id']}").json()

3 · Stream live prices

Subscribe to the WebSocket for real-time fills and odds. See WebSockets for the full event set.

const ws = new WebSocket('wss://api.swaytrade.xyz/agent/stream');
ws.onmessage = (e) => {
  const ev = JSON.parse(e.data);
  if (ev.type === 'fill') console.log('fill', ev.market_id, ev.price);
};
Next: to place orders you sign an order from your Safe smart account (gasless). See Authentication and Orders & Settlement.

Core Concepts

Markets & Events

A market is a single yes/no question about the world, with a defined close time and a resolution source.

Each market has a stable market_id (keccak256(questionId, resolver, seq)), a human question, a close time (trading ends), and a bound resolver that settles it. Related markets group into events — e.g. a multi-candidate race is several mutually-exclusive yes/no markets shown as one field.

Outcomes & Shares

Every market has two outcomes — ● Yes and ● No. You hold outcome shares; a winning share redeems for $1.00, a losing share for $0. Price is the market's implied probability, quoted 0–1 (e.g. 0.55 = 55%). Buying Yes is Sway Yes; buying No is Sway No.

Resolution & Oracles

Sway resolves markets automatically and on-chain wherever possible. A market is bound to one of four resolver tiers:

TierHow it settlesExample
Api3A Tier-1 API3 dAPI price feed read on-chain at close."ETH ≥ $4,000 by Friday?"
SignedAn AirnodeHub-signed attestation verified on-chain (EIP-191).Esports, crypto headers
OptimisticA bonded assertion with a dispute window → committee vote.Subjective / news
ReportableOperator-reported outcome (testnet / bootstrapping).Manual markets

If a market can't resolve (e.g. an oracle was never configured), it can be voided to a 50/50 refund — no funds are ever stranded. See Void & Refunds.

Non-custody & Escrow

Sway never holds your money. Your balance lives in your own Safe smart account; collateral for open positions sits in an on-chain Escrow contract, backed 1:1. Every market surfaces "Held in escrow, not by Sway" with the escrow address and a verifiable transaction + block. Non-custodial and verifiable — shown, not claimed.

The relayer that submits your signed transactions can never move user escrow — it only settles orders you signed. Governance (fees, pauses) sits behind a multisig Vault.

Market Structure

Collateral

Markets are collateralized in a single stablecoin per deployment.

The beta uses Circle USDC on Base Sepolia (6 decimals). Prices, sizes, and fees are quoted in 6-decimal fixed point — 550000 = $0.55, 100000000 = 100 shares. Deposits can arrive same-chain or cross-chain (Circle CCTP / intents), and are always converted to the deployment's collateral at the door.

Orders & Settlement

Orders are EIP-712 signed by your Safe and submitted to POST /orders/signed. The relayer matches and settles them on-chain, gaslessly. Every order carries a signed max-fee cap (maxFee) — the protocol can never charge above what you signed.

// Shape of a signed limit order (see Authentication for signing).
await fetch('https://api.swaytrade.xyz/orders/signed', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    order: {
      trader: safeAddress,
      marketId,
      outcome: 1,            // 1 = Yes, 2 = No
      price: 550000,        // 0.55 (6dp)
      size: 100000000,      // 100 shares (6dp)
      maxFee,               // signed fee cap (A2)
      nonce, deadline,
    },
    signature,              // EIP-712 / ERC-1271 from the Safe
  }),
});

Void & Refunds

Every market has a refund path. If a market can't be resolved, it is voided: both sides redeem a 50/50 refund of the collateral they staked, and any fee charged is refunded. No position is ever permanently frozen (invariant INV-11).


API

REST Reference

Public reads need no auth. Trading uses signed orders; operator routes are token-gated.

GET/deploymentActive chain, contracts, fee policy
GET/marketsList all markets
GET/markets/{id}One market
POST/orders/signedSubmit an EIP-712 signed order
POST/orders/{id}/cancelCancel a resting order
GET/fees/summaryLive fee policy & your accruals
WS/agent/streamLive fills & odds
Full reference coming: request/response schemas, error codes, and rate limits land here. For now the shapes above match the live beta on api.swaytrade.xyz.

Authentication

Three access modes:

  • Public reads — GET /markets, /deployment, prices: no auth.
  • Trading — orders are EIP-712 signed by your Safe smart account (verified on-chain via ERC-1271). There is no API key for human trading; the signature is the auth.
  • Agents — programmatic traders use a scoped API key, passed as Authorization: Bearer sway_ak_<id>_<secret>. See Agent API.

Agent API keys

Mint a key for a Safe with POST /agent/keys. The plaintext key is returned once and is never recoverable — only a SHA-256 of the secret is stored. The key is scoped (default ["read","trade"]) and owner-bound to the Safe you name.

const res = await fetch('https://api.swaytrade.xyz/agent/keys', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ label: 'my-bot', safe: '0xYourSafe…', scope: ['read', 'trade'] }),
}).then(r => r.json());
// { agent_id, safe, key_id, api_key: 'sway_ak_<id>_<secret>' }  <- store api_key now; shown once
res = requests.post("https://api.swaytrade.xyz/agent/keys",
    json={"label": "my-bot", "safe": "0xYourSafe…", "scope": ["read", "trade"]}).json()
# res["api_key"] == "sway_ak_<id>_<secret>"  -> store it now; it is shown once

Every request is default-deny: a missing, malformed, revoked, or out-of-scope key is rejected, and the secret check is a constant-time compare. Keep the key server-side — never ship it in a browser bundle.

Testnet posture. On the beta, key issuance is open (self-serve) and the key↔Safe binding is taken on trust. Non-custody bounds the risk — a key can only act on funds its own Safe has signed for, so it can never touch another user's balance. Before mainnet, issuance will require a Safe-ownership signature.

API

WebSockets

A single authenticated stream pushes live fills and odds as markets move.

WSwss://api.swaytrade.xyz/agent/stream?token=sway_ak_<id>_<secret>fills · odds

The key travels in a ?token= query param — a browser WebSocket can't set an Authorization header. It's the same scoped agent key, checked the same way: a missing, bad, or out-of-scope token closes the socket.

const key = process.env.SWAY_AGENT_KEY; // sway_ak_<id>_<secret>
const ws = new WebSocket(`wss://api.swaytrade.xyz/agent/stream?token=${key}`);
ws.onmessage = (e) => {
  const ev = JSON.parse(e.data);
  switch (ev.type) {
    case 'fill': console.log('fill', ev.market_id, ev.outcome, ev.price); break;
    case 'odds': console.log('odds', ev.market_id, ev.yes); break;
  }
};
# pip install websockets
import asyncio, json, websockets

async def main():
    async with websockets.connect(f"wss://api.swaytrade.xyz/agent/stream?token={KEY}") as ws:
        async for raw in ws:
            ev = json.loads(raw)
            if ev["type"] == "fill":
                print("fill", ev["market_id"], ev["price"])

asyncio.run(main())

Economics

Fees & Rebates

A single, transparent taker fee — read from chain, capped by your signature, and shared back to makers and referrers.

ComponentValueNotes
Taker fee1.5% (150 bps)An extra debit at settlement — the winner's $1.00 payout is never shaved.
Maker rebate30% of the feeAccrues to the resting order that got filled.
Referral10% of the feeAccrues to the referrer of the taker.
Signed capper orderEvery order carries a maxFee you sign — the protocol can't charge above it.

The live fee is read on-chain from the FeePolicy contract (GET /fees/summary echoes it), so it's always verifiable. Rebates accrue off-chain and are paid out automatically.

Incentive programs (maker rebate boosts, referral tiers) will be published here.

Agents

Agent API

AI agents are first-class traders on Sway — they trade right next to people.

An agent authenticates with a scoped API key (issued, rotated, and revoked from your console), owner-bound to a Safe with per-key caps and allowlists. The /agent/* surface mirrors the trading API, adds the live stream, and offers optional metered premium data (x402). A built-in runaway halt caps per-window activity so a misbehaving agent can't run away.

const res = await fetch('https://api.swaytrade.xyz/agent/markets', {
  headers: { Authorization: `Bearer ${process.env.SWAY_AGENT_KEY}` },
});

Trading surface

Every route below takes the Authorization: Bearer key and mirrors the public API, scoped to the key's Safe.

GET/agent/marketsscope: read
GET/agent/markets/{id}/bookorder book · read
GET/agent/positionsyour positions · read
GET/agent/orders POST/agent/orderslist · place · scope: trade
POST/agent/orders/{id}/canceltrade

Key lifecycle

POST/agent/keysissue (returns api_key once)
GET/agent/keys   GET/agent/owned/{safe}list
POST/agent/keys/{key_id}/rotatenew secret, old revoked
POST/agent/keys/{key_id}/revoke POST…/deletedisable / remove

Scopes & policy caps

Keys carry scopes — read and trade — enforced per route (a read-only key can't place orders). Each agent also has a policy (default-deny spine): the operator sets per-agent caps and allowlists via PUT /agent/policy/{agent_id}, and the platform's minimum-order floor always applies. A SnapBack runaway-halt caps per-window activity so a misbehaving agent trips a breaker instead of running away.

GuaranteeHow
Secret never storedonly SHA-256(secret) is persisted; the key is shown once
Timing-safeconstant-time compare on the key check
Least-privilegeper-key scopes + per-agent policy caps, default-deny
Non-custodiala key can only act on funds its own Safe signed for

SDKs

Official Python & TypeScript SDKs are on the way. Until then the REST + WebSocket API is stable and SDK-free — every example in these docs is plain fetch / requests. Watch the Changelog.

More

Partner Integration

Coming soon. White-label markets, embedded widgets, revenue-share, and institutional onboarding will be documented here. Reach out on Discord →

System Status

Live uptime for the API, WebSocket, relayer, oracles, and funding rails is published at status.swaytrade.xyz.

 Each component maps to a Watchdog probe — API & WebSocket uptime, relayer health, oracle freshness, funding rails, and incident history. Open the status page →

Changelog

Notable platform changes. Full history lives in the repository.

2026-11-26Api3 void-escape live — any market now has a guaranteed on-chain refund path.
2026-11-25Signed-order fee cap (per-order maxFee) and multisig governance.
2026-11-24Fee-aware settlement with maker rebates & referrals.
2026-11-20Agent tier — scoped API keys, live stream, runaway halt.