# 5-Minute Bitcoin Prediction Markets on BlockForecast
Source: https://docs.blockforecast.io/5-minute-bitcoin-markets
Trade BTC, ETH, and SOL up-or-down on rolling 5- and 15-minute markets. Pyth-oracle resolved, USDC on Base, always-on — the fastest crypto prediction product.
BlockForecast's 5-minute markets are the fastest prediction product on the platform. The premise is simple: at the start of each round, the current spot price is captured as the anchor; at the end, the market resolves UP if the spot price is at or above that anchor, and DOWN if it's below. Markets are rolling and always-on — when one round closes, the next is already open.
## How a round works
At the start of each round, the live spot price for BTC, ETH, or SOL is captured from the **Pyth Hermes price feed** on Base. This becomes the "price to beat" — the anchor for the round.
You can buy UP or DOWN shares at the current market price. For 5-minute rounds, the trading window runs for **4 minutes 30 seconds**. For 15-minute rounds, it runs for **14 minutes**.
Trading freezes **30 seconds before resolution** on 5-minute rounds (60 seconds for 15-minute rounds). This halt window prevents last-second exploitation where a trader can see the outcome is clearly locked in and dump size into stale quotes.
At the resolution moment, the Pyth Hermes feed delivers the canonical spot price. **UP wins if spot ≥ anchor; DOWN wins if spot \< anchor.** Winning shares pay \$1 each.
Rounds are pre-created so there's never a gap. As one round resolves, the next is already open and accepting trades.
## Available markets
Rolling, always-on. Anchor set from Pyth Hermes BTC/USD feed.
Rolling, always-on. Longer window for slightly less noisy price action.
Rolling, always-on. ETH/USD from Pyth Hermes.
Rolling, always-on.
Rolling, always-on. SOL/USD from Pyth Hermes.
Rolling, always-on.
Additional assets are available on request — Pyth covers 50+ crypto assets.
## Why 5-minute markets are interesting
**Tight feedback loop.** Traditional prediction markets run for days, weeks, or months. You wait a long time to find out whether your forecast was right. On 5-minute markets, you know within minutes. This makes the product useful for skill-building: you get dozens of data points per day rather than a handful per month.
**Pure price-action trading.** You don't need a long-term thesis on Bitcoin's value. The question is narrower: which way is BTC moving in the next five minutes? This suits technical traders, momentum traders, and anyone who watches charts closely.
**Always-on.** Crypto trades 24 hours a day, seven days a week. So do these markets. There's no waiting for a market to open.
## Reading the chart
The market page shows a live spot price chart sourced from the Pyth feed. A **horizontal line** marks the anchor price for the current round. A **pulsing dot** tracks the current spot price at the rightmost edge of the chart.
The dot and chart color update in real time:
* **Green** — current spot is above the anchor (UP is currently winning)
* **Red** — current spot is below the anchor (DOWN is currently winning)
The color flips instantly as the price crosses the anchor. The chart is informational — it does not predict where the price will be at resolution.
## Trade protections
Short-duration markets attract a specific kind of risk: a well-capitalized trader who can observe the spot price ticking clearly toward resolution can dump large size into the market seconds before close, exploiting stale market-maker quotes. BlockForecast layers four defenses against this:
The order book closes 30 seconds before resolution on 5-minute rounds, and 60 seconds before resolution on 15-minute rounds. No trades are accepted during this window.
The maximum price impact per trade tightens as resolution approaches. Large orders placed close to resolution receive a worse fill rather than moving the price significantly.
Per-wallet USDC exposure on a single round steps down as the round nears resolution, which prevents late-stage position-building by well-capitalized accounts. The current schedule is shown on the market page.
If your order size exceeds available depth, the system returns a smaller fitting quote rather than failing the order outright. You get a partial fill at the available price rather than an error.
## Fees
The standard creator fee is **0.5%** per trade, plus a small protocol fee. As a round approaches resolution, the effective fee ramps up to deter last-second informed flow. This ramp applies only in the window immediately before the halt — the live fee for any round is shown on the market page before you confirm a trade.
## How to place a trade
You need USDC on Base. Use the in-app bridge to convert any crypto in one click. See [How to Deposit](/how-to-deposit). Minimum trade is \$1 USDC.
Navigate to [Markets](https://blockforecast.io/markets?category=binary) and filter by the binary category, or search for BTC, ETH, or SOL.
Check the anchor price (horizontal line on the chart), the current spot price, and the time remaining. Current YES and NO share prices reflect the crowd's directional lean.
Click **UP** if you believe the price will be at or above the anchor at resolution. Click **DOWN** if you believe it will be below. Enter your USDC amount and confirm.
The round resolves at the snapshot moment. Winning shares pay \$1 each, automatically credited to your wallet. The next round is already open.
5-minute markets are short-duration and highly volatile. A price that looks clearly directional 3 minutes before resolution can reverse in seconds. The market will not always move the way the chart suggests it's heading. Only trade size you're prepared to lose entirely on a given round. The time-decaying position caps are there for a reason — use the early part of the trading window when price impact and exposure limits are most favorable.
## FAQ
The Pyth Hermes price feed on Base. The canonical price is the Pyth snapshot at the exact resolution moment.
The engine falls through automatically: **Pyth Hermes → CoinGecko → Binance**. If all three sources are unavailable at the resolution moment, the round is voided and all traders are refunded in full.
Yes — the CLOB (central limit order book) phase of trading accepts resting limit orders that fill against incoming market orders.
Rounds are pre-created so there's no gap between them. Before the next round opens, the timer shows "Starts in MM:SS". Once the round is live, it flips to a countdown to the halt time.
\$1 USDC.
# Apply for Creator Access on BlockForecast
Source: https://docs.blockforecast.io/creators/apply
Submit your creator application at blockforecast.io/apply. Reviewed in under 24 hours. Learn what the team looks for and how to write a strong submission.
The creator application is a quality gate, not a gatekeeper. BlockForecast reviews every application to make sure the platform stays free of ambiguous, low-effort, or unresolvable markets — but the bar is reasonable. If you have a specific topic area, can write clear binary questions, and have a plan to bring traders to your markets, you'll get approved. The review typically completes in under 24 hours.
There's no automatic email or DM when a decision is made. **Check your status at [/create](https://blockforecast.io/create) any time** — the page shows your wallet's current state (`pending`, `approved`, `rejected`, or `suspended`) plus any rejection reason recorded by the reviewer. The status is also queryable programmatically at `GET /api/v2/creator/status?address=0x...` if you want to poll from a script.
Creator access is required before you can publish any market on BlockForecast. You cannot reach the market creation form at `/create` without approved creator status.
## What BlockForecast looks for
Approvals are based on four things:
1. **Question quality.** Your example markets should be specific, time-bounded, and answerable from a public source. "Will Arsenal beat Chelsea on 5 May?" is good. "Will Arsenal do well this season?" is not.
2. **Resolvability.** Every market needs an authoritative source the AI oracle can read at resolution time — a sports API, CoinGecko, Pyth, AP News, an official election body. If the answer lives only in a private or ambiguous place, the market won't pass.
3. **No insider information.** Markets must be questions any member of the public could answer from publicly available sources at resolution time. Markets that give an unfair edge to someone with insider access are rejected.
4. **Distribution intent.** A creator who actively promotes their markets generates more volume. You don't need a huge audience, but having some plan — a newsletter, a Discord, a Farcaster community, a Twitter following — helps both your approval odds and your earnings.
## The application form
The form at [blockforecast.io/apply](https://blockforecast.io/apply) asks for five things:
* **Display name and X handle** — Discord and Farcaster are optional but helpful.
* **Topic areas** — pick up to five categories you'd create markets in (e.g., "Premier League, La Liga, MLS football").
* **Two example markets** — full question text, time-bounded, written exactly as you'd publish them.
* **Distribution plan** — how you'll bring traders to your markets: audience size, platforms, community.
* **Short paragraph** — 50–600 characters on why you want to create on BlockForecast.
The example markets field carries the most weight in the review. Write them exactly as you'd publish them — full question text, specific resolution date. Vague examples result in slower reviews and lower approval odds.
## How to apply, step by step
Go to [blockforecast.io/apply](https://blockforecast.io/apply) and sign in with the wallet you intend to use for creating markets. BlockForecast uses Privy — you can sign in with Google, Apple, email, or an existing Web3 wallet. Use the wallet you want your creator fees paid to.
Enter your display name and X handle. Add Discord or Farcaster handles if you have them.
Select up to five categories. Be specific: "Premier League and La Liga football" is more credible than "sports." The team looks for applicants with genuine expertise in their chosen domains.
Write two markets you'd actually launch in week one. Use the format: "Will \[subject] \[verb] by \[specific date/time]?" Include a resolution date and make sure the answer would be available from a public source. Treat this like a live submission.
Explain where your traders will come from. This doesn't need to be large — a 500-person Discord or a niche Farcaster channel counts. The team wants to see that you've thought about bringing volume to your markets.
Submit the form. The applicant page will switch to "Application received." Reviews typically complete in under 24 hours — often faster during business hours. To find out if you've been approved, **check [/create](https://blockforecast.io/create)** — your wallet's status is shown there. If you're still in `pending` after 48 hours, email [support@blockforecast.io](mailto:support@blockforecast.io).
## What happens after you submit
Once your application is under review, the team checks your example markets against the resolvability and quality criteria. Most decisions land in under 24 hours. **There's no outbound notification — check your status at [/create](https://blockforecast.io/create) any time.**
**If approved:** your wallet is upgraded to creator status immediately, and the next time you load `/create` you'll see the market-creation wizard. Any draft you started before applying is preserved so you can pick up where you left off.
**If not approved:** `/create` shows the rejection reason recorded by the reviewer plus a "Reapply" button. Common reasons are ambiguous example markets or no clear distribution plan — both fixable with a revised submission. The reapply form pre-fills with your previous answers.
## What to do while you wait
* **Browse active markets** on the platform to get a feel for question style and resolution criteria.
* **Study the [create-a-market guide](/creators/create-a-market)** so you're ready to launch immediately after approval.
* **Draft your first 5–10 markets** in a text file. Having a queue of questions ready means you can launch your portfolio on day one.
No. Creator access is tied to the wallet you sign in with at application time. If you want to create markets from a different wallet, you'll need to submit a new application with that wallet.
No. The application is free. Creating a market via the website is free for approved creators (gas only, cents on Base). Creating via the [x402 Agent API](/developers/x402-overview) costs \$1 USDC per market — paid by the agent wallet, non-refundable on unapproved wallets.
Yes. Open [/create](https://blockforecast.io/create) — if your wallet is in `rejected` state the page shows the recorded reason and a "Reapply" button. Address the feedback and resubmit. Most applicants who reapply with stronger example markets and a clearer distribution plan are approved on the second attempt.
Visit [/create](https://blockforecast.io/create). The page shows your wallet's current state (`pending`, `approved`, `rejected`, or `suspended`). When you're approved, the market-creation wizard appears immediately. There's no automatic email or DM — checking the page is the canonical signal.
# How to Create a Prediction Market on BlockForecast
Source: https://docs.blockforecast.io/creators/create-a-market
Step-by-step guide to launching a prediction market after creator approval. Covers the creation form, writing resolution criteria, and what topics perform best.
Once you have creator access, publishing a market takes under two minutes. You write a question in plain English, the AI rewrites it for clarity and generates resolution criteria, you confirm or edit, and the market is live. The LSMR automated market maker provides instant liquidity from the moment you launch — you don't need to find a counter-party. Every trade on your market earns you 0.5% in real time for as long as the market is open.
You must have approved creator access before you can reach the market creation form. If you haven't applied yet, start at [Apply for creator access](/creators/apply).
## What makes a good market
Before opening the form, it's worth knowing what the AI quality gate looks for. A strong market has four properties:
* **Specific.** "Will Arsenal beat Chelsea on 5 May at 20:00 UTC?" not "Will Arsenal do well?"
* **Time-bounded.** An explicit resolution moment — not "this year" or "soon."
* **Source-citable.** There must be a public, authoritative source the oracle can read at resolution — a sports API, CoinGecko, Pyth, AP News, an official election body.
* **Binary or small-N outcome.** Yes/no, or a fixed set of named outcomes (A wins / Draw / B wins).
Markets that fail one or more of these properties get flagged by the AI with a suggested rewrite. The same criteria that get markets approved also drive trading volume — clear, specific markets attract more confident traders.
## Step-by-step: creating a market
Sign in and navigate to [/create](https://blockforecast.io/create). The form is only visible to accounts with approved creator status.
Type the question in the **Title** field in plain English. Keep it under 60 characters if possible — the question appears prominently on market cards and in share previews, so shorter is better. Templates that work well:
* `Will [subject] [verb] by [date/time]?`
* `Will [price/stat] be above [threshold] at [time]?`
* `Who will win [event]: [A] / [B] / [C]?`
The AI will rewrite long or ambiguous questions automatically, but starting clean speeds up the process and gives you more control over the final wording.
The **Description** field is optional but recommended. Use it to add context that doesn't fit in the title: which competition, which exchange's price feed, which official source will be used, or any clarifying scope. A good description reduces trader confusion and support requests.
The AI proposes:
* The authoritative sources it will consult at resolution
* Tie-breaker rules (e.g., what happens if a match is postponed)
* Edge case handling (e.g., what happens if an exchange goes down at the resolution moment)
Read these carefully. **Resolution criteria are immutable once trading starts** — that's a fairness commitment to traders. You can edit them before confirming, but not after. If the proposed criteria don't match your intent, rewrite them now.
Pick the exact moment when the market should resolve. Match it to the actual event:
* **Sports:** kickoff time. Trading closes at kickoff; the market resolves a few minutes after the final whistle.
* **Crypto prices:** a specific UTC timestamp. The Pyth or CoinGecko snapshot at that moment is the answer.
* **Politics / news:** the event itself plus a small buffer for sources to publish (typically 24–48 hours).
* **Long-running questions:** the deadline by which the answer must be known.
Select the category that best matches your topic. Categories affect how the market is surfaced in browse and search views. Available categories include crypto, sports, politics, tech, culture, and entertainment.
Review everything — title, description, resolution criteria, resolution date, category. When you're satisfied, confirm. The market goes live immediately and is tradeable from that moment.
## Topic categories and what performs well
Different topics draw different trader audiences. Here's what tends to generate strong volume by category:
Price prediction markets are the highest-volume category on BlockForecast. BTC and ETH dominate, but altcoin markets — especially around token launches, protocol upgrades, or listing events — often outperform on a per-market basis because competition from other creators is lower. Pyth and CoinGecko provide real-time oracle feeds for resolution.
The oracle reads sports APIs, which means you can create markets on virtually any match in any covered league. The highest-volume sports markets are typically major football (soccer) fixtures — Premier League, Champions League, La Liga — but niche leagues (Nigerian Premier League, Argentinian Primera División, esports tournaments) are underserved and often yield higher creator returns relative to the effort to create them.
Election outcomes, official appointments, legislative votes, and international agreements. These markets attract engaged, high-conviction traders. Resolution requires a public official source — election authority results, official government announcements, or reputable news wires.
Token launches, mainnet launches, product releases, IPOs, and DAO votes. These work best when the resolution event is specific — "Will \[project] launch mainnet by \[date]?" rather than "Will \[project] succeed?"
Awards (Grammys, Oscars, BAFTAs), chart positions, box office rankings, album releases. The oracle resolves these against official public sources — Billboard, Academy, box office databases. Lower average volume per market, but strong engagement from creator audiences with a following in those areas.
## Writing clear resolution criteria
Resolution criteria are the most important thing you write. Traders decide how much to trade based on how confident they are in the resolution — ambiguous criteria suppress volume.
Write resolution criteria as if explaining them to someone who disagrees with you about the outcome. If the criteria leave room for argument, rewrite them.
**Good resolution criteria:**
* "Resolves YES if the official final score published by the Premier League at [premierleague.com/results](https://www.premierleague.com/results) shows Arsenal as the winner of this fixture. Resolves NO otherwise, including draws."
* "Resolves YES if the BTC/USD price on CoinGecko at exactly 2026-12-31 23:59:59 UTC is at or above \$100,000. Resolves NO if it is below \$100,000."
**Weak resolution criteria:**
* "Resolves YES if Arsenal wins." (Which source? What counts as a win in extra time?)
* "Resolves YES if Bitcoin is doing well by year end." (No threshold, no source, no timestamp.)
Specify: the source, the exact timestamp or trigger event, how ties or edge cases are handled, and what "NO" means explicitly.
## Common rejection reasons
The AI quality gate rejects markets that fail these checks. A rejection is not permanent — fix the issue and resubmit.
* **Ambiguous wording** — "Did the team perform well?" has no objective answer.
* **No clear source** — "Will my friend get the job?" can't be resolved from public data.
* **Insider information risk** — markets that trade well only if you have non-public information are rejected outright.
* **Person-specific private life** — markets about a named individual's personal choices or private events.
* **Already-known outcome** — the answer is already public at creation time.
* **No resolution moment** — "Will X eventually happen?" with no deadline.
# How Creator Fees Work: Earn 0.5% on Every Trade
Source: https://docs.blockforecast.io/creators/earn-fees
BlockForecast pays creators 0.5% of every trade in real time. Learn how the fee is calculated, when you get paid, and strategies to maximize your earnings.
Every time a trader buys or sells a position on a market you created, **0.5% of that trade is credited to your on-platform creator balance** in real time. There's no batching, no review process for the credit itself, and no vesting schedule — the moment a trade settles, the fee shows up in your balance. If you never log in again after launching a market, fees keep accruing in that balance until the market resolves.
When you withdraw your balance to your wallet, the platform deducts a **30% withdrawal fee** (the platform cut on creator earnings). The remaining 70% is sent to your wallet as USDC on Base.
## How the fee is calculated
The creator fee is 0.5% of each trade's notional value, charged at trade entry. It is separate from any other protocol fee — traders see the total fee at trade time. The 0.5% creator portion is locked at market creation and won't change if BlockForecast later adjusts its protocol fee.
| Market lifetime volume | Gross fee (0.5%) | After 30% platform cut at withdrawal | Net to your wallet |
| ---------------------- | ---------------- | ------------------------------------ | ------------------ |
| \$1,000 | \$5 | −\$1.50 | **\$3.50** |
| \$10,000 | \$50 | −\$15 | **\$35** |
| \$50,000 | \$250 | −\$75 | **\$175** |
| \$100,000 | \$500 | −\$150 | **\$350** |
| \$500,000 | \$2,500 | −\$750 | **\$1,750** |
| \$1,000,000 | \$5,000 | −\$1,500 | **\$3,500** |
A single high-volume market can be meaningful, but most creators build earnings across a portfolio. Thirty markets each doing \$20,000 generate \$3,000 gross / **\$2,100 net** — the same as one \$600,000 market, but with much lower variance.
Creator fees are only paid on resolved trade volume. If a market is voided (for example, because the resolution event was cancelled with no outcome), fees are not paid for trades on that market.
## When fees are paid (and the withdrawal mechanics)
Fees are credited to your on-platform creator balance in real time on each trade. To move them to your own wallet, use the withdrawal flow on your creator dashboard.
* **Minimum withdrawal:** \$10 USD (gross). If your balance is below \$10 the withdrawal endpoint returns an error and tells you the current balance.
* **Platform cut at withdrawal:** 30% — deducted from the gross amount; the remaining 70% goes to your wallet as USDC on Base.
* **Network gas:** typically a few cents on Base, paid by the engine signer.
* **No vesting, no review queue.** As long as your balance ≥ \$10 you can withdraw at any time.
## Where to view your earnings
Your creator dashboard at `/creator-dashboard` shows:
* **Total lifetime earnings** across all markets
* **Per-market breakdown** — volume, number of trades, fee income, and resolution status for each market you've created
* **Withdrawal history** — a record of every time you've transferred earnings to your wallet
* **Trader count** — how many unique addresses have traded on each market
The leaderboard at `/leaderboard` also surfaces top creators by volume, which provides additional platform visibility for high-performing creators.
## How to maximize your creator earnings
### Cover topics with built-in audiences
The highest-earning markets are ones where traders arrive without the creator needing to recruit them. Major sports fixtures, BTC/ETH price milestones, and US election events have pre-existing trader interest. But niche markets — where you're the only creator covering a specific league or topic — can outperform on creator yield because you face no competition and you're the go-to source for that audience.
### Launch markets well before the event
A sports market launched five days before kickoff captures the full pre-match trading curve. The same market launched on game day captures only a fraction of the potential volume. For crypto markets, give traders enough time to form a view and build a position.
For recurring events — weekly fixtures, monthly price snapshots, quarterly earnings — set up a regular publishing schedule. Traders who trade your first market will return if they know you publish consistently.
### Distribute your markets actively
Platform discovery helps, but creators who share market URLs directly earn significantly more than those who rely solely on browse traffic. Share to X, Discord, Farcaster, newsletters, or community channels where your audience is. The link to any market is shareable directly — there's no friction for a new user to arrive at your market and place a trade.
### Build a portfolio, not a one-shot
One viral market is unpredictable. A portfolio of 20–50 well-chosen markets in your domain is a reliable income stream. Top creators treat this like a content schedule: a set number of new markets per week, covering upcoming events in their topic areas, maintained consistently.
### Write markets that attract confident traders
Traders place larger positions when resolution criteria are unambiguous. A clear, specific market with tight criteria draws higher average trade sizes than a vague market with the same topic. Time spent on resolution criteria pays off in volume. See [Create a market](/creators/create-a-market) for guidance on writing strong criteria.
## FAQ
The 0.5% creator fee is part of the total trading fee that traders see at trade time. It does not reduce your winning payout if you also trade on your own market — it is paid at trade entry, not at resolution.
Creator fees are locked at 0.5% at market creation. Protocol fee changes apply only to new markets created after the change. Your existing markets continue to pay you 0.5% for their entire lifetime.
Yes. There is no restriction on creators trading on their own markets. However, creating markets based on insider information you hold is prohibited and will result in account termination.
Go to your creator dashboard and use the withdrawal flow to transfer your balance to USDC on Base. The minimum withdrawal is \$10 (gross). At withdrawal, the platform deducts a 30% cut and sends the remaining 70% to your wallet — for example, withdrawing a \$250 balance nets you \$175. No vesting, no waiting period, no review queue. Gas on Base is usually under a cent and is paid by the engine signer.
The 0.5% creator fee covers your share of every trade. The 30% cut at withdrawal funds platform operations — oracle resolution, infrastructure, settlement, and ongoing development. Your net share (0.35% effective per trade) is still meaningfully above the prediction-market norm, where creators are typically paid nothing.
The LSMR automated market maker provides initial liquidity but does not generate creator fees — only trades by external users do. As user volume grows, the LSMR's share of activity decreases relative to organic trading.
# Creator Program: Earn Fees on Every Prediction Market Trade
Source: https://docs.blockforecast.io/creators/overview
Approved creators on BlockForecast can launch their own prediction markets on any topic and earn 0.5% of every trade — credited in real time, withdrawable to your wallet on Base.
BlockForecast runs an open creator program that lets approved users publish prediction markets on any topic and earn a fee on every trade those markets generate. Once you're approved, you can launch markets in under two minutes and start earning immediately. There are no caps on how many markets you can create, no vesting schedules, and no approval required for each individual market after your initial access is granted.
## How it works
Every time someone places a trade on a market you created, **0.5% of that trade is credited to your on-platform creator balance** in real time. The fee is locked in at market creation — it doesn't change if the platform's protocol fee structure changes later. When you withdraw to your wallet, the platform deducts a 30% withdrawal cut and sends the remaining 70% as USDC on Base. So a market that does \$50,000 in lifetime volume generates \$250 in gross fees and **\$175 net to your wallet**. [Full mechanics →](/creators/earn-fees)
The LSMR automated market maker provides instant liquidity from the moment your market is live, so you don't need to recruit counter-traders. Your job is to write good markets and point an audience at them.
## Who the creator program is for
You have a price thesis, a time horizon, and an audience on X or Farcaster that follows your analysis. Turn your calls into tradeable markets.
You follow a league closely enough to write clean matchup questions. Niche leagues — regional football, esports, MMA — are underserved and often outperform mainstream fixtures in creator yield.
Your audience trusts your judgment. Markets you create become a new engagement layer — followers trade alongside your predictions instead of just reading them.
Politics, tech launches, culture, awards, regional events. If you know a space well enough to write a resolvable question, there's a market for it.
## Benefits of creator access
* **0.5% fee on every trade** — credited in real time, withdraw anytime once balance ≥ \$10 (30% platform cut at withdrawal; net 70% to your wallet)
* **No limit on markets** — launch as many as you want across any covered topic category
* **Creator dashboard** — per-market volume, earnings history, and trader analytics
* **Creator profile page** — traders can follow your profile and discover your markets
* **Featured creator slots** — high-volume creators get additional platform distribution
Creator access is required before you can publish a market. You do not need to reapply for each new market — one approval covers all your future markets.
## Get started
Submit your application and get a decision within 24 hours.
Step-by-step walkthrough of the market creation flow, post-approval.
# API Authentication: Wallet Signatures and API Keys
Source: https://docs.blockforecast.io/developers/authentication
Authenticate with the BlockForecast API. Issue, regenerate, and revoke keys via a nonce-bound wallet signature flow. No accounts, no OAuth — your wallet is your identity.
BlockForecast uses a wallet-signature authentication model: you prove ownership of an EVM address by signing a server-issued challenge, and the API returns a long-lived key tied to that address. Every subsequent request passes this key in the `X-API-Key` header. There is no username/password and no OAuth flow.
**Easiest path:** sign in at [blockforecast.io/settings/api-keys](https://blockforecast.io/settings/api-keys) and tap **Generate key**. Privy pops the wallet signature, the key is shown once, you copy and store it. Use the programmatic flow below only if you're issuing keys from CI / a server / a script.
## Issue a key (programmatic flow)
Three steps: request a challenge, sign the exact message it returns, post both back. Each nonce is single-use and bound to your wallet + the action (`issue`, `revoke`, `regenerate`), so an intercepted signature can't be replayed for any other operation.
`POST /api/v2/auth/challenge` returns a single-use nonce + the exact message your wallet must sign.
```bash curl theme={null}
curl -X POST https://blockforecast.io/api/v2/auth/challenge \
-H "Content-Type: application/json" \
-d '{ "address": "0xYourWalletAddress", "action": "issue" }'
```
```python Python theme={null}
import requests
chal = requests.post(
"https://blockforecast.io/api/v2/auth/challenge",
json={"address": address, "action": "issue"},
).json()["data"]
nonce, message = chal["nonce"], chal["message"]
```
```typescript JavaScript / TypeScript theme={null}
const chal = await fetch("https://blockforecast.io/api/v2/auth/challenge", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ address, action: "issue" }),
}).then(r => r.json());
const { nonce, message } = chal.data;
```
Response shape:
```json theme={null}
{
"success": true,
"data": {
"nonce": "<48-hex-chars>",
"message": "BlockForecast API Key\nAction: issue\nAddress: 0x...\nNonce: \nTimestamp: 1777408738",
"expiresAt": "2026-04-28T20:43:58.000Z"
}
}
```
The challenge expires in 5 minutes. The message format includes the action and your address so a signature for `issue` can't be replayed for `revoke` or `regenerate`.
Use EIP-191 personal sign (`personal_sign`) with the wallet whose address you sent in step 1. Don't construct your own message — sign the one the server returned verbatim.
```python Python (web3.py) theme={null}
from eth_account import Account
from eth_account.messages import encode_defunct
signed = Account.sign_message(encode_defunct(text=message), private_key=PRIVATE_KEY)
signature = signed.signature.hex()
```
```typescript JavaScript / TypeScript (viem) theme={null}
import { privateKeyToAccount } from "viem/accounts";
const account = privateKeyToAccount(PRIVATE_KEY as `0x${string}`);
const signature = await account.signMessage({ message });
```
```typescript Browser (MetaMask / Privy) theme={null}
const signature = await wallet.signMessage({ message });
// or via raw EIP-1193:
// const signature = await provider.request({
// method: "personal_sign", params: [message, address],
// });
```
`POST /api/v2/auth/token` with the address, signature, the message, the nonce, and an optional label.
```bash curl theme={null}
curl -X POST https://blockforecast.io/api/v2/auth/token \
-H "Content-Type: application/json" \
-d "{
\"address\": \"$ADDRESS\",
\"message\": \"$MESSAGE\",
\"signature\": \"$SIGNATURE\",
\"nonce\": \"$NONCE\",
\"label\": \"prod-bot\"
}"
```
```python Python theme={null}
resp = requests.post(
"https://blockforecast.io/api/v2/auth/token",
json={
"address": address, "message": message, "signature": signature,
"nonce": nonce, "label": "prod-bot",
},
).json()
api_key = resp["data"]["apiKey"]
```
```typescript JavaScript / TypeScript theme={null}
const resp = await fetch("https://blockforecast.io/api/v2/auth/token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ address, message, signature, nonce, label: "prod-bot" }),
}).then(r => r.json());
const apiKey = resp.data.apiKey;
```
Response (the only time the raw `apiKey` is shown):
```json theme={null}
{
"success": true,
"data": {
"id": 7,
"apiKey": "bf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"prefix": "bf_xxxxxxxx...",
"label": "prod-bot",
"rateLimit": 60,
"createdAt": "2026-04-28T20:43:00.000Z",
"note": "Store this key securely. It cannot be retrieved again."
}
}
```
The server only stores the SHA-256 hash of the key. Even with a database leak, the raw key cannot be reconstructed.
## Use your key
Pass it in the `X-API-Key` header on every request to a `/api/v2/public/*` endpoint.
```bash curl theme={null}
curl https://blockforecast.io/api/v2/public/markets \
-H "X-API-Key: bf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```
```python Python theme={null}
import os, requests
resp = requests.get(
"https://blockforecast.io/api/v2/public/markets",
headers={"X-API-Key": os.environ["BLOCKFORECAST_API_KEY"]},
)
```
```typescript JavaScript / TypeScript theme={null}
const resp = await fetch("https://blockforecast.io/api/v2/public/markets", {
headers: { "X-API-Key": process.env.BLOCKFORECAST_API_KEY! },
});
```
## List your active keys
Returns prefixes (not raw keys), labels, rate limit, scopes, created/last-used timestamps. No auth required — a key's prefix isn't a secret. Used by the [`/settings/api-keys`](https://blockforecast.io/settings/api-keys) page.
```bash theme={null}
curl "https://blockforecast.io/api/v2/auth/keys?address=0xYourWalletAddress"
```
## Revoke a key
Suspected leak? Revoke instantly. The action is wallet-signed (same nonce flow with `action: "revoke"` and the key's `id`).
```bash theme={null}
# 1. Challenge
curl -X POST https://blockforecast.io/api/v2/auth/challenge \
-H "Content-Type: application/json" \
-d '{ "address": "0x...", "action": "revoke", "keyId": 7 }'
# 2. Sign the returned message, then:
curl -X POST https://blockforecast.io/api/v2/auth/keys/7/revoke \
-H "Content-Type: application/json" \
-d '{ "address": "0x...", "message": "...", "signature": "0x...", "nonce": "..." }'
```
The key is invalidated synchronously — any request using it after this point returns `401`.
## Regenerate a key (atomic rotate)
Same scopes + rate limit, new key value. Useful when you want to rotate without losing your "key slot" or having to update label references downstream.
```bash theme={null}
# 1. Challenge with action: "regenerate"
curl -X POST https://blockforecast.io/api/v2/auth/challenge \
-H "Content-Type: application/json" \
-d '{ "address": "0x...", "action": "regenerate", "keyId": 7 }'
# 2. Sign + post — the server atomically revokes the old key and issues a new one
curl -X POST https://blockforecast.io/api/v2/auth/keys/7/regenerate \
-H "Content-Type: application/json" \
-d '{ "address": "0x...", "message": "...", "signature": "0x...", "nonce": "..." }'
```
The response shape matches `POST /auth/token` — the new key is shown once.
## Caps
* **5 active keys per wallet.** Revoke or regenerate to free a slot.
* **Default 60 req/min per key.** Higher quotas on request — see [Rate Limits](/developers/rate-limits).
* Persistent failed-auth attempts from a single IP are throttled at the edge.
## Error responses
| HTTP | Body `error` field | Meaning |
| ----------------------- | --------------------------------------------------------------------- | ---------------------------------------------------------------- |
| `400 Bad Request` | `address, signature, message, and nonce are required` | Missing required field on `/auth/token` etc. |
| `400 Bad Request` | `Nonce invalid, expired, or already used. Request a fresh challenge.` | Replay attempt or stale nonce — restart from `/auth/challenge`. |
| `400 Bad Request` | `Maximum 5 active API keys per wallet…` | Revoke or regenerate to free a slot. |
| `401 Unauthorized` | `Invalid or missing API key.` | Header missing, malformed, or key has been revoked. |
| `401 Unauthorized` | `Invalid signature` | Signature doesn't verify against the recovered address. |
| `401 Unauthorized` | `Signature does not match address` | Recovered signer is a different wallet. |
| `403 Forbidden` | `This API key lacks required scope: ` | Key is valid but lacks permission for the endpoint. |
| `404 Not Found` | `Key not found or not owned by this wallet` | Bad `keyId`, or the wallet you signed with doesn't own that key. |
| `429 Too Many Requests` | `Rate limit exceeded. Max 60 requests per minute.` | Wait per the `Retry-After` header. |
| `429 Too Many Requests` | `Too many failed authentication attempts. Try again later.` | IP-level brute-force throttle. |
All success responses are `{ "success": true, "data": {...} }`; errors are `{ "success": false, "error": "" }`.
## Security best practices
Never expose `bf_…` keys in client-side JavaScript, public repos, or build logs. Anyone with the key can trade and read account data on behalf of the wallet that issued it.
* Store in your secrets manager (AWS Secrets Manager, Doppler, 1Password, env-file mounted at runtime). Never commit.
* Use one key per environment (`prod-bot`, `staging-bot`, `local-dev`) — the label keeps you sane and revoke is single-key, not single-wallet.
* Rotate via [`/keys/:id/regenerate`](#regenerate-a-key-atomic-rotate) on a schedule or after any suspected exposure. Old key dies the moment the new one is shown.
* For server-to-server integrations, give each agent its own dedicated wallet so a leak doesn't expose your trading wallet's positions.
In CI / serverless where you can't interactively sign, generate the key once from a local wallet (or via the `/settings/api-keys` UI) and inject the resulting `bf_…` value as a build secret. The key is what production uses; the signing wallet only needs to be online during issuance.
# Claude Code Skill — /bf-create-market
Source: https://docs.blockforecast.io/developers/claude-skill
Install the bf-create-market skill in Claude Code and create BlockForecast prediction markets with one slash command. Wraps the full x402 + creator-fee flow — no glue code.
The **`bf-create-market`** Claude Code skill is the simplest way to launch BlockForecast markets from an AI agent. Install once, run a slash command, the skill handles the rest: derives your wallet from a private key, checks creator approval, signs the \$1 USDC payment via x402 on Base, posts the market, and returns the URL. Creator-fee earnings (0.5% of every trade) flow back to your wallet automatically.
If you're not using Claude Code, see the manual [x402 Quickstart](/developers/x402-create-market) — same endpoint, you write the glue code.
## Install
In a Claude Code session:
```bash theme={null}
/plugin marketplace add gr8estman/blockforecast-skills
/plugin install bf-create-market@gr8estman
```
The skill is open source — source on GitHub: [gr8estman/blockforecast-skills](https://github.com/gr8estman/blockforecast-skills).
## One-time setup
Any tooling — `viem`, MetaMask, Coinbase, hardware wallet. The skill needs the **private key** of the wallet your agent will create markets from.
```js theme={null}
import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
const key = generatePrivateKey();
console.log('address:', privateKeyToAccount(key).address);
console.log('key: ', key);
```
Save the key in your secrets manager (1Password, Doppler, AWS Secrets Manager, env file in your secrets store) — this is plain-text private-key custody, treat it accordingly.
Send \~\$5 USDC (Base mainnet) to the agent address. Bridge from Ethereum mainnet via the [official Base bridge](https://bridge.base.org), or off-ramp directly from Coinbase to Base. Each market creation costs **\$1 USDC** plus a few cents of gas.
Visit [blockforecast.io/apply](https://blockforecast.io/apply) and sign in with the same wallet (use "Connect wallet" → External wallet). Submit the application. Approval typically lands in under 24 hours — there's no outbound notification, so check [/create](https://blockforecast.io/create) to see your status.
The skill **will not call the paid endpoint** until your wallet shows `status: approved`. The \$1 x402 fee is non-refundable on unapproved wallets, so apply first.
```bash theme={null}
export BF_AGENT_KEY="0x"
```
Add it to your shell rc, your secrets store, or whatever launches your Claude Code session.
## Usage
```
/bf-create-market "Will the Fed cut rates in May 2026?" 2026-05-31
```
The skill will:
1. Check `BF_AGENT_KEY` is set
2. Verify the wallet is approved
3. Show you a confirmation summary
4. **Wait for your "yes"** before spending USDC
5. POST to BlockForecast with x402 payment
6. Return the live market URL
### Dry run
To verify your setup without spending USDC:
```bash theme={null}
DRY_RUN=1 /bf-create-market "Will X happen by Y?" 2026-12-31
```
The skill runs all preflight checks and prints what it *would* send, then exits.
## Inputs
| Argument | Required | Format | Notes |
| ------------- | -------- | ------------------------------------------------------------------------------------- | --------------------- |
| `question` | yes | string ≥10 chars | Binary, ends with `?` |
| `resolveDate` | yes | `YYYY-MM-DD` | Must be in the future |
| `category` | no | one of `crypto`, `politics`, `sports`, `culture`, `science`, `world`, `ai`, `esports` | Default: `crypto` |
Behind the scenes the skill `POST`s to `/api/v2/x402/markets` — the [Create Market via x402](/developers/x402-create-market) page documents the underlying payload and response.
## Costs
| Action | Cost |
| ------------------------------- | ------------------------------------------------------ |
| Apply for creator access | Free |
| Create one market via the skill | \$1 USDC + \~\$0.001 gas |
| Earn from trades on your market | 0.5% of every trade — paid to your wallet in real time |
| Withdraw earnings | Gas only |
A market doing \$50k of lifetime volume nets the creator \$250. Most active creators run a portfolio of 30+ markets.
## Errors and what to do
| Skill error | Meaning |
| ---------------------- | ---------------------------------------------------------------------------------- |
| `missing_key` | Run `export BF_AGENT_KEY="0x..."` |
| `bad_key` | Key must be 32 bytes hex with optional `0x` prefix |
| `creator_not_approved` | One-time apply at [/apply](https://blockforecast.io/apply) |
| `creator_pending` | Wait for approval (\~24h) — re-check at [/create](https://blockforecast.io/create) |
| `creator_rejected` | See rejection reason; address it; reapply at /apply |
| `creator_suspended` | Contact [support@blockforecast.io](mailto:support@blockforecast.io) |
| `insufficient_usdc` | Add USDC on Base to the agent wallet |
| `payment_failed` | Coinbase CDP facilitator hiccup — retry in a minute |
## Security notes
* The skill **only signs the exact x402 payment payload** for `POST /api/v2/x402/markets`. It does not trade, withdraw, or move funds.
* Creator-fee earnings flow to the wallet derived from `BF_AGENT_KEY`. Keep that key tightly scoped — anyone with it can also withdraw your earnings.
* The skill prompts for explicit confirmation before every paid call. There is no auto-execute mode.
* Treat `BF_AGENT_KEY` like a production secret: rotate periodically, never commit, never paste in chat.
## Roadmap
These skills are planned next — they share the same wallet + creator setup:
* `bf-resolve-oracle` — query oracle consensus on any yes/no question (\$0.05 USDC per call)
* `bf-check-balance` — read agent wallet's USDC balance + open positions
* `bf-list-markets` — search BlockForecast markets by category
* `bf-trade` — place a trade on an existing market
## Source + support
* Skill source: [github.com/gr8estman/blockforecast-skills](https://github.com/gr8estman/blockforecast-skills)
* Issues / feature requests: [open one on GitHub](https://github.com/gr8estman/blockforecast-skills/issues)
* Email: [support@blockforecast.io](mailto:support@blockforecast.io)
# Public REST API Reference: Markets and Trades
Source: https://docs.blockforecast.io/developers/public-api
Complete reference for all BlockForecast public REST API endpoints — list markets, fetch trade data, place trades, and create markets with creator access.
The BlockForecast public REST API exposes prediction market data and trading functionality over standard HTTP. All endpoints live under `https://blockforecast.io/api/v2/public/` and require an `X-API-Key` header. This page documents every endpoint with full parameter descriptions, response field definitions, and working code examples in curl, Python, and TypeScript. If you have not yet obtained an API key, start with [Authentication](/developers/authentication).
All monetary values are returned as floating-point USD (e.g., `18420.50`) in the REST API. On-chain, amounts are USDC with 6-decimal precision — keep this in mind if you are reconciling against on-chain data.
***
## GET /public/markets
Returns a paginated, filterable list of prediction markets.
### Query parameters
Filter by market status. One of `open` (trading), `resolved` (settled). Omit to return all statuses.
Filter by category slug. Common values: `crypto`, `sports`, `politics`, `science`, `entertainment`. Matched case-insensitively. Omit to return all categories.
Number of markets to return per page. Maximum `100`. Default `20`.
Pagination offset. Default `0`.
Sort order. One of `volume_desc` (default), `created_desc`, `resolve_asc`.
### Response fields
Array of market objects.
Numeric market identifier (e.g., `781`).
Human-readable ticker (e.g., `BF-0781`).
URL-friendly market slug (e.g., `will-btc-close-above-150k-dec-2026`).
The full market question text.
Category slug.
One of `open` (trading), `resolving` (closed, awaiting oracle), `resolved` (settled).
Current LSMR YES price as a probability (0–1).
Current LSMR NO price as a probability (0–1).
Total trade volume in USD.
Available liquidity in USD.
ISO 8601 resolution date.
ISO 8601 creation timestamp.
Total number of markets matching the query (before pagination).
The effective limit applied.
The effective offset applied.
### Examples
```bash theme={null}
curl "https://blockforecast.io/api/v2/public/markets?status=open&category=crypto&limit=5" \
-H "X-API-Key: $BLOCKFORECAST_API_KEY"
```
```python theme={null}
import os, requests
resp = requests.get(
"https://blockforecast.io/api/v2/public/markets",
headers={"X-API-Key": os.environ["BLOCKFORECAST_API_KEY"]},
params={"status": "open", "category": "crypto", "limit": 5},
)
resp.raise_for_status()
data = resp.json()
for market in data["markets"]:
print(f"{market['question']} — YES: {market['yesPrice']:.2f}")
```
```typescript theme={null}
const resp = await fetch(
"https://blockforecast.io/api/v2/public/markets?status=open&category=crypto&limit=5",
{ headers: { "X-API-Key": process.env.BLOCKFORECAST_API_KEY! } }
);
if (!resp.ok) throw new Error(`API error: ${resp.status}`);
const data = await resp.json();
for (const market of data.markets) {
console.log(`${market.question} — YES: ${market.yesPrice.toFixed(2)}`);
}
```
**Example response:**
```json theme={null}
{
"markets": [
{
"id": 781,
"tickerId": "BF-0781",
"slug": "will-btc-close-above-150k-dec-2026",
"question": "Will BTC close above $150k on Dec 31, 2026?",
"category": "crypto",
"status": "open",
"yesPrice": 0.34,
"noPrice": 0.66,
"volume": 18420.50,
"liquidity": 4100.00,
"resolveDate": "2026-12-31T23:59:59Z",
"createdAt": "2026-01-15T10:22:00Z"
}
],
"total": 142,
"limit": 5,
"offset": 0
}
```
***
## GET /public/markets/:id
Fetches a single market by its numeric ID, ticker ID, or slug.
### Path parameters
The market's numeric `id` (e.g., `781`), `tickerId` (e.g., `BF-0781`), or `slug`. All three are accepted.
### Response fields
Returns a single market object with all the fields described in `GET /markets`, plus:
The plain-text criteria the AI oracle uses to resolve the market.
Creator metadata.
The Ethereum address of the market creator.
Creator display name, if set.
Present only on resolved markets.
`YES` or `NO`.
ISO 8601 timestamp when the oracle resolved the market.
Oracle confidence score (0–1) at resolution time.
### Examples
```bash theme={null}
curl "https://blockforecast.io/api/v2/public/markets/781" \
-H "X-API-Key: $BLOCKFORECAST_API_KEY"
```
```python theme={null}
import os, requests
market_id = 781
resp = requests.get(
f"https://blockforecast.io/api/v2/public/markets/{market_id}",
headers={"X-API-Key": os.environ["BLOCKFORECAST_API_KEY"]},
)
resp.raise_for_status()
market = resp.json()
print(f"YES: {market['yesPrice']}, NO: {market['noPrice']}")
```
```typescript theme={null}
const marketId = 781;
const resp = await fetch(
`https://blockforecast.io/api/v2/public/markets/${marketId}`,
{ headers: { "X-API-Key": process.env.BLOCKFORECAST_API_KEY! } }
);
if (!resp.ok) throw new Error(`API error: ${resp.status}`);
const market = await resp.json();
console.log(`YES: ${market.yesPrice}, NO: ${market.noPrice}`);
```
***
## POST /public/markets
Creates a new prediction market. Requires your wallet to have approved creator status. [Apply for creator access](/creators/apply) — applications are reviewed within 24 hours.
### Request body
The market question. Should be phrased as a binary yes/no question. Maximum 280 characters.
Additional context about the market. Markdown supported. Maximum 2000 characters.
Clear, unambiguous criteria that define how the market resolves. The AI oracle uses this text. Maximum 1000 characters.
ISO 8601 date-time for when the market is eligible for resolution (e.g., `2026-12-31T23:59:59Z`). Must be at least 1 hour in the future.
Category slug. One of: `crypto`, `sports`, `politics`, `science`, `entertainment`, `other`.
### Response fields
Returns the newly created market object with all fields from `GET /markets/:id`.
The new market's numeric identifier.
The URL slug generated from the question.
Always `open` on creation.
### Examples
```bash theme={null}
curl -X POST "https://blockforecast.io/api/v2/public/markets" \
-H "X-API-Key: $BLOCKFORECAST_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"question": "Will ETH surpass $10,000 before July 2027?",
"description": "Tracks ETH/USD price on Coinbase Pro at any point before the resolution date.",
"resolutionCriteria": "Resolves YES if ETH/USD closes above $10,000 on Coinbase Pro on any day before July 1, 2027. Resolves NO otherwise.",
"resolveDate": "2027-07-01T00:00:00Z",
"category": "crypto"
}'
```
```python theme={null}
import os, requests
resp = requests.post(
"https://blockforecast.io/api/v2/public/markets",
headers={
"X-API-Key": os.environ["BLOCKFORECAST_API_KEY"],
"Content-Type": "application/json",
},
json={
"question": "Will ETH surpass $10,000 before July 2027?",
"description": "Tracks ETH/USD price on Coinbase Pro at any point before the resolution date.",
"resolutionCriteria": "Resolves YES if ETH/USD closes above $10,000 on Coinbase Pro on any day before July 1, 2027. Resolves NO otherwise.",
"resolveDate": "2027-07-01T00:00:00Z",
"category": "crypto",
},
)
resp.raise_for_status()
market = resp.json()
print(f"Created market: https://blockforecast.io/market/{market['slug']}")
```
```typescript theme={null}
const resp = await fetch("https://blockforecast.io/api/v2/public/markets", {
method: "POST",
headers: {
"X-API-Key": process.env.BLOCKFORECAST_API_KEY!,
"Content-Type": "application/json",
},
body: JSON.stringify({
question: "Will ETH surpass $10,000 before July 2027?",
description: "Tracks ETH/USD price on Coinbase Pro at any point before the resolution date.",
resolutionCriteria:
"Resolves YES if ETH/USD closes above $10,000 on Coinbase Pro on any day before July 1, 2027. Resolves NO otherwise.",
resolveDate: "2027-07-01T00:00:00Z",
category: "crypto",
}),
});
if (!resp.ok) throw new Error(`API error: ${resp.status}`);
const market = await resp.json();
console.log(`Created: https://blockforecast.io/market/${market.slug}`);
```
If your API key's wallet does not have creator status, this endpoint returns `403 Forbidden` with code `INSUFFICIENT_PERMISSIONS`. Apply at [blockforecast.io/apply](/creators/apply) — the same approval covers both the public API and the x402 Agent API.
***
## GET /public/markets/:id/trades
Returns a paginated list of trades for a specific market, ordered from most recent to oldest.
### Path parameters
The market ID or slug.
### Query parameters
Number of trades to return. Maximum `100`. Default `20`.
Pagination offset. Default `0`.
Filter by trade side. One of `YES`, `NO`. Omit to return both.
### Response fields
Array of trade objects.
Numeric trade identifier.
The numeric ID of the market this trade belongs to.
`YES` or `NO`.
Number of shares purchased.
Effective price per share at execution (0–1).
Total USDC cost of the trade.
Ethereum address of the trader (may be partial for privacy).
ISO 8601 timestamp of the trade.
Total number of trades for this market.
### Examples
```bash theme={null}
curl "https://blockforecast.io/api/v2/public/markets/781/trades?limit=10" \
-H "X-API-Key: $BLOCKFORECAST_API_KEY"
```
```python theme={null}
import os, requests
market_id = "781"
resp = requests.get(
f"https://blockforecast.io/api/v2/public/markets/{market_id}/trades",
headers={"X-API-Key": os.environ["BLOCKFORECAST_API_KEY"]},
params={"limit": 10},
)
resp.raise_for_status()
data = resp.json()
for trade in data["trades"]:
print(f"{trade['side']} | {trade['shares']} shares @ {trade['pricePerShare']:.3f}")
```
```typescript theme={null}
const marketId = "781";
const resp = await fetch(
`https://blockforecast.io/api/v2/public/markets/${marketId}/trades?limit=10`,
{ headers: { "X-API-Key": process.env.BLOCKFORECAST_API_KEY! } }
);
if (!resp.ok) throw new Error(`API error: ${resp.status}`);
const data = await resp.json();
for (const trade of data.trades) {
console.log(`${trade.side} | ${trade.shares} shares @ ${trade.pricePerShare.toFixed(3)}`);
}
```
**Example response:**
```json theme={null}
{
"trades": [
{
"id": 31487,
"marketId": 781,
"side": "YES",
"shares": 50.0,
"pricePerShare": 0.341,
"totalCost": 17.05,
"traderAddress": "0x1a2b...f9e0",
"createdAt": "2026-04-27T14:35:12Z"
}
],
"total": 1204,
"limit": 10,
"offset": 0
}
```
***
## Additional endpoints
The following endpoints are available but covered in detail in [Authentication](/developers/authentication). The auth flow is **two-step** — `/auth/challenge` must be called before `/auth/token`:
| Method | Path | Description |
| ------ | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `POST` | `/api/v2/auth/challenge` | **Step 1 — required prerequisite for `/auth/token`.** Issues a single-use nonce for a wallet-signed action (`issue` / `revoke` / `regenerate`). |
| `POST` | `/api/v2/auth/token` | **Step 2.** Exchange a wallet signature + the nonce from step 1 for a `bf_…` API key. |
| `GET` | `/api/v2/auth/keys?address=` | List active keys (prefixes only) for a wallet. |
| `POST` | `/api/v2/auth/keys/:id/revoke` | Revoke a specific key by id. |
| `POST` | `/api/v2/auth/keys/:id/regenerate` | Atomically rotate — old revoked, new issued. |
| `GET` | `/api/v2/public/markets/:id/price` | Current LSMR price and price impact for a given quote size. |
| `GET` | `/api/v2/public/markets/:id/history` | OHLC price history. |
| `POST` | `/api/v2/public/markets/:id/trade` | Place a trade on a market. |
| `GET` | `/api/v2/public/positions` | Open positions for your wallet. |
| `GET` | `/api/v2/public/positions/history` | Trade history for your wallet. |
| `GET` | `/api/v2/public/balance` | Your USDC balance on BlockForecast. |
To create markets programmatically without the manual creator approval flow, see the [x402 Agent API](/developers/x402-overview) — autonomous agents can pay \$1 USDC per market with no signup required (creator approval still needed, but the flow is fully programmatic).
# Developer Quickstart: BlockForecast REST API
Source: https://docs.blockforecast.io/developers/quickstart
Make your first BlockForecast API request in under five minutes. Get an API key, list active markets, and explore the full developer surface.
The BlockForecast REST API gives you programmatic access to prediction markets — list and filter markets, stream trade data, place trades, and create your own markets with creator approval. The base URL for all v2 endpoints is `https://blockforecast.io/api/v2`. Authentication uses a long-lived API key (`bf_<32 hex>`) that you obtain by signing a one-time challenge with your wallet. This guide walks you through every step from zero to your first successful response.
**Building an AI agent that creates markets?** Skip the manual setup — install the [`/bf-create-market` Claude Code skill](/developers/claude-skill). One slash command wraps the full x402 + creator-fee flow.
**Just need a key?** Sign in at [blockforecast.io/settings/api-keys](https://blockforecast.io/settings/api-keys) and tap **Generate key** — Privy pops the wallet signature, the key is shown once. No curl needed for the happy path.
Keys are issued in a two-step nonce-bound flow: request a challenge, sign the exact message it returns, post both back. No account required — your wallet address is your identity. Each nonce is single-use, so the same signature can't be replayed for any other action.
```bash curl theme={null}
# 1. Request a challenge
curl -X POST https://blockforecast.io/api/v2/auth/challenge \
-H "Content-Type: application/json" \
-d '{
"address": "0xYourWalletAddress",
"action": "issue"
}'
# response → { "success": true, "data": {
# "nonce": "<48-hex-chars>",
# "message": "BlockForecast API Key\nAction: issue\nAddress: 0x...\nNonce: ...\nTimestamp: 1777408738",
# "expiresAt": "2026-04-28T20:43:58.000Z"
# } }
# 2. Sign data.message with your wallet (any EVM tool: viem, ethers, MetaMask…)
# 3. Post the signature + nonce back
curl -X POST https://blockforecast.io/api/v2/auth/token \
-H "Content-Type: application/json" \
-d '{
"address": "0xYourWalletAddress",
"message": "",
"signature": "0xYourSignedMessage",
"nonce": "",
"label": "prod-bot"
}'
```
The response contains your API key (shown once):
```json theme={null}
{
"success": true,
"data": {
"id": 7,
"apiKey": "bf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"prefix": "bf_xxxxxxxx...",
"label": "prod-bot",
"rateLimit": 60,
"createdAt": "2026-04-28T20:43:00.000Z",
"note": "Store this key securely. It cannot be retrieved again."
}
}
```
Store the `apiKey` value as a secret in your deployment platform — the server only stores its SHA-256 hash, so a leaked DB doesn't leak keys, but the raw key cannot be re-fetched. See [Authentication](/developers/authentication) for the full signing flow, the regenerate/revoke endpoints, and error reference.
With your key in hand, call `GET /api/v2/public/markets` to fetch the current list of active prediction markets.
```bash curl theme={null}
curl https://blockforecast.io/api/v2/public/markets \
-H "X-API-Key: $BLOCKFORECAST_API_KEY"
```
```python Python theme={null}
import os
import requests
resp = requests.get(
"https://blockforecast.io/api/v2/public/markets",
headers={"X-API-Key": os.environ["BLOCKFORECAST_API_KEY"]},
)
resp.raise_for_status()
body = resp.json()
# Every v2 endpoint wraps results: { success: true, data: {...} }
markets = body["data"]["markets"]
total = body["data"]["total"]
print(f"Found {total} markets")
```
```typescript JavaScript / TypeScript theme={null}
const resp = await fetch("https://blockforecast.io/api/v2/public/markets", {
headers: {
"X-API-Key": process.env.BLOCKFORECAST_API_KEY!,
},
});
if (!resp.ok) throw new Error(`API error: ${resp.status}`);
const body = await resp.json();
// Every v2 endpoint wraps results: { success: true, data: {...} }
const { markets, total } = body.data;
console.log(`Found ${total} markets`);
```
You can filter results with query parameters: `?status=active&category=crypto&limit=10`. See [Public API](/developers/public-api) for the full parameter reference.
A successful `GET /markets` response looks like this:
```json theme={null}
{
"markets": [
{
"id": 781,
"tickerId": "BF-0781",
"slug": "will-btc-close-above-150k-dec-2026",
"question": "Will BTC close above $150k on Dec 31, 2026?",
"category": "crypto",
"status": "open",
"yesPrice": 0.34,
"noPrice": 0.66,
"volume": 18420.50,
"liquidity": 4100.00,
"resolveDate": "2026-12-31T23:59:59Z",
"createdAt": "2026-01-15T10:22:00Z"
}
],
"total": 142,
"limit": 20,
"offset": 0
}
```
Each market object includes the current LSMR prices (`yesPrice`, `noPrice`), aggregate volume, available liquidity, and the resolution date. Prices are expressed as probabilities between 0 and 1 — a `yesPrice` of `0.34` means the market currently prices the YES outcome at 34 cents per share. The `status` field is `open` while trading is live, `resolving` after close, and `resolved` once the oracle settles.
All monetary values in the API are denominated in USDC (6-decimal precision on-chain, returned as floating-point USD in the REST API).
You have the basics working. Here is where to go next depending on what you want to build:
Full endpoint reference with request params, response fields, and multi-language examples for every route.
Wallet-signature auth flow, error codes, key rotation, and security best practices.
Default limits, 429 handling, exponential backoff examples, and how to request a higher limit.
Create markets from an autonomous AI agent — no API key required, just \$1 USDC per market via x402.
# API Rate Limits: Quotas, Headers, and Backoff
Source: https://docs.blockforecast.io/developers/rate-limits
BlockForecast enforces 60 requests per minute per API key. Learn how to read rate-limit headers, handle 429 errors gracefully, and request a higher quota.
Every API key on BlockForecast is subject to a default rate limit of **60 requests per minute**. The limit is enforced per key on a rolling 60-second window — it is not a fixed-clock reset. If you exceed the limit, the API returns `429 Too Many Requests` and you must wait before retrying. This page explains how to read the rate-limit headers included on every response, how to implement exponential backoff, and how to stay within the default quota for common workloads.
## Rate-limit headers
Every API response includes three headers that tell you your current quota status:
| Header | Type | Description |
| ----------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------- |
| `X-RateLimit-Limit` | integer | Your total allowed requests per 60-second window (default: `60`). |
| `X-RateLimit-Remaining` | integer | Requests remaining in the current window. |
| `X-RateLimit-Reset` | Unix timestamp | The time (in seconds since epoch) when the window resets and `X-RateLimit-Remaining` returns to `X-RateLimit-Limit`. |
Example response headers:
```http theme={null}
HTTP/2 200
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 42
X-RateLimit-Reset: 1745001060
Content-Type: application/json
```
## When you exceed the limit
If `X-RateLimit-Remaining` reaches `0`, the next request returns:
```http theme={null}
HTTP/2 429 Too Many Requests
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1745001060
Retry-After: 23
Content-Type: application/json
```
```json theme={null}
{
"error": "RATE_LIMIT_EXCEEDED",
"message": "You have exceeded the rate limit of 60 requests/min. Retry after the Retry-After interval.",
"retryAfter": 23
}
```
The `Retry-After` header tells you exactly how many seconds to wait before the window resets.
## Handling 429s: exponential backoff
Immediately retrying after a `429` will only trigger another `429`. Use exponential backoff with jitter:
```python Python theme={null}
import os, time, random, requests
API_KEY = os.environ["BLOCKFORECAST_API_KEY"]
BASE_URL = "https://blockforecast.io/api/v2"
def get_with_backoff(path: str, params: dict = None, max_retries: int = 5):
url = f"{BASE_URL}{path}"
headers = {"X-API-Key": API_KEY}
for attempt in range(max_retries):
resp = requests.get(url, headers=headers, params=params)
if resp.status_code == 429:
retry_after = int(resp.headers.get("Retry-After", 1))
# Add jitter: wait retry_after seconds + up to 1s random
wait = retry_after + random.random()
print(f"Rate limited. Waiting {wait:.1f}s (attempt {attempt + 1}/{max_retries})")
time.sleep(wait)
continue
resp.raise_for_status()
return resp.json()
raise Exception("Max retries exceeded after repeated 429 responses")
markets = get_with_backoff("/public/markets", params={"status": "active"})
```
```typescript JavaScript / TypeScript theme={null}
const API_KEY = process.env.BLOCKFORECAST_API_KEY!;
const BASE_URL = "https://blockforecast.io/api/v2";
async function getWithBackoff(
path: string,
params?: Record,
maxRetries = 5
): Promise {
const url = new URL(`${BASE_URL}${path}`);
if (params) {
Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
}
for (let attempt = 0; attempt < maxRetries; attempt++) {
const resp = await fetch(url.toString(), {
headers: { "X-API-Key": API_KEY },
});
if (resp.status === 429) {
const retryAfter = parseInt(resp.headers.get("Retry-After") ?? "1", 10);
const jitter = Math.random();
const wait = (retryAfter + jitter) * 1000;
console.log(`Rate limited. Waiting ${(wait / 1000).toFixed(1)}s (attempt ${attempt + 1}/${maxRetries})`);
await new Promise((resolve) => setTimeout(resolve, wait));
continue;
}
if (!resp.ok) throw new Error(`API error: ${resp.status}`);
return resp.json();
}
throw new Error("Max retries exceeded after repeated 429 responses");
}
const markets = await getWithBackoff("/public/markets", { status: "active" });
```
Read `X-RateLimit-Remaining` proactively on every response and slow down when it approaches zero — don't wait for a `429` to trigger your backoff logic.
## Tips for staying within the limit
**Cache responses locally.** Market state does not change on every tick. For most read workloads, caching `GET /markets` for 5–10 seconds and individual market details for 1–2 seconds dramatically reduces API calls without meaningfully staling your data.
**Batch reads with pagination.** Rather than making one request per market, use the `limit` parameter on `GET /markets` to fetch up to 100 markets in a single call. Then page through with `offset` as needed.
**Use the real-time feed for high-frequency data.** If you need market prices at sub-second latency, the x402 feed endpoint (`GET /api/v2/x402/feed`, \$0.001/call) is designed for that use case and does not count against your REST rate limit.
**Deduplicate inflight requests.** In async or multi-threaded code, use a simple in-memory cache or request-deduplication layer to prevent the same resource from being fetched concurrently by multiple coroutines or threads.
**Avoid polling loops with short intervals.** A loop that calls `GET /markets/:id` every second will exhaust your quota in one minute. Use a minimum 5-second poll interval for market state, or switch to the WebSocket broadcaster for real-time updates.
## Request a higher rate limit
If your use case requires more than 60 requests per minute — for example, a trading desk pulling tick-level data or an arbitrage bot running across hundreds of markets simultaneously — you can request a higher quota.
Email [support@blockforecast.io](mailto:support@blockforecast.io) with:
* Your wallet address (the one attached to your API key)
* A brief description of your use case
* The approximate request rate you need
Higher-limit keys are provisioned manually and are typically turned around within one business day.
x402 pay-per-request endpoints (`/api/v2/x402/*`) are not subject to the same per-minute quota. Each call is independently metered by payment, so there is no burst limit — you can make as many calls as you can pay for.
# Create a Prediction Market via the x402 Agent API
Source: https://docs.blockforecast.io/developers/x402-create-market
Create BlockForecast markets from an AI agent: set up a Base wallet, fund with USDC, get creator approval, then POST /x402/markets for $1 USDC per market.
This guide walks you through the complete end-to-end flow for creating a BlockForecast prediction market from an autonomous agent using the x402 payment protocol. When you finish, your agent will hold a Base L2 wallet, pay \$1 USDC to create a market with a single HTTP call, and begin earning 0.5% of every trade on that market in real time. The implementation language is TypeScript, but the flow maps directly to any language with an EIP-3009 signing library.
**Building in Claude Code?** Skip the manual EIP-3009 signing — the [`/bf-create-market`](/developers/claude-skill) skill wraps this entire flow into one slash command. Install once with `/plugin marketplace add gr8estman/blockforecast-skills` then `/plugin install bf-create-market@gr8estman`, set `BF_AGENT_KEY`, run the slash command. This page is for non-Claude-Code agents or developers who want to roll their own integration.
`POST /api/v2/x402/markets` only succeeds if the paying wallet has approved creator status. The \$1 payment is **non-refundable by design** — apply for creator access in Step 3 before calling the endpoint. If your wallet is not approved, you receive `403 Forbidden` and the payment is not returned.
## Prerequisites
* Node.js 18+ with TypeScript support
* An Ethereum wallet (or you will generate one in Step 1)
* USDC on Base mainnet (\~\$5 to cover gas and several market creations)
Install the required packages:
```bash theme={null}
npm install viem x402-fetch
```
***
## Step 1: Set up a Base L2 wallet
Your agent needs a dedicated EVM wallet whose private key it can access at runtime for signing. You can generate a fresh wallet programmatically:
```typescript theme={null}
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
// Generate a new private key — do this once and save the result
const privateKey = generatePrivateKey();
const account = privateKeyToAccount(privateKey);
console.log("Agent address:", account.address);
console.log("Private key (save this securely!):", privateKey);
```
Store the private key in a secrets manager — AWS Secrets Manager, Doppler, 1Password, or a `.env` file that is never committed to source control. Anyone with access to this key can spend the wallet's funds.
If you already have a wallet (MetaMask, Coinbase Wallet), you can export the private key from Settings and use it directly. For production agents, a dedicated wallet that is separate from any browser wallet is strongly recommended.
Load the key from your environment at runtime:
```typescript theme={null}
import { privateKeyToAccount } from "viem/accounts";
const account = privateKeyToAccount(
process.env.AGENT_PRIVATE_KEY as `0x${string}`
);
console.log("Agent address:", account.address);
```
***
## Step 2: Fund the wallet with USDC on Base
The x402 endpoints use USDC on Base mainnet (CAIP-2 identifier: `eip155:8453`). Your wallet needs:
* **\$1.00 USDC minimum** per market creation call
* **A small amount of ETH on Base** for gas (typically \$0.01–\$0.05 per transaction)
* A buffer for other x402 endpoints if you plan to use them (`feed`, `oracle/resolve`)
**Option A — Bridge from Ethereum mainnet:**
Use the [official Base bridge](https://bridge.base.org). Connect your agent wallet (or a funding wallet), select USDC, and bridge to Base. Bridging takes \~1 minute.
**Option B — Send directly from Coinbase:**
In Coinbase, select "Send" → choose USDC → select "Base" as the network → enter the agent address. Funds arrive in seconds.
**Option C — Programmatic funding (for CI/testing):**
```typescript theme={null}
import { createWalletClient, http, parseUnits } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { base } from "viem/chains";
// USDC contract on Base mainnet
const USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
const USDC_ABI = [
{
name: "transfer",
type: "function",
inputs: [
{ name: "to", type: "address" },
{ name: "amount", type: "uint256" },
],
outputs: [{ name: "", type: "bool" }],
},
] as const;
const fundingAccount = privateKeyToAccount(
process.env.FUNDING_PRIVATE_KEY as `0x${string}`
);
const client = createWalletClient({
account: fundingAccount,
chain: base,
transport: http(),
});
const txHash = await client.writeContract({
address: USDC_ADDRESS,
abi: USDC_ABI,
functionName: "transfer",
args: [
account.address, // agent address
parseUnits("5", 6), // 5 USDC (6 decimals)
],
});
console.log("Funded agent wallet. Tx:", txHash);
```
Verify the balance before proceeding:
```typescript theme={null}
import { createPublicClient, http, formatUnits } from "viem";
import { base } from "viem/chains";
const USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
const ERC20_ABI = [
{
name: "balanceOf",
type: "function",
inputs: [{ name: "account", type: "address" }],
outputs: [{ name: "", type: "uint256" }],
stateMutability: "view",
},
] as const;
const publicClient = createPublicClient({ chain: base, transport: http() });
const balance = await publicClient.readContract({
address: USDC_ADDRESS,
abi: ERC20_ABI,
functionName: "balanceOf",
args: [account.address],
});
console.log("USDC balance:", formatUnits(balance, 6), "USDC");
```
***
## Step 3: Apply for creator access
Creator approval is a one-time, per-wallet step. Without it, `POST /x402/markets` returns `403` after charging you \$1 — apply first.
1. Visit [blockforecast.io/apply](/creators/apply).
2. Click **Connect wallet** and choose **External wallet**.
3. Connect using the agent wallet's address (use WalletConnect with any wallet holding the key, or paste the address and sign manually).
4. Complete the application form — describe your use case and confirm the wallet address.
5. You will hear back within 24 hours. Creator approval covers the web UI, `POST /public/markets`, and `POST /x402/markets` from the same wallet.
You only do this once per agent wallet. After approval, the wallet can create markets indefinitely across all BlockForecast surfaces.
To check approval status programmatically before paying for a market — `/x402/info` does **not** include per-wallet status. Use the public creator-status endpoint:
```bash theme={null}
curl "https://blockforecast.io/api/v2/creator/status?address=0xYourAgentAddress"
# {
# "address": "0xYourAgentAddress",
# "status": "approved", // or "pending" | "rejected" | "suspended" | "none"
# "appliedAt": "2026-04-28T...",
# "approvedAt": "2026-04-29T...",
# "rejectedReason": null
# }
```
Always poll this before calling `POST /x402/markets`. The \$1 payment is **not refundable** if the call fails the creator gate (returns 403).
***
## Step 4: POST /x402/markets
With a funded, approved wallet, you are ready to create a market. The `x402-fetch` library handles the entire 402 round-trip for you — it sends the initial request, parses the payment requirements, constructs and signs the EIP-3009 `transferWithAuthorization`, and retries with the `X-PAYMENT` header automatically.
### Full working example
```typescript theme={null}
import { wrapFetchWithPayment } from "x402-fetch";
import { privateKeyToAccount } from "viem/accounts";
// Load account from environment
const account = privateKeyToAccount(
process.env.AGENT_PRIVATE_KEY as `0x${string}`
);
// Wrap fetch with automatic x402 payment handling
const fetchPaid = wrapFetchWithPayment(fetch, account);
async function createMarket(params: {
question: string;
category: string;
resolveDate: string;
description?: string;
resolutionCriteria?: string;
}) {
const resp = await fetchPaid(
"https://blockforecast.io/api/v2/x402/markets",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(params),
}
);
if (!resp.ok) {
const error = await resp.json().catch(() => ({ message: resp.statusText }));
throw new Error(`Market creation failed (${resp.status}): ${error.message}`);
}
return resp.json();
}
// Create a market
const market = await createMarket({
question: "Will BTC close above $150k on Dec 31, 2026?",
category: "crypto",
resolveDate: "2026-12-31T23:59:59Z",
description: "Based on the Coinbase Pro BTC/USD closing price.",
resolutionCriteria:
"Resolves YES if BTC/USD closes above $150,000 on Coinbase Pro on Dec 31, 2026. Resolves NO otherwise.",
});
console.log("Market created!");
console.log("ID:", market.id);
console.log("URL:", `https://blockforecast.io/market/${market.slug}`);
console.log("Creator earnings flow to:", account.address);
```
### What x402-fetch does under the hood
If you prefer to implement the protocol directly (for a different language or a custom client), here is the manual flow:
```typescript theme={null}
import { createWalletClient, http, parseUnits } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { base } from "viem/chains";
const USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
const account = privateKeyToAccount(process.env.AGENT_PRIVATE_KEY as `0x${string}`);
const walletClient = createWalletClient({ account, chain: base, transport: http() });
const requestBody = {
question: "Will BTC close above $150k on Dec 31, 2026?",
category: "crypto",
resolveDate: "2026-12-31T23:59:59Z",
};
// Step 1: Send request without payment — expect 402
const probe = await fetch("https://blockforecast.io/api/v2/x402/markets", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
});
if (probe.status !== 402) throw new Error(`Expected 402, got ${probe.status}`);
const paymentReqs = await probe.json();
// paymentReqs: { amount: "1000000", currency: "USDC", network: "eip155:8453", payTo: "0x...", nonce: "..." }
// Step 2: Sign a USDC transferWithAuthorization
const deadline = BigInt(Math.floor(Date.now() / 1000) + 300); // 5-min expiry
const nonce = paymentReqs.nonce;
const signature = await walletClient.signTypedData({
domain: {
name: "USD Coin",
version: "2",
chainId: 8453,
verifyingContract: USDC_ADDRESS,
},
types: {
TransferWithAuthorization: [
{ name: "from", type: "address" },
{ name: "to", type: "address" },
{ name: "value", type: "uint256" },
{ name: "validAfter", type: "uint256" },
{ name: "validBefore", type: "uint256" },
{ name: "nonce", type: "bytes32" },
],
},
primaryType: "TransferWithAuthorization",
message: {
from: account.address,
to: paymentReqs.payTo,
value: BigInt(paymentReqs.amount),
validAfter: BigInt(0),
validBefore: deadline,
nonce: nonce,
},
});
// Step 3: Encode payment payload and retry
const paymentPayload = Buffer.from(
JSON.stringify({
from: account.address,
to: paymentReqs.payTo,
value: paymentReqs.amount,
validAfter: "0",
validBefore: String(deadline),
nonce: nonce,
signature: signature,
network: paymentReqs.network,
currency: paymentReqs.currency,
})
).toString("base64");
const result = await fetch("https://blockforecast.io/api/v2/x402/markets", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-PAYMENT": paymentPayload,
},
body: JSON.stringify(requestBody),
});
if (!result.ok) throw new Error(`Failed: ${result.status}`);
const market = await result.json();
console.log("Market created:", market.id);
```
***
## Response: the created market object
A successful `201 Created` response returns the new market:
```json theme={null}
{
"id": 1042,
"tickerId": "BF-1042",
"slug": "will-btc-close-above-150k-dec-2026",
"question": "Will BTC close above $150k on Dec 31, 2026?",
"category": "crypto",
"status": "open",
"yesPrice": 0.50,
"noPrice": 0.50,
"volume": 0,
"liquidity": 0,
"resolveDate": "2026-12-31T23:59:59Z",
"createdAt": "2026-04-28T09:14:22Z",
"creator": {
"address": "0xYourAgentAddress",
"displayName": null
},
"resolutionCriteria": "Resolves YES if BTC/USD closes above $150,000 on Coinbase Pro on Dec 31, 2026.",
"resolution": null
}
```
The market is immediately live and tradeable at `https://blockforecast.io/market/{slug}`. Creator fee earnings (0.5% of every trade) flow to `account.address` in real time.
***
## Error handling
| HTTP status | Condition | What to do |
| ------------------------------- | -------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `402 Payment Required` | Initial response — no payment sent | Expected behavior. Client must sign and retry. |
| `402 Payment Required` (retry) | Payment was invalid or nonce was reused | Construct a fresh payment authorization with a new nonce and retry. |
| `403 Forbidden` | Paying wallet does not have creator approval | [Apply for creator access](/creators/apply) before calling this endpoint. Payment is not refunded. |
| `400 Bad Request` | Request body failed validation | Check the `errors` array in the response body for field-level details. |
| `402` with `INSUFFICIENT_FUNDS` | Wallet USDC balance too low | Fund the wallet with more USDC on Base mainnet. |
| `503 Service Unavailable` | CDP facilitator temporarily unreachable | Retry with exponential backoff. The payment was not settled. |
Full error handling example:
```typescript theme={null}
async function createMarketSafe(params: object): Promise