### Run Flash MCP Setup Wizard Source: https://flash.definitive.fi/docs/flash-mcp Command to launch the interactive setup wizard for API keys and wallet configuration. ```bash npx -y @definitive-fi/flash-mcp setup ``` -------------------------------- ### WebSocket Integration Example Source: https://flash.definitive.fi/docs/api-reference/flash/websocket A TypeScript reference implementation demonstrating connection management, subscription, and message handling. ```ts const WS_URL = "wss://flash.definitive.fi/v1/ws"; const API_KEY = "dpka_…"; // read-scoped Flash key const FUNDER = "0x…"; const orders = new Map(); // orderId -> FlashOrderUpdate const OPEN = new Set([ "ORDER_STATUS_PENDING", "ORDER_STATUS_ACCEPTED", "ORDER_STATUS_PARTIALLY_FILLED", ]); let attempts = 0; // grows on each failed reconnect, resets on a good connection function connect() { const ws = new WebSocket(WS_URL); let stop = false; // set on a terminal error so we don't reconnect ws.onopen = () => { attempts = 0; ws.send(JSON.stringify({ channel: "orders", type: "subscribe", funderAddress: FUNDER, apiKey: API_KEY })); ws.send(JSON.stringify({ channel: "heartbeats", type: "subscribe", apiKey: API_KEY })); // keeps the socket alive }; ws.onmessage = (e) => { const f = JSON.parse(e.data); if (f.type === "snapshot") { orders.clear(); for (const o of f.orders) orders.set(o.orderId, o); render(orders); } else if (f.type === "update") { for (const o of f.orders) { if (OPEN.has(o.status)) orders.set(o.orderId, o); // replace by orderId else orders.delete(o.orderId); // drop terminal orders } render(orders); } else if (f.type === "error") { console.warn("[flash-ws]", f.code, f.message); if (f.code === "UNAUTHORIZED") { stop = true; ws.close(); } // bad key: fix it, don't retry // other errors leave the socket open; fall back to GET /orders if the stream stays down } // heartbeat and ack frames need no action }; ws.onclose = () => { if (stop) return; const backoff = Math.min(30_000, 1_000 * 2 ** attempts++); setTimeout(connect, backoff / 2 + Math.random() * (backoff / 2)); // equal jitter; re-subscribes on reopen }; } ``` -------------------------------- ### Install and Configure Flash MCP for Codex Source: https://flash.definitive.fi/docs/flash-mcp Commands and configuration for adding the Flash MCP server to Codex. ```bash codex mcp add definitive-flash -- npx -y @definitive-fi/flash-mcp ``` ```toml [mcp_servers.definitive-flash] command = "npx" args = ["-y", "@definitive-fi/flash-mcp"] ``` -------------------------------- ### Execute Stop-Loss Trigger Order on Solana Source: https://flash.definitive.fi/docs/trigger-orders Demonstrates the full flow of creating a stop-loss order, handling ATA setup, managing delegation, and signing the final order message. ```typescript async function sendIxs(instructions: any[]) { const { blockhash } = await connection.getLatestBlockhash(); const message = new TransactionMessage({ payerKey: funder.publicKey, recentBlockhash: blockhash, instructions: instructions.map(toIx), }).compileToV0Message(); const tx = new VersionedTransaction(message); tx.sign([funder]); const sig = await connection.sendRawTransaction(tx.serialize()); await connection.confirmTransaction(sig, "confirmed"); } const order = { targetChain: "solana", contraChain: "solana", targetAsset: "So11111111111111111111111111111111111111112", // WSOL contraAsset: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // USDC side: "sell", qty: "5", orderType: "stop-loss", triggers: [{ notionalPrice: "120", triggerType: "lower" }], }; const quote = await post("/quote", { ...order, funderAddress: funder.publicKey.toBase58() }); if (quote.svm.ataSetupIxs) await sendIxs(quote.svm.ataSetupIxs); let delegateFields = {}; if (quote.svm.sponsoredDelegateTx) { const tx = VersionedTransaction.deserialize(Buffer.from(quote.svm.sponsoredDelegateTx, "base64")); tx.sign([funder]); delegateFields = { svmSponsoredDelegateTx: Buffer.from(tx.serialize()).toString("base64") }; } else if (quote.svm.delegateIx) { await sendIxs([quote.svm.delegateIx]); } const signature = nacl.sign.detached(new TextEncoder().encode(quote.svm.orderMessage), funder.secretKey); const userSignature = bs58.encode(signature); const { orderId } = await post("/order", { ...order, funderAddress: funder.publicKey.toBase58(), quoteId: quote.quoteId, userSignature, svmNonce: quote.svm.nonce, svmDeadline: quote.svm.deadline, ...delegateFields, }); console.log("orderId", orderId); ``` -------------------------------- ### GET /orders Source: https://flash.definitive.fi/docs/api-reference/flash/list-orders List Flash orders for a funder. Returns up to pageSize orders, most recent first. ```APIDOC ## GET /orders ### Description List Flash orders for a funder. Returns up to `pageSize` orders, most recent first. ### Method GET ### Endpoint /orders ### Parameters #### Query Parameters - **funderAddress** (string) - Required - Funder wallet address whose orders to list. - **statuses** (string) - Optional - Comma-separated list of order statuses to filter by. When omitted, orders of every status are returned. - **pageSize** (integer) - Optional - Number of orders to return. Defaults to 50; capped at 200. ### Response #### Success Response (200) - **orders** (array) - List of Flash orders. #### Error Responses - **400** - Invalid request parameters - **401** - Authentication failed - **403** - Permission denied - **404** - Resource not found - **422** - Resource state prevents the requested operation - **429** - Rate limit exceeded - **500** - Internal server error - **503** - Service temporarily unavailable - **504** - Gateway timeout ``` -------------------------------- ### GET /orders/{orderId} Source: https://flash.definitive.fi/docs/api-reference/flash/get-order Fetch a single Flash order with its execution fills. ```APIDOC ## GET /orders/{orderId} ### Description Fetch a single Flash order with its execution fills. ### Method GET ### Endpoint https://flash.definitive.fi/v1/orders/{orderId} ### Parameters #### Path Parameters - **orderId** (string, uuid) - Required - Flash order ID. #### Query Parameters - **funderAddress** (string) - Required - Funder wallet address that placed the order. ### Response #### Success Response (200) - **order** (object) - The order details. - **fills** (array) - List of execution fills for the order. ``` -------------------------------- ### Install Flash MCP for Claude Code Source: https://flash.definitive.fi/docs/flash-mcp Commands to add the Flash MCP server or plugin to Claude Code. ```bash claude mcp add definitive-flash -- npx -y @definitive-fi/flash-mcp ``` ```bash /plugin marketplace add DefinitiveCo/flash-mcp /plugin install definitive-flash@flash-mcp ``` -------------------------------- ### OpenAPI Specification for List Orders Source: https://flash.definitive.fi/docs/api-reference/flash/list-orders Defines the GET /orders endpoint, including required query parameters like funderAddress and optional filters for statuses and page size. ```yaml openapi: 3.1.0 info: title: Definitive Flash API version: 2.0.0 description: Flash swap API for decentralized token trading. servers: - url: https://flash.definitive.fi/v1 security: [] paths: /orders: get: tags: - Flash summary: List orders description: >- List Flash orders for a funder. Returns up to `pageSize` orders, most recent first. parameters: - schema: type: string minLength: 1 description: Funder wallet address whose orders to list. required: true name: funderAddress in: query - schema: type: string description: >- Comma-separated list of order statuses to filter by. When omitted, orders of every status are returned. example: ORDER_STATUS_FILLED,ORDER_STATUS_CANCELLED required: false name: statuses in: query - schema: type: integer minimum: 1 maximum: 200 default: 50 description: Number of orders to return. Defaults to 50; capped at 200. required: false name: pageSize in: query responses: '200': description: Orders returned successfully content: application/json: schema: $ref: '#/components/schemas/FlashListOrdersResponse' '400': description: Invalid request parameters content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '401': description: Authentication failed content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '403': description: Permission denied content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '404': description: Resource not found content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '422': description: Resource state prevents the requested operation content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '429': description: Rate limit exceeded content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '500': description: Internal server error content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '503': description: Service temporarily unavailable content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '504': description: Gateway timeout content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' security: - ApiKeyAuth: [] components: schemas: FlashListOrdersResponse: type: object properties: orders: type: array items: $ref: '#/components/schemas/FlashOrder' required: - orders ErrorResponse: type: object properties: error: type: object properties: code: type: string message: type: string details: nullable: true required: - code - message required: - error FlashOrder: type: object properties: orderId: type: string orderType: $ref: '#/components/schemas/OrderType' side: $ref: '#/components/schemas/OrderSide' status: $ref: '#/components/schemas/FlashOrderStatus' closeReason: type: string nullable: true description: >- Reason the order was closed (e.g. `REASON_USER_REQUESTED`, `REASON_FULLY_FILLED`); null while the order is still active. funderAddress: type: string targetAsset: $ref: '#/components/schemas/FlashAssetRef' contraAsset: $ref: '#/components/schemas/FlashAssetRef' qty: type: string filled: ``` -------------------------------- ### Get order detail OpenAPI specification Source: https://flash.definitive.fi/docs/api-reference/flash/get-order Defines the GET /orders/{orderId} endpoint, requiring a UUID orderId and a funderAddress query parameter. ```yaml openapi: 3.1.0 info: title: Definitive Flash API version: 2.0.0 description: Flash swap API for decentralized token trading. servers: - url: https://flash.definitive.fi/v1 security: [] paths: /orders/{orderId}: get: tags: - Flash summary: Get order detail description: Fetch a single Flash order with its execution fills. parameters: - schema: type: string format: uuid description: Flash order ID. required: true name: orderId in: path - schema: type: string minLength: 1 description: Funder wallet address that placed the order. required: true name: funderAddress in: query responses: '200': description: Order detail returned successfully content: application/json: schema: $ref: '#/components/schemas/FlashGetOrderResponse' '400': description: Invalid request parameters content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '401': description: Authentication failed content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '403': description: Permission denied content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '404': description: Resource not found content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '422': description: Resource state prevents the requested operation content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '429': description: Rate limit exceeded content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '500': description: Internal server error content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '503': description: Service temporarily unavailable content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '504': description: Gateway timeout content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' security: - ApiKeyAuth: [] components: schemas: FlashGetOrderResponse: type: object properties: order: $ref: '#/components/schemas/FlashOrder' fills: type: array items: $ref: '#/components/schemas/FlashFill' required: - order - fills ErrorResponse: type: object properties: error: type: object properties: code: type: string message: type: string details: nullable: true required: - code - message required: - error FlashOrder: type: object properties: orderId: type: string orderType: $ref: '#/components/schemas/OrderType' side: $ref: '#/components/schemas/OrderSide' status: $ref: '#/components/schemas/FlashOrderStatus' closeReason: type: string nullable: true description: >- Reason the order was closed (e.g. `REASON_USER_REQUESTED`, `REASON_FULLY_FILLED`); null while the order is still active. funderAddress: type: string targetAsset: $ref: '#/components/schemas/FlashAssetRef' contraAsset: $ref: '#/components/schemas/FlashAssetRef' qty: type: string filled: $ref: '#/components/schemas/FlashOrderFilled' limitNotionalPrice: type: string nullable: true limitCrossPrice: type: string nullable: true trigger: allOf: - $ref: '#/components/schemas/PriceTrigger' - nullable: true brackets: type: array nullable: true items: ``` -------------------------------- ### Execute SVM (Solana) Limit Order Source: https://flash.definitive.fi/docs/limit-order Demonstrates setting up Solana instructions for token accounts and delegations before signing and submitting a limit order. ```typescript import { Connection, Keypair, PublicKey, TransactionInstruction, TransactionMessage, VersionedTransaction, } from "@solana/web3.js"; import nacl from "tweetnacl"; import bs58 from "bs58"; const BASE_URL = "https://flash.definitive.fi/v1"; const API_KEY = "dpka_513a2bd7_57a2_46d2_927b_2a3857fe271b"; const connection = new Connection(process.env.SOLANA_RPC_URL!, "confirmed"); const funder = Keypair.fromSecretKey(bs58.decode(process.env.SOLANA_SECRET_KEY!)); const post = (path: string, body: unknown) => fetch(`${BASE_URL}${path}`, { method: "POST", headers: { "content-type": "application/json", "x-definitive-api-key": API_KEY }, body: JSON.stringify(body), }).then((r) => r.json()); const toIx = (ix: any) => new TransactionInstruction({ programId: new PublicKey(ix.programId), keys: ix.accounts.map((a: any) => ({ pubkey: new PublicKey(a.pubkey), isSigner: a.isSigner, isWritable: a.isWritable, })), data: Buffer.from(bs58.decode(ix.data)), }); ``` -------------------------------- ### Execute TWAP Order on Solana Source: https://flash.definitive.fi/docs/twap-order Demonstrates the full flow of setting up instructions, requesting a quote, handling delegate transactions, and submitting the final order. ```typescript async function sendIxs(instructions: any[]) { const { blockhash } = await connection.getLatestBlockhash(); const message = new TransactionMessage({ payerKey: funder.publicKey, recentBlockhash: blockhash, instructions: instructions.map(toIx), }).compileToV0Message(); const tx = new VersionedTransaction(message); tx.sign([funder]); const sig = await connection.sendRawTransaction(tx.serialize()); await connection.confirmTransaction(sig, "confirmed"); } const order = { targetChain: "solana", contraChain: "solana", targetAsset: "So11111111111111111111111111111111111111112", // WSOL contraAsset: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // USDC side: "sell", qty: "5", orderType: "twap", }; // durationSeconds is a quote-time field, so it is not echoed on submit const quote = await post("/quote", { ...order, durationSeconds: 3600, funderAddress: funder.publicKey.toBase58() }); if (quote.svm.ataSetupIxs) await sendIxs(quote.svm.ataSetupIxs); let delegateFields = {}; if (quote.svm.sponsoredDelegateTx) { const tx = VersionedTransaction.deserialize(Buffer.from(quote.svm.sponsoredDelegateTx, "base64")); tx.sign([funder]); delegateFields = { svmSponsoredDelegateTx: Buffer.from(tx.serialize()).toString("base64") }; } else if (quote.svm.delegateIx) { await sendIxs([quote.svm.delegateIx]); } const signature = nacl.sign.detached(new TextEncoder().encode(quote.svm.orderMessage), funder.secretKey); const userSignature = bs58.encode(signature); const { orderId } = await post("/order", { ...order, funderAddress: funder.publicKey.toBase58(), quoteId: quote.quoteId, userSignature, svmNonce: quote.svm.nonce, svmDeadline: quote.svm.deadline, ...delegateFields, }); console.log("orderId", orderId); ``` -------------------------------- ### Execute EVM Market Order Source: https://flash.definitive.fi/docs/market-order Demonstrates buying WETH with USDC on Base, including handling approvals and permit signatures via viem. ```typescript import { createWalletClient, createPublicClient, http } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { base } from "viem/chains"; const BASE_URL = "https://flash.definitive.fi/v1"; const API_KEY = "dpka_513a2bd7_57a2_46d2_927b_2a3857fe271b"; const account = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`); const wallet = createWalletClient({ account, chain: base, transport: http(process.env.EVM_RPC_URL) }); const publicClient = createPublicClient({ chain: base, transport: http(process.env.EVM_RPC_URL) }); const post = (path: string, body: unknown) => fetch(`${BASE_URL}${path}`, { method: "POST", headers: { "content-type": "application/json", "x-definitive-api-key": API_KEY }, body: JSON.stringify(body), }).then((r) => r.json()); const order = { targetChain: "base", contraChain: "base", targetAsset: "0x4200000000000000000000000000000000000006", // WETH contraAsset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC side: "buy", qty: "100", orderType: "market", maxSlippage: "0.05", }; const quote = await post("/quote", { ...order, funderAddress: account.address }); if (quote.evm.approveTx) { const hash = await wallet.sendTransaction({ to: quote.evm.approveTx.to, data: quote.evm.approveTx.data, value: 0n, }); await publicClient.waitForTransactionReceipt({ hash }); } let permitFields = {}; if (quote.evm.permitTypedData) { const evmPermitSignature = await account.signTypedData(JSON.parse(quote.evm.permitTypedData)); permitFields = { evmPermitTypedData: quote.evm.permitTypedData, evmPermitSignature }; } const { domain, types, primaryType, message } = JSON.parse(quote.evm.orderTypedData); const userSignature = await account.signTypedData({ domain, types, primaryType, message }); const { orderId } = await post("/order", { ...order, funderAddress: account.address, quoteId: quote.quoteId, userSignature, evmOrderTypedData: quote.evm.orderTypedData, ...permitFields, }); console.log("orderId", orderId); ``` -------------------------------- ### OpenAPI Quote Endpoint Definition Source: https://flash.definitive.fi/docs/api-reference/flash/quote The OpenAPI specification for the /quote POST endpoint, including the request schema and example payload. ```yaml openapi: 3.1.0 info: title: Definitive Flash API version: 2.0.0 description: Flash swap API for decentralized token trading. servers: - url: https://flash.definitive.fi/v1 security: [] paths: /quote: post: tags: - Flash summary: Get a quote description: >- Request a quote for a flash swap. Returns pricing, fee breakdown, asset amounts, and market quality indicators. requestBody: content: application/json: schema: $ref: '#/components/schemas/QuoteRequest' example: targetChain: base contraChain: base targetAsset: '0x4200000000000000000000000000000000000006' contraAsset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' side: buy qty: '100' orderType: market funderAddress: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045' maxSlippage: '0.01' responses: '200': description: Quote generated successfully content: application/json: schema: $ref: '#/components/schemas/QuoteResponse' '400': description: Invalid request parameters content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '401': description: Authentication failed content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '403': description: Permission denied content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '404': description: Resource not found content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '422': description: Resource state prevents the requested operation content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '429': description: Rate limit exceeded content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '500': description: Internal server error content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '503': description: Service temporarily unavailable content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '504': description: Gateway timeout content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' security: - ApiKeyAuth: [] components: schemas: QuoteRequest: type: object properties: targetChain: $ref: '#/components/schemas/Chain' contraChain: allOf: - $ref: '#/components/schemas/Chain' - description: Chain of the contra (counter) asset. targetAsset: type: string minLength: 1 description: Address of the target (traded) asset. example: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2' contraAsset: type: string minLength: 1 description: >- Address of the contra (counter) asset — spent on buys, received on sells. example: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' side: allOf: - $ref: '#/components/schemas/OrderSide' - description: direction of the order example: buy qty: type: string description: >- Amount of the asset being spent (sold), as a decimal string in the asset's normalized units. For `buy` orders this is in `contraAsset` units; for `sell` orders this is in `targetAsset` units. example: '1.5' orderType: allOf: - $ref: '#/components/schemas/OrderType' - example: market quickTrade: type: boolean description: >- Execution mode for sniping newly launched tokens (exclusive to market swaps). Reach out to the Definitive team to find out whether QuickTrade is a good fit for your use case. ``` -------------------------------- ### Enable QuickTrade in Order Request Source: https://flash.definitive.fi/docs/quicktrade Include the quickTrade flag set to true within your market order request to enable low-latency execution. ```json { "targetChain": "base", "contraChain": "base", "targetAsset": "0x4200000000000000000000000000000000000006", // WETH "contraAsset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC "side": "buy", "qty": "100", "orderType": "market", "quickTrade": true } ``` -------------------------------- ### POST /order Source: https://flash.definitive.fi/docs/solana-overview Submits a signed order to the Flash program for execution on the Solana network. ```APIDOC ## POST /order ### Description Submits the order to the Flash system. This endpoint handles priority fees, MEV protection, and onchain execution. ### Method POST ### Endpoint /order ### Request Body - **funderAddress** (string) - Required - The address of the funder. - **quoteId** (string) - Required - The ID of the quote obtained previously. - **userSignature** (string) - Required - The base58 encoded Ed25519 signature of the order message. - **svmNonce** (string) - Required - The nonce echoed back from the quote. - **svmDeadline** (string) - Required - The deadline echoed back from the quote. - **svmSponsoredDelegateTx** (string) - Optional - The signed sponsored delegation transaction if required by the quote. ### Response #### Success Response (200) - **orderId** (string) - The unique identifier for the submitted order. ``` -------------------------------- ### Manage Flash MCP via CLI Source: https://flash.definitive.fi/docs/flash-mcp Individual CLI commands for managing keys, RPC endpoints, and organization settings. ```bash flash-mcp set-key evm # or: svm, api flash-mcp set-rpc base https://your-rpc flash-mcp set-org 5VYFCW7M flash-mcp status # show what's configured flash-mcp remove-key evm ``` -------------------------------- ### Order Request Body Structure Source: https://flash.definitive.fi/docs/placing-orders The request body structure for placing market and limit orders. The provided examples demonstrate how to configure target assets, contra assets, order sides, quantities, and pricing constraints. ```APIDOC ## Order Request Body ### Description This structure defines the parameters required to place a market or limit order for assets on a specified chain. ### Request Body - **targetChain** (string) - The blockchain network for the target asset. - **contraChain** (string) - The blockchain network for the contra asset. - **targetAsset** (string) - The contract address of the target asset. - **contraAsset** (string) - The contract address of the contra asset. - **side** (string) - The side of the order: "buy" or "sell". - **qty** (string) - The quantity of the asset to trade. - **orderType** (string) - The type of order: "market" or "limit". - **maxSlippage** (string) - Optional: Maximum slippage allowed for market orders. - **limitNotionalPrice** (string) - Optional: The price limit for limit orders in USD. - **limitCrossPrice** (string) - Optional: The price limit for limit orders in the pair rate. ### Request Example (Market Buy) { "targetChain": "base", "contraChain": "base", "targetAsset": "0x4200000000000000000000000000000000000006", "contraAsset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "side": "buy", "qty": "100", "orderType": "market", "maxSlippage": "0.05" } ### Request Example (Limit Buy) { "targetChain": "base", "contraChain": "base", "targetAsset": "0x4200000000000000000000000000000000000006", "contraAsset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "side": "buy", "qty": "100", "orderType": "limit", "limitNotionalPrice": "1000" } ``` -------------------------------- ### POST /order Source: https://flash.definitive.fi/docs/api-reference/flash/order Submit a flash order for MEV-protected execution. Requires a quoteId and chain-specific cryptographic signatures. ```APIDOC ## POST /order ### Description Submit a flash order for MEV-protected execution. The funder wallet must sign data returned by the quote request before calling this endpoint. ### Method POST ### Endpoint /order ### Request Body - **targetChain** (Chain) - Required - The target chain for the order. - **contraChain** (Chain) - Required - Chain of the contra (counter) asset. - **targetAsset** (string) - Required - The asset identifier. ### Response #### Success Response (201) - **Order submitted successfully** #### Error Responses - **400** - Invalid request parameters - **401** - Authentication failed - **403** - Permission denied - **404** - Resource not found - **422** - Resource state prevents the requested operation - **429** - Rate limit exceeded - **500** - Internal server error - **503** - Service temporarily unavailable - **504** - Gateway timeout ``` -------------------------------- ### POST /quote Source: https://flash.definitive.fi/docs/for-agents Retrieves pricing for a swap and generates the necessary signing payloads based on the target chain. ```APIDOC ## POST /quote ### Description Returns pricing for a swap. Pass asset details, side, quantity, order type, and the funder address to receive signing payloads. ### Method POST ### Endpoint /quote ### Parameters #### Request Body - **targetAsset** (string) - Required - The target asset address. - **contraAsset** (string) - Required - The contra asset address. - **targetChain** (string) - Required - The target chain identifier. - **contraChain** (string) - Required - The contra chain identifier. - **side** (string) - Required - 'buy' or 'sell'. - **qty** (string) - Required - Decimal string in the spent asset's units. - **orderType** (string) - Required - The type of order. - **funderAddress** (string) - Required - The wallet address that will sign and fund the order. - **flashIntegratorFeeBps** (integer) - Optional - Integrator fee in basis points. ``` -------------------------------- ### Orders Snapshot Source: https://flash.definitive.fi/docs/api-reference/flash/websocket The initial message received after subscribing, containing the current list of open orders for the funder. ```json { "channel": "orders", "type": "snapshot", "orders": [ /* FlashOrderUpdate[] */ ] } ``` -------------------------------- ### Stop Order Configuration Source: https://flash.definitive.fi/docs/trigger-orders JSON payload for a stop order to buy WETH using a specified amount of USDC when the price reaches a threshold. ```jsonc { "targetChain": "base", "contraChain": "base", "targetAsset": "0x4200000000000000000000000000000000000006", // WETH "contraAsset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC "side": "buy", "qty": "100", "orderType": "stop", "triggers": [{ "notionalPrice": "5000", "triggerType": "upper" }] } ``` -------------------------------- ### Take-Profit Order Configuration Source: https://flash.definitive.fi/docs/trigger-orders JSON payload for a take-profit order to sell WETH when the price reaches a specific threshold. ```jsonc { "targetChain": "base", "contraChain": "base", "targetAsset": "0x4200000000000000000000000000000000000006", // WETH "contraAsset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC "side": "sell", "qty": "0.05", "orderType": "take-profit", "triggers": [{ "notionalPrice": "5000", "triggerType": "upper" }] } ``` -------------------------------- ### EVM Order Signing Source: https://flash.definitive.fi/docs/for-agents Instructions for signing EIP-712 order payloads using viem. ```APIDOC ## EVM Order Signing ### Description Parse the JSON-stringified EIP-712 payload provided by the quote and sign it using the wallet's `signTypedData` method. The resulting signature is passed as `userSignature` during submission. ### Example ```ts import { privateKeyToAccount } from "viem/accounts"; const account = privateKeyToAccount("0x..."); const { domain, types, primaryType, message } = JSON.parse(quote.evm.orderTypedData); const userSignature = await account.signTypedData({ domain, types, primaryType, message }); ``` ``` -------------------------------- ### Request a Quote with Integrator Fee Source: https://flash.definitive.fi/docs/monetizing-your-integration Include the flashIntegratorFeeBps parameter as a string in the POST /quote request body to set the fee percentage. ```bash curl -X POST https://flash.definitive.fi/v1/quote \ -H "x-definitive-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "targetChain": "base", "contraChain": "base", "targetAsset": "0x4200000000000000000000000000000000000006", "contraAsset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "side": "buy", "qty": "100", "orderType": "market", "flashIntegratorFeeBps": "50" }' ``` -------------------------------- ### POST /order Source: https://flash.definitive.fi/docs/for-agents Executes a swap order using a previously obtained quote ID and user signature. ```APIDOC ## POST /order ### Description Executes the swap order. Requires trade fields from the quote, a quoteId, and a userSignature. ### Method POST ### Endpoint /order ### Request Body - **funderAddress** (string) - Required - Wallet funding the swap - **quoteId** (string) - Required - ID from the quote step - **userSignature** (string) - Required - Signature from the signing step - **flashIntegratorFeeBps** (string) - Optional - Fee value if included in the quote - **evmOrderTypedData** (object) - Optional - Required for EVM; echo of quote.evm.orderTypedData - **evmPermitTypedData** (object) - Optional - Required for EVM if Permit2 is used - **evmPermitSignature** (string) - Optional - Required for EVM if Permit2 is used - **erc8021AttributionCode** (string) - Optional - Attribution code for Base builder - **svmNonce** (number) - Optional - Required for Solana; echo of quote.svmNonce - **svmDeadline** (number) - Optional - Required for Solana; echo of quote.svmDeadline - **svmSponsoredDelegateTx** (string) - Optional - Required for Solana if quote returned sponsoredDelegateTx ### Response #### Success Response (200) - **orderId** (string) - The unique identifier for the submitted order ``` -------------------------------- ### SVM Order Signing Source: https://flash.definitive.fi/docs/for-agents Instructions for signing Solana order messages using @solana/web3.js. ```APIDOC ## SVM Order Signing ### Description Sign the plaintext UTF-8 message provided in `svm.orderMessage` using the wallet's Ed25519 key. The 64-byte signature must be encoded as base58 and passed as `userSignature`. ### Example ```ts import { Keypair } from "@solana/web3.js"; import nacl from "tweetnacl"; import bs58 from "bs58"; const keypair = Keypair.fromSecretKey(bs58.decode("...")); const message = new TextEncoder().encode(quote.svm.orderMessage); const signature = nacl.sign.detached(message, keypair.secretKey); const userSignature = bs58.encode(signature); ``` ``` -------------------------------- ### Submit a Limit Order Source: https://flash.definitive.fi/docs/limit-order Demonstrates the full flow of fetching a quote, handling transaction instructions, signing the order, and submitting it to the API. ```typescript async function sendIxs(instructions: any[]) { const { blockhash } = await connection.getLatestBlockhash(); const message = new TransactionMessage({ payerKey: funder.publicKey, recentBlockhash: blockhash, instructions: instructions.map(toIx), }).compileToV0Message(); const tx = new VersionedTransaction(message); tx.sign([funder]); const sig = await connection.sendRawTransaction(tx.serialize()); await connection.confirmTransaction(sig, "confirmed"); } const order = { targetChain: "solana", contraChain: "solana", targetAsset: "So11111111111111111111111111111111111111112", // WSOL contraAsset: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // USDC side: "buy", qty: "100", orderType: "limit", limitNotionalPrice: "150", }; const quote = await post("/quote", { ...order, funderAddress: funder.publicKey.toBase58() }); if (quote.svm.ataSetupIxs) await sendIxs(quote.svm.ataSetupIxs); let delegateFields = {}; if (quote.svm.sponsoredDelegateTx) { const tx = VersionedTransaction.deserialize(Buffer.from(quote.svm.sponsoredDelegateTx, "base64")); tx.sign([funder]); delegateFields = { svmSponsoredDelegateTx: Buffer.from(tx.serialize()).toString("base64") }; } else if (quote.svm.delegateIx) { await sendIxs([quote.svm.delegateIx]); } const signature = nacl.sign.detached(new TextEncoder().encode(quote.svm.orderMessage), funder.secretKey); const userSignature = bs58.encode(signature); const { orderId } = await post("/order", { ...order, funderAddress: funder.publicKey.toBase58(), quoteId: quote.quoteId, userSignature, svmNonce: quote.svm.nonce, svmDeadline: quote.svm.deadline, ...delegateFields, }); console.log("orderId", orderId); ``` -------------------------------- ### Submit an Order with Integrator Fee Source: https://flash.definitive.fi/docs/monetizing-your-integration Ensure the same flashIntegratorFeeBps value used in the quote is passed when submitting the order via POST /order. ```bash curl -X POST https://flash.definitive.fi/v1/order \ -H "x-definitive-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "targetChain": "base", "contraChain": "base", "targetAsset": "0x4200000000000000000000000000000000000006", "contraAsset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "side": "buy", "qty": "100", "orderType": "market", "funderAddress": "0xUSER_WALLET", "quoteId": "q_abc123", "userSignature": "0x...", "evmOrderTypedData": "...", "flashIntegratorFeeBps": "50" }' ``` -------------------------------- ### Configure Flash MCP for Cursor Source: https://flash.definitive.fi/docs/flash-mcp JSON configuration for the Cursor MCP settings file. ```json { "mcpServers": { "definitive-flash": { "command": "npx", "args": ["-y", "@definitive-fi/flash-mcp"] } } } ```