# Chainworks API Source: http://localhost:3000/docs.md Section: Getting Started # Chainworks API Welcome to the Chainworks API documentation. Build powerful DeFi applications with our unified WebSocket API. --- ## What is Chainworks? Chainworks provides a **WebSocket-based DeFi API** that enables developers and institutions to easily access trading, token analysis, and other DeFi functionality across multiple blockchains. --- ## Supported Chains | Chain | Identifier | Type | Native Token | | --- | --- | --- | --- | | Ethereum | `eth` | EVM | ETH | | Base | `base` | EVM | ETH | | BNB Chain | `bsc` | EVM | BNB | | Solana | `sol` | SVM | SOL | --- ## Core Features ### Token Trading Execute swaps across multiple DEXes with optimal routing. Get quotes, build transactions, and send them with MEV protection. ### Price Quotes Real-time price quotes with slippage calculation, price impact analysis, and liquidity information. ### Token Reports Comprehensive token analysis including: - Liquidity depth - Buy/sell taxes - Transfer limits - Holder restrictions - Market data ### Multi-Chain Transfers Build and send native currency and token transfers across all supported chains. --- ## Quick Example ```typescript import { io } from "socket.io-client"; const socket = io(CHAINWORKS_API_URL, { transports: ["websocket"], auth: { token: CHAINWORKS_API_AUTH_TOKEN }, }); socket.on("connect", () => { console.log("Connected to Chainworks API"); // Get a buy quote socket.emit("/evm/buy/quote", { chain: "eth", token: "0x6982508145454Ce325dDbE47a25d4ec3d2311933", swapMode: "ExactIn", amountIn: "1000000000000000000", wallet: "0xYourWallet", }); }); socket.on("/evm/buy/quote", (response) => { if (response.success) { console.log("Price:", response.result.price); } }); ``` --- ## Next Steps - **[Quick Start](/docs/quickstart)** — Set up your environment and make your first request - **[Authentication](/docs/authentication)** — Learn how to connect with your credentials - **[EVM Endpoints](/docs/evm)** — Explore Ethereum, Base, and BSC APIs - **[SVM Endpoints](/docs/svm)** — Explore Solana APIs - **[Playground](/playground)** — Test the API interactively ## Frequently Asked Questions ### What is Chainworks? Chainworks is a unified WebSocket API for building DeFi applications. One integration gives you trading, quotes, wallet data, and token info across Solana, Ethereum, Base, and BNB Chain. ### Which blockchains does Chainworks support? Solana is the primary supported chain. Ethereum, Base, and BNB Chain are supported in beta. All chains share the same WebSocket API surface so you can write one integration. ### How do I authenticate with the Chainworks API? Authentication is token-based. You pass your API URL and auth token to the Socket.IO client on connect; see /docs/authentication for the exact handshake. ### What transport does the API use? The Chainworks API is delivered over a single WebSocket connection using Socket.IO. You emit requests and listen for responses on the same event name — no REST calls and no polling. ### Can I try the API without writing code? Yes. The /playground page is an interactive tester where you can pick an endpoint, fill in parameters, connect with your credentials, and inspect the live response. ### Where can I see the full machine-readable docs? Every docs page has a .md twin (for example, /docs/quickstart.md), and /llms-full.txt contains all documentation concatenated for LLM ingestion. /llms.txt is a compact index. --- # Quick Start Source: http://localhost:3000/docs/quickstart.md Section: Getting Started # Quick Start Get up and running with the Chainworks API in just a few minutes. ## Prerequisites - Node.js 18+ or Python 3.8+ - Chainworks API credentials (API URL and Auth Token) - Basic understanding of WebSocket communication ## Installation ### TypeScript/JavaScript ```bash npm install socket.io-client ``` ### Python ```bash pip install python-socketio ``` ## Connecting to the API The Chainworks API uses WebSocket connections via Socket.IO. This provides real-time, bidirectional communication with low latency. ### TypeScript ```typescript import { io } from "socket.io-client"; const CHAINWORKS_API_URL = "https://api.chainworks.co"; const CHAINWORKS_API_AUTH_TOKEN = "your-auth-token"; const socket = io(CHAINWORKS_API_URL, { transports: ["websocket"], auth: { token: CHAINWORKS_API_AUTH_TOKEN, }, }); socket.on("connect", () => { console.log("Connected to Chainworks API"); }); socket.on("connect_error", (error) => { console.error("Connection failed:", error.message); }); socket.on("disconnect", (reason) => { console.log("Disconnected:", reason); }); ``` ### Python ```python import socketio CHAINWORKS_API_URL = "https://api.chainworks.co" CHAINWORKS_API_AUTH_TOKEN = "your-auth-token" sio = socketio.Client() @sio.event def connect(): print("Connected to Chainworks API") @sio.event def connect_error(data): print(f"Connection failed: {data}") @sio.event def disconnect(): print("Disconnected") sio.connect( CHAINWORKS_API_URL, transports=["websocket"], auth={"token": CHAINWORKS_API_AUTH_TOKEN} ) ``` ## Your First Request Let's get a buy quote for a token on Ethereum: ### TypeScript ```typescript // Request a buy quote socket.emit("/evm/buy/quote", { chain: "eth", token: "0x6982508145454Ce325dDbE47a25d4ec3d2311933", // PEPE swapMode: "ExactIn", amountIn: "1000000000000000000", // 1 ETH in wei wallet: "0xYourWalletAddress", }); // Listen for the response socket.on("/evm/buy/quote", (response) => { if (response.success) { console.log("Price:", response.result.price); console.log("Expected output:", response.result.expectedAmountOut); console.log("Price impact:", response.result.priceImpact); } else { console.error("Error:", response.error.message); } }); ``` ### Python ```python @sio.on("/evm/buy/quote") def on_quote(response): if response.get("success"): result = response["result"] print(f"Price: {result['price']}") print(f"Expected output: {result['expectedAmountOut']}") print(f"Price impact: {result['priceImpact']}") else: print(f"Error: {response['error']['message']}") sio.emit("/evm/buy/quote", { "chain": "eth", "token": "0x6982508145454Ce325dDbE47a25d4ec3d2311933", "swapMode": "ExactIn", "amountIn": "1000000000000000000", "wallet": "0xYourWalletAddress" }) ``` ## Response Format All API responses follow a consistent format: ### Success Response ```json { "success": true, "result": { // Response data specific to the endpoint } } ``` ### Error Response ```json { "success": false, "error": { "code": "ERROR_CODE", "message": "Human-readable error description" }, "partialResult": { // Optional helpful data even when request fails } } ``` ## Next Steps - [Authentication](/docs/authentication) - Learn about token authentication - [EVM Endpoints](/docs/evm) - Explore Ethereum, Base, and BSC endpoints - [SVM Endpoints](/docs/svm) - Explore Solana endpoints - [Playground](/playground) - Test the API interactively --- # Authentication Source: http://localhost:3000/docs/authentication.md Section: Getting Started # Authentication The Chainworks API uses token-based authentication over WebSocket connections. ## Authentication Flow 1. Obtain your API credentials (API URL and Auth Token) 2. Connect to the WebSocket server with your token 3. The server validates your token on connection 4. If valid, you can start making API requests ## Connecting with Credentials ### TypeScript ```typescript import { io } from "socket.io-client"; const socket = io(CHAINWORKS_API_URL, { transports: ["websocket"], auth: { token: CHAINWORKS_API_AUTH_TOKEN, }, }); ``` ### Python ```python import socketio sio = socketio.Client() sio.connect( CHAINWORKS_API_URL, transports=["websocket"], auth={"token": CHAINWORKS_API_AUTH_TOKEN} ) ``` ## Environment Variables We recommend storing your credentials in environment variables: ```bash # .env CHAINWORKS_API_URL=https://api.chainworks.co CHAINWORKS_API_AUTH_TOKEN=your-secret-token ``` ```typescript const socket = io(process.env.CHAINWORKS_API_URL!, { transports: ["websocket"], auth: { token: process.env.CHAINWORKS_API_AUTH_TOKEN!, }, }); ``` ## Connection Events Handle connection lifecycle events to ensure robust operation: ```typescript socket.on("connect", () => { console.log("Connected successfully"); // Start making API requests }); socket.on("connect_error", (error) => { console.error("Connection error:", error.message); // Handle authentication failures if (error.message.includes("unauthorized")) { console.error("Invalid API token"); } }); socket.on("disconnect", (reason) => { console.log("Disconnected:", reason); // Handle reconnection if needed }); ``` ## Reconnection Socket.IO automatically handles reconnection. You can configure the behavior: ```typescript const socket = io(CHAINWORKS_API_URL, { transports: ["websocket"], auth: { token: CHAINWORKS_API_AUTH_TOKEN, }, reconnection: true, reconnectionAttempts: 5, reconnectionDelay: 1000, reconnectionDelayMax: 5000, }); ``` ## Security Best Practices 1. **Never expose tokens in client-side code** - Use server-side proxies for browser applications 2. **Rotate tokens regularly** - Contact us to regenerate compromised tokens 3. **Use environment variables** - Never hardcode tokens in source code 4. **Monitor usage** - Track API calls to detect unauthorized access ## Rate Limits API rate limits depend on your subscription tier. Contact us for details about rate limits and quotas. ## Getting Credentials To obtain API credentials: 1. Contact us at [info@chainworks.co](mailto:info@chainworks.co) 2. Describe your use case 3. We'll provision credentials for your application ## Next Steps - [Quick Start](/docs/quickstart) - Get started with your first request - [EVM Endpoints](/docs/evm) - Explore Ethereum, Base, and BSC endpoints - [SVM Endpoints](/docs/svm) - Explore Solana endpoints --- # SVM Endpoints Source: http://localhost:3000/docs/svm.md Section: SVM (Solana) # SVM Endpoints Complete API reference for Solana (SVM). --- ## Supported Chains | Chain | Identifier | Native Token | | --- | --- | --- | | Solana | `sol` | SOL | --- ## Supported DEXes The API automatically routes through the best available DEX: | DEX | Type | Description | | --- | --- | --- | | RaydiumV4 | AMM | Classic Raydium pools | | RaydiumCLMM | CLMM | Concentrated liquidity | | RaydiumCPMM | CPMM | Constant product | | RaydiumLaunchLab | Launchpad | New token launches | | PumpFun | Bonding Curve | Meme token launches | | PumpSwap | AMM | PumpFun graduated tokens | | MeteoraDLMM | DLMM | Dynamic liquidity | | Meteora DYN | AMM | Dynamic fee AMM pools | | Meteora DYN2 | AMM | Enhanced dynamic pools | | Meteora Dynamic Bonding Curve (DBC) | Bonding Curve | Meteora token launches | | Whirlpool | CLMM | Orca concentrated liquidity | --- ## Endpoints - **[Quotes](/docs/svm/quotes)** — Get buy/sell price quotes - **[Transactions](/docs/svm/transactions)** — Build unsigned swap transactions - **[Transfers](/docs/svm/transfers)** — SOL, token, and multi-transfers - **[Wallet](/docs/svm/wallet)** — Query SOL and token balances - **[Token Info](/docs/svm/token-info)** — Token metadata and reports - **[Fees & Routes](/docs/svm/fees-and-routes)** — Priority fees, bribe fees, and send routes - **[Send Transaction](/docs/svm/send-transaction)** — Broadcast signed transactions - **[Price Subscriptions](/docs/svm/price-subscriptions)** — Real-time token price update streams --- # SVM Quotes Source: http://localhost:3000/docs/svm/quotes.md Section: SVM (Solana) # SVM Quotes Get price quotes for token swaps without executing transactions. ## Get Buy Quote Get a price quote for buying tokens with SOL. **Endpoint:** `/svm/buy/quote` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Always `sol` | | `token` | string | Yes | Token mint address | | `swapMode` | string | Yes | `ExactIn` or `ExactOut` | | `amountIn` | string | Conditional | Amount of SOL in lamports. Required for `ExactIn` | | `amountOut` | string | Conditional | Amount of tokens. Required for `ExactOut` | | `wallet` | string | Yes | Wallet public key | | `pool` | string | No | When supplied, this parameter restricts quoting to the specified pool, subject to liquidity and compatibility requirements. | **Example:** ```typescript socket.emit("/svm/buy/quote", { chain: "sol", token: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", // BONK swapMode: "ExactIn", amountIn: "1000000000", // 1 SOL in lamports wallet: "YourSolanaWalletPublicKey", pool: "PoolAddress", // Optional: specific pool address }); ``` **Response:** ```json { "success": true, "result": { "chain": "sol", "isBuy": true, "token": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", "swapMode": "ExactIn", "dex": "RaydiumV4", "price": 0.00000156, "priceImpact": 0.0008, "amountIn": "1000000000", "expectedAmountOut": "641025641025641" } } ``` ## Get Sell Quote Get a price quote for selling tokens for SOL. **Endpoint:** `/svm/sell/quote` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Always `sol` | | `token` | string | Yes | Token mint address | | `swapMode` | string | Yes | `ExactIn` or `ExactOut` | | `amountIn` | string | Conditional | Amount of tokens. Required for `ExactIn` | | `wallet` | string | Yes | Wallet public key | | `pool` | string | No | When supplied, this parameter restricts quoting to the specified pool, subject to liquidity and compatibility requirements. | --- # SVM Transactions Source: http://localhost:3000/docs/svm/transactions.md Section: SVM (Solana) # SVM Transactions Build unsigned transactions for token swaps. ## Get Buy Transaction Build an unsigned transaction for buying tokens. **Endpoint:** `/svm/buy/transaction` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Always `sol` | | `token` | string | Yes | Token mint address | | `swapMode` | string | Yes | `ExactIn` or `ExactOut` | | `amountIn` | string | Yes | Amount of SOL in lamports | | `wallet` | string | Yes | Wallet public key | | `slippageBps` | number | No | Slippage tolerance (default: 100 = 1%) | | `feeBps` | number | No | Fee in basis points (0-175) | | `feeRecipient` | string | No | Wallet to receive fees | | `sendRoute` | string | No | `Public`, `PublicWithNonce`, `Antimev`, or{" "} `AntimevWithNonce` | | `prioFees` | string | No | Priority fees (see below) | | `bribeFees` | string | Based on sendRoute | bribe fees (see below) | | `nonceAccount` | string | Based on sendRoute | Nonce account for transaction exclusivity | | `pool` | string | No | When supplied, this parameter restricts quoting to the specified pool, subject to liquidity and compatibility requirements. | **Example:** ```typescript socket.emit("/svm/buy/transaction", { chain: "sol", token: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", swapMode: "ExactIn", amountIn: "1000000000", wallet: "YourSolanaWalletPublicKey", slippageBps: 100, prioFees: "100000", pool: "PoolAddress", // Optional: specific pool address }); ``` ## Get Sell Transaction **Endpoint:** `/svm/sell/transaction` Same parameters as buy transaction. --- # SVM Transfers Source: http://localhost:3000/docs/svm/transfers.md Section: SVM (Solana) # SVM Transfers Build transactions for SOL and token transfers. ## SOL Transfer Transfer SOL to another address. **Endpoint:** `/svm/transfer/transaction` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Always `sol` | | `recipient` | string | Yes | Recipient public key | | `amount` | string | Yes | Amount in lamports | | `wallet` | string | Yes | Sender public key | | `sendRoute` | string | No | `Public`, `PublicWithNonce`, `Antimev`, or{" "} `AntimevWithNonce` | | `prioFees` | string | No | Priority fees (see below) | | `bribeFees` | string | Based on sendRoute | bribe fees (see below) | | `nonceAccount` | string | Based on sendRoute | Nonce account for transaction exclusivity | ## Token Transfer Transfer SPL tokens. **Endpoint:** `/svm/transfer/token/transaction` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Always `sol` | | `token` | string | Yes | Token mint address | | `recipient` | string | Yes | Recipient public key | | `amount` | string | Yes | Amount in token decimals | | `wallet` | string | Yes | Sender public key | | `ensureRecipientAssociatedTokenAccount` | boolean | No | Create ATA if needed (default: true) | | `sendRoute` | string | No | `Public`, `PublicWithNonce`, `Antimev`, or{" "} `AntimevWithNonce` | | `prioFees` | string | No | Priority fees (see below) | | `bribeFees` | string | Based on sendRoute | bribe fees (see below) | | `nonceAccount` | string | Based on sendRoute | Nonce account for transaction exclusivity | ## Multi-Transfer Send SOL to multiple recipients in one transaction. **Endpoint:** `/svm/transfer/multi/transaction` ```typescript socket.emit("/svm/transfer/multi/transaction", { chain: "sol", wallet: "YourSolanaWalletPublicKey", recipients: [ { address: "Recipient1PublicKey", amount: "100000000" }, { address: "Recipient2PublicKey", amount: "200000000" }, ], }); ``` --- # SVM Wallet Source: http://localhost:3000/docs/svm/wallet.md Section: SVM (Solana) # SVM Wallet Query wallet balances. ## Get SOL Balance **Endpoint:** `/svm/wallet/balance` ```typescript socket.emit("/svm/wallet/balance", { chain: "sol", wallet: "YourSolanaWalletPublicKey", }); ``` ## Get Token Balance **Endpoint:** `/svm/wallet/balance/token` ```typescript socket.emit("/svm/wallet/balance/token", { chain: "sol", token: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", wallet: "YourSolanaWalletPublicKey", }); ``` --- # SVM Token Information Source: http://localhost:3000/docs/svm/token-info.md Section: SVM (Solana) # SVM Token Information ## Get Token Metadata **Endpoint:** `/svm/token/meta` Returns name, symbol, decimals, and supply. ## Get Token Report **Endpoint:** `/svm/token/report` Returns comprehensive token analysis including liquidity and market data. --- # SVM Transaction Fees & Send Routes Source: http://localhost:3000/docs/svm/fees-and-routes.md Section: SVM (Solana) # SVM Transaction Fees & Send Routes ## Fee Parameters Solana transactions support two types of fees: ### Priority Fees (`prioFees`) Priority fees are paid to validators to prioritize your transaction in the block. | Property | Type | Default | Description | | --- | --- | --- | --- | | `prioFees` | string | `"0"` | Amount in lamports to pay as priority fees | **Example:** ```typescript socket.emit("/svm/buy/transaction", { chain: "sol", token: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", swapMode: "ExactIn", amountIn: "1000000000", wallet: "YourSolanaWalletPublicKey", prioFees: "100000", // 0.0001 SOL in lamports }); ``` **Notes:** - Higher priority fees increase the likelihood of faster inclusion - Paid regardless of transaction success or failure - Optional - defaults to `"0"` if not specified ### Bribe Fees (`bribeFees`) Bribe fees (also called MEV tips) are paid to MEV protection providers (e.g., Jito) to include your transaction in their bundles. | Property | Type | Minimum | Description | | --- | --- | --- | --- | | `bribeFees` | string | `"1000000"` | Amount in lamports to pay as bribe/tip fees | **Example:** ```typescript socket.emit("/svm/buy/transaction", { chain: "sol", token: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", swapMode: "ExactIn", amountIn: "1000000000", wallet: "YourSolanaWalletPublicKey", sendRoute: "Antimev", prioFees: "100000", bribeFees: "1000000", // 0.001 SOL (minimum) }); ``` **Notes:** - Required for `PublicWithNonce`, `Antimev`, and `AntimevWithNonce` routes - Minimum value is **1,000,000 lamports** (0.001 SOL) - Provides MEV protection by routing through specialized providers - Only paid if the transaction lands successfully (for revert-protected routes) ## Send Routes The `sendRoute` parameter determines how your transaction is submitted to the network. | Route | Default | Requires bribeFees | Requires nonceAccount | Description | | --- | --- | --- | --- | --- | | `Public` | ✅ Yes | ❌ No | ❌ No | Standard RPC submission only | | `PublicWithNonce` | ❌ No | ✅ Yes | ✅ Yes | RPC + all MEV providers with tip | | `Antimev` | ❌ No | ✅ Yes | ❌ No | Revert-protected MEV providers only | | `AntimevWithNonce` | ❌ No | ✅ Yes | ✅ Yes | All MEV providers (revert-protected + others) | ### `Public` (Default) The simplest route - sends your transaction through the standard public RPC only. ```typescript socket.emit("/svm/buy/transaction", { chain: "sol", token: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", swapMode: "ExactIn", amountIn: "1000000000", wallet: "YourSolanaWalletPublicKey", sendRoute: "Public", prioFees: "100000", }); ``` ### `PublicWithNonce` Sends through both public RPC and all MEV providers with a tip. ```typescript socket.emit("/svm/buy/transaction", { chain: "sol", token: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", swapMode: "ExactIn", amountIn: "1000000000", wallet: "YourSolanaWalletPublicKey", sendRoute: "PublicWithNonce", prioFees: "100000", bribeFees: "1000000", nonceAccount: "YourNonceAccountPublicKey", }); ``` ### `Antimev` Sends exclusively through revert-protected MEV providers (e.g., Jito bundles). ```typescript socket.emit("/svm/buy/transaction", { chain: "sol", token: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", swapMode: "ExactIn", amountIn: "1000000000", wallet: "YourSolanaWalletPublicKey", sendRoute: "Antimev", prioFees: "100000", bribeFees: "1000000", }); ``` **Best for:** High-value swaps where you want MEV protection and bribe fees only paid on success. ### `AntimevWithNonce` Sends through all MEV providers (both revert-protected and non-revert-protected). ```typescript socket.emit("/svm/buy/transaction", { chain: "sol", token: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", swapMode: "ExactIn", amountIn: "1000000000", wallet: "YourSolanaWalletPublicKey", sendRoute: "AntimevWithNonce", prioFees: "100000", bribeFees: "1000000", nonceAccount: "YourNonceAccountPublicKey", }); ``` **Best for:** Maximizing MEV protection coverage across all providers. --- # SVM Send Transaction Source: http://localhost:3000/docs/svm/send-transaction.md Section: SVM (Solana) # SVM Send Transaction Broadcast signed transactions to Solana. **Endpoint:** `/svm/send-transaction` > ⚠️ **Warning:** This endpoint sends real transactions to the blockchain. | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Always `sol` | | `signedTransactions` | string[] | Yes | Array of base64-encoded signed transactions | | `simulateBeforeSend` | boolean | No | Simulate before sending (default: true) | --- # SVM Price Subscriptions Source: http://localhost:3000/docs/svm/price-subscriptions.md Section: SVM (Solana) # SVM Price Subscriptions Subscribe to real-time price updates for Solana tokens. When a subscribed token's price changes, you receive a `priceUpdate` event on your Socket.IO connection with the latest price from the highest-liquidity pool. > **Socket.IO only:** Price updates are delivered as server-emitted events on your Socket.IO connection. You must be connected via Socket.IO to receive them. --- ## Subscription Limits Maximum active subscriptions per tier: | Tier | Max Subscriptions | | --- | --- | | Free | 0 | | Basic | 10 | | Premium | 100 | | Enterprise | 1,000 | --- ## Subscribe Subscribe to price updates for one or more tokens. **Endpoint:** `/svm/price/subscribe` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Always `sol` | | `tokens` | string[] | Yes | Array of token mint addresses (min 1) | | `ttlMs` | number | No | Subscription duration in milliseconds. Max: 604,800,000 (7d), default: 21,600,000 (6h) | **Example:** ```typescript socket.emit("/svm/price/subscribe", { chain: "sol", tokens: [ "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "So11111111111111111111111111111111111111112", ], ttlMs: 21600000, // 6 hours }); ``` **Response:** ```json { "success": true, "result": { "subscribed": [ "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "So11111111111111111111111111111111111111112" ] } } ``` Re-subscribing to an already-subscribed token refreshes its TTL without counting against the subscription limit. --- ## Unsubscribe Unsubscribe from price updates for one or more tokens. **Endpoint:** `/svm/price/unsubscribe` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Always `sol` | | `tokens` | string[] | Yes | Array of token mint addresses to unsubscribe | **Example:** ```typescript socket.emit("/svm/price/unsubscribe", { chain: "sol", tokens: ["EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"], }); ``` **Response:** ```json { "success": true, "result": { "unsubscribed": [ "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" ] } } ``` --- ## Active Subscriptions List all active (non-expired) price subscriptions. **Endpoint:** `/svm/price/active_subscriptions` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Always `sol` | **Example:** ```typescript socket.emit("/svm/price/active_subscriptions", { chain: "sol", }); ``` **Response:** ```json { "success": true, "result": { "tokens": [ "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "So11111111111111111111111111111111111111112" ] } } ``` --- ## Price Update Event When a subscribed token's price changes, you receive a `priceUpdate` event. Updates are sourced from the highest-liquidity pool for the token and deduplicated so you only receive meaningful price changes. ```typescript socket.on("priceUpdate", (data) => { console.log(data); }); ``` **Event payload:** ```json { "chain": "sol", "token": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "pool": { "type": "RaydiumV4", "lp": "58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2", "backingToken": "So11111111111111111111111111111111111111112", "rawPrice": 0.000034, "priceUsd": 0.0051, "tokenReserve": "1000000000000", "backingReserve": "34000000" }, "slotNumber": 285000000, "timestamp": 1710979200 } ``` | Field | Type | Description | | --- | --- | --- | | `chain` | string | Always `sol` | | `token` | string | Token mint address | | `pool.type` | string | DEX type (e.g. `RaydiumV4`, `PumpSwap`, `MeteoraDLMM`) | | `pool.lp` | string | Liquidity pool address | | `pool.backingToken` | string | Backing token mint (e.g. SOL or USDC) | | `pool.rawPrice` | number | Raw price ratio (token lamports / backing lamports) | | `pool.priceUsd` | number | Price of 1 full token in USD | | `pool.tokenReserve` | string | Token reserve amount in the pool | | `pool.backingReserve` | string | Backing token reserve amount in the pool | | `slotNumber` | number | Solana slot number of the update | | `timestamp` | number | Unix timestamp in seconds | --- ## Subscription Expiring Event You receive a `subscriptionExpiring` event shortly before a subscription expires, and again when it actually expires. Use this to re-subscribe if needed. ```typescript socket.on("subscriptionExpiring", (data) => { console.log(data); }); ``` **Event payload:** ```json { "chain": "sol", "token": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "expiresAt": 1711065600, "expired": false } ``` | Field | Type | Description | | --- | --- | --- | | `chain` | string | Always `sol` | | `token` | string | Token mint address | | `expiresAt` | number | Unix timestamp (seconds) when the subscription expires | | `expired` | boolean | `false` when expiring soon, `true` when already expired | --- # EVM Endpoints Source: http://localhost:3000/docs/evm.md Section: EVM Chains # EVM Endpoints Complete API reference for EVM-compatible chains including Ethereum, Base, and BNB Chain. --- ## Supported Chains | Chain | Identifier | Native Token | | --- | --- | --- | | Ethereum | `eth` | ETH | | Base | `base` | ETH | | BNB Chain | `bsc` | BNB | --- ## Endpoints - **[Quotes](/docs/evm/quotes)** — Get price quotes for token swaps - **[Transactions](/docs/evm/transactions)** — Build unsigned transactions for swaps - **[Transfers](/docs/evm/transfers)** — Transfer native currency and tokens - **[Wallet](/docs/evm/wallet)** — Query wallet balances - **[Token Info](/docs/evm/token-info)** — Get token metadata and reports - **[Send Transaction](/docs/evm/send-transaction)** — Broadcast signed transactions - **[AutoSnipe](/docs/evm/autosnipe)** — Real-time token launch detection signals --- # EVM Quotes Source: http://localhost:3000/docs/evm/quotes.md Section: EVM Chains # EVM Quotes Get price quotes for token swaps without executing transactions. --- ## Get Buy Quote Get a price quote for buying tokens with native currency. **Endpoint:** `/evm/buy/quote` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Chain identifier: `eth`, `base`, or `bsc` | | `token` | string | Yes | Token contract address | | `swapMode` | string | Yes | `ExactIn` (specify input) or `ExactOut` (specify output) | | `amountIn` | string | Conditional | Amount of native currency in wei. Required for `ExactIn` | | `amountOut` | string | Conditional | Amount of tokens to receive. Required for `ExactOut` | | `wallet` | string | Yes | Wallet address for the quote | **Example:** ```typescript socket.emit("/evm/buy/quote", { chain: "eth", token: "0x6982508145454Ce325dDbE47a25d4ec3d2311933", swapMode: "ExactIn", amountIn: "1000000000000000000", // 1 ETH wallet: "0x10a64c6d7f12c47b7c66c5b4e20e72bc1fcd5d9e", }); ``` **Response:** ```json { "success": true, "result": { "chain": "eth", "isBuy": true, "token": "0x6982508145454Ce325dDbE47a25d4ec3d2311933", "swapMode": "ExactIn", "price": 0.00000234, "priceImpact": 0.0012, "amountIn": "1000000000000000000", "expectedAmountOut": "427350427350427350427350" } } ``` --- ## Get Sell Quote Get a price quote for selling tokens for native currency. **Endpoint:** `/evm/sell/quote` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Chain identifier | | `token` | string | Yes | Token contract address | | `swapMode` | string | Yes | `ExactIn` or `ExactOut` | | `amountIn` | string | Conditional | Amount of tokens to sell. Required for `ExactIn` | | `wallet` | string | Yes | Wallet address | --- # EVM Transactions Source: http://localhost:3000/docs/evm/transactions.md Section: EVM Chains # EVM Transactions Build unsigned transactions for token swaps. --- ## Get Buy Transaction Build an unsigned transaction for buying tokens. **Endpoint:** `/evm/buy/transaction` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Chain identifier | | `token` | string | Yes | Token contract address | | `swapMode` | string | Yes | `ExactIn` or `ExactOut` | | `amountIn` | string | Yes | Amount of native currency in wei | | `wallet` | string | Yes | Wallet address | | `slippageBps` | number | No | Slippage tolerance in basis points (default: 100 = 1%) | | `feeBps` | number | No | Fee in basis points (0-175) | | `feeRecipient` | string | No | Wallet to receive fees | | `sendRoute` | string | No | `Public`, `Private`, or `Both` for MEV protection | **Example:** ```typescript socket.emit("/evm/buy/transaction", { chain: "eth", token: "0x6982508145454Ce325dDbE47a25d4ec3d2311933", swapMode: "ExactIn", amountIn: "1000000000000000000", wallet: "0x10a64c6d7f12c47b7c66c5b4e20e72bc1fcd5d9e", slippageBps: 100, sendRoute: "Private", }); ``` --- ## Get Sell Transaction **Endpoint:** `/evm/sell/transaction` Same parameters as buy transaction. May require a permit for V3 pools. --- ## Get Approve Transaction Build a transaction to approve token spending. **Endpoint:** `/evm/approve/transaction` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Chain identifier | | `token` | string | Yes | Token contract address | | `wallet` | string | Yes | Wallet granting approval | | `spender` | string | Yes | Contract address to approve | --- # EVM Transfers Source: http://localhost:3000/docs/evm/transfers.md Section: EVM Chains # EVM Transfers Build transactions for native and token transfers. --- ## Native Transfer Transfer ETH/BNB to another address. **Endpoint:** `/evm/transfer/transaction` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Chain identifier | | `recipient` | string | Yes | Recipient address | | `amount` | string | Yes | Amount in wei | | `wallet` | string | Yes | Sender address | --- ## Token Transfer Transfer ERC-20 tokens. **Endpoint:** `/evm/transfer/token/transaction` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Chain identifier | | `token` | string | Yes | Token contract address | | `recipient` | string | Yes | Recipient address | | `amount` | string | Yes | Amount in token decimals | | `wallet` | string | Yes | Sender address | --- # EVM Wallet Source: http://localhost:3000/docs/evm/wallet.md Section: EVM Chains # EVM Wallet Query wallet balances. --- ## Get Native Balance **Endpoint:** `/evm/wallet/balance` ```typescript socket.emit("/evm/wallet/balance", { chain: "eth", wallet: "0x10a64c6d7f12c47b7c66c5b4e20e72bc1fcd5d9e", }); ``` --- ## Get Token Balance **Endpoint:** `/evm/wallet/balance/token` ```typescript socket.emit("/evm/wallet/balance/token", { chain: "eth", token: "0x6982508145454Ce325dDbE47a25d4ec3d2311933", wallet: "0x10a64c6d7f12c47b7c66c5b4e20e72bc1fcd5d9e", }); ``` --- # EVM Token Information Source: http://localhost:3000/docs/evm/token-info.md Section: EVM Chains # EVM Token Information --- ## Get Token Metadata **Endpoint:** `/evm/token/meta` Returns name, symbol, decimals, and total supply. --- ## Get Token Report **Endpoint:** `/evm/token/report` Returns comprehensive token analysis: - Basic metadata (name, symbol, decimals) - Liquidity information - Buy/sell taxes - Transfer limits - Market cap and volume --- # EVM Send Transaction Source: http://localhost:3000/docs/evm/send-transaction.md Section: EVM Chains # EVM Send Transaction Broadcast signed transactions to the network. **Endpoint:** `/evm/send-transaction` > ⚠️ **Warning:** This endpoint sends real transactions to the blockchain. | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Chain identifier | | `signedTransactions` | string[] | Yes | Array of signed transaction hex strings | | `simulateBeforeSend` | boolean | No | Simulate before sending (default: true) | --- # EVM AutoSnipe Source: http://localhost:3000/docs/evm/autosnipe.md Section: EVM Chains # EVM AutoSnipe Monitor unlaunched EVM tokens and receive real-time signals when they become buyable. AutoSnipe watches the mempool and new blocks for liquidity events, simulates buyability, and pushes a signal to your Socket.IO connection the moment a token launches. > **Socket.IO only:** AutoSnipe signals are delivered as server-emitted events on your Socket.IO connection. You must be connected via Socket.IO to receive them. --- ## Register Watch Register a watch on a token to be notified when it becomes buyable. **Endpoint:** `/evm/autosnipe/register` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Chain identifier: `eth`, `base`, or `bsc` | | `token` | string | Yes | Token contract address to watch | | `ttlMs` | number | No | Watch duration in milliseconds. Min: 3,600,000 (1h), max: 172,800,000 (2d), default: 86,400,000 (24h) | **Example:** ```typescript socket.emit("/evm/autosnipe/register", { chain: "eth", token: "0x1234567890abcdef1234567890abcdef12345678", ttlMs: 86400000, // 24 hours }); ``` **Response:** ```json { "success": true, "result": { "chain": "eth", "token": "0x1234567890abcdef1234567890abcdef12345678", "owner": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd", "expiresAt": 1711065600 } } ``` Registration will be rejected if: - The address is not a contract - The token is already launched and buyable - The token or its owner is on the ignored addresses list (stablecoins, WETH, known MEV bots, etc.) --- ## Remove Watch Remove an active AutoSnipe watch. **Endpoint:** `/evm/autosnipe/remove` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Chain identifier | | `token` | string | Yes | Token contract address | **Example:** ```typescript socket.emit("/evm/autosnipe/remove", { chain: "eth", token: "0x1234567890abcdef1234567890abcdef12345678", }); ``` **Response:** ```json { "success": true, "result": { "chain": "eth", "token": "0x1234567890abcdef1234567890abcdef12345678" } } ``` --- ## List Watches List all active AutoSnipe watches on a chain. **Endpoint:** `/evm/autosnipe/list` | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `chain` | string | Yes | Chain identifier | **Example:** ```typescript socket.emit("/evm/autosnipe/list", { chain: "eth", }); ``` **Response:** ```json { "success": true, "result": [ { "chain": "eth", "partnerId": "your-partner-id", "token": "0x1234567890abcdef1234567890abcdef12345678", "owner": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd", "expiresAt": 1711065600, "registeredAt": 1710979200 } ] } ``` --- ## AutoSnipe Signal Event When a watched token becomes buyable, you receive an `autoSnipeSignal` event on your Socket.IO connection. Watches are automatically removed after a signal fires. ```typescript socket.on("autoSnipeSignal", (data) => { console.log(data); }); ``` **Event payload:** ```json { "chain": "eth", "token": "0x1234567890abcdef1234567890abcdef12345678", "type": "block0", "blockNumber": "19500000", "taxes": { "buyTaxBps": 500, "sellTaxBps": 500 }, "limits": { "buyLowerLimit": null, "buyUpperLimit": "1000000000000000000", "sellLowerLimit": null, "sellUpperLimit": null }, "triggeringTx": "0x02f8...", "timestamp": 1710979200 } ``` | Field | Type | Description | | --- | --- | --- | | `chain` | string | Chain where the token launched | | `token` | string | Token contract address | | `type` | string | `block0` (detected in mempool before mining) or `block1` (detected in mined block) | | `blockNumber` | string | Block number at detection time | | `taxes.buyTaxBps` | number \| null | Buy tax in basis points (null if unknown) | | `taxes.sellTaxBps` | number \| null | Sell tax in basis points (null if unknown) | | `limits.buyLowerLimit` | string \| null | Minimum buy amount in wei (null if none) | | `limits.buyUpperLimit` | string \| null | Maximum buy amount in wei (null if none) | | `limits.sellLowerLimit` | string \| null | Minimum sell amount in wei (null if none) | | `limits.sellUpperLimit` | string \| null | Maximum sell amount in wei (null if none) | | `triggeringTx` | string \| null | RLP-serialized transaction that triggered the launch (block0 only) | | `timestamp` | number | Unix timestamp in seconds | ### Signal Types - **`block0`** — The token was detected as buyable from a pending mempool transaction _before_ it was mined. This gives you the earliest possible signal. The `triggeringTx` field contains the serialized liquidity-adding transaction. - **`block1`** — The token was detected as buyable in the first block after the liquidity transaction was mined. This is a fallback for cases where mempool detection was not possible. --- # Error Handling Source: http://localhost:3000/docs/errors.md Section: Reference # Error Handling The Chainworks API uses consistent error responses across all endpoints. --- ## Error Response Format When a request fails, you receive an error response: ```json { "success": false, "error": { "code": "ERROR_CODE", "message": "Human-readable error description" }, "partialResult": { // Optional: helpful data even when the request fails } } ``` The `partialResult` field may contain useful information even when the request fails, such as partial token data or pool information. --- ## Common Error Codes ### Connection Errors | Code | Description | Solution | | --- | --- | --- | | `UNAUTHORIZED` | Invalid or expired auth token | Check your API credentials | | `CONNECTION_TIMEOUT` | Server didn't respond in time | Retry the request | | `RATE_LIMITED` | Too many requests | Implement backoff and retry | ### Request Errors | Code | Description | Solution | | --- | --- | --- | | `INVALID_CHAIN` | Unsupported chain identifier | Use `eth`, `base`, `bsc`, or `sol` | | `INVALID_TOKEN` | Token address not found | Verify the token contract address | | `INVALID_WALLET` | Invalid wallet address format | Check the address format | | `INVALID_AMOUNT` | Amount is zero or negative | Provide a valid positive amount | | `MISSING_PARAMETER` | Required parameter not provided | Include all required parameters | ### Trading Errors | Code | Description | Solution | | --- | --- | --- | | `INSUFFICIENT_LIQUIDITY` | Not enough liquidity for trade | Reduce trade size or try later | | `PRICE_IMPACT_TOO_HIGH` | Trade would cause excessive slippage | Reduce trade size | | `TOKEN_NOT_TRADEABLE` | Token trading is restricted | Check token contract for restrictions | | `NO_ROUTE_FOUND` | No DEX route available | Token may not have liquidity | ### Transaction Errors | Code | Description | Solution | | --- | --- | --- | | `INSUFFICIENT_BALANCE` | Wallet lacks funds | Add funds to wallet | | `APPROVAL_REQUIRED` | Token approval needed | Call approve endpoint first | | `PERMIT_REQUIRED_FOR_V3_SELL` | V3 pool requires permit | Sign permit and include in request | | `TRANSACTION_SIMULATION_FAILED` | Transaction would revert | Check parameters and balances | | `NONCE_TOO_LOW` | Transaction nonce already used | Use a higher nonce | --- ## Handling Errors ### TypeScript ```typescript socket.on("/evm/buy/quote", (response) => { if (response.success) { console.log("Quote:", response.result); } else { const { code, message } = response.error; switch (code) { case "INSUFFICIENT_LIQUIDITY": console.log("Not enough liquidity. Try a smaller amount."); break; case "INVALID_TOKEN": console.log("Token not found. Check the address."); break; default: console.error(`Error ${code}: ${message}`); } // partialResult may contain useful info if (response.partialResult) { console.log("Partial data:", response.partialResult); } } }); ``` ### Python ```python @sio.on("/evm/buy/quote") def on_quote(response): if response.get("success"): print("Quote:", response["result"]) else: error = response["error"] code = error["code"] message = error["message"] if code == "INSUFFICIENT_LIQUIDITY": print("Not enough liquidity. Try a smaller amount.") elif code == "INVALID_TOKEN": print("Token not found. Check the address.") else: print(f"Error {code}: {message}") if "partialResult" in response: print("Partial data:", response["partialResult"]) ``` --- ## V3 Pool Permit Flow When selling tokens on UniswapV3-style pools, you may receive a `PERMIT_REQUIRED_FOR_V3_SELL` error: ```json { "success": false, "error": { "code": "PERMIT_REQUIRED_FOR_V3_SELL", "message": "V3 pool requires permit signature" }, "partialResult": { "hashToSign": "0x...", "prefix": "0x..." } } ``` **To resolve:** 1. Sign the `hashToSign` with your wallet 2. Concatenate `prefix + signature` 3. Retry with the `permit` field: ```typescript socket.emit("/evm/sell/transaction", { // ... same params as before permit: prefix + signature, }); ``` --- ## Retry Strategy For transient errors, implement exponential backoff: ```typescript async function requestWithRetry(path: string, params: object, maxRetries = 3): Promise { for (let attempt = 0; attempt < maxRetries; attempt++) { try { const response = await makeRequest(path, params); if (response.success) { return response.result; } // Don't retry certain errors const noRetry = ["INVALID_TOKEN", "INVALID_WALLET", "UNAUTHORIZED"]; if (noRetry.includes(response.error.code)) { throw new Error(response.error.message); } // Exponential backoff const delay = Math.pow(2, attempt) * 1000; await new Promise((resolve) => setTimeout(resolve, delay)); } catch (error) { if (attempt === maxRetries - 1) { throw error; } } } } ``` --- ## Debugging Tips 1. **Check the console** — Log full responses to see error details 2. **Use the playground** — Test requests interactively at [/playground](/playground) 3. **Validate addresses** — Ensure addresses are correct for the target chain 4. **Check token contract** — Some tokens have transfer restrictions 5. **Monitor connection** — Ensure WebSocket connection is stable --- ## Getting Help If you encounter persistent errors: 1. Note the error code and message 2. Capture the full request parameters 3. Contact us at [info@chainworks.co](mailto:info@chainworks.co)