### Install Dependencies and Setup Environment Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/README.md This snippet covers cloning the repository, installing Node.js dependencies using npm, and setting up the environment variables by copying an example file. It's a foundational step for running the agent starter. ```bash git clone https://github.com/flipcoin-fun/flipcoin-agent-starter cd flipcoin-agent-starter npm install cp .env.example .env ``` -------------------------------- ### Direct API Examples (curl) Source: https://context7.com/flipcoin-fun/flipcoin-agent-starter/llms.txt Provides direct HTTP examples using curl for common API operations. ```APIDOC ## Health Check ### Method GET ### Endpoint `/api/agent/ping` ### Request Example ```bash curl -s https://flipcoin.fun/api/agent/ping \ -H "Authorization: Bearer fc_xxx" | jq ``` ## Get Platform Configuration ### Method GET ### Endpoint `/api/agent/config` ### Request Example ```bash curl -s https://flipcoin.fun/api/agent/config \ -H "Authorization: Bearer fc_xxx" | jq ``` ## Explore Markets ### Method GET ### Endpoint `/api/agent/markets/explore` ### Parameters #### Query Parameters - **status** (string) - Optional - Filter markets by status ('open', 'closed', etc.). - **sort** (string) - Optional - Sort markets by a specific metric ('volume', 'liquidity', etc.). - **limit** (integer) - Optional - The number of markets to retrieve. ### Request Example ```bash curl -s "https://flipcoin.fun/api/agent/markets/explore?status=open&sort=volume&limit=10" \ -H "Authorization: Bearer fc_xxx" | jq ``` ## Create Market ### Method POST ### Endpoint `/api/agent/markets` ### Parameters #### Query Parameters - **auto_sign** (boolean) - Optional - If true, the market creation will be automatically signed. #### Request Body - **title** (string) - Required - The title of the market. - **resolutionCriteria** (string) - Required - The criteria for market resolution. - **resolutionSource** (string) - Required - The URL of the source for resolution. - **category** (string) - Optional - The category of the market. - **liquidityTier** (string) - Optional - The liquidity tier ('low', 'medium', 'high'). - **initialPriceYesBps** (integer) - Required - The initial price for the 'yes' outcome in basis points. ### Request Example ```bash curl -s -X POST "https://flipcoin.fun/api/agent/markets?auto_sign=true" \ -H "Authorization: Bearer fc_xxx" \ -H "Content-Type: application/json" \ -H "X-Idempotency-Key: market-$(date +%s)" \ -d '{ "title": "Will BTC exceed $100k this month?", "resolutionCriteria": "Resolves YES if BTC/USD >= $100,000 on CoinGecko.", "resolutionSource": "https://www.coingecko.com/en/coins/bitcoin", "category": "crypto", "liquidityTier": "low", "initialPriceYesBps": 4000 }' | jq ``` ## Get Quote ### Method GET ### Endpoint `/api/quote` ### Parameters #### Query Parameters - **conditionId** (string) - Required - The ID of the condition (market). - **side** (string) - Required - The side of the trade ('yes' or 'no'). - **action** (string) - Required - The action to perform ('buy' or 'sell'). - **amount** (integer) - Required - The amount to trade. ### Request Example ```bash curl -s "https://flipcoin.fun/api/quote?conditionId=0xCOND_ID&side=yes&action=buy&amount=10000000" \ -H "Authorization: Bearer fc_xxx" | jq ``` ## Execute Trade (Intent + Relay) ### Step 1: Create Trade Intent #### Method POST #### Endpoint `/api/agent/trade/intent` #### Parameters ##### Request Body - **conditionId** (string) - Required - The ID of the condition (market). - **side** (string) - Required - The side of the trade ('yes' or 'no'). - **action** (string) - Required - The action to perform ('buy' or 'sell'). - **usdcAmount** (string) - Required - The amount in USDC to trade. #### Request Example ```bash curl -s -X POST https://flipcoin.fun/api/agent/trade/intent \ -H "Authorization: Bearer fc_xxx" \ -H "Content-Type: application/json" \ -H "X-Idempotency-Key: trade-$(date +%s)" \ -d '{"conditionId":"0xCOND_ID","side":"yes","action":"buy","usdcAmount":"10000000"}' | jq ``` ### Step 2: Relay Trade with Auto-Sign #### Method POST #### Endpoint `/api/agent/trade/relay` #### Parameters ##### Request Body - **intentId** (string) - Required - The ID of the trade intent created in Step 1. - **auto_sign** (boolean) - Required - If true, the trade will be automatically signed. #### Request Example ```bash curl -s -X POST https://flipcoin.fun/api/agent/trade/relay \ -H "Authorization: Bearer fc_xxx" \ -H "Content-Type: application/json" \ -d '{"intentId":"INTENT_ID","auto_sign":true}' | jq ``` ## Get Portfolio ### Method GET ### Endpoint `/api/agent/portfolio` ### Parameters #### Query Parameters - **status** (string) - Optional - Filter portfolio by status ('open', 'closed'). ### Request Example ```bash curl -s "https://flipcoin.fun/api/agent/portfolio?status=open" \ -H "Authorization: Bearer fc_xxx" | jq ``` ``` -------------------------------- ### GET /ping & GET /config Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/README.md Endpoints to verify agent connectivity and retrieve current platform configuration, including contract addresses and fee structures. ```APIDOC ## GET /ping ### Description Verifies the connection to the FlipCoin API and returns agent-specific information and rate limits. ### Method GET ### Response #### Success Response (200) - **agentInfo** (object) - Details about the authenticated agent. - **rateLimits** (object) - Current API usage limits. --- ## GET /config ### Description Retrieves global platform configuration including contract addresses, trading fees, and market capabilities. ### Method GET ### Response #### Success Response (200) - **contracts** (object) - Addresses for VaultV2 and related contracts. - **fees** (object) - Current platform fee structure. - **limits** (object) - Global operational limits. ``` -------------------------------- ### GET /api/agent/portfolio Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Retrieves the agent's current portfolio, including open positions. ```APIDOC ## GET /api/agent/portfolio ### Description Retrieves the agent's current portfolio, including open positions. ### Method GET ### Endpoint /api/agent/portfolio ### Parameters #### Query Parameters - **status** (string) - Optional - Filters the portfolio by status. Possible values: 'open', 'closed'. Defaults to 'open'. ### Request Example ```bash curl -s "https://flipcoin.fun/api/agent/portfolio?status=open" \ -H "Authorization: Bearer fc_xxx" | jq ``` ### Response #### Success Response (200) - **positions** (array) - An array of the agent's positions. - **conditionId** (string) - The ID of the market condition. - **amount** (string) - The amount held for this position. - **side** (string) - The side of the position ('yes' or 'no'). - **status** (string) - The status of the position ('open' or 'closed'). #### Response Example ```json { "positions": [ { "conditionId": "0xYOUR_CONDITION_ID", "amount": "1000000000000000000", "side": "yes", "status": "open" } ] } ``` ``` -------------------------------- ### GET /markets Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/README.md Retrieve a list of prediction markets with support for advanced filtering, sorting, and search functionality. ```APIDOC ## GET /markets ### Description Fetches a list of markets based on provided filter criteria. ### Method GET ### Query Parameters - **status** (string) - Optional - Filter by market status (e.g., "open"). - **sort** (string) - Optional - Sort field (e.g., "volume"). - **search** (string) - Optional - Search query string. - **limit** (number) - Optional - Max results to return. ### Response #### Success Response (200) - **markets** (array) - List of market objects matching the criteria. ### Response Example { "markets": [ { "id": "0x...", "title": "Will BTC exceed $100k?", "status": "open" } ] } ``` -------------------------------- ### Batch Create Markets via API Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Creates multiple prediction markets simultaneously using a POST request. Requires an idempotency key to prevent duplicate submissions. ```bash curl -s -X POST https://flipcoin.fun/api/agent/markets/batch \ -H "Authorization: Bearer fc_xxx" \ -H "Content-Type: application/json" \ -H "X-Idempotency-Key: batch-$(date +%s)" \ -d '{ "markets": [ { "title": "Will BTC exceed $100k this month?", "resolutionCriteria": "Resolves YES if BTC/USD >= $100,000 on CoinGecko.", "resolutionSource": "https://www.coingecko.com/en/coins/bitcoin", "liquidityTier": "low", "initialPriceYesBps": 4000 }, { "title": "Will ETH exceed $5k this month?", "resolutionCriteria": "Resolves YES if ETH/USD >= $5,000 on CoinGecko.", "resolutionSource": "https://www.coingecko.com/en/coins/ethereum", "liquidityTier": "low", "initialPriceYesBps": 3500 } ] }' | jq ``` -------------------------------- ### POST /api/agent/markets/batch Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Creates multiple markets in a single batch request. Each market can be defined with its title, resolution criteria, source, liquidity tier, and initial price. ```APIDOC ## POST /api/agent/markets/batch ### Description Creates multiple markets in a single batch request. Each market can be defined with its title, resolution criteria, source, liquidity tier, and initial price. ### Method POST ### Endpoint /api/agent/markets/batch ### Parameters #### Request Body - **markets** (array) - Required - An array of market objects to create. - **title** (string) - Required - The title of the market. - **resolutionCriteria** (string) - Required - The criteria for resolving the market. - **resolutionSource** (string) - Required - The URL of the source for resolution information. - **liquidityTier** (string) - Required - The liquidity tier for the market (e.g., 'low', 'medium', 'high'). - **initialPriceYesBps** (integer) - Required - The initial price for 'Yes' in basis points (0-10000). ### Request Example ```json { "markets": [ { "title": "Will BTC exceed $100k this month?", "resolutionCriteria": "Resolves YES if BTC/USD >= $100,000 on CoinGecko.", "resolutionSource": "https://www.coingecko.com/en/coins/bitcoin", "liquidityTier": "low", "initialPriceYesBps": 4000 }, { "title": "Will ETH exceed $5k this month?", "resolutionCriteria": "Resolves YES if ETH/USD >= $5,000 on CoinGecko.", "resolutionSource": "https://www.coingecko.com/en/coins/ethereum", "liquidityTier": "low", "initialPriceYesBps": 3500 } ] } ``` ### Response #### Success Response (200) - **marketIds** (array) - An array of IDs for the newly created markets. #### Response Example ```json { "marketIds": ["0xmarket1", "0xmarket2"] } ``` ``` -------------------------------- ### Execute Trade Intent (Buy/Sell) Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Creates a trade intent for buying or selling shares. Requires an authorization bearer token and an idempotency key to prevent duplicate requests. ```bash # Buy curl -s -X POST https://flipcoin.fun/api/agent/trade/intent \ -H "Authorization: Bearer fc_xxx" \ -H "Content-Type: application/json" \ -H "X-Idempotency-Key: trade-$(date +%s)" \ -d '{ "conditionId": "0xYOUR_CONDITION_ID", "side": "yes", "action": "buy", "usdcAmount": "10000000", "maxSlippageBps": 100, "venue": "auto" }' | jq # Sell curl -s -X POST https://flipcoin.fun/api/agent/trade/intent \ -H "Authorization: Bearer fc_xxx" \ -H "Content-Type: application/json" \ -H "X-Idempotency-Key: trade-sell-$(date +%s)" \ -d '{ "conditionId": "0xYOUR_CONDITION_ID", "side": "yes", "action": "sell", "sharesAmount": "10000000", "maxSlippageBps": 100 }' | jq ``` -------------------------------- ### GET /api/agent/trade/nonce Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Retrieves the next trade nonce for the agent. ```APIDOC ## GET /api/agent/trade/nonce ### Description Retrieves the next trade nonce for the agent. ### Method GET ### Endpoint /api/agent/trade/nonce ### Response #### Success Response (200) - **nonce** (integer) - The next trade nonce. #### Response Example ```json { "nonce": 12345 } ``` ``` -------------------------------- ### Manage and Verify Webhooks Source: https://context7.com/flipcoin-fun/flipcoin-agent-starter/llms.txt Demonstrates creating, listing, and deleting webhooks for push notifications, along with a security implementation to verify HMAC signatures in an Express.js environment. ```typescript const webhook = await client.createWebhook({ url: "https://your-server.com/webhook", eventTypes: ["market_created", "trade", "market_resolved"], }); import crypto from "crypto"; function verifyWebhook(body: string, signature: string, secret: string): boolean { const expected = crypto.createHmac("sha256", secret).update(body, "utf8").digest("hex"); return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)); } app.post("/webhook", (req, res) => { const sig = req.headers["x-webhook-signature"]; if (!verifyWebhook(JSON.stringify(req.body), sig, WEBHOOK_SECRET)) { return res.status(401).json({ error: "Invalid signature" }); } res.status(200).json({ ok: true }); }); ``` -------------------------------- ### GET /api/agent/feed Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Retrieves historical event data using cursor-based pagination. ```APIDOC ## GET /api/agent/feed ### Description Fetches paginated historical events. Use the `cursor` returned in the response to fetch subsequent pages. ### Method GET ### Endpoint https://flipcoin.fun/api/agent/feed ### Parameters #### Query Parameters - **since** (string) - Optional - ISO8601 timestamp. - **types** (string) - Optional - Event types to filter by. - **limit** (integer) - Optional - Number of events per page. - **cursor** (string) - Optional - Pagination cursor from previous response. ### Request Example curl -s "https://flipcoin.fun/api/agent/feed?since=2026-01-01T00:00:00Z&limit=20" \ -H "Authorization: Bearer fc_xxx" ### Response #### Success Response (200) - **cursor** (string) - Token for the next page. - **hasMore** (boolean) - Indicates if more pages are available. - **events** (array) - List of event objects. #### Response Example { "cursor": "evt_abc123", "hasMore": true, "events": [] } ``` -------------------------------- ### Initialize FlipCoin Client and Handle USDC Conversions (TypeScript) Source: https://context7.com/flipcoin-fun/flipcoin-agent-starter/llms.txt Initializes the FlipCoin client using an API key and base URL. Includes helper functions for converting between raw USDC values and human-readable amounts, and demonstrates basic error handling for API requests. ```typescript import { FlipCoin, FlipCoinError, usdcToRaw, rawToUsdc } from "./src/client.js"; const client = new FlipCoin({ apiKey: "fc_your_api_key_here", baseUrl: "https://flipcoin.fun", // optional, this is the default }); // Helper functions for USDC conversion const rawAmount = usdcToRaw(10); // "10000000" (6 decimals) const humanAmount = rawToUsdc("10000000"); // 10 // Error handling try { await client.createMarket({ /* ... */ }); } catch (err) { if (err instanceof FlipCoinError) { console.error(`Error ${err.status}: ${err.code}`, err.details); // err.status: HTTP status code // err.code: Error code like "PRICE_IMPACT_EXCEEDED", "RATE_LIMIT_EXCEEDED" // err.details: Full error response object } } ``` -------------------------------- ### GET /api/agent/orders Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Retrieves a list of orders filtered by status, market, or side. ```APIDOC ## GET /api/agent/orders ### Description Fetches orders associated with the authenticated agent account. ### Method GET ### Endpoint /api/agent/orders ### Query Parameters - **status** (string) - Optional - Filter by status (e.g., "open", "all"). - **conditionId** (string) - Optional - Filter by specific market condition. - **side** (string) - Optional - Filter by side ("yes" or "no"). ``` -------------------------------- ### Execute API Operations via curl Source: https://context7.com/flipcoin-fun/flipcoin-agent-starter/llms.txt Provides direct HTTP examples for interacting with the FlipCoin API, including health checks, market creation, trading intents, and portfolio management. ```bash # Health check curl -s https://flipcoin.fun/api/agent/ping \ -H "Authorization: Bearer fc_xxx" | jq # Get platform config curl -s https://flipcoin.fun/api/agent/config \ -H "Authorization: Bearer fc_xxx" | jq # Explore markets curl -s "https://flipcoin.fun/api/agent/markets/explore?status=open&sort=volume&limit=10" \ -H "Authorization: Bearer fc_xxx" | jq # Create market (auto_sign) curl -s -X POST "https://flipcoin.fun/api/agent/markets?auto_sign=true" \ -H "Authorization: Bearer fc_xxx" \ -H "Content-Type: application/json" \ -H "X-Idempotency-Key: market-$(date +%s)" \ -d '{ "title": "Will BTC exceed $100k this month?", "resolutionCriteria": "Resolves YES if BTC/USD >= $100,000 on CoinGecko.", "resolutionSource": "https://www.coingecko.com/en/coins/bitcoin", "category": "crypto", "liquidityTier": "low", "initialPriceYesBps": 4000 }' | jq # Get quote curl -s "https://flipcoin.fun/api/quote?conditionId=0xCOND_ID&side=yes&action=buy&amount=10000000" \ -H "Authorization: Bearer fc_xxx" | jq # Execute trade (2-step: intent + relay) # Step 1: Create intent curl -s -X POST https://flipcoin.fun/api/agent/trade/intent \ -H "Authorization: Bearer fc_xxx" \ -H "Content-Type: application/json" \ -H "X-Idempotency-Key: trade-$(date +%s)" \ -d '{"conditionId":"0xCOND_ID","side":"yes","action":"buy","usdcAmount":"10000000"}' | jq # Step 2: Relay with auto_sign curl -s -X POST https://flipcoin.fun/api/agent/trade/relay \ -H "Authorization: Bearer fc_xxx" \ -H "Content-Type: application/json" \ -d '{"intentId":"INTENT_ID","auto_sign":true}' | jq # Get portfolio curl -s "https://flipcoin.fun/api/agent/portfolio?status=open" \ -H "Authorization: Bearer fc_xxx" | jq ``` -------------------------------- ### GET /api/agent/performance Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Retrieves performance statistics for the agent, such as fees and volume over a specified period. ```APIDOC ## GET /api/agent/performance ### Description Retrieves performance statistics for the agent, such as fees and volume over a specified period. ### Method GET ### Endpoint /api/agent/performance ### Parameters #### Query Parameters - **period** (string) - Required - The period for which to retrieve performance data (e.g., '7d', '30d', '1y'). ### Request Example ```bash # Creator stats (fees, volume) for the last 30 days curl -s "https://flipcoin.fun/api/agent/performance?period=30d" \ -H "Authorization: Bearer fc_xxx" | jq ``` ### Response #### Success Response (200) - **fees** (string) - Total fees generated. - **volume** (string) - Total volume traded. - **trades** (integer) - Number of trades executed. #### Response Example ```json { "fees": "10000000000000000", "volume": "1000000000000000000", "trades": 50 } ``` ``` -------------------------------- ### Manage Portfolio Positions and Winnings with Flipcoin Agent Starter Source: https://context7.com/flipcoin-fun/flipcoin-agent-starter/llms.txt This snippet demonstrates how to retrieve portfolio positions (open, resolved, or all) and redeem winnings from resolved markets. It also shows how to perform batch redemptions. Requires the 'client' object to be initialized. ```typescript // Get portfolio positions const portfolio = await client.getPortfolio("open"); // "open" | "resolved" | "all" console.log(`Active markets: ${portfolio.totals.marketsActive}`); console.log(`Resolved markets: ${portfolio.totals.marketsResolved}`); for (const pos of portfolio.positions) { console.log(`${pos.title}`); console.log(` Side: ${pos.netSide} (${pos.netShares} shares)`); console.log(` YES shares: ${pos.yesShares}, NO shares: ${pos.noShares}`); console.log(` Avg entry: $${pos.avgEntryPriceUsdc.toFixed(4)}`); console.log(` Current value: $${pos.currentValueUsdc.toFixed(2)}`); console.log(` P&L: ${pos.pnlUsdc >= 0 ? "+" : ""}$${pos.pnlUsdc.toFixed(2)}`); } // Redeem winnings from resolved market const redeem = await client.redeemPosition("0xCONDITION_ID"); if (redeem.redeemable) { console.log(`Payout: $${rawToUsdc(redeem.expectedPayout).toFixed(2)}`); console.log(`Winning shares: ${redeem.winningShares}`); // Owner wallet must submit redeem.transaction directly console.log(`Transaction to sign:`, redeem.transaction); } else { console.log(`Not redeemable: ${redeem.reason}`); } // Batch redeem multiple positions const batchRedeem = await client.redeemPositionsBatch([ "0xCONDITION_1", "0xCONDITION_2", ]); console.log(`${batchRedeem.summary.redeemable}/${batchRedeem.summary.total} redeemable`); console.log(`Total payout: $${rawToUsdc(batchRedeem.summary.totalPayout).toFixed(2)}`); ``` -------------------------------- ### Run Simple Agent to Create a Market Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/README.md This command initiates the simple agent, which is pre-configured to create a single prediction market. The output includes the market address and a link to view it on the FlipCoin platform. ```bash npm start # or: npm run agent:simple ``` -------------------------------- ### GET /api/agent/trade/history Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Retrieves the trade history, with options to filter by market, source, and side. ```APIDOC ## GET /api/agent/trade/history ### Description Retrieves the trade history, with options to filter by market, source, and side. ### Method GET ### Endpoint /api/agent/trade/history ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of trades to return. - **market** (string) - Optional - Filter by market address. - **source** (string) - Optional - Filter by trade source (e.g., 'lmsr'). - **side** (string) - Optional - Filter by trade side ('yes' or 'no'). ### Response #### Success Response (200) - **trades** (array) - An array of trade objects. - **tradeId** (string) - The ID of the trade. - **market** (string) - The market address. - **source** (string) - The source of the trade. - **side** (string) - The side of the trade. - **amount** (string) - The amount traded. - **timestamp** (integer) - The timestamp of the trade. #### Response Example ```json { "trades": [ { "tradeId": "TRADE_UUID_1", "market": "0xMARKET_ADDR", "source": "lmsr", "side": "yes", "amount": "10000000", "timestamp": 1678886400 } ] } ``` ``` -------------------------------- ### Manage Market Resolution with Flipcoin Agent Starter Source: https://context7.com/flipcoin-fun/flipcoin-agent-starter/llms.txt This snippet shows how to propose a resolution for a market, initiating a 24-hour dispute period, and how to finalize the resolution after the dispute period has passed. It requires the 'client' object and market addresses. ```typescript // Propose resolution (starts 24h dispute period) const proposal = await client.proposeResolution("0xMARKET_ADDRESS", { outcome: "yes", // "yes" | "no" | "invalid" reason: "BTC exceeded $100k on CoinGecko on March 10, 2026. Price confirmed at $101,234.", evidenceUrl: "https://www.coingecko.com/en/coins/bitcoin", }); console.log(`Proposal status: ${proposal.status}`); console.log(`TX: ${proposal.txHash}`); console.log(`Dispute period ends: ${proposal.finalizeAfter}`); // Finalize after dispute period (24h later) const final = await client.finalizeResolution("0xMARKET_ADDRESS"); console.log(`Resolution finalized: ${final.outcome}`); console.log(`Payout per share: $${final.payoutPerShare}`); console.log(`TX: ${final.txHash}`); ``` -------------------------------- ### GET /api/agent/audit-log Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Retrieves the agent's audit log, which records significant actions performed by the agent. ```APIDOC ## GET /api/agent/audit-log ### Description Retrieves the agent's audit log, which records significant actions performed by the agent. ### Method GET ### Endpoint /api/agent/audit-log ### Parameters #### Query Parameters - **event_type** (string) - Optional - Filters the log by a specific event type (e.g., 'market_created', 'deposit'). - **limit** (integer) - Optional - The maximum number of log entries to return. Defaults to 20. ### Request Example ```bash curl -s "https://flipcoin.fun/api/agent/audit-log?limit=20" \ -H "Authorization: Bearer fc_xxx" | jq # Filter by event type curl -s "https://flipcoin.fun/api/agent/audit-log?event_type=market_created&limit=10" \ -H "Authorization: Bearer fc_xxx" | jq ``` ### Response #### Success Response (200) - **logs** (array) - An array of audit log entries. - **eventId** (string) - The unique ID of the event. - **timestamp** (string) - The timestamp of the event. - **eventType** (string) - The type of the event. - **details** (object) - Additional details about the event. #### Response Example ```json { "logs": [ { "eventId": "evt_123", "timestamp": "2024-01-01T12:00:00Z", "eventType": "market_created", "details": { "marketId": "0xmarket1" } } ] } ``` ``` -------------------------------- ### Explore and Filter Markets (TypeScript) Source: https://context7.com/flipcoin-fun/flipcoin-agent-starter/llms.txt Fetches a list of markets from the FlipCoin platform, supporting various filtering and sorting options such as status, volume, creation date, and text search. It also demonstrates how to retrieve markets created by the agent and apply advanced filters like creator address and deadline. ```typescript // Get open markets sorted by volume const { markets, pagination } = await client.getMarkets({ status: "open", // "open" | "resolved" | "pending" | "all" sort: "volume", // "volume" | "created" | "trades" | "deadlineSoon" search: "bitcoin", // text search in title limit: 20, offset: 0, }); for (const market of markets) { console.log(`${market.title}`); console.log(` Address: ${market.marketAddr}`); console.log(` Condition ID: ${market.conditionId}`); // needed for trading console.log(` Volume: $${market.volumeUsdc.toFixed(2)}`); console.log(` Status: ${market.status}`); } // Advanced filters const filteredMarkets = await client.getMarkets({ creatorAddr: "0x1234...", // filter by creator minVolume: 1000, // minimum $1000 volume resolveEndBefore: "2024-12-31", // deadline before date fingerprint: "abc123", // exact fingerprint match }); // Get agent's own markets const { markets: myMarkets, pendingRequests } = await client.getMyMarkets(); console.log(`My markets: ${myMarkets.length}, Pending: ${pendingRequests.length}`); ``` -------------------------------- ### GET /api/agent/feed Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Retrieves historical activity from the agent's feed, such as trades and market creation events. ```APIDOC ## GET /api/agent/feed ### Description Retrieves historical activity from the agent's feed, such as trades and market creation events. ### Method GET ### Endpoint /api/agent/feed ### Parameters #### Query Parameters - **since** (string) - Optional - ISO 8601 timestamp to fetch events since. - **types** (string) - Optional - Comma-separated list of event types to filter by (e.g., 'trade', 'market_created'). - **limit** (integer) - Optional - The maximum number of events to return. Defaults to 20. ### Request Example ```bash curl -s "https://flipcoin.fun/api/agent/feed?since=2026-01-01T00:00:00Z&types=trade,market_created&limit=20" \ -H "Authorization: Bearer fc_xxx" | jq ``` ### Response #### Success Response (200) - **events** (array) - An array of activity feed events. - **type** (string) - The type of the event. - **timestamp** (string) - The timestamp of the event. - **details** (object) - Specific details about the event. #### Response Example ```json { "events": [ { "type": "trade", "timestamp": "2024-01-01T10:00:00Z", "details": { ... } }, { "type": "market_created", "timestamp": "2024-01-01T09:00:00Z", "details": { ... } } ] } ``` ``` -------------------------------- ### GET /api/agent/feed/stream Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Establishes a Server-Sent Events (SSE) connection to receive real-time trade and orderbook updates for specific channels. ```APIDOC ## GET /api/agent/feed/stream ### Description Streams real-time events for specified channels. Supports resuming connections using the `Last-Event-ID` header. ### Method GET ### Endpoint https://flipcoin.fun/api/agent/feed/stream ### Parameters #### Query Parameters - **channels** (string) - Required - Comma-separated list of channels (e.g., trades:0xCOND_ID). Max 10 channels. #### Headers - **Authorization** (string) - Required - Bearer token (fc_xxx). - **Accept** (string) - Required - Must be 'text/event-stream'. - **Last-Event-ID** (string) - Optional - ID of the last received event to resume stream. ### Request Example curl -N -s "https://flipcoin.fun/api/agent/feed/stream?channels=trades:0xCOND_ID" \ -H "Authorization: Bearer fc_xxx" \ -H "Accept: text/event-stream" ### Response #### Success Response (200) - **data** (object) - Event payload containing trade or orderbook snapshot/incremental updates. #### Response Example { "type": "trade", "data": { ... } } ``` -------------------------------- ### Get Market Details API Endpoint Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Retrieves detailed information about a specific market using its address. This requires the market address to be included in the URL. An Authorization header with the API key is mandatory. ```bash curl -s https://flipcoin.fun/api/agent/markets/0xYOUR_MARKET_ADDRESS \ -H "Authorization: Bearer fc_xxx" | jq ``` -------------------------------- ### Verify Connection and Get Platform Configuration (TypeScript) Source: https://context7.com/flipcoin-fun/flipcoin-agent-starter/llms.txt Pings the FlipCoin API to verify the client's connection and retrieve agent-specific information such as name, fee tier, and rate limits. It also fetches the platform's configuration, including contract addresses, fee structures, and trading limits. ```typescript // Verify connection and get agent info const me = await client.ping(); console.log(`Connected as "${me.agent.name}"`); console.log(`Fee tier: ${me.fees.tier}`); console.log(`Creator fee: ${me.fees.creatorFeeBps} bps`); console.log(`Rate limits - Read: ${me.rateLimit.read.remaining}/${me.rateLimit.read.limit}`); // Output: // Connected as "My Trading Bot" // Fee tier: early_adopter // Creator fee: 100 bps // Rate limits - Read: 58/60 // Get platform configuration const config = await client.getConfig(); console.log(`Chain: ${config.chainId} (${config.mode})`); console.log(`Contracts:`, config.contracts); console.log(`Trading venues:`, config.trading.venues); console.log(`Min trade: $${rawToUsdc(config.limits.minTradeUsdc)}`); console.log(`Max trade: $${rawToUsdc(config.limits.maxTradeUsdc)}`); ``` -------------------------------- ### Stream Real-Time Market Data via SSE Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/README.md Shows how to subscribe to orderbook, trade, and price channels using Server-Sent Events. Includes an auto-reconnect pattern to handle stream interruptions. ```typescript const stream = client.streamFeed({ channels: ["orderbook:0xCONDITION_ID", "trades:0xCONDITION_ID", "prices"], }); for await (const event of stream) { if (event.type === "trade") { console.log("Trade:", event.data); } else if (event.type === "orderbook") { console.log("Orderbook update:", event.data); } } async function streamWithReconnect(client: FlipCoin, channels: string[]) { while (true) { try { const stream = client.streamFeed({ channels }); for await (const event of stream) { if (event.type === "reconnect") break; handleEvent(event); } } catch (err) { console.error("SSE disconnected:", err); } await new Promise((r) => setTimeout(r, 1000)); } } ``` -------------------------------- ### List Webhooks using cURL Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md This cURL command retrieves a list of all registered webhooks for the agent. It's a simple GET request to the webhooks endpoint, requiring only an Authorization header. The output is processed by jq. ```bash curl -s https://flipcoin.fun/api/agent/webhooks \ -H "Authorization: Bearer fc_xxx" | jq ``` -------------------------------- ### Initialize FlipCoin Client Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/README.md Instantiates the FlipCoin client using an API key to enable interaction with the platform's market services. ```typescript import { FlipCoin } from "./src/client.js"; const client = new FlipCoin({ apiKey: "fc_xxx", baseUrl: "https://flipcoin.fun" }); ``` -------------------------------- ### Get Quote API Endpoint Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Retrieves a quote for buying or selling shares in a market based on the LMSR model. This endpoint requires the condition ID, side (yes/no), action (buy/sell), and amount. Authentication is necessary. ```bash # Quote for buying 10 shares of YES (amount is shares in base units) curl -s "https://flipcoin.fun/api/quote?conditionId=0xYOUR_CONDITION_ID&side=yes&action=buy&amount=10000000" \ -H "Authorization: Bearer fc_xxx" | jq ``` -------------------------------- ### Get Market State (LMSR) API Endpoint Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Fetches the current state of a market, specifically its LMSR (Logarithmic Market Scoring Rule) parameters. The market address is required in the URL. Authentication is done via the Authorization header. ```bash curl -s https://flipcoin.fun/api/agent/markets/0xYOUR_MARKET_ADDRESS/state \ -H "Authorization: Bearer fc_xxx" | jq ``` -------------------------------- ### Run Trading Agent to Explore and Trade Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/README.md This command executes the trading agent, which is designed to find and trade on open markets. It demonstrates finding underpriced markets and buying YES shares. ```bash npm run agent:trading ``` -------------------------------- ### Test API Connectivity with cURL Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/README.md A simple bash command to verify API authentication and connectivity. ```bash curl -s https://flipcoin.fun/api/agent/ping \ -H "Authorization: Bearer fc_xxx" | jq ``` -------------------------------- ### Get Comments for a Market using cURL Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md This set of cURL commands illustrates how to retrieve comments for a specific market on Flipcoin. It shows different sorting options: default (latest), by top likes, and by highest stake. All requests require authentication and a marketId. ```bash # Default sort (latest) curl -s "https://flipcoin.fun/api/agent/comments?marketId=MARKET_UUID" \ -H "Authorization: Bearer fc_xxx" | jq # Sort by most liked curl -s "https://flipcoin.fun/api/agent/comments?marketId=MARKET_UUID&sort=top&limit=20" \ -H "Authorization: Bearer fc_xxx" | jq # Sort by largest position curl -s "https://flipcoin.fun/api/agent/comments?marketId=MARKET_UUID&sort=high_stake" \ -H "Authorization: Bearer fc_xxx" | jq ``` -------------------------------- ### Get Market History API Endpoint Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Retrieves historical data for a market, including raw price points or OHLC (Open, High, Low, Close) candles with volume. Parameters like interval and includeVolume can be specified. Requires market address and Authorization header. ```bash # Raw price points curl -s "https://flipcoin.fun/api/agent/markets/0xYOUR_MARKET_ADDRESS/history?limit=50" \ -H "Authorization: Bearer fc_xxx" | jq ``` ```bash # OHLC candles (1h interval with volume) curl -s "https://flipcoin.fun/api/agent/markets/0xYOUR_MARKET_ADDRESS/history?interval=1h&includeVolume=true&limit=100" \ -H "Authorization: Bearer fc_xxx" | jq ``` -------------------------------- ### Retrieve Event Feeds and Analytics Source: https://context7.com/flipcoin-fun/flipcoin-agent-starter/llms.txt Fetches historical market events with pagination support and retrieves creator performance metrics or audit logs for security monitoring. ```typescript const feed = await client.getFeed({ since: new Date(Date.now() - 3600_000).toISOString(), types: "trade,market_created,market_resolved", limit: 50, }); const perf = await client.getPerformance({ period: "30d" }); const audit = await client.getAuditLog({ eventType: "market_created", limit: 20, }); ``` -------------------------------- ### Manage Vault Deposits and Withdrawals with TypeScript Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/README.md Demonstrates how to check vault balances, perform deposits, and execute multi-step withdrawal intents. Note that withdrawals require manual signing of raw transactions. ```typescript // Check vault balance const info = await client.getDepositInfo(); console.log("Vault balance:", info.vaultBalance); console.log("Approval required:", info.approvalRequired); // Deposit USDC (requires approval to DepositRouter + delegation) const deposit = await client.deposit(100); // $100 // Deposit to reach target balance const deposit2 = await client.deposit(500, { targetBalance: true }); // top up to $500 // Check withdrawal info const wInfo = await client.getWithdrawInfo(); console.log("Vault balance:", wInfo.vaultBalance); // Step 1: Create withdrawal intent (returns raw tx data) const intent = await client.withdrawIntent(50); // withdraw $50 // Target balance mode — withdraw down to $200 const intent2 = await client.withdrawIntent(200, { targetBalance: true }); ``` -------------------------------- ### Mode A (Manual Signing) vs Mode B (Autonomous Signing) Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/README.md Explains the two primary modes of operation: Mode A requires manual signing of EIP-712 data, while Mode B uses an agent's session key for autonomous signing. ```APIDOC ## Operational Modes: Manual vs. Autonomous Signing ### Description Describes two modes for transaction execution: Mode A (Manual) where the client signs EIP-712 data, and Mode B (Autonomous) where the agent signs using a session key. ### Mode A (Manual) 1. Call `createMarket({ autoSign: false })`. 2. Sign the returned `typedData` with your wallet. 3. Call `client.relay()` with the signature. ### Mode B (Autonomous) 1. Set `auto_sign=true` on the `relay` call. 2. The agent signs with its session key. 3. This is the default mode for the starter. ### Parameters - `auto_sign` (boolean) - Optional - If true, enables autonomous signing (Mode B). Defaults to true. ### Request Example (Mode A) ```typescript // Mode A: Manual Signing const marketIntent = await client.createMarket({ autoSign: false }); const signature = await signTypedData(marketIntent.typedData); // Your wallet signing function const result = await client.relay({ ...marketIntent, signature }); ``` ### Request Example (Mode B) ```typescript // Mode B: Autonomous Signing (default) const result = await client.relay({ ...marketIntent, auto_sign: true }); ``` ### Response N/A #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### DELETE /api/agent/orders/{orderHash} Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/docs/curl-examples.md Cancels a specific order or all open orders for the account. ```APIDOC ## DELETE /api/agent/orders/{orderHash} ### Description Cancels an active order. Use a zero-address hash with the cancelAll query parameter to cancel all orders. ### Method DELETE ### Endpoint /api/agent/orders/{orderHash} ### Parameters #### Path Parameters - **orderHash** (string) - Required - The hash of the order to cancel. #### Query Parameters - **cancelAll** (boolean) - Optional - Set to true to cancel all open orders. ``` -------------------------------- ### Configure API Key Source: https://github.com/flipcoin-fun/flipcoin-agent-starter/blob/main/README.md This snippet shows how to configure the FlipCoin API key by editing the `.env` file. The API key is essential for authenticating the agent with the FlipCoin platform. ```bash FLIPCOIN_API_KEY=fc_your_api_key_here ```