# Api Overview Source: https://docs.dkit.xyz/api-overview Our API unifies top providers and protocols, giving you broad chain and token coverage without managing multiple integrations. It supports both cross-chain swaps and in-chain DEX aggregation, all with minimal setup. ## Cross-chain Swap Paths Seamless cross-chain swaps made simple. The table below lists **single-signature** paths.
{/* Bitcoin */} {/* Ethereum */} {/* Solana */} {/* Arbitrum */} {/* Base */} {/* BSC */} {/* AVAX */} {/* Ripple */} {/* Litecoin */} {/* Bitcoin Cash */} {/* Dogecoin */} {/* Cosmos */} {/* Dash */} {/* THORChain */} {/* MayaChain */} {/* Kujira */} {/* Polkadot */} {/* Radix */}
Source Chain Output Chains
Bitcoin (BTC)
SOLSOL ETHETH ARBARB BaseBase BSCBSC XRPXRP AVAXAVAX LTCLTC BCHBCH DOGEDOGE ATOMATOM DASHDASH THORTHOR MAYAMAYA KUJIKUJI DOTDOT XRDXRD
Ethereum (ETH)
BTCBTC SOLSOL ARBARB BaseBase BSCBSC XRPXRP AVAXAVAX LTCLTC BCHBCH DOGEDOGE ATOMATOM DASHDASH THORTHOR MAYAMAYA KUJIKUJI DOTDOT XRDXRD
Solana (SOL)
BTCBTC ETHETH ARBARB XRPXRP BaseBase DOTDOT
Arbitrum (ARB)
BTCBTC SOLSOL ETHETH XRPXRP DASHDASH THORTHOR MAYAMAYA KUJIKUJI DOTDOT XRDXRD
Base
BTCBTC ETHETH BSCBSC XRPXRP AVAXAVAX LTCLTC BCHBCH DOGEDOGE ATOMATOM DASHDASH THORTHOR
Binance Smart Chain (BSC)
BTCBTC ETHETH BaseBase XRPXRP AVAXAVAX LTCLTC BCHBCH DOGEDOGE ATOMATOM THORTHOR
Avalanche (AVAX)
BTCBTC ETHETH BaseBase BSCBSC XRPXRP LTCLTC BCHBCH DOGEDOGE ATOMATOM THORTHOR
Ripple (XRP)
BTCBTC ETHETH BaseBase BSCBSC AVAXAVAX LTCLTC BCHBCH DOGEDOGE ATOMATOM THORTHOR
Litecoin (LTC)
BTCBTC ETHETH BaseBase BSCBSC XRPXRP AVAXAVAX BCHBCH DOGEDOGE ATOMATOM THORTHOR
Bitcoin Cash (BCH)
BTCBTC ETHETH BaseBase BSCBSC XRPXRP AVAXAVAX LTCLTC DOGEDOGE ATOMATOM THORTHOR
Dogecoin (DOGE)
BTCBTC ETHETH BaseBase BSCBSC XRPXRP AVAXAVAX LTCLTC BCHBCH ATOMATOM THORTHOR
Cosmos (ATOM)
BTCBTC ETHETH BaseBase BSCBSC XRPXRP AVAXAVAX LTCLTC BCHBCH DOGEDOGE THORTHOR
Dash
BTCBTC ETHETH ARBARB THORTHOR MAYAMAYA KUJIKUJI XRDXRD
THORChain (RUNE)
BTCBTC ETHETH ARBARB BaseBase BSCBSC XRPXRP AVAXAVAX LTCLTC BCHBCH DOGEDOGE ATOMATOM DASHDASH MAYAMAYA KUJIKUJI XRDXRD
MayaChain (CACAO)
BTCBTC ETHETH ARBARB DASHDASH THORTHOR KUJIKUJI XRDXRD
Kujira (KUJI)
BTCBTC ETHETH ARBARB DASHDASH THORTHOR MAYAMAYA XRDXRD
Polkadot (DOT)
BTCBTC SOLSOL ETHETH ARBARB
Radix (XRD)
BTCBTC ETHETH ARBARB DASHDASH THORTHOR MAYAMAYA KUJIKUJI
*** ## πŸ› οΈ How to Use the API Getting started with **dKit** is quick and straightforward. Here’s the recommended workflow:

Endpoint: /providers

Returns all providers and the chains they support.

Endpoint: /tokens

Retrieves the complete list of tokens across all chains and providers.

Endpoint: /quote

Get real-time swap prices, required parameters, and estimated fees/slippage before execution.

Endpoint: /track

Monitor swap progress in real-time and retrieve completion status.

Configure affiliate streaming. See Revenue Generation for setup.

*** ### ⚑ Pro Tip Once you’re familiar with dKit, you can skip steps 1 and 2 for faster development. Cache /providers and /tokens, then go straight to requesting quotes. # API Versioning & Deprecation Source: https://docs.dkit.xyz/api-reference/api-versioning Learn about our API versioning strategy and deprecation policy to ensure smooth migrations. ## API Versioning Our API uses versioning to ensure backward compatibility while introducing new features and improvements. Understanding our versioning approach helps you build resilient integrations. ### Current Version The dKit API is currently at version **v1**. All endpoints use the version prefix in the URL path: * `https://api.dkit.xyz/v1/quote` * `https://api.dkit.xyz/v1/track` * `https://api.dkit.xyz/v1/tokens` * `https://api.dkit.xyz/v1/providers` ### Version Headers API responses include version information in custom headers: | Header | Description | Example | | ---------------- | ---------------------- | ------- | | `x-api-version` | Current API version | `v1` | | `x-api-versions` | Available API versions | `v1` | *** ## Deprecation Policy We follow a structured deprecation process to give developers ample time to migrate to newer API versions when they become available. ### Deprecation Notifications When an API version is scheduled for deprecation, we will: 1. **Announce** the deprecation at least 6 months in advance 2. **Include deprecation headers** in API responses 3. **Provide migration guides** and documentation 4. **Send notifications** to registered developers ### Planned Deprecation Headers When deprecation is active, API responses will include: ```http HTTP/1.1 200 OK Warning: 299 - "This API version is deprecated and will be removed soon" x-api-deprecated: true x-api-sunset-date: 2026-06-01T00:00:00Z ``` | Header | Description | | ------------------- | ------------------------------------------- | | `Warning` | HTTP standard deprecation notice (code 299) | | `x-api-deprecated` | Boolean indicating deprecation status | | `x-api-sunset-date` | ISO 8601 date when version will be removed | *** ## Sunset Timeline Our standard deprecation timeline ensures you have sufficient time to migrate:

Duration: 6 months before deprecation

New version released, documentation updated, migration guides published

Duration: 6-12 months

API marked as deprecated, warning headers included in responses

Duration: 30 days before removal

Final notices sent, increased warning visibility

API version removed, requests return 410 Gone status

*** ## Handling Deprecation ### Best Practices ```javascript // Check for deprecation warnings fetch('https://api.dkit.xyz/v1/quote', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(quoteRequest) }) .then(response => { // Check deprecation status when available if (response.headers.get('x-api-deprecated') === 'true') { const sunsetDate = response.headers.get('x-api-sunset-date'); console.warn(`API v1 is deprecated. Sunset date: ${sunsetDate}`); // Trigger migration workflow } // Check for warning header const warning = response.headers.get('Warning'); if (warning && warning.includes('299')) { console.warn(`API Warning: ${warning}`); } return response.json(); }); ``` ```javascript // Handle version-specific errors async function makeApiRequest(endpoint, params) { try { const response = await fetch( `https://api.dkit.xyz/v1/${endpoint}`, params ); if (!response.ok) { // Handle 410 Gone for sunset versions if (response.status === 410) { throw new Error('API version has been sunset'); } throw new Error(`API error: ${response.status}`); } // Log any deprecation warnings const deprecated = response.headers.get('x-api-deprecated'); if (deprecated === 'true') { console.warn('Using deprecated API version'); } return response.json(); } catch (error) { console.error('API request failed:', error); throw error; } } ``` ```javascript // Track API version information class ApiVersionManager { constructor() { this.currentVersion = 'v1'; this.deprecationStatus = null; } async checkVersion() { const response = await fetch('https://api.dkit.xyz/v1/providers'); // Store version info from headers this.currentVersion = response.headers.get('x-api-version') || 'v1'; this.deprecationStatus = { isDeprecated: response.headers.get('x-api-deprecated') === 'true', sunsetDate: response.headers.get('x-api-sunset-date'), warning: response.headers.get('Warning') }; return this.deprecationStatus; } getVersionedUrl(endpoint) { return `https://api.dkit.xyz/${this.currentVersion}/${endpoint}`; } } ``` ### Migration Strategy 1. **Early Detection**: Monitor deprecation headers in your production environment 2. **Gradual Migration**: Test new versions in staging before production deployment 3. **Feature Flags**: Use feature flags to switch between API versions 4. **Monitoring**: Track API version usage and deprecation warnings in your logs *** ## Version Compatibility ### Breaking Changes Breaking changes are only introduced in major version updates (e.g., v1 β†’ v2): * Removed endpoints * Changed required parameters * Modified response structures * Authentication changes ### Non-Breaking Changes These changes can occur within the same version: * New optional parameters * Additional response fields * New endpoints * Performance improvements * Bug fixes *** ## Example Response A deprecated API response will look like: ```http HTTP/1.1 200 OK Content-Type: application/json Warning: 299 - "This API version is deprecated and will be removed soon" x-api-version: v1 x-api-versions: v1, v2 x-api-deprecated: true x-api-sunset-date: 2026-06-01T00:00:00Z Date: Mon, 01 Dec 2025 12:00:00 GMT ... ``` *** ## Notifications Stay informed about API changes: * **GitHub**: Follow our [GitHub repository](https://github.com/el-Dorado-Market) for updates * **Support**: Contact [team@dkit.xyz](mailto:team@dkit.xyz) for migration assistance * **Status Page**: Check [dkit.instatus.com](https://dkit.instatus.com) for announcements **Important**: Always implement proper error handling to ensure your integration remains robust. # Get Quote Source: https://docs.dkit.xyz/api-reference/core-endpoints/get-quote api-reference/openapi.json post /v1/quote Returns available swap routes for the given sell and buy assets. # Track Swap Source: https://docs.dkit.xyz/api-reference/core-endpoints/track-swap api-reference/openapi.json post /v1/track Track the status of a swap via a route from the quote endpoint. # Get Connected Assets Source: https://docs.dkit.xyz/api-reference/data-endpoints/get-connected-assets api-reference/openapi.json get /v1/connected-assets Returns assets that can be swapped with the given sell asset # Get Networks Graph Source: https://docs.dkit.xyz/api-reference/data-endpoints/get-networks-graph api-reference/openapi.json get /v1/networks-graph Returns supported networks and their connections # Get pool rates Source: https://docs.dkit.xyz/api-reference/data-endpoints/get-pool-rates api-reference/openapi.json get /v1/poolrates Returns pool rates in stables (median USDT/USDC price) # Get Providers Source: https://docs.dkit.xyz/api-reference/data-endpoints/get-providers api-reference/openapi.json get /v1/providers Returns information about all supported swap providers # Get tokens Source: https://docs.dkit.xyz/api-reference/data-endpoints/get-tokens api-reference/openapi.json get /v1/tokens Returns list of supported tokens, optionally filtered by provider # Quickstart Source: https://docs.dkit.xyz/api-reference/quickstart Complete a cross-chain swap in 3 steps This quickstart guide walks you through performing a cross-chain swap using the dKit API. We'll swap ETH on Ethereum to BTC on Bitcoin via THORChain as an example. Make sure you have your wallet connected and funded with the asset you want to swap. ## Step 1: Get a Quote First, get available routes and pricing for your swap. The quote endpoint will return the best available routes across all integrated DEXs. ```bash curl --location 'https://api.dkit.xyz/v1/quote' \ --header 'Content-Type: application/json' \ --header 'x-api-key: 86c3fc76-25c8-455c-8d6d-0ecea88d0f6e' \ --data '{ "sellAsset": "ETH.ETH", "sellAmount": "0.5", "buyAsset": "BTC.BTC", "slippage": 3, "affiliate": "dkit", "affiliateFee": 50, "includeTx": true, "providers": [ "THORCHAIN" ], "sourceAddress": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb7", "destinationAddress": "bc1qns9f7yfx3ry9lj6yz7c9er0vwa0ye2eklpzqfw" }' ``` ```javascript const getQuote = async () => { const response = await fetch('https://api.dkit.xyz/v1/quote', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': '86c3fc76-25c8-455c-8d6d-0ecea88d0f6e' }, body: JSON.stringify({ sellAsset: 'ETH.ETH', sellAmount: '0.5', buyAsset: 'BTC.BTC', slippage: 3, affiliate: 'dkit', affiliateFee: 50, includeTx: true, providers: ['THORCHAIN'], sourceAddress: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb7', destinationAddress: 'bc1qns9f7yfx3ry9lj6yz7c9er0vwa0ye2eklpzqfw' }) }); const quote = await response.json(); console.log('Best route:', quote.routes[0]); return quote.routes[0]; // Use the best route }; ``` ```python import requests import json def get_quote(): url = "https://api.dkit.xyz/v1/quote" headers = { 'Content-Type': 'application/json', 'x-api-key': '86c3fc76-25c8-455c-8d6d-0ecea88d0f6e' } payload = { 'sellAsset': 'ETH.ETH', 'sellAmount': '0.5', 'buyAsset': 'BTC.BTC', 'slippage': 3, 'affiliate': 'dkit', 'affiliateFee': 50, 'includeTx': True, 'providers': ['THORCHAIN'], 'sourceAddress': '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb7', 'destinationAddress': 'bc1qns9f7yfx3ry9lj6yz7c9er0vwa0ye2eklpzqfw' } response = requests.post(url, headers=headers, json=payload) quote = response.json() best_route = quote['routes'][0] print(f"Best route via: {best_route['providers']}") print(f"Expected output: {best_route['expectedBuyAmount']} BTC") return best_route ``` The `quoteId` and `routeIndex` of the response are used to fetch the status of the swap via the `/track` endpoint and return rich information on the route. ```json { "quoteId": "a7c4b3ef-51d2-4c78-b8e1-8b3e12f7a6d9", "routes": [ { "buyAsset": "BTC.BTC", "destinationAddress": "bc1qns9f7yfx3ry9lj6yz7c9er0vwa0ye2eklpzqfw", "estimatedTime": { "inbound": 600, "swap": 6, "outbound": 600, "total": 1206 }, "expectedBuyAmount": "0.02145678", "expectedBuyAmountMaxSlippage": "0.02081307", "expiration": "1754920807", "fees": [ { "type": "liquidity", "amount": "1245", "asset": "BTC.BTC", "chain": "THOR", "protocol": "THORCHAIN" }, { "type": "outbound", "amount": "15000", "asset": "BTC.BTC", "chain": "BTC", "protocol": "THORCHAIN" }, { "type": "affiliate", "amount": "10728", "asset": "BTC.BTC", "chain": "THOR", "protocol": "THORCHAIN" }, { "type": "inbound", "amount": "0", "asset": "ETH.ETH", "chain": "ETH", "protocol": "THORCHAIN" } ], "inboundAddress": "0x8c7c3f4e8b1d3a4e5c9f2b6a7d9e1f3c5b8a2d6e", "legs": [ { "provider": "THORCHAIN", "sellAsset": "ETH.ETH", "sellAmount": "0.5", "buyAsset": "BTC.BTC", "buyAmount": "0.02145678", "buyAmountMaxSlippage": "0.02081307", "fees": [ { "type": "liquidity", "amount": "1245", "asset": "BTC.BTC", "chain": "THOR", "protocol": "THORCHAIN" }, { "type": "outbound", "amount": "15000", "asset": "BTC.BTC", "chain": "BTC", "protocol": "THORCHAIN" }, { "type": "affiliate", "amount": "10728", "asset": "BTC.BTC", "chain": "THOR", "protocol": "THORCHAIN" }, { "type": "inbound", "amount": "0", "asset": "ETH.ETH", "chain": "ETH", "protocol": "THORCHAIN" } ] } ], "memo": "=:BTC.BTC:bc1qns9f7yfx3ry9lj6yz7c9er0vwa0ye2eklpzqfw:2081307:dkit:50", "meta": { "priceImpact": 0.12, "assets": [ { "asset": "ETH.ETH", "price": 3450.25, "image": "https://crispy.sfo3.cdn.digitaloceanspaces.com/eth.eth.png" }, { "asset": "BTC.BTC", "price": 67890.50, "image": "https://crispy.sfo3.cdn.digitaloceanspaces.com/btc.btc.png" } ], "affiliate": "dkit", "affiliateFee": 50, "tags": [], "txType": "EVM" }, "providers": [ "THORCHAIN" ], "sellAmount": "0.5", "sellAsset": "ETH.ETH", "sourceAddress": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb7", "totalSlippageBps": 300, "warnings": [] } ] } ``` ## Step 2: Execute the Swap Use the quote information to submit your transaction on-chain. For this ETH to BTC swap via THORChain, you'll send ETH to the inbound address with the memo. ```javascript import { ethers } from 'ethers'; const executeSwap = async (route) => { // Connect to wallet (MetaMask, WalletConnect, etc.) const provider = new ethers.providers.Web3Provider(window.ethereum); const signer = provider.getSigner(); // For THORChain swaps: send ETH to inbound address with memo const tx = { to: route.inboundAddress, value: ethers.utils.parseEther(route.sellAmount), // Convert 0.5 ETH to wei data: ethers.utils.toUtf8Bytes(route.memo), gasLimit: 100000 }; const txResponse = await signer.sendTransaction(tx); console.log('Transaction sent:', txResponse.hash); // Wait for transaction confirmation const receipt = await txResponse.wait(); console.log('Transaction confirmed in block:', receipt.blockNumber); return txResponse.hash; }; // Execute using the route from Step 1 const route = await getQuote(); const txHash = await executeSwap(route); ``` Always verify the `targetAddress` or `inboundAddress` matches what the quote returned before sending funds. ## Step 3: Track Your Swap Monitor the progress of your swap until completion. The swap tracking endpoint accepts the `quoteId` and `routeIndex` from the quote response and provides real-time status updates with rich route information. ```bash curl --location 'https://api.dkit.xyz/v1/track' \ --header 'content-type: application/json' \ --header 'x-api-key: 86c3fc76-25c8-455c-8d6d-0ecea88d0f6e' \ --data '{ "hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", "chainId": "ethereum", "quoteId": "a7c4b3ef-51d2-4c78-b8e1-8b3e12f7a6d9", "routeIndex": 0 }' ``` ```javascript const trackSwap = async (hash, chainId, quoteId, routeIndex) => { const response = await fetch('https://api.dkit.xyz/v1/track', { method: 'POST', headers: { 'content-type': 'application/json', 'x-api-key': '86c3fc76-25c8-455c-8d6d-0ecea88d0f6e' }, body: JSON.stringify({ hash: hash, chainId: chainId, quoteId: quoteId, routeIndex: routeIndex }) }); const status = await response.json(); return status; }; // Poll for updates const pollSwapStatus = async (hash, chainId, quoteId, routeIndex) => { let isComplete = false; while (!isComplete) { const status = await trackSwap(hash, chainId, quoteId, routeIndex); console.log(`Status: ${status.trackingStatus}`); console.log(`Stage: ${status.stage}`); if (status.trackingStatus === 'completed') { console.log('Swap completed!'); console.log(`BTC output tx: ${status.data.outbound?.hash}`); isComplete = true; } else if (status.trackingStatus === 'failed' || status.trackingStatus === 'refunded') { console.error('Swap failed or refunded:', status.error); isComplete = true; } // Wait 10 seconds before next check if (!isComplete) { await new Promise(resolve => setTimeout(resolve, 10000)); } } }; // Track the swap from Step 2 (use actual values from your transaction) await pollSwapStatus( txHash, // from Step 2 'ethereum', 'a7c4b3ef-51d2-4c78-b8e1-8b3e12f7a6d9', // from Step 1 quote response 0 ); ``` ```python import time import requests def track_swap(hash, chain_id, quote_id, route_index): url = "https://api.dkit.xyz/v1/track" headers = { 'content-type': 'application/json', 'x-api-key': '86c3fc76-25c8-455c-8d6d-0ecea88d0f6e' } payload = { "hash": hash, "chainId": chain_id, "quoteId": quote_id, "routeIndex": route_index } response = requests.post(url, headers=headers, json=payload) return response.json() def poll_swap_status(hash, chain_id, quote_id, route_index): """Poll swap status until completion""" while True: status = track_swap(hash, chain_id, quote_id, route_index) print(f"Status: {status['trackingStatus']}") print(f"Stage: {status.get('stage', 'N/A')}") if status['trackingStatus'] == 'completed': print('Swap completed!') if 'data' in status and 'outbound' in status['data']: print(f"BTC output tx: {status['data']['outbound'].get('hash')}") break elif status['trackingStatus'] in ['failed', 'refunded']: print(f"Swap failed or refunded: {status.get('error', 'Unknown error')}") break # Wait 10 seconds before next check time.sleep(10) return status # Example usage (use actual values from your transaction) final_status = poll_swap_status( "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", "ethereum", "a7c4b3ef-51d2-4c78-b8e1-8b3e12f7a6d9", 0 ) ``` ```json { "success": true, "trackingStatus": "completed", "stage": "outbound", "data": { "quoteInfo": { "quoteId": "a7c4b3ef-51d2-4c78-b8e1-8b3e12f7a6d9", "routeIndex": 0, "senderAddress": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb7", "recipientAddress": "bc1qns9f7yfx3ry9lj6yz7c9er0vwa0ye2eklpzqfw", "provider": "THORCHAIN", "trackParams": { "hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", "chainId": "ethereum" } }, "inbound": { "hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", "amount": "0.5", "asset": "ETH.ETH", "confirmations": 12, "blockNumber": 18765432 }, "swap": { "swapId": "ABC123DEF456", "status": "success", "swapTime": 8 }, "outbound": { "hash": "3f2329b4d5e6c8a9f1b7d4c5e6f8a9b0c1d2e3f4567890abcdef1234567890ab", "amount": "0.02081307", "asset": "BTC.BTC", "confirmations": 2, "blockNumber": 823456 }, "route": { "fees": [ { "type": "liquidity", "asset": "BTC.BTC", "chain": "THOR", "amount": "1245", "protocol": "THORCHAIN" }, { "type": "outbound", "asset": "BTC.BTC", "chain": "BTC", "amount": "15000", "protocol": "THORCHAIN" }, { "type": "affiliate", "asset": "BTC.BTC", "chain": "THOR", "amount": "10728", "protocol": "THORCHAIN" } ], "legs": [ { "provider": "THORCHAIN", "sellAsset": "ETH.ETH", "sellAmount": "0.5", "buyAsset": "BTC.BTC", "buyAmount": "0.02081307", "actualBuyAmount": "0.02081307" } ], "memo": "=:BTC.BTC:bc1qns9f7yfx3ry9lj6yz7c9er0vwa0ye2eklpzqfw:2081307:dkit:50", "meta": { "assets": [ { "asset": "ETH.ETH", "image": "https://crispy.sfo3.cdn.digitaloceanspaces.com/eth.eth.png", "price": 3450.25 }, { "asset": "BTC.BTC", "image": "https://crispy.sfo3.cdn.digitaloceanspaces.com/btc.btc.png", "price": 67890.50 } ], "txType": "EVM", "affiliate": "dkit", "priceImpact": 0.12, "affiliateFee": 50 }, "buyAsset": "BTC.BTC", "providers": ["THORCHAIN"], "sellAsset": "ETH.ETH", "sellAmount": "0.5", "actualBuyAmount": "0.02081307", "expectedBuyAmount": "0.02145678", "sourceAddress": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb7", "destinationAddress": "bc1qns9f7yfx3ry9lj6yz7c9er0vwa0ye2eklpzqfw", "inboundAddress": "0x8c7c3f4e8b1d3a4e5c9f2b6a7d9e1f3c5b8a2d6e", "totalSlippageBps": 300 } } } ``` Congratulations! You've completed your first cross-chain swap with dKit. ## What's Next? * [**Quote Endpoint**](/api-reference/endpoints/quote) - Detailed quote parameters and options * [**Track Endpoint**](/api-reference/endpoints/track) - Advanced tracking features * [**Supported Assets**](/api-reference/endpoints/tokens-new) - Browse all available tokens * [**Fee Structure**](/essentials/fees) - Understand fee breakdowns # Create Chainflip deposit channel Source: https://docs.dkit.xyz/api-reference/service-endpoints/create-chainflip-deposit-channel api-reference/openapi.json post /v1/chainflip-deposit-channel Creates a broker deposit channel for a Chainflip swap. # Track Transaction Source: https://docs.dkit.xyz/api-reference/service-endpoints/track-transaction api-reference/openapi.json post /v1/track-tx Track the status of a transaction # Asset Notation Source: https://docs.dkit.xyz/essentials/asset-notation Understanding how assets are identified in the dKit API ## Overview dKit uses a standardized notation system to identify assets across different blockchains. This ensures consistency and clarity when specifying assets for swaps. ## Asset Format Assets are identified using one of two formats: ### Native Assets ``` CHAIN.SYMBOL ``` Native blockchain assets (gas tokens) use a simple format with the chain identifier and symbol. **Examples:** * `ETH.ETH` - Native Ethereum * `BTC.BTC` - Native Bitcoin * `SOL.SOL` - Native Solana * `AVAX.AVAX` - Native Avalanche * `THOR.RUNE` - THORChain's native RUNE ### Tokens ``` CHAIN.SYMBOL-ADDRESS ``` Non-native tokens include the contract address to ensure uniqueness. **Examples:** * `ETH.USDC-0XA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48` - USDC on Ethereum * `ARB.USDC-0XAF88D065E77C8CC2239327C5EDB3A432268E5831` - USDC on Arbitrum * `ETH.WBTC-0X2260FAC5E5542A773AA44FBCFEDF7C193BC2C599` - Wrapped Bitcoin on Ethereum * `SOL.USDC-EPJFWDD5AUFQSSQEM2QN1XZYBAPC8G4WEGGKZWYTDT1V` - USDC on Solana ## Chain Identifiers Common chain identifiers used in the API: | Chain | Identifier | Example Asset | | ------------------- | ---------- | ------------- | | Arbitrum | `ARB` | `ARB.ETH` | | Avalanche | `AVAX` | `AVAX.AVAX` | | Base | `BASE` | `BASE.ETH` | | Binance Smart Chain | `BSC` | `BSC.BNB` | | Bitcoin | `BTC` | `BTC.BTC` | | Bitcoin Cash | `BCH` | `BCH.BCH` | | Cosmos | `GAIA` | `GAIA.ATOM` | | Dash | `DASH` | `DASH.DASH` | | Dogecoin | `DOGE` | `DOGE.DOGE` | | Ethereum | `ETH` | `ETH.ETH` | | Kujira | `KUJI` | `KUJI.KUJI` | | Litecoin | `LTC` | `LTC.LTC` | | Maya Protocol | `MAYA` | `MAYA.CACAO` | | Polkadot | `DOT` | `DOT.DOT` | | Solana | `SOL` | `SOL.SOL` | | THORChain | `THOR` | `THOR.RUNE` | ## Special Cases ### Synthetic Assets THORChain and MayaChain support synthetic assets that represent assets from other chains: * `THOR.BTC` - Synthetic Bitcoin on THORChain * `THOR.ETH` - Synthetic Ethereum on THORChain * `MAYA.BTC` - Synthetic Bitcoin on MayaChain ### Layer 2 Networks Layer 2 networks have their own chain identifiers: * `ARB.ETH` - Native ETH on Arbitrum * `BASE.ETH` - Native ETH on Base * `OP.ETH` - Native ETH on Optimism ### Wrapped Assets Wrapped assets maintain the original asset symbol but include the wrapper contract address: * `ETH.WBTC-0X2260FAC5E5542A773AA44FBCFEDF7C193BC2C599` - Wrapped Bitcoin * `ETH.WETH-0XC02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2` - Wrapped Ethereum ## Address Formats Different chains use different address formats: ```javascript EVM // Ethereum and EVM-compatible chains // 42-character hex string starting with 0x const evmAddress = "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb8" // Token addresses are also 42-character hex strings const usdcAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" ``` ```javascript Bitcoin // Bitcoin addresses (multiple formats supported) // Legacy (P2PKH) const legacyAddress = "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa" // SegWit (P2WPKH) const segwitAddress = "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh" // Taproot (P2TR) const taprootAddress = "bc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr" ``` ```javascript Solana // Solana uses Base58 encoded addresses const solanaAddress = "7VJsBtJzgTftYzEeooSDYyjKXvYRWJHdwvbwfBvTg9K" // SPL token addresses are also Base58 const splTokenMint = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" ``` ```javascript Cosmos // Cosmos ecosystem uses Bech32 addresses const cosmosAddress = "cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x" const thorchainAddress = "thor1vx8knpllrj7n963p9ttd80w47kpacrhuts497x" const mayaAddress = "maya1vx8knpllrj7n963p9ttd80w47kpacrhuts497x" ``` ## Asset Discovery ### Finding Available Assets Use the `/tokens` endpoint to discover available assets: ```javascript // Get all available tokens const response = await fetch('https://api.dkit.xyz/v1/tokens'); const tokenLists = await response.json(); // Get tokens for a specific provider const thorchainTokens = await fetch('https://api.dkit.xyz/v1/tokens?provider=THORCHAIN'); ``` ### Checking Asset Connectivity Use the `/connected-assets` endpoint to find what assets can be swapped: ```javascript // Find all assets that can be swapped from ETH const response = await fetch('https://api.dkit.xyz/v1/connected-assets?asset_id=ETH.ETH'); const connectedAssets = await response.json(); // Returns object with asset IDs as keys // { // "BTC.BTC": 1, // "SOL.SOL": 1, // "ETH.USDC-0XA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48": 1, // ... // } ``` ## Best Practices ### 1. Case Sensitivity Chain and symbol identifiers are case-sensitive. Always use uppercase: ```javascript // βœ… Correct "ETH.USDC-0XA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48" // ❌ Incorrect "eth.usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" ``` ### 2. Address Validation Always validate addresses before making requests: ```javascript const isValidEVMAddress = (address) => { return /^0x[a-fA-F0-9]{40}$/i.test(address); }; const isValidBitcoinAddress = (address) => { // Simplified check - use proper library in production return /^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,87}$/.test(address); }; ``` ### 3. Token Disambiguation Always use the full identifier with address for tokens to avoid ambiguity: ```javascript // ❌ Ambiguous - USDC exists on multiple chains "ETH.USDC" // βœ… Specific "ETH.USDC-0XA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48" ``` ### 4. Chain-Asset Compatibility Ensure the asset belongs to the specified chain: ```javascript // βœ… Correct - BTC on Bitcoin network "BTC.BTC" // ❌ Incorrect - BTC doesn't exist natively on Ethereum "ETH.BTC" // βœ… Correct - Wrapped BTC on Ethereum "ETH.WBTC-0X2260FAC5E5542A773AA44FBCFEDF7C193BC2C599" ``` ## Common Patterns ### Cross-Chain Swaps ```javascript // Swap native Bitcoin to native Ethereum { sellAsset: "BTC.BTC", buyAsset: "ETH.ETH" } // Swap Ethereum USDC to Solana USDC { sellAsset: "ETH.USDC-0XA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48", buyAsset: "SOL.USDC-EPJFWDD5AUFQSSQEM2QN1XZYBAPC8G4WEGGKZWYTDT1V" } ``` ### Same-Chain Swaps ```javascript // Swap ETH to USDC on Ethereum { sellAsset: "ETH.ETH", buyAsset: "ETH.USDC-0XA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48" } // Swap between tokens on Arbitrum { sellAsset: "ARB.USDC-0XAF88D065E77C8CC2239327C5EDB3A432268E5831", buyAsset: "ARB.USDT-0XFD086BC7CD5C481DCC9C85EBE478A1C0B69FCBB9" } ``` ### Using Synthetic Assets ```javascript // Swap to synthetic BTC on THORChain (faster, lower fees) { sellAsset: "ETH.ETH", buyAsset: "THOR.BTC" } // Swap from synthetic back to native { sellAsset: "THOR.BTC", buyAsset: "BTC.BTC" } ``` # Fees Source: https://docs.dkit.xyz/essentials/fees Understanding fee structures across different providers ## Overview Every swap involves various fees that affect the final output amount. dKit provides transparent fee breakdowns to help you understand the true cost of each route. ## Fee Types ### Network Fees (Gas) Blockchain transaction fees paid to validators/miners. **Fee Structure:** Sats per byte **Typical Cost:** \$2-20 per transaction **Factors:** Network congestion, transaction size ```javascript { "type": "NETWORK", "amount": "50000", // 0.0005 BTC "asset": "BTC.BTC", "chain": "BTC", "protocol": "BITCOIN" } ``` **Fee Structure:** Base fee + priority fee **Typical Cost:** \$5-50 per transaction **Factors:** Network activity, transaction complexity ```javascript { "type": "NETWORK", "amount": "5000000000000000", // 0.005 ETH "asset": "ETH.ETH", "chain": "ETH", "protocol": "ETHEREUM" } ``` **Fee Structure:** Fixed fee per signature **Typical Cost:** \$0.00025 per transaction **Factors:** Number of signatures, priority fees ```javascript { "type": "NETWORK", "amount": "5000", // 0.000005 SOL "asset": "SOL.SOL", "chain": "SOL", "protocol": "SOLANA" } ``` ### Protocol Fees Fees charged by the swap protocol for facilitating the trade. | Provider | Fee Structure | Typical Rate | | --------- | ------------------------------ | ------------ | | THORChain | Dynamic based on network costs | 0.2-0.5% | | Chainflip | Fixed percentage | 0.1-0.3% | | MayaChain | Similar to THORChain | 0.2-0.5% | | Jupiter | Varies by route | 0.0-0.3% | | 1inch | Positive slippage capture | 0.0-0.1% | **Example:** ```javascript { "type": "PROTOCOL", "amount": "1000000", // Amount in asset units "asset": "ETH.ETH", "chain": "ETH", "protocol": "THORCHAIN" } ``` ### Liquidity Provider Fees Compensation for liquidity providers who enable the swap. ```javascript { "type": "LIQUIDITY", "amount": "3000000", // 0.3% of swap amount "asset": "ETH.USDC", "chain": "ETH", "protocol": "UNISWAP" } ``` **Typical LP Fees:** * Stablecoin pairs: 0.01-0.05% * Major pairs: 0.05-0.3% * Exotic pairs: 0.3-1% ### Affiliate Fees Optional fees for integrators and affiliates. ```javascript { "type": "AFFILIATE", "amount": "1000000", // Custom basis points "asset": "BTC.BTC", "chain": "BTC", "protocol": "THORCHAIN" } ``` **Setting Affiliate Fees:** ```javascript const quote = await getQuote({ sellAsset: "BTC.BTC", buyAsset: "ETH.ETH", sellAmount: "1.0", affiliate: "myAffiliate", // THORName or address affiliateFee: 100 // 100 basis points = 1% }); ``` ### Tax Fees Fees for tokens with built-in taxation mechanisms. ```javascript { "type": "TAX", "amount": "5000000", // Token's tax amount "asset": "ETH.TAXTOKEN", "chain": "ETH", "protocol": "TOKEN_CONTRACT" } ``` ## Fee Calculation Examples ### Simple Swap Fee Breakdown ETH to USDC swap on Ethereum: ```javascript const fees = [ { type: "NETWORK", amount: "5000000000000000", // 0.005 ETH gas asset: "ETH.ETH", chain: "ETH" }, { type: "LIQUIDITY", amount: "3000000", // 3 USDC (0.3% of 1000 USDC) asset: "ETH.USDC", chain: "ETH" } ]; // Total cost: 0.005 ETH + 3 USDC ``` ### Cross-Chain Swap Fees BTC to ETH via THORChain: ```javascript const fees = [ { type: "NETWORK", amount: "50000", // BTC network fee asset: "BTC.BTC", chain: "BTC" }, { type: "PROTOCOL", amount: "200000", // THORChain fee (0.2%) asset: "BTC.BTC", chain: "THOR" }, { type: "LIQUIDITY", amount: "100000000000000", // LP fee in ETH asset: "ETH.ETH", chain: "THOR" }, { type: "NETWORK", amount: "3000000000000000", // ETH outbound fee asset: "ETH.ETH", chain: "ETH" } ]; ``` ## Fee Optimization Strategies ### 1. Provider Selection Compare total fees across providers: ```javascript const compareFees = (routes) => { return routes.map(route => { const totalFees = route.fees.reduce((sum, fee) => { // Convert all fees to USD for comparison const feeUSD = convertToUSD(fee.amount, fee.asset); return sum + feeUSD; }, 0); return { provider: route.providers[0], totalFeesUSD: totalFees, outputAmount: route.expectedBuyAmount }; }).sort((a, b) => a.totalFeesUSD - b.totalFeesUSD); }; ``` ### 2. Timing Optimization Execute swaps during low-fee periods: ```javascript const getOptimalTiming = async () => { // Check gas prices for EVM chains const gasPrice = await getGasPrice('ETH'); if (gasPrice.fast > 100) { // Gwei return { recommendation: 'WAIT', reason: 'High network congestion', estimatedSavings: calculateSavings(gasPrice) }; } return { recommendation: 'EXECUTE', currentFees: gasPrice.standard }; }; ``` ### 3. Batching Strategies Combine multiple swaps to amortize fixed fees: ```javascript const shouldBatchSwaps = (swaps) => { const individualCost = swaps.reduce((sum, swap) => { return sum + estimateNetworkFee(swap); }, 0); const batchedCost = estimateBatchNetworkFee(swaps); return { shouldBatch: batchedCost < individualCost, savings: individualCost - batchedCost }; }; ``` ### 4. Route Optimization Choose routes that minimize fee layers: ```javascript const optimizeForFees = (routes) => { return routes.map(route => { const feeEfficiency = route.expectedBuyAmount / getTotalFees(route); return { ...route, feeEfficiency, recommendation: feeEfficiency > 100 ? 'GOOD' : 'EXPENSIVE' }; }).sort((a, b) => b.feeEfficiency - a.feeEfficiency); }; ``` ## Streaming Swap Fees THORChain streaming swaps have unique fee characteristics: ```javascript // Regular swap (single transaction) const regularFees = { network: "50000", // One network fee protocol: "200000", // Standard protocol fee liquidity: "300000" // Higher slippage }; // Streaming swap (multiple sub-swaps) const streamingFees = { network: "50000", // Still one network fee protocol: "200000", // Same protocol fee liquidity: "150000" // Lower slippage due to smaller chunks }; // Streaming is beneficial for large swaps despite longer time ``` ## Fee Estimation ### Pre-Quote Estimation Estimate fees before requesting quotes: ```javascript const estimateFees = (sellAsset, buyAsset, amount) => { const estimates = { network: estimateNetworkFee(sellAsset.split('.')[0]), protocol: amount * 0.003, // ~0.3% average liquidity: amount * 0.003, // ~0.3% average total: 0 }; estimates.total = estimates.network + estimates.protocol + estimates.liquidity; return estimates; }; ``` ### Dynamic Fee Updates Monitor fee changes in real-time: ```javascript const monitorFees = async () => { const feeWatcher = setInterval(async () => { const currentFees = await getCurrentFees(); if (hasSignificantChange(currentFees, lastFees)) { // Re-quote if fees changed significantly await refreshQuote(); } lastFees = currentFees; }, 30000); // Check every 30 seconds }; ``` ## Fee Display Best Practices ### 1. Transparent Breakdown Always show users complete fee information: ```javascript const displayFees = (route) => { const breakdown = { 'Network Fees': formatFee(route.fees.filter(f => f.type === 'NETWORK')), 'Protocol Fees': formatFee(route.fees.filter(f => f.type === 'PROTOCOL')), 'LP Fees': formatFee(route.fees.filter(f => f.type === 'LIQUIDITY')), 'Affiliate Fees': formatFee(route.fees.filter(f => f.type === 'AFFILIATE')), 'Total Fees': formatFee(route.fees) }; return breakdown; }; ``` ### 2. Relative Fee Display Show fees as percentage of swap amount: ```javascript const calculateFeePercentage = (fees, swapAmount) => { const totalFeeValue = fees.reduce((sum, fee) => { return sum + convertToBaseAsset(fee.amount, fee.asset); }, 0); return (totalFeeValue / swapAmount * 100).toFixed(2) + '%'; }; ``` ### 3. Fee Impact Visualization Help users understand fee impact: ```javascript const visualizeFeeImpact = (route) => { const inputValue = convertToUSD(route.sellAmount, route.sellAsset); const outputValue = convertToUSD(route.expectedBuyAmount, route.buyAsset); const feeValue = inputValue - outputValue; return { inputUSD: inputValue, outputUSD: outputValue, feesUSD: feeValue, feePercentage: (feeValue / inputValue * 100).toFixed(2), impact: getFeeImpactLevel(feeValue / inputValue) }; }; const getFeeImpactLevel = (percentage) => { if (percentage < 0.005) return 'MINIMAL'; if (percentage < 0.01) return 'LOW'; if (percentage < 0.03) return 'MODERATE'; if (percentage < 0.05) return 'HIGH'; return 'VERY_HIGH'; }; ``` ## Common Fee Scenarios ### High-Frequency Trading For frequent swaps, minimize per-transaction costs: * Use providers with no protocol fees * Batch transactions when possible * Choose chains with low network fees * Consider fee rebate programs ### Large Value Swaps For large amounts, optimize for percentage fees: * Use streaming swaps to reduce slippage * Negotiate affiliate fee sharing * Consider OTC alternatives for very large amounts * Split across multiple routes if beneficial ### Cross-Chain Arbitrage Factor all fees into profit calculations: * Include both inbound and outbound network fees * Account for time value during execution * Consider MEV protection costs * Calculate break-even thresholds # Providers Source: https://docs.dkit.xyz/essentials/providers Understanding DEX providers and their capabilities ## Overview dKit aggregates liquidity from multiple decentralized exchange protocols, each with unique strengths and supported assets. Understanding providers helps you optimize your swaps for speed, cost, and availability. ## Available Providers ### THORChain **Type:** Cross-chain Liquidity Protocol\ **Specialty:** Native asset swaps without wrapped tokens\ **Chains:** 12+ blockchains including Bitcoin, Ethereum, Cosmos\ **Best for:** Large cross-chain swaps with deep liquidity **Key Features:** * Native asset swaps (no wrapping required) * Continuous Liquidity Pools (CLP) * Streaming swaps for large amounts * Built-in slip protection * No impermanent loss for LPs **Supported Chains:** * Bitcoin, Ethereum, Binance Smart Chain * Avalanche, Cosmos, THORChain * Litecoin, Bitcoin Cash, Dogecoin **When to Use:** * Cross-chain native asset swaps * Large swap amounts (\$10k+) * When security is paramount * Bitcoin to/from any chain ### Chainflip **Type:** State Chain Protocol\ **Specialty:** Fast cross-chain swaps with JIT liquidity\ **Chains:** Bitcoin, Ethereum, Arbitrum, Polkadot\ **Best for:** Speed and competitive pricing **Key Features:** * Just-In-Time (JIT) AMM * State chain architecture * Fast finality (\~1-2 minutes) * Competitive pricing * Native cross-chain swaps **Supported Chains:** * Bitcoin, Ethereum, Arbitrum * Polkadot (unique support) * More chains coming soon **When to Use:** * Need fastest cross-chain execution * Polkadot ecosystem swaps * Medium-sized swaps ($1k-$100k) * Arbitrum cross-chain swaps ### MayaChain **Type:** THORChain Fork\ **Specialty:** Optimized for specific asset pairs\ **Chains:** Bitcoin, Ethereum, THORChain, Dash, Kujira\ **Best for:** CACAO token and Dash swaps **Key Features:** * Fork of THORChain with modifications * Native CACAO token * Specialized pools * Unique Dash and Kujira support * Capital efficiency improvements **Supported Chains:** * Bitcoin, Ethereum, THORChain * Dash (unique support) * Kujira (Cosmos ecosystem) * Maya Protocol native **When to Use:** * Dash cryptocurrency swaps * CACAO token trading * Kujira ecosystem access * Alternative to THORChain routes ### Jupiter **Type:** Solana DEX Aggregator\ **Specialty:** Best rates for Solana ecosystem\ **Chains:** Solana only\ **Best for:** SPL token swaps with optimal routing **Key Features:** * Aggregates 30+ Solana DEXs * Smart order routing * Auto-slippage calculation * Transaction priority fees * Support for 2500+ SPL tokens **Integrated DEXs:** * Orca, Raydium, Serum * Phoenix, Lifinity * And many more **When to Use:** * Any Solana token swap * Need best SPL token rates * Complex token routes on Solana * Small to large amounts ### 1inch **Type:** EVM Chain Aggregator\ **Specialty:** Optimal routing across EVM DEXs\ **Chains:** Ethereum, Arbitrum, Base, BSC, Avalanche\ **Best for:** EVM token swaps with gas optimization **Key Features:** * Aggregates 300+ liquidity sources * CHI gas token integration * Partial fill support * Complex routing algorithms * MEV protection **Supported EVM Chains:** * Ethereum, Arbitrum, Base * Binance Smart Chain * Avalanche C-Chain * 10+ other EVM chains **When to Use:** * EVM token-to-token swaps * Need gas optimization * Complex routing requirements * Arbitrage opportunities ## DEX Aggregation Chains dKit supports multi-hop routes combining different providers: ### JUPITER β†’ CHAINFLIP * **Use Case:** Solana to Bitcoin/Ethereum * **Path:** SPL tokens β†’ SOL β†’ FLIP β†’ BTC/ETH * **Benefits:** Access Solana liquidity for cross-chain ### ONEINCH β†’ CHAINFLIP * **Use Case:** EVM tokens to Bitcoin * **Path:** ERC-20 β†’ ETH β†’ FLIP β†’ BTC * **Benefits:** Optimal EVM routing to cross-chain ### CHAINFLIP β†’ ONEINCH * **Use Case:** Bitcoin to EVM tokens * **Path:** BTC β†’ FLIP β†’ ETH β†’ ERC-20 * **Benefits:** Direct Bitcoin to any EVM token ## Provider Selection Strategy ### Automatic Selection By default, dKit queries all relevant providers and returns the best routes: ```javascript // Let the API choose the best provider const quote = await fetch('/quote', { body: JSON.stringify({ sellAsset: 'BTC.BTC', buyAsset: 'ETH.ETH', sellAmount: '1.0' // providers field omitted - uses all }) }); ``` ### Manual Provider Selection Specify providers when you have specific requirements: ```javascript // Use only THORChain for maximum security const quote = await fetch('/quote', { body: JSON.stringify({ sellAsset: 'BTC.BTC', buyAsset: 'ETH.ETH', sellAmount: '1.0', providers: ['THORCHAIN'] }) }); // Use multiple specific providers const quote = await fetch('/quote', { body: JSON.stringify({ sellAsset: 'BTC.BTC', buyAsset: 'ETH.ETH', sellAmount: '1.0', providers: ['THORCHAIN', 'CHAINFLIP'] }) }); ``` ## Provider Comparison | Provider | Cross-Chain | Speed | Liquidity | Unique Features | | --------- | ------------- | ----------------- | --------- | --------------------- | | THORChain | βœ… Excellent | Medium (5-10 min) | Deep | Native BTC, Streaming | | Chainflip | βœ… Excellent | Fast (1-3 min) | Growing | JIT AMM, Polkadot | | MayaChain | βœ… Good | Medium (5-10 min) | Moderate | Dash, CACAO | | Jupiter | ❌ Solana only | Instant | Excellent | 2500+ tokens | | 1inch | ❌ EVM only | Instant | Excellent | 300+ sources | ## Streaming Swaps THORChain and MayaChain support streaming swaps for large amounts: ```javascript // Large swaps automatically use streaming const largeSwap = { sellAsset: 'BTC.BTC', buyAsset: 'ETH.ETH', sellAmount: '10.0', // 10 BTC in decimal format providers: ['THORCHAIN'] }; // Track streaming progress const tracking = await fetch('/track', { body: JSON.stringify({ hash: txHash, chainId: 'BTC', quoteId: quoteId, routeIndex: 0 }) }); if (tracking.data.isStreaming) { console.log(`Progress: ${tracking.data.streamingProgress.percentage}%`); } ``` ## Provider-Specific Features ### THORChain Memos THORChain uses transaction memos for swap instructions: ``` =:ETH.ETH:0x...address:100:thor1...affiliate:100 ``` Components: * `=` : Swap identifier * `ETH.ETH` : Target asset * `0x...` : Destination address * `100` : Slip limit (basis points) * `thor1...` : Affiliate address * `100` : Affiliate fee (basis points) ### Chainflip Deposit Channels Chainflip uses unique deposit addresses: ```javascript { "inboundAddress": "0x123...", // Unique deposit address "depositChannel": { "id": "cf-123", "expiryBlock": 1234567 } } ``` ### Jupiter Route Info Jupiter provides detailed route information: ```javascript { "route": { "marketInfos": [ { "id": "orca", "label": "Orca", "inputMint": "So11...", "outputMint": "EPjF..." } ] } } ``` ## Error Handling by Provider Different providers return different error codes: ### THORChain Errors * `INSUFFICIENT_LIQUIDITY` - Pool too shallow * `TRADING_HALTED` - Chain halted * `SLIP_TOLERANCE_EXCEEDED` - Price impact too high ### Chainflip Errors * `PAIR_NOT_SUPPORTED` - Asset pair not available * `AMOUNT_TOO_SMALL` - Below minimum * `CHANNEL_EXPIRED` - Deposit channel expired ### Jupiter Errors * `ROUTE_NOT_FOUND` - No route available * `SLIPPAGE_TOO_HIGH` - Price impact exceeds limit * `TOKEN_NOT_VERIFIED` - Unverified token ## Best Practices ### 1. Provider Fallbacks ```javascript const getQuoteWithFallback = async (params) => { // Try preferred provider first try { const preferredQuote = await getQuote({ ...params, providers: ['CHAINFLIP'] // Fastest }); if (preferredQuote.routes.length > 0) { return preferredQuote; } } catch (error) { console.log('Preferred provider failed, trying others'); } // Fallback to all providers return await getQuote(params); }; ``` ### 2. Provider-Specific Optimization ```javascript // Optimize for THORChain const thorchainOptimized = { sellAmount: amount, slippage: 5, // THORChain handles slip well providers: ['THORCHAIN'] }; // Optimize for Jupiter const jupiterOptimized = { sellAmount: amount, slippage: 1, // Tighter slippage for on-chain providers: ['JUPITER'] }; ``` ### 3. Multi-Provider Strategies ```javascript // Get quotes from all providers and compare const getAllQuotes = async (params) => { const providers = ['THORCHAIN', 'CHAINFLIP', 'MAYACHAIN']; const quotes = await Promise.allSettled( providers.map(provider => getQuote({ ...params, providers: [provider] }) ) ); // Analyze results return quotes .filter(q => q.status === 'fulfilled') .map(q => q.value) .filter(q => q.routes.length > 0); }; ``` # Routing Source: https://docs.dkit.xyz/essentials/routing How dKit finds the best swap paths across providers ## Overview dKit's routing engine intelligently finds the most efficient path for your swaps, whether direct or through multiple hops. The system considers factors like liquidity, fees, slippage, and execution time to optimize your trades. ## Route Types ### Direct Routes Single-hop swaps within one provider: ```mermaid graph LR A[BTC] -->|THORChain| B[ETH] ``` **Characteristics:** * Single transaction * Lower complexity * Predictable fees * Faster execution **Example:** ```javascript { "providers": ["THORCHAIN"], "legs": [], // No intermediate legs for direct routes "estimatedTime": { "total": 600 // ~10 minutes } } ``` ### Multi-Leg Routes Swaps requiring multiple steps within a provider: ```mermaid graph LR A[USDC] -->|1inch| B[ETH] B -->|1inch| C[WBTC] ``` **Characteristics:** * Multiple swaps in one transaction * Optimized routing through liquidity pools * Higher gas costs on EVM chains * Better rates for illiquid pairs ### DEX Aggregation Routes Cross-provider routes combining different protocols: ```mermaid graph LR A[SOL Token] -->|Jupiter| B[SOL] B -->|Chainflip| C[ETH] C -->|1inch| D[USDC] ``` **Characteristics:** * Multiple transactions across chains * Combines strengths of different providers * Enables otherwise impossible swaps * Requires careful tracking ## Route Discovery Process ### 1. Asset Analysis The routing engine first analyzes the assets: ```javascript const analyzeAssets = (sellAsset, buyAsset) => { return { sellChain: sellAsset.split('.')[0], buyChain: buyAsset.split('.')[0], isCrossChain: sellChain !== buyChain, isNativeToNative: !sellAsset.includes('-') && !buyAsset.includes('-'), requiresWrapping: needsWrapping(sellAsset, buyAsset) }; }; ``` ### 2. Provider Selection Based on asset analysis, relevant providers are identified: ```javascript const selectProviders = (analysis) => { const providers = []; if (analysis.isCrossChain) { // Cross-chain providers providers.push('THORCHAIN', 'CHAINFLIP', 'MAYACHAIN'); } if (analysis.sellChain === 'SOL') { providers.push('JUPITER'); } if (isEVMChain(analysis.sellChain)) { providers.push('ONEINCH'); } return providers; }; ``` ### 3. Route Calculation Each provider calculates possible routes: * **Liquidity depth** at each hop * **Price impact** based on swap size * **Fee structure** (network, protocol, LP fees) * **Execution time** estimates ### 4. Route Optimization Routes are ranked by: 1. **Output amount** (after all fees) 2. **Execution speed** 3. **Route complexity** 4. **Security considerations** ## Route Metadata Each route includes rich metadata for decision-making: ### Price Impact ```javascript { "meta": { "priceImpact": 0.15, // 0.15% price impact "tags": ["BEST", "LOW_IMPACT"] } } ``` **Thresholds:** * `< 0.1%` - Negligible impact * `0.1% - 1%` - Low impact * `1% - 3%` - Moderate impact * `3% - 5%` - High impact * `> 5%` - Very high impact ### Route Tags Routes are tagged for easy identification: | Tag | Description | | ------------- | ----------------------- | | `FASTEST` | Quickest execution time | | `CHEAPEST` | Lowest fees | | `BEST` | Best overall value | | `RECOMMENDED` | Platform recommendation | ### Time Estimates ```javascript { "estimatedTime": { "inbound": 600, // Time for source chain confirmation "swap": 10, // Time for swap execution "outbound": 180, // Time for destination delivery "total": 790 // Total seconds (~13 minutes) } } ``` ## Complex Routing Examples ### Cross-Chain Token to Token Swapping USDC on Ethereum to USDC on Solana: ```mermaid graph LR A[ETH.USDC] -->|THORChain| B[ETH.ETH] B -->|THORChain| C[SOL.SOL] C -->|Jupiter| D[SOL.USDC] ``` **Route Structure:** ```javascript { "providers": ["THORCHAIN", "JUPITER"], "legs": [ { "provider": "THORCHAIN", "sellAsset": "ETH.USDC", "buyAsset": "SOL.SOL" }, { "provider": "JUPITER", "sellAsset": "SOL.SOL", "buyAsset": "SOL.USDC" } ] } ``` ### Arbitrage Routes Finding profitable paths between assets: ```javascript // Triangular arbitrage detection const findArbitrageRoute = async (startAsset, amount) => { // Path 1: Asset A β†’ B β†’ C β†’ A const path1 = await getQuote({ sellAsset: startAsset, buyAsset: 'ETH.USDC', sellAmount: amount }); const path2 = await getQuote({ sellAsset: 'ETH.USDC', buyAsset: 'ETH.WBTC', sellAmount: path1.routes[0].expectedBuyAmount }); const path3 = await getQuote({ sellAsset: 'ETH.WBTC', buyAsset: startAsset, sellAmount: path2.routes[0].expectedBuyAmount }); const profit = BigInt(path3.routes[0].expectedBuyAmount) - BigInt(amount); return { profitable: profit > 0, profitAmount: profit.toString(), route: [path1, path2, path3] }; }; ``` ## Route Selection Strategies ### Optimizing for Speed ```javascript const getFastestRoute = (routes) => { return routes .filter(r => r.estimatedTime) .sort((a, b) => a.estimatedTime.total - b.estimatedTime.total)[0]; }; ``` ### Optimizing for Output ```javascript const getBestOutput = (routes) => { return routes .sort((a, b) => BigInt(b.expectedBuyAmount) - BigInt(a.expectedBuyAmount) )[0]; }; ``` ### Balanced Optimization ```javascript const getBalancedRoute = (routes) => { // Score each route const scored = routes.map(route => { const outputScore = calculateOutputScore(route); const timeScore = calculateTimeScore(route); const feeScore = calculateFeeScore(route); return { route, score: outputScore * 0.5 + timeScore * 0.3 + feeScore * 0.2 }; }); return scored.sort((a, b) => b.score - a.score)[0].route; }; ``` ## Streaming Routes For large swaps, THORChain automatically creates streaming routes: ```javascript { "meta": { "streamingInterval": 10, // Blocks between swaps "maxStreamingQuantity": 100, // Number of sub-swaps "tags": ["STREAMING", "LOW_IMPACT"] } } ``` **Benefits:** * Reduced price impact * Better execution price * Protection against manipulation **Trade-offs:** * Longer execution time * Multiple transactions * Complex tracking ## Route Warnings Routes may include warnings about potential issues: ```javascript { "warnings": [ { "code": "HIGH_PRICE_IMPACT", "display": "High price impact", "tooltip": "This swap will move the market price by >3%" }, { "code": "LOW_LIQUIDITY", "display": "Low liquidity", "tooltip": "Limited liquidity may result in partial fills" } ] } ``` Common warning codes: * `HIGH_PRICE_IMPACT` - Significant market impact * `LOW_LIQUIDITY` - Shallow pools * `LONG_EXECUTION` - Extended completion time * `REQUIRES_APPROVAL` - Token approval needed * `EXPERIMENTAL_ROUTE` - New or untested path ## Route Execution ### Pre-execution Checks ```javascript const validateRoute = (route) => { const checks = { hasInboundAddress: !!route.inboundAddress || !!route.targetAddress, hasValidMemo: route.memo && route.memo.length > 0, withinExpiration: !route.expiration || Date.now() < route.expiration, acceptableSlippage: route.totalSlippageBps < 500 // 5% }; return Object.values(checks).every(check => check); }; ``` ### Transaction Building Different routes require different transaction formats: ```javascript // Native cross-chain (THORChain) const nativeTx = { to: route.inboundAddress, value: sellAmount, memo: route.memo }; // EVM contract interaction const evmTx = { to: route.tx.to, from: userAddress, value: route.tx.value, data: route.tx.data, gasLimit: estimateGas(route.tx) }; // Solana transaction const solanaTx = { instructions: route.tx.instructions, signers: [userWallet], feePayer: userWallet.publicKey }; ``` ## Route Monitoring Track multi-leg route progress: ```javascript const trackMultiLegRoute = async (quoteId, routeIndex) => { let completed = false; while (!completed) { const status = await fetch('/track', { body: JSON.stringify({ hash: currentTxHash, chainId: currentChainId, quoteId, routeIndex }) }); if (status.data.isDexAgg) { const { currentLeg, totalLegs, legs } = status.data.dexAggProgress; console.log(`Leg ${currentLeg}/${totalLegs}`); // Check if we need to execute next leg if (currentLeg < totalLegs && legs[currentLeg].status === 'waiting_user_action') { // Execute next leg transaction await executeNextLeg(legs[currentLeg]); } } completed = status.data.trackingStatus === 'completed'; await sleep(5000); } }; ``` ## Best Practices 1. **Always check route validity** before execution 2. **Monitor expiration times** for time-sensitive routes 3. **Implement fallback routes** for critical swaps 4. **Cache route calculations** for repeated queries 5. **Use appropriate slippage** based on route complexity 6. **Track all legs** of multi-hop routes 7. **Handle partial fills** gracefully # Introduction Source: https://docs.dkit.xyz/index Swap or provide liquidity with any token, from any wallet, to any chain, by integrating dKit seamlessly into your front or backend application. ## Welcome to dKit dKit is a unified DEX aggregation API that enables cross-chain token swaps across 15+ blockchains and multiple decentralized exchange protocols. Find the best rates, execute swaps, and track transactions - all through a single API. ## Quick Links Explore our comprehensive API documentation Get up and running in under 5 minutes Learn how to request swap quotes Monitor your swap transactions in real-time ## Why dKit? Automatically compare rates across THORChain, Chainflip, MayaChain, Jupiter, and 1inch to find the best price for your swaps. {" "} Swap native assets without wrapped tokens. Go from Bitcoin to Ethereum, Solana to Avalanche, or any combination of our supported chains. {" "} Monitor swap progress with detailed status updates, including streaming swap progress and multi-hop route tracking. One API, multiple DEXs. No need to integrate each protocol separately - we handle the complexity for you. ### Supported Blockchains
ETH
Ethereum ETH
AVAX
Avalanche AVAX
BSC
BNB Chain BSC
MATIC
Polygon MATIC
ARB
Arbitrum ARB
HYPE
HyperEVM HYPE
BASE
Base BASE
OP
Optimism OP
BTC
Bitcoin BTC
LTC
Litecoin LTC
DOGE
Dogecoin DOGE
BCH
Bitcoin Cash BCH
DASH
Dash DASH
ZEC
Zcash ZEC
GAIA
Cosmos Hub GAIA
THOR
THORChain THOR
MAYA
Maya Protocol MAYA
KUJI
Kujira KUJI
SOL
Solana SOL
DOT
Polkadot DOT
XRD
Radix XRD
XRP
Ripple XRP
### Supported Protocols and Aggregators }> Decentralized liquidity protocol enabling cross-chain swaps without the need for wrapped tokens. {" "} }> Decentralized protocol enabling seamless cross-chain swaps through automated market makers (AMMs). {" "} }> Decentralized liquidity protocol, forked from THORChain, enabling cross-chain asset swaps with enhanced interoperability. {" "} }> 1inch is a Decentralized exchange aggregator that sources liquidity from multiple DEXs to optimize token swap rates. {" "} }> Decentralized protocol that enables fast, trustless atomic swaps between Bitcoin (BTC) and other blockchains, facilitating seamless cross-chain transactions without the need for wrapped tokens. }> Decentralized liquidity aggregator on Solana that finds the best rates across various DEXs for efficient token swaps. ### Supported Wallets
MetamaskMetamask
CTRLCTRL
KEPLRKEPLR
Leap WalletLeap Wallet
RainbowRainbow
Trust BrowserTrust Browser
Brave WalletBrave Wallet
TalismanTalisman
PhantomPhantom
OKX WalletOKX Wallet
KeystoreKeystore
{" "}
WalletConnect WalletConnect
Trust Wallet Trust Wallet
Coinbase Wallet Coinbase Wallet
OKX Wallet OKX Wallet
LedgerLedger
TrezorTrezor
KeepKeyKeepKey
## Core Features

πŸ”„ Smart Routing

Automatically finds the best route for your swap, whether it's a direct path or requires multiple hops through different protocols.

{" "}

πŸ’§ Streaming Swaps

Break large swaps into smaller chunks to minimize price impact and maximize output.

{" "}

πŸ” Non-Custodial

Your funds go directly from source to destination. We never hold your assets.

⚑ Fast Execution

Optimized for speed with typical swap times of 1–10 minutes depending on the chains involved.

## Example Request ```bash curl -X POST https://api.dkit.xyz/v1/quote \ -H "Content-Type: application/json" \ -d '{ "sellAsset": "ETH.ETH", "buyAsset": "BTC.BTC", "sellAmount": "1.0", "sourceAddress": "0x...", "destinationAddress": "bc1q..." }' ``` ## Getting Started Browse our [API documentation](/api-reference/introduction) to understand available endpoints. {" "} Use the [/quote endpoint](/api-reference/endpoints/quote) to get swap rates. {" "} Send the transaction using the provided transaction data. {" "} Monitor your swap with the [/track endpoint](/api-reference/endpoints/track). Automatically stream affiliate fees to the wallets you specify. See the [Revenue Generation guide](https://docs.dkit.xyz/revenue-generation) for setup details. ## Need Help? Try the API in your browser View source code and examples Contact our support team # Quick Start Source: https://docs.dkit.xyz/quickstart Start integrating dKit API in under 5 minutes ## Get started in three steps Integrate the dKit API into your application with this quick guide. ### Step 1: Get Your First Quote Start by requesting a swap quote to see available routes and prices. ```bash cURL curl --location 'https://api.dkit.xyz/v1/quote' \ --header 'Content-Type: application/json' \ --header 'api-key: 86c3fc76-25c8-455c-8d6d-0ecea88d0f6e' \ --data '{ "sellAsset": "ZEC.ZEC", "sellAmount": "2", "buyAsset": "ETH.ETH", "slippage": 1, "affiliate": "eld", "affiliateFee": 88, "includeTx": true, "providers": [ "MAYACHAIN" ], "sourceAddress": "t1Tmw3syVocrsRUDuCq7jteVjMSNfwpgz88", "destinationAddress": "0x817bFA97Cc8E5Bfa499D401f43E3087B07AE96f9" }' ``` ```javascript JavaScript const getSwapQuote = async () => { const response = await fetch('https://api.dkit.xyz/v1/quote', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': '86c3fc76-25c8-455c-8d6d-0ecea88d0f6e' }, body: JSON.stringify({ sellAsset: 'ZEC.ZEC', sellAmount: '2', buyAsset: 'ETH.ETH', slippage: 1, affiliate: 'eld', affiliateFee: 88, includeTx: true, providers: ['MAYACHAIN'], sourceAddress: 't1Tmw3syVocrsRUDuCq7jteVjMSNfwpgz88', destinationAddress: '0x817bFA97Cc8E5Bfa499D401f43E3087B07AE96f9' }) }); const quote = await response.json(); console.log(`Quote ID: ${quote.quoteId}`); console.log(`Available routes: ${quote.routes.length}`); return quote; }; ``` ```python Python import requests def get_swap_quote(): response = requests.post( 'https://api.dkit.xyz/v1/quote', headers={ 'Content-Type': 'application/json', 'x-api-key': '86c3fc76-25c8-455c-8d6d-0ecea88d0f6e' }, json={ 'sellAsset': 'ZEC.ZEC', 'sellAmount': '2', 'buyAsset': 'ETH.ETH', 'slippage': 1, 'affiliate': 'eld', 'affiliateFee': 88, 'includeTx': True, 'providers': ['MAYACHAIN'], 'sourceAddress': 't1Tmw3syVocrsRUDuCq7jteVjMSNfwpgz88', 'destinationAddress': '0x817bFA97Cc8E5Bfa499D401f43E3087B07AE96f9' } ) quote = response.json() print(f"Quote ID: {quote['quoteId']}") print(f"Available routes: {len(quote['routes'])}") return quote ``` ### Step 2: Execute the Swap Use the transaction details from the quote to execute the swap on-chain. For native cross-chain swaps (e.g., BTC to ETH via THORChain): ```javascript const route = quote.routes[0]; // Select best route // Send native transaction to the inbound address with memo const tx = { to: route.inboundAddress, value: sellAmount, memo: route.memo // Required for THORChain/Maya }; // Execute with your wallet const txHash = await wallet.sendTransaction(tx); ``` For EVM chain swaps with contract interaction: ```javascript const route = quote.routes[0]; // Use provided transaction object if (route.tx) { const tx = { to: route.tx.to, from: route.tx.from, value: route.tx.value, data: route.tx.data }; // Execute with ethers.js or web3.js const txHash = await signer.sendTransaction(tx); } ``` ### Step 3: Track the Swap Monitor your swap progress in real-time. ```javascript const trackSwap = async (txHash, chainId, quoteId, routeIndex) => { const response = await fetch('https://api.dkit.xyz/v1/track', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': '86c3fc76-25c8-455c-8d6d-0ecea88d0f6e' }, body: JSON.stringify({ hash: txHash, chainId: chainId, quoteId: quoteId, routeIndex: routeIndex }) }); const tracking = await response.json(); if (tracking.success) { console.log(`Status: ${tracking.data.trackingStatus}`); // Check if complete if (tracking.data.trackingStatus === 'completed') { console.log(`Output tx: ${tracking.data.trackMeta.outputTxHash}`); } } return tracking; }; // Poll for updates const pollStatus = async (params) => { let status = 'not_started'; while (status !== 'completed' && status !== 'refunded') { const result = await trackSwap(params); if (result.success) { status = result.data.trackingStatus; console.log(`Current status: ${status}`); } await new Promise(resolve => setTimeout(resolve, 5000)); // Wait 5 seconds } }; ``` ## Complete Example Here's a complete example that ties everything together: ```javascript async function performSwap() { try { // 1. Get quote const quote = await fetch('https://api.dkit.xyz/v1/quote', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sellAsset: 'ETH.ETH', buyAsset: 'BTC.BTC', sellAmount: '1.0', sourceAddress: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb8', destinationAddress: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh', slippage: 3 }) }).then(r => r.json()); console.log(`Got ${quote.routes.length} routes`); // 2. Select best route const route = quote.routes[0]; console.log(`Best route: ${route.providers.join(' β†’ ')}`); console.log(`Expected output: ${route.expectedBuyAmount} sats`); // 3. Execute swap (implementation depends on your wallet) const txHash = await executeSwap(route); console.log(`Transaction sent: ${txHash}`); // 4. Track the swap let tracking; do { tracking = await fetch('https://api.dkit.xyz/v1/track', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ hash: txHash, chainId: '1', // Ethereum mainnet quoteId: quote.quoteId, routeIndex: 0 }) }).then(r => r.json()); if (tracking.success) { console.log(`Status: ${tracking.data.trackingStatus}`); if (tracking.data.isStreaming) { const progress = tracking.data.streamingProgress; console.log(`Streaming: ${progress.percentage}% complete`); } } await new Promise(r => setTimeout(r, 5000)); // Wait 5 seconds } while ( tracking.success && !['completed', 'refunded'].includes(tracking.data.trackingStatus) ); if (tracking.data.trackingStatus === 'completed') { console.log('Swap completed successfully!'); console.log(`Output tx: ${tracking.data.trackMeta.outputTxHash}`); } } catch (error) { console.error('Swap failed:', error); } } ``` ## Next Steps Explore all available endpoints and parameters Deep dive into quote requests and responses Learn how to handle errors gracefully Advanced strategies for optimizing quotes ## Common Integration Patterns ```javascript // MetaMask example const executeEVMSwap = async (route) => { const accounts = await ethereum.request({ method: 'eth_requestAccounts' }); const tx = { from: accounts[0], to: route.targetAddress || route.inboundAddress, value: route.tx?.value || '0x0', data: route.tx?.data || route.memo || '0x' }; return await ethereum.request({ method: 'eth_sendTransaction', params: [tx] }); }; ``` ```javascript const swapWithRetry = async (params, maxRetries = 3) => { for (let i = 0; i < maxRetries; i++) { try { const quote = await getQuote(params); if (quote.routes.length > 0) { return await executeSwap(quote.routes[0]); } // Check provider errors if (quote.providerErrors) { const retriable = quote.providerErrors.some(e => e.errorCode === 'RATE_LIMITED' || e.errorCode === 'PROVIDER_UNAVAILABLE' ); if (!retriable) throw new Error('No routes available'); } } catch (error) { if (i === maxRetries - 1) throw error; await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } } }; ``` ```javascript // Convert human-readable amounts to base units const toBaseUnits = (amount, decimals) => { const factor = BigInt(10 ** decimals); const [whole, fraction = ''] = amount.split('.'); const fractionPadded = fraction.padEnd(decimals, '0').slice(0, decimals); return (BigInt(whole) * factor + BigInt(fractionPadded)).toString(); }; // Convert base units to human-readable const fromBaseUnits = (amount, decimals) => { const value = BigInt(amount); const factor = BigInt(10 ** decimals); const whole = value / factor; const remainder = value % factor; if (remainder === 0n) return whole.toString(); const fraction = remainder.toString().padStart(decimals, '0'); return `${whole}.${fraction.replace(/0+$/, '')}`; }; ``` # Revenue Generation Source: https://docs.dkit.xyz/revenue-generation Collect affiliate fees from every trade facilitated through our SDK/API. Any project that implements dKit can earn fees based on the volume they drive. export const RevenueCalc = () => { const [volume, setVolume] = useState(100000); const [bps, setBps] = useState(50); const fmtInt = useMemo(() => new Intl.NumberFormat("en-US"), []); const fmtUSD = useMemo(() => new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2 }), []); const parseIntSafe = str => { const cleaned = String(str ?? "").replace(/[^\d]/g, ""); return cleaned ? parseInt(cleaned, 10) : 0; }; const clamp = (n, min, max) => Math.max(min, Math.min(max, n)); const revenue = volume * (bps / 10000); return

Revenue Calculator

Estimated Monthly Revenue
{fmtUSD.format(revenue)}
; };
Try the Quote API API Playground
## Start monetizing your dApp There are 2 primary ways to monetize your application and earn fees with dKit: *** ## Fee Earning Overview
Type Revenue Source Setup Required
THORChain / Maya / Chainflip Direct cross-chain protocol fees
THORName Maya node Chainflip Broker
DEX Aggregation Swaps Cross-chain DEX aggregation revenue Affiliate address setup
## Implementation Setup When fetching trade quotes through our SDK, you can configure:
Parameter Description Format
Affiliate Address Your designated affiliate address Wallet address
Fee Percentage Your commission rate Basis points (e.g., 100 = 1%)
```ts import { getQuote } from "@dkit/sdk"; const quote = await getQuote({ sellAsset: "ETH.ETH", buyAsset: "BTC.BTC", sellAmount: "1", affiliate: { address: "YOUR_AFFILIATE_ADDRESS", bps: 75, // 0.75% }, }); ``` ```bash curl -X POST https://api.dkit.xyz/quote \ -H 'content-type: application/json' \ -d '{ "sellAsset":"ETH.ETH", "buyAsset":"BTC.BTC", "sellAmount":"1", "affiliate":{"address":"YOUR_AFFILIATE_ADDRESS","bps":75} }' ``` *** ## How It Works
  1. Earn fees from swaps executed through your front-end / dApp / wallet.
  2. Your affiliate address is tied to a THORName / Maya node or Chainflip broker.
  3. Fees can be sent automatically to your chosen address in RUNE, CACAO, or even USDC.
*** ## Setting up a THORName

Create your THORName to receive protocol-native fees.

Attach BTC, ETH, and other chains to your THORName.

Set affiliate.address and affiliate.bps in your quote requests.

Fees accrue automatically; monitor in your analytics.

Pro Tip: THORName Optimization
Keep your THORName 3 characters or shorter. THORChain transactions include affiliate names in the memo field; shorter names avoid issues on BTC/UTXO chains with \~80-character limits.
*** ## DEX Aggregation Swaps **What’s covered.** Cross-chain movements like ARC20/ERC20/SPL to assets on another blockchain. Examples: Arbitrum β†’ Solana (ARC20 β†’ SPL), Ethereum β†’ Bitcoin (ERC20 β†’ BTC), Solana β†’ Arbitrum (SPL β†’ ARC20). **Revenue Generation** * Generate revenue from cross-chain swaps utilizing DEX aggregation. * Includes swaps moving in and out of Chainflip, THORChain and Maya Protocol. * Automatic revenue collection available. *** ## Perfect For * Cross-chain DEX protocols * Multi-chain wallets * DeFi aggregators * Trading apps / dApps * NFT marketplaces *** ## Revenue Calculator *** ## Questions? Want to start monetizing your dApp? Reach out to our team on Telegram and we’ll get you started with personalized onboarding and technical support!