EXAMPLES
Code Examples
Copy-paste working examples for common x402 API workflows. Each example uses @x402/fetch for automatic payment negotiation and can run as a standalone script.
Example [1]
Create Market & Place Prediction
Full flow: create a prediction market, then place a privacy-preserving prediction using a commitment hash.
TypeScript
import { wrapFetch } from "@x402/fetch";
import { createSvmSigner } from "@x402/svm";
import { Keypair } from "@solana/web3.js";
const API = "https://api.oyrade.com";
async function createAndPredict() {
// Setup x402-enabled fetch with a funded Solana wallet
const keypair = Keypair.fromSecretKey(/* your secret key */);
const signer = createSvmSigner(keypair);
const x402Fetch = wrapFetch(fetch, signer);
// Step 1: Create a prediction market ($0.50)
const createRes = await x402Fetch(`${API}/api/v1/markets/create`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
token_mint: "DfnxGQUsXdDH7DYdroeeSBG8etqTy1kufxBikHwTTGTa",
question: "Will ETH reach $10K by June 2026?",
market_name: "ETH 10K Q2 2026",
slug: "eth-10k-q2-2026",
category: "crypto",
end_date: Math.floor(new Date("2026-06-01").getTime() / 1000),
oracle_feed: "ETH/USD",
price_target: 10000,
comparison_type: "above",
}),
});
const { data: market } = await createRes.json();
console.log("Market created:", market.market_id);
console.log("YES token:", market.yes_token_mint);
console.log("NO token:", market.no_token_mint);
console.log("Tx:", market.tx_signature);
// Step 2: Place a prediction on YES ($0.01 + 3% of amount)
const predictRes = await x402Fetch(
`${API}/api/v1/markets/${market.market_id}/predict`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
outcome: "YES",
amount: 0.5,
commitment_hash:
"a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2",
}),
}
);
const { data: prediction } = await predictRes.json();
console.log("Prediction ID:", prediction.prediction_id);
console.log("Tokens received:", prediction.tokens_received);
console.log("Effective price:", prediction.effective_price);
console.log("YES price after:", prediction.yes_price_after);
console.log("NO price after:", prediction.no_price_after);
}
createAndPredict().catch(console.error);Expected Output
Market created: 7xKp...
YES token: 4rQz...
NO token: 8mNp...
Tx: 5vGh...
Prediction ID: pred_01H...
Tokens received: 0.612
Effective price: 0.817
YES price after: 0.83
NO price after: 0.17Example [2]
Sell Position & Claim Winnings
Sell an existing position for SOL, or claim winnings from a resolved market using your commitment hash.
TypeScript
import { wrapFetch } from "@x402/fetch";
import { createSvmSigner } from "@x402/svm";
import { Keypair } from "@solana/web3.js";
const API = "https://api.oyrade.com";
async function sellAndClaim() {
const keypair = Keypair.fromSecretKey(/* your secret key */);
const signer = createSvmSigner(keypair);
const x402Fetch = wrapFetch(fetch, signer);
const marketId = "7xKp...";
const commitmentHash =
"a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2";
const payoutAddress = "YourSo1anaWa11etAddress...";
// Sell a position before market resolves ($0.01)
console.log("=== Selling Position ===");
const sellRes = await x402Fetch(
`${API}/api/v1/markets/${marketId}/sell`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
commitment_hash: commitmentHash,
payout_address: payoutAddress,
amount: 0.3, // optional: partial sell
}),
}
);
const { data: sell } = await sellRes.json();
console.log("Tokens sold:", sell.tokens_sold);
console.log("SOL received:", sell.sol_received);
console.log("Payout address:", sell.payout_address);
console.log("Tx:", sell.tx_signature);
// Claim winnings after market resolves ($0.01)
console.log("\n=== Claiming Winnings ===");
const claimRes = await x402Fetch(
`${API}/api/v1/markets/${marketId}/claim`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
commitment_hash: commitmentHash,
payout_address: payoutAddress,
}),
}
);
const { data: claim } = await claimRes.json();
if (claim.claimable) {
console.log("Winnings claimed!");
console.log("SOL received:", claim.sol_received);
console.log("Winning outcome:", claim.winning_outcome);
console.log("Tx:", claim.tx_signature);
} else {
console.log("Not claimable:", claim.reason);
}
}
sellAndClaim().catch(console.error);Expected Output
=== Selling Position ===
Tokens sold: 0.30
SOL received: 0.245
Payout address: YourSo1ana...
Tx: 3kFm...
=== Claiming Winnings ===
Winnings claimed!
SOL received: 0.312
Winning outcome: YES
Tx: 9pLx...Example [3]
Resolve Market & Check Positions
Trigger oracle-based resolution for a market, then check your open positions across markets.
TypeScript
import { wrapFetch } from "@x402/fetch";
import { createSvmSigner } from "@x402/svm";
import { Keypair } from "@solana/web3.js";
const API = "https://api.oyrade.com";
async function resolveAndCheckPositions() {
const keypair = Keypair.fromSecretKey(/* your secret key */);
const signer = createSvmSigner(keypair);
const x402Fetch = wrapFetch(fetch, signer);
const marketId = "7xKp...";
// Resolve market via oracle ($0.05)
console.log("=== Resolving Market ===");
const resolveRes = await x402Fetch(
`${API}/api/v1/markets/${marketId}/resolve`
);
const { data: resolution } = await resolveRes.json();
if (resolution.resolved) {
console.log("Market resolved!");
console.log("Winning outcome:", resolution.winning_outcome);
console.log("Oracle price:", resolution.oracle_price);
console.log("Oracle source:", resolution.oracle_source);
console.log("Tx:", resolution.tx_signature);
console.log("Resolved at:", resolution.resolved_at);
} else {
console.log("Not ready:", resolution.reason);
console.log("End date:", resolution.end_date);
}
// Check positions across markets (free)
console.log("\n=== Checking Positions ===");
const hashes = [
"a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2",
"f6e5d4c3b2a1f6e5d4c3b2a1f6e5d4c3b2a1f6e5d4c3b2a1f6e5d4c3b2a1f6e5",
].join(",");
const posRes = await fetch(
`${API}/api/v1/positions?commitment_hash=${hashes}`
);
const { data: posData } = await posRes.json();
for (const pos of posData.positions) {
console.log(`\nPosition: ${pos.commitment_hash.slice(0, 8)}...`);
console.log(" Market:", pos.market_id);
console.log(" Outcome:", pos.outcome);
console.log(" Tokens remaining:", pos.tokens_remaining);
console.log(" Current value:", pos.current_value_sol, "SOL");
console.log(" Payout if win:", pos.payout_if_win, "SOL");
console.log(" Status:", pos.status);
}
}
resolveAndCheckPositions().catch(console.error);Expected Output
=== Resolving Market ===
Market resolved!
Winning outcome: YES
Oracle price: 10523.45
Oracle source: switchboard
Tx: 5vGh...
Resolved at: 2026-06-01T00:05:00Z
=== Checking Positions ===
Position: a1b2c3d4...
Market: 7xKp...
Outcome: YES
Tokens remaining: 0.612
Current value: 0.612 SOL
Payout if win: 0.612 SOL
Status: claimable
Position: f6e5d4c3...
Market: 9mNq...
Outcome: NO
Tokens remaining: 1.05
Current value: 0.42 SOL
Payout if win: 1.05 SOL
Status: activeExample [4]
Full Demo Agent
End-to-end agent script: health check, list markets, create market, predict, check positions, resolve, and claim.
TypeScript
import { wrapFetch } from "@x402/fetch";
import { createSvmSigner } from "@x402/svm";
import { Keypair } from "@solana/web3.js";
const API = "https://api.oyrade.com";
async function runDemoAgent() {
const keypair = Keypair.fromSecretKey(/* your secret key */);
const signer = createSvmSigner(keypair);
const x402Fetch = wrapFetch(fetch, signer);
// 1. Health check (free)
console.log("=== Step 1: Health Check ===");
const healthRes = await fetch(`${API}/health`);
const { data: health } = await healthRes.json();
console.log("Status:", health.status);
console.log("Network:", health.network);
console.log("Version:", health.version);
console.log("Markets:", health.market_count);
// 2. List markets (free)
console.log("\n=== Step 2: List Markets ===");
const listRes = await fetch(`${API}/api/v1/markets`);
const { data: listData } = await listRes.json();
console.log(`Found ${listData.markets.length} markets`);
for (const m of listData.markets.slice(0, 3)) {
console.log(` ${m.question} — YES: ${m.yes_price} / NO: ${m.no_price}`);
}
// 3. Create market ($0.50)
console.log("\n=== Step 3: Create Market ===");
const createRes = await x402Fetch(`${API}/api/v1/markets/create`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
token_mint: "DfnxGQUsXdDH7DYdroeeSBG8etqTy1kufxBikHwTTGTa",
question: "Will SOL reach $500 by Q2 2026?",
market_name: "SOL 500 Q2 2026",
slug: "sol-500-q2-2026",
category: "crypto",
end_date: Math.floor(new Date("2026-06-30").getTime() / 1000),
}),
});
const { data: market } = await createRes.json();
console.log("Market ID:", market.market_id);
// 4. Place prediction ($0.01 + 3% of 0.5 SOL)
console.log("\n=== Step 4: Place Prediction ===");
const commitmentHash =
"a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2";
const predictRes = await x402Fetch(
`${API}/api/v1/markets/${market.market_id}/predict`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
outcome: "YES",
amount: 0.5,
commitment_hash: commitmentHash,
}),
}
);
const { data: prediction } = await predictRes.json();
console.log("Prediction ID:", prediction.prediction_id);
console.log("Tokens received:", prediction.tokens_received);
console.log("Effective price:", prediction.effective_price);
// 5. Check positions (free)
console.log("\n=== Step 5: Check Positions ===");
const posRes = await fetch(
`${API}/api/v1/positions?commitment_hash=${commitmentHash}`
);
const { data: posData } = await posRes.json();
for (const pos of posData.positions) {
console.log("Outcome:", pos.outcome);
console.log("Tokens:", pos.tokens_remaining);
console.log("Current value:", pos.current_value_sol, "SOL");
}
// 6. Resolve market ($0.05)
console.log("\n=== Step 6: Resolve Market ===");
const resolveRes = await x402Fetch(
`${API}/api/v1/markets/${market.market_id}/resolve`
);
const { data: resolution } = await resolveRes.json();
console.log("Resolved:", resolution.resolved);
if (resolution.resolved) {
console.log("Winner:", resolution.winning_outcome);
}
// 7. Claim winnings ($0.01)
console.log("\n=== Step 7: Claim Winnings ===");
const claimRes = await x402Fetch(
`${API}/api/v1/markets/${market.market_id}/claim`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
commitment_hash: commitmentHash,
payout_address: keypair.publicKey.toBase58(),
}),
}
);
const { data: claim } = await claimRes.json();
if (claim.claimable) {
console.log("Claimed:", claim.sol_received, "SOL");
} else {
console.log("Not claimable:", claim.reason);
}
console.log("\n=== Demo Complete ===");
console.log("Total x402 cost: ~$0.57");
console.log("(create $0.50 + predict ~$0.025 + resolve $0.05 + claim $0.01)");
}
runDemoAgent().catch(console.error);Expected Output
=== Step 1: Health Check ===
Status: ok
Network: devnet
Version: 0.1.0
Markets: 42
=== Step 2: List Markets ===
Found 42 markets
Will ETH reach $10K by June 2026? — YES: 0.62 / NO: 0.38
Will BTC hit $200K by 2027? — YES: 0.45 / NO: 0.55
Will SOL flip ETH market cap? — YES: 0.12 / NO: 0.88
=== Step 3: Create Market ===
Market ID: 9pLx...
=== Step 4: Place Prediction ===
Prediction ID: pred_01H...
Tokens received: 0.612
Effective price: 0.817
=== Step 5: Check Positions ===
Outcome: YES
Tokens: 0.612
Current value: 0.5 SOL
=== Step 6: Resolve Market ===
Resolved: false
=== Step 7: Claim Winnings ===
Not claimable: Market not yet resolved
=== Demo Complete ===
Total x402 cost: ~$0.57
(create $0.50 + predict ~$0.025 + resolve $0.05 + claim $0.01)Want to see the full API reference and types?
View API Reference