### Execute a Complete Regular Swap Flow with SwapSDK Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/08-usage-patterns.md This example demonstrates the full lifecycle of a regular swap using the SwapSDK, from getting a quote to opening a deposit channel. Ensure you have the necessary SDK imports and network configuration. ```typescript import { SwapSDK } from '@chainflip/sdk/swap'; import axios from 'axios'; async function executeRegularSwap() { const sdk = new SwapSDK({ network: 'perseverance' }); // 1. Get quote console.log('Getting quote...'); const { quotes } = await sdk.getQuoteV2({ srcChain: 'Bitcoin', srcAsset: 'BTC', destChain: 'Ethereum', destAsset: 'ETH', amount: '0.5', // BTC amount as decimal string }); const regularQuote = quotes.find((q) => q.type === 'REGULAR'); if (!regularQuote) throw new Error('No quote available'); console.log(`Quote: ${regularQuote.egressAmount} ETH for ${regularQuote.depositAmount} BTC`); // 2. Open deposit channel console.log('Opening deposit channel...'); const channel = await sdk.requestDepositAddressV2({ quote: regularQuote, srcAddress: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh', // optional destAddress: '0xa56A6be23b6Cf39D9448FF6e897C29c41c8fbDFF', fillOrKillParams: { slippageTolerancePercent: regularQuote.recommendedSlippageTolerancePercent, refundAddress: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh', retryDurationBlocks: 100, }, }); console.log(`Deposit to: ${channel.depositAddress}`); console.log(`Channel ID: ${channel.depositChannelId}`); console.log(`Expires at block: ${channel.depositChannelExpiryBlock}`); // 3. Monitor status (in real app, this would run periodically) let status = await sdk.getStatusV2({ id: channel.depositChannelId }); console.log(`Status: ${status.state}`); // 4. In real scenario, user sends funds to channel.depositAddress // Then you would poll until COMPLETED return channel; } ``` -------------------------------- ### Install Chainflip Lending SDK Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/packages/lending-sdk/README.md Install the lending SDK package using npm. ```bash npm install @chainflip/lending-sdk ``` -------------------------------- ### Supported Assets Response Example Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/packages/lending-sdk/sdk-api-reference.md Example of the array returned by `getSupportedAssets`, listing available assets. ```json ["Usdc", "Usdt", "Eth", "Btc", "Sol"] ``` -------------------------------- ### GET /networkInfo Example Response Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/04-endpoints.md An example JSON response for the /networkInfo endpoint, illustrating the format for asset information and broker commission. ```json { "assets": [ { "asset": "BTC", "vaultSwapDepositsEnabled": true, "depositChannelDepositsEnabled": true, "depositChannelCreationEnabled": true, "egressEnabled": true, "boostDepositsEnabled": true, "livePriceProtectionEnabled": true }, { "asset": "ETH", "vaultSwapDepositsEnabled": true, "depositChannelDepositsEnabled": true, "depositChannelCreationEnabled": true, "egressEnabled": true, "boostDepositsEnabled": false, "livePriceProtectionEnabled": true } ], "cfBrokerCommissionBps": 0 } ``` -------------------------------- ### Install Chainflip SDK Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/00-index.md Install the Chainflip SDK using npm. This is the first step to using the SDK in your project. ```bash npm install @chainflip/sdk ``` -------------------------------- ### Complete Fund and Redeem Cycle Example Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/02-funding-sdk.md Demonstrates the full lifecycle of funding a validator account and later redeeming it using the FundingSDK. Includes setup, balance checks, approvals, funding, checking pending redemptions, and executing the redemption. ```typescript import { FundingSDK } from '@chainflip/sdk/funding'; import { ethers } from 'ethers'; async function fundAndRedeemValidator() { // Setup const provider = new ethers.JsonRpcProvider('https://eth-rpc.chainflip.io'); const signer = new ethers.Wallet(process.env.PRIVATE_KEY!, provider); const fundingSDK = new FundingSDK({ signer, network: 'perseverance' }); const accountId = '0x' + 'a'.repeat(64) as `0x${string}`; const fundAmount = ethers.parseUnits('1000', 18); // Check balance const balance = await fundingSDK.getFlipBalance(); console.log('Current FLIP balance:', ethers.formatUnits(balance, 18)); // Approve and fund console.log('Approving gateway...'); const approveTx = await fundingSDK.approveStateChainGateway(fundAmount); if (approveTx) { await provider.waitForTransaction(approveTx); } console.log('Funding validator account...'); const fundTx = await fundingSDK.fundStateChainAccount(accountId, fundAmount); await provider.waitForTransaction(fundTx); console.log('Funded:', fundTx); // Later: request redemption on state chain (not shown here) // Then check pending redemption console.log('Checking pending redemption...'); const pending = await fundingSDK.getPendingRedemption(accountId); if (pending) { const delay = await fundingSDK.getRedemptionDelay(); const tax = await fundingSDK.getRedemptionTax(); console.log('Pending amount:', ethers.formatUnits(pending.amount, 18), 'FLIP'); console.log('Redemption tax:', ethers.formatUnits(tax, 18), 'FLIP'); console.log('Will receive:', ethers.formatUnits(pending.amount - tax, 18), 'FLIP'); // Wait for delay if needed const elapsed = BigInt(Math.floor(Date.now() / 1000)) - pending.requestAt; if (elapsed < delay) { const waitSeconds = Number(delay - elapsed); console.log(`Must wait ${waitSeconds} more seconds...`); await new Promise((resolve) => setTimeout(resolve, waitSeconds * 1000)); } // Execute redemption console.log('Executing redemption...'); const redeemTx = await fundingSDK.executeRedemption(accountId); await provider.waitForTransaction(redeemTx); console.log('Redemption executed:', redeemTx); } } await fundAndRedeemValidator(); ``` -------------------------------- ### GET /v2/quote Request Example Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/04-endpoints.md Example of a GET request to the /v2/quote endpoint to retrieve swap quotations. Specify source and destination chains/assets, and the amount. ```bash curl "https://perseverance.chainflip.io/api/v2/quote?srcChain=Bitcoin&srcAsset=BTC&destChain=Ethereum&destAsset=ETH&amount=50000000" ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/CLAUDE.md Installs project dependencies using pnpm workspaces. Ensure pnpm is installed globally. ```bash pnpm install ``` -------------------------------- ### Asset Pool Info Response Example Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/packages/lending-sdk/sdk-api-reference.md Example structure of the array returned by `getAssetPoolInfo`, detailing metrics for each lending pool asset. ```json [ { asset: "Usdc", totalSuppliedAmount: "5000000", totalSuppliedAmountUsd: "5000000", totalBorrowedAmount: "3000000", totalBorrowedAmountUsd: "3000000", totalAvailableAmount: "2000000", totalAvailableAmountUsd: "2000000", utilisation: "0.60", supplyApy: "4.25", borrowApy: "7.80", maxLtv: "0.75", liquidationThreshold: "0.80", liquidationFeeBps: "500", originationFeeBps: "100" }, ...] ``` -------------------------------- ### V2 Quote Response Example Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/04-endpoints.md Example JSON response for the /v2/quote endpoint, showing a regular swap with boost quote details. Includes deposit and egress amounts, fees, pool information, and estimated durations. ```json [ { "type": "REGULAR", "depositAmount": "50000000", "egressAmount": "25000000000000000000", "intermediateAmount": null, "includedFees": [ { "type": "INGRESS", "amount": "100000", "chain": "Bitcoin", "asset": "BTC" }, { "type": "EGRESS", "amount": "10000000000000000", "chain": "Ethereum", "asset": "ETH" } ], "poolInfo": [ { "baseAsset": { "chain": "Bitcoin", "asset": "BTC" }, "quoteAsset": { "chain": "Ethereum", "asset": "ETH" }, "fee": { "amount": "500000", "type": "LIQUIDITY" } } ], "estimatedDurationSeconds": 600, "estimatedDurationsSeconds": { "deposit": 120, "swap": 300, "egress": 180 }, "estimatedPrice": "0.5", "recommendedSlippageTolerancePercent": 1.5, "recommendedRetryDurationMinutes": 30, "boostQuote": { "estimatedBoostFeeBps": 50, "maxBoostFeeBps": 100, "type": "REGULAR", "depositAmount": "50000000", "egressAmount": "24500000000000000000" } } ] ``` -------------------------------- ### Initialize FundingSDK with Basic Setup Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/05-configuration.md Set up the FundingSDK with an ethers v6 signer and specify the target network. Requires a private key and RPC URL. ```typescript import { FundingSDK } from '@chainflip/sdk/funding'; import { ethers } from 'ethers'; // Basic setup const provider = new ethers.JsonRpcProvider('https://eth-rpc.chainflip.io'); const signer = new ethers.Wallet(process.env.PRIVATE_KEY!, provider); const fundingSDK = new FundingSDK({ signer, network: 'perseverance', }); ``` -------------------------------- ### Develop Swap Service with pnpm Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/CLAUDE.md Runs the swap service in development mode against the perseverance testnet. Requires envlocker setup. ```bash pnpm run --dir=packages/swap dev:perseverance ``` -------------------------------- ### Borrow Options Response Example Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/packages/lending-sdk/sdk-api-reference.md Example structure of the response object returned by `getLoanQuote` when calculating borrowable amounts for a given collateral. ```json { loanAssetTiers: { conservative: { Btc: "1", Usdc: "5000", Sol: "200", ltv: "0" }, optimal: { Btc: "5", Usdc: "10000", Sol: "2000", ltv: "0.5" }, risky: { Btc: "10", Usdc: "50000", Sol: "10000", ltv: "0.75" } }, lendingPools: { /* fee breakdown per asset */ } } ``` -------------------------------- ### Request Deposit Address V2 Example Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/01-swap-sdk.md Demonstrates how to request a deposit address for a swap using a regular quote. Ensure you have obtained a quote first. ```typescript const sdk = new SwapSDK(); // Get quote first const { quotes } = await sdk.getQuoteV2({ srcChain: 'Bitcoin', srcAsset: 'BTC', destChain: 'Ethereum', destAsset: 'ETH', amount: '0.5', }); const regularQuote = quotes.find((q) => q.type === 'REGULAR'); // Open deposit channel const channel = await sdk.requestDepositAddressV2({ quote: regularQuote, srcAddress: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh', destAddress: '0xa56A6be23b6Cf39D9448FF6e897C29c41c8fbDFF', fillOrKillParams: { slippageTolerancePercent: regularQuote.recommendedSlippageTolerancePercent, refundAddress: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh', retryDurationBlocks: 100, }, }); console.log('Deposit to:', channel.depositAddress); console.log('Channel expires at block:', channel.depositChannelExpiryBlock); console.log('Channel opening fee:', channel.channelOpeningFee); ``` -------------------------------- ### Configure SwapSDK and FundingSDK from Environment Variables Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/05-configuration.md Instantiate SwapSDK and FundingSDK using values from environment variables. Ensure necessary imports and provider/signer setup for FundingSDK. ```typescript import { SwapSDK } from '@chainflip/sdk/swap'; import { FundingSDK } from '@chainflip/sdk/funding'; import { ethers } from 'ethers'; // SwapSDK const swapSDK = new SwapSDK({ network: (process.env.CHAINFLIP_NETWORK as ChainflipNetwork) || 'perseverance', backendUrl: process.env.CHAINFLIP_BACKEND_URL, rpcUrl: process.env.CHAINFLIP_RPC_URL, broker: process.env.CHAINFLIP_BROKER_URL ? { url: process.env.CHAINFLIP_BROKER_URL } : undefined, brokerAccount: process.env.CHAINFLIP_BROKER_ACCOUNT as `cF${string}` | undefined, enabledFeatures: { dcaV2: process.env.ENABLE_DCA_V2 === 'true', }, }); // FundingSDK const provider = new ethers.JsonRpcProvider( process.env.ETHEREUM_RPC_URL || 'https://eth-rpc.chainflip.io' ); const signer = new ethers.Wallet(process.env.PRIVATE_KEY!, provider); const fundingSDK = new FundingSDK({ signer, network: (process.env.CHAINFLIP_NETWORK as ChainflipNetwork) || 'perseverance', rpcUrl: process.env.CHAINFLIP_RPC_URL, }); ``` -------------------------------- ### Get Lending Configuration Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/packages/lending-sdk/README.md Retrieve the global configuration settings for the lending protocol. ```APIDOC ## Get Lending Configuration ### Description Fetches the global configuration parameters for the lending protocol. ### Method `getLendingConfig()` ### Usage ```typescript const config = await client.getLendingConfig(); ``` ``` -------------------------------- ### Single Leg Quote Request Example Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/packages/swap/python-client/README.md An example of a `quote_request` event for a single leg swap from FLIP to USDC. The `amount` is in the atomic unit. ```json { "request_id": "018ee1c7-b949-71f2-889e-a2284cee7712", "legs": [ { "amount": "1000000000000000000", // 1 $FLIP "base_asset": { "chain": "Ethereum", "asset": "FLIP" }, "quote_asset": { "chain": "Ethereum", "asset": "USDC" }, "side": "SELL", }, ], } ``` -------------------------------- ### Single Leg Quote Example Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/packages/swap/python-client/README.md An example demonstrating a single leg quote request and its corresponding response. ```APIDOC ## Single Leg Example ### Quote Request ```json { "request_id": "018ee1c7-b949-71f2-889e-a2284cee7712", "legs": [ { "amount": "1000000000000000000", // 1 $FLIP "base_asset": { "chain": "Ethereum", "asset": "FLIP" }, "quote_asset": { "chain": "Ethereum", "asset": "USDC" }, "side": "SELL", }, ], } ``` ### Quote Response ```json { "request_id": "018ee1c7-b949-71f2-889e-a2284cee7712", "legs": [ [ [-268100, "1137934"], [-268000, "1149370"], ], ], } ``` This response indicates two `BUY` orders in response to the `SELL` swap, each buying approximately 0.5 $FLIP. ``` -------------------------------- ### Basic Swap Usage with SwapSDK Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/00-index.md Demonstrates how to perform a basic asset swap using the SwapSDK. This includes getting a quote, requesting a deposit address, and monitoring the swap status. Ensure you have the necessary network and asset details. ```typescript import { SwapSDK } from '@chainflip/sdk/swap'; const sdk = new SwapSDK({ network: 'perseverance' }); // Get quote const { quotes } = await sdk.getQuoteV2({ srcChain: 'Bitcoin', srcAsset: 'BTC', destChain: 'Ethereum', destAsset: 'ETH', amount: '0.5', }); // Open deposit channel const channel = await sdk.requestDepositAddressV2({ quote: quotes[0], destAddress: '0xa56A6be23b6Cf39D9448FF6e897C29c41c8fbDFF', fillOrKillParams: { slippageTolerancePercent: quotes[0].recommendedSlippageTolerancePercent, refundAddress: 'bc1q...', retryDurationBlocks: 100, }, }); // Monitor status const status = await sdk.getStatusV2({ id: channel.depositChannelId }); console.log('Swap status:', status.state); ``` -------------------------------- ### Single Leg Quote Response Example Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/packages/swap/python-client/README.md An example `quote_response` event in response to a SELL swap request. It includes two BUY orders to fill the swap. ```json { "request_id": "018ee1c7-b949-71f2-889e-a2284cee7712", "legs": [ [ [-268100, "1137934"], [-268000, "1149370"], ], ], } ``` -------------------------------- ### Loan Quote Response Example Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/packages/lending-sdk/sdk-api-reference.md Example structure of the response object returned by `getLoanQuote` when calculating collateral requirements for a borrow amount. ```json { collateralTiers: { conservative: { usdValue: "5000", Btc: "1", Usdc: "5000", Sol: "200" ltv: "0" // min threshold }, optimal: { usdValue: "4000", Btc: "0.8", Usdc: "4000", Sol: "150", ltv: "0.5" }, risky: { usdValue: "3000", Btc: "0.7", Usdc: "3000", Sol: "100", ltv: "0.75" // based on current targetLtvThreshold } }, lendingPools: { Usdc: { originationFee: "123", originationFeeUsd: "123", brokerOriginationFee: "123", brokerOriginationFeeUsd: "123", networkFee: "456", networkFeeUsd: "456", brokerInterestFee: "789", brokerInterestFeeUsd: "789", totalFee: "10000", totalFeeUsd: "10000" }, // ... other assets } } ``` -------------------------------- ### Chainflip Network Export Example Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/06-constants-assets-chains.md Demonstrates how to import and use the ChainflipNetworks map for type-safe access to network identifiers. ```typescript import { ChainflipNetworks } from '@chainflip/sdk/swap'; // ChainflipNetworks is a map for type-safe access const network = ChainflipNetworks.perseverance; // 'perseverance' ``` -------------------------------- ### Channel Opening Fees Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/06-constants-assets-chains.md Get the fees associated with opening a deposit channel for each source chain. ```APIDOC ## getChannelOpeningFees ### Description Retrieves the fees charged by each source chain to open a deposit channel. ### Method `sdk.getChannelOpeningFees()` ### Response Example ```json { "Bitcoin": 10000n, // satoshis "Ethereum": 10000000000000000n // wei } ``` ``` -------------------------------- ### Get Swap Limits Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/06-constants-assets-chains.md Fetch the minimum and maximum swap amounts for different assets. Note that 'null' indicates an unlimited amount. ```typescript const sdk = new SwapSDK(); const limits = await sdk.getSwapLimits(); // { // minimumSwapAmounts: { Bitcoin: { Btc: 10000n }, ... }, // maximumSwapAmounts: { Ethereum: { Eth: null }, ... } // } // BTC minimum: 10000 satoshis (0.0001 BTC) const btcMin = limits.minimumSwapAmounts.Bitcoin.Btc; // ETH maximum: null (unlimited) const ethMax = limits.maximumSwapAmounts.Ethereum.Eth; ``` -------------------------------- ### Swap SDK Methods Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/README.md Documentation for the SwapSDK class, which is the main integration point for performing swaps. It includes methods for getting quotes, requesting deposit addresses, encoding vault swap data, and checking swap status. ```APIDOC ## SwapSDK Class This class serves as the primary interface for interacting with the Chainflip swap functionality. ### Methods - **getQuoteV2**: Retrieves a swap quote. - **requestDepositAddressV2**: Requests a deposit address for a swap. - **encodeVaultSwapData**: Encodes data for vault swaps. - **getStatusV2**: Retrieves the status of a swap. ``` -------------------------------- ### Get Channel Opening Fees Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/06-constants-assets-chains.md Retrieve the fees required to open a deposit channel for each source chain. Fees are denominated in the chain's native unit (e.g., satoshis for Bitcoin, wei for Ethereum). ```typescript const sdk = new SwapSDK(); const fees = await sdk.getChannelOpeningFees(); // { // Bitcoin: 10000n, // satoshis // Ethereum: 10000000000000000n, // wei // ... // } ``` -------------------------------- ### Swap Status Response Example (Completed) Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/04-endpoints.md This JSON object represents a completed swap, detailing source and destination assets, amounts, transaction references, and estimated durations. It includes common fields and state-specific details for the 'COMPLETED' state. ```json { "state": "COMPLETED", "srcChain": "Bitcoin", "srcAsset": "BTC", "destChain": "Ethereum", "destAsset": "ETH", "swapId": "swap-123", "destAddress": "0xa56A6be23b6Cf39D9448FF6e897C29c41c8fbDFF", "deposit": { "amount": "50000000", "txRef": "tx:abcdef123456", "txConfirmations": 6, "witnessedAt": 1695000000, "witnessedBlockIndex": "1000" }, "swap": { "originalInputAmount": "50000000", "remainingInputAmount": "0", "swappedInputAmount": "50000000", "swappedIntermediateAmount": "50000000", "swappedOutputAmount": "24900000000000000000", "regular": { "inputAmount": "50000000", "outputAmount": "24900000000000000000", "scheduledAt": 1695000100, "scheduledBlockIndex": "1001", "executedAt": 1695000200, "executedBlockIndex": "1010" } }, "swapEgress": { "amount": "24890000000000000000", "scheduledAt": 1695000200, "scheduledBlockIndex": "1010", "txRef": "tx:ethereum123", "witnessedAt": 1695000500, "witnessedBlockIndex": "1050" }, "estimatedDurationSeconds": 600, "estimatedDurationsSeconds": { "deposit": 120, "swap": 300, "egress": 180 }, "srcChainRequiredBlockConfirmations": 6, "brokers": [ { "account": "cFMbpxtvY96gMgBQxJQNYj3pNwj6YrqhKSXqgm3YD9dLLfKKq", "commissionBps": "50" } ], "fees": [ { "type": "INGRESS", "amount": "100000", "chain": "Bitcoin", "asset": "BTC" }, { "type": "EGRESS", "amount": "10000000000000000", "chain": "Ethereum", "asset": "ETH" } ] } ``` -------------------------------- ### Get Redemption Tax Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/02-funding-sdk.md Retrieves the tax amount in wei that is applied to redemptions. This tax is deducted before the funds are returned to Ethereum. The example shows how to calculate the amount received after tax. ```typescript const tax = await fundingSDK.getRedemptionTax(); console.log('Redemption tax:', ethers.formatUnits(tax, 18), 'FLIP'); const pending = await fundingSDK.getPendingRedemption(accountId); if (pending) { const afterTax = pending.amount - tax; console.log('Will receive:', ethers.formatUnits(afterTax, 18), 'FLIP'); } ``` -------------------------------- ### Initialize SwapSDK with Minimal Configuration Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/05-configuration.md Instantiate the SwapSDK with default options, which uses the 'perseverance' network. ```typescript import { SwapSDK } from '@chainflip/sdk/swap'; // Minimal configuration (uses perseverance) const sdk = new SwapSDK(); ``` -------------------------------- ### Initialize SwapSDK with Broker Configuration Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/05-configuration.md Configure the SwapSDK to use a specific broker service URL and associate quotes with a broker account. ```typescript import { SwapSDK } from '@chainflip/sdk/swap'; // With broker configuration const sdk = new SwapSDK({ network: 'perseverance', broker: { url: 'https://broker-service.example.com', }, brokerAccount: 'cFMbpxtvY96gMgBQxJQNYj3pNwj6YrqhKSXqgm3YD9dLLfKKq', }); ``` -------------------------------- ### Chainflip Lending SDK Method Overview Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/packages/lending-sdk/sdk-api-reference.md Provides a high-level overview of the available methods within the Chainflip Lending SDK, categorized into read and write operations. ```text ┌──────────────────────────────────────────────────────────┐ │ CHAINFLIP LENDING SDK │ ├──────────────────────────────────────────────────────────┤ │ │ │ READ METHODS │ │ ├─ getLoanQuote() → Calculate loan terms │ │ ├─ getSupportedAssets() → List available assets │ │ ├─ getAssetPoolInfo() → Pool metrics │ │ ├─ getProjectedDepositInfo()→ Simulate supply │ │ ├─ getSuppliedPositionInfo()→ User supply position │ │ ├─ getBalances() → Account balances │ │ ├─ getLoanStatus() → Loan information │ │ └─ getDepositChannelStatus()→ Check deposit status │ │ │ │ WRITE METHODS │ │ │ │ DEPOSIT CHANNEL │ │ └─ openDepositChannel() → Create channel │ │ │ │ BORROW FLOWS │ │ ├─ requestLoan() → Create new loan │ │ ├─ expandLoan() → Increase loan amount │ │ └─ topUpCollateral() → Add collateral │ │ │ │ REPAYMENT FLOWS │ │ ├─ repayLoan() → Partial/full repayment │ │ ├─ repayAndClose() → Repay + close position │ │ ├─ initiateVoluntaryLiquidation() → Opt into liquidation│ │ └─ stopVoluntaryLiquidation() → Cancel liquidation │ │ │ │ COLLATERAL MANAGEMENT FLOWS │ │ ├─ swapCollateral() → Replace collateral │ │ └─ deleverage() → Repay + remove collateral │ │ │ │ SUPPLY FLOWS │ │ ├─ supplyMultiple() → Deposit to pools │ │ └─ withdrawSupply() → Withdraw from pools │ │ │ │ ADVANCED FLOWS │ │ └─refinance() → Close old + open new │ │ │ └──────────────────────────────────────────────────────────┘ ``` -------------------------------- ### GET /v2/quote Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/04-endpoints.md Retrieves swap quotations with estimated amounts and execution details. This endpoint allows users to get real-time swap quotes based on source and destination assets, chains, and the desired amount. ```APIDOC ## GET /v2/quote ### Description Retrieves swap quotations with estimated amounts and execution details. ### Method GET ### Endpoint /api/v2/quote ### Parameters #### Query Parameters - **srcChain** (string) - Required - Source blockchain (Bitcoin, Ethereum, Polkadot, Solana, Arbitrum, Assethub, Tron) - **srcAsset** (string) - Required - Source asset symbol (BTC, ETH, USDC, etc.) - **destChain** (string) - Required - Destination blockchain - **destAsset** (string) - Required - Destination asset symbol - **amount** (string) - Required - Swap amount in base units (satoshis, wei, lamports, etc.) as numeric string - **brokerCommissionBps** (string) - Optional - Total broker commission in basis points - **ccmGasBudget** (string) - Optional - CCM gas budget (numeric or hex) - **ccmMessageLengthBytes** (string) - Optional - CCM message length in bytes - **dcaV2Enabled** (string) - Optional - Enable DCA v2 quote type ("true" or "false") - **isVaultSwap** (string) - Optional - Vault swap flag ("true" or "false") - **isOnChain** (string) - Optional - On-chain swap flag ("true" or "false") - **brokerIdSs58** (string) - Optional - Broker Chainflip SS58 address ### Response #### Success Response (200) - **type** (string) - 'REGULAR' or 'DCA' - **depositAmount** (string) - Amount to deposit in source asset base units - **egressAmount** (string) - Amount expected to receive in destination asset base units - **intermediateAmount** (string) - Intermediate amount (if applicable) - **includedFees** (Array) - List of fees - **poolInfo** (Array) - Liquidity pools involved - **estimatedDurationSeconds** (number) - Total estimated execution time - **estimatedDurationsSeconds** (object) - { deposit, swap, egress } durations - **estimatedPrice** (string) - Output/Input price ratio - **recommendedSlippageTolerancePercent** (number) - Suggested slippage tolerance - **recommendedRetryDurationMinutes** (number) - Suggested retry duration - **boostQuote** (object) - Optional boost version of quote - **estimatedBoostFeeBps** (number) - Estimated boost fee - **maxBoostFeeBps** (number) - Maximum possible boost fee ### Request Example ```bash curl "https://perseverance.chainflip.io/api/v2/quote?srcChain=Bitcoin&srcAsset=BTC&destChain=Ethereum&destAsset=ETH&amount=50000000" ``` ### Response Example ```json [ { "type": "REGULAR", "depositAmount": "50000000", "egressAmount": "25000000000000000000", "intermediateAmount": null, "includedFees": [ { "type": "INGRESS", "amount": "100000", "chain": "Bitcoin", "asset": "BTC" }, { "type": "EGRESS", "amount": "10000000000000000", "chain": "Ethereum", "asset": "ETH" } ], "poolInfo": [ { "baseAsset": { "chain": "Bitcoin", "asset": "BTC" }, "quoteAsset": { "chain": "Ethereum", "asset": "ETH" }, "fee": { "amount": "500000", "type": "LIQUIDITY" } } ], "estimatedDurationSeconds": 600, "estimatedDurationsSeconds": { "deposit": 120, "swap": 300, "egress": 180 }, "estimatedPrice": "0.5", "recommendedSlippageTolerancePercent": 1.5, "recommendedRetryDurationMinutes": 30, "boostQuote": { "estimatedBoostFeeBps": 50, "maxBoostFeeBps": 100, "type": "REGULAR", "depositAmount": "50000000", "egressAmount": "24500000000000000000" } } ] ``` ``` -------------------------------- ### SwapSDK Constructor Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/01-swap-sdk.md Initializes a SwapSDK instance with optional configuration for network, backend URL, broker details, RPC endpoint, enabled features, and broker account. ```APIDOC ## SwapSDK Constructor ### Description Initializes a SwapSDK instance with optional configuration. ### Signature ```typescript constructor(options?: SwapSDKOptions): SwapSDK ``` ### Parameters #### options (`SwapSDKOptions`) - `network` (ChainflipNetwork, Optional, Default: 'perseverance'): Chainflip network to use. - `backendUrl` (string, Optional): Backend service URL for swap requests. - `broker.url` (string, Optional): Optional broker service URL for broker-facilitated swaps. - `rpcUrl` (string, Optional): State chain RPC endpoint. - `enabledFeatures.dcaV2` (boolean, Optional, Default: false): Enable DCA v2 (Dollar-Cost Averaging) quote type. - `brokerAccount` (`cF${string}`, Optional): Chainflip broker SS58 address attributed to quote requests. ### Example ```typescript import { SwapSDK } from '@chainflip/sdk/swap'; // Basic initialization (uses perseverance testnet) const sdk = new SwapSDK(); // With custom network const sdk = new SwapSDK({ network: 'sisyphos', enabledFeatures: { dcaV2: true }, }); // With broker account const sdk = new SwapSDK({ network: 'perseverance', brokerAccount: 'cFMbpxtvY96gMgBQxJQNYj3pNwj6YrqhKSXqgm3YD9dLLfKKq', }); ``` ``` -------------------------------- ### Initialize SwapSDK Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/01-swap-sdk.md Initialize a SwapSDK instance. Basic initialization uses the default testnet. Custom networks and features can be specified. ```typescript import { SwapSDK } from '@chainflip/sdk/swap'; // Basic initialization (uses perseverance testnet) const sdk = new SwapSDK(); // With custom network const sdk = new SwapSDK({ network: 'sisyphos', enabledFeatures: { dcaV2: true }, }); // With broker account const sdk = new SwapSDK({ network: 'perseverance', brokerAccount: 'cFMbpxtvY96gMgBQxJQNYj3pNwj6YrqhKSXqgm3YD9dLLfKKq', }); ``` -------------------------------- ### Get Lending Pools Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/packages/lending-sdk/README.md Retrieve information about all available lending pools. ```APIDOC ## Get Lending Pools ### Description Fetches a list of all available lending pools, providing details about each pool. ### Method `getLendingPools()` ### Usage ```typescript const pools = await client.getLendingPools(); ``` ``` -------------------------------- ### Initialize SwapSDK with DCA v2 Enabled Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/05-configuration.md Enable support for DCA v2 quote types in the SwapSDK and set a default broker account for attribution. ```typescript import { SwapSDK } from '@chainflip/sdk/swap'; // With all features enabled const sdk = new SwapSDK({ network: 'perseverance', enabledFeatures: { dcaV2: true, }, brokerAccount: 'cFBrokerAddress123', }); ``` -------------------------------- ### Swap SDK - Get Status Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/00-index.md Retrieves the status of a swap operation using its ID. ```APIDOC ## getStatusV2 ### Description Retrieves the status of a swap operation. ### Method `sdk.getStatusV2(params)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **id** (string) - Required - The ID of the swap operation. ### Request Example ```json { "id": "some-channel-id" } ``` ### Response #### Success Response (200) - **state** (string) - The current state of the swap (e.g., 'SWAPPED'). #### Response Example ```json { "state": "SWAPPED" } ``` ``` -------------------------------- ### getRequiredBlockConfirmations() Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/01-swap-sdk.md Gets the number of block confirmations required on a source chain before a deposit is considered finalized and processed. ```APIDOC ## getRequiredBlockConfirmations() ### Description Returns the number of source chain block confirmations required before a deposit is considered final. ### Method `async getRequiredBlockConfirmations(): Promise>` ### Return Type: ChainMap Map of chain to required confirmations or null. ``` -------------------------------- ### Database Migrations for Swap Package Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/CLAUDE.md Manages database migrations for the swap package. Use 'migrate:dev' to create a new migration and 'migrate:deploy' to apply existing migrations. ```bash pnpm run --dir=packages/swap migrate:dev pnpm run --dir=packages/swap migrate:deploy ``` -------------------------------- ### Chainflip Chains Export Example Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/06-constants-assets-chains.md Shows how to import and use the Chains map for type-safe access to supported blockchain identifiers. ```typescript import { Chains } from '@chainflip/sdk/swap'; // Type-safe chain access Chains.Bitcoin // 'Bitcoin' Chains.Ethereum // 'Ethereum' Chains.Polkadot // 'Polkadot' Chains.Solana // 'Solana' Chains.Arbitrum // 'Arbitrum' Chains.Assethub // 'Assethub' Chains.Tron // 'Tron' ``` -------------------------------- ### Basic Funding Usage with FundingSDK Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/00-index.md Shows how to fund a validator account using the FundingSDK. This requires an ethers provider, a signer with a private key, and the account ID to fund. Ensure your PRIVATE_KEY environment variable is set. ```typescript import { FundingSDK } from '@chainflip/sdk/funding'; import { ethers } from 'ethers'; const provider = new ethers.JsonRpcProvider('https://eth-rpc.com'); const signer = new ethers.Wallet(process.env.PRIVATE_KEY!, provider); const fundingSDK = new FundingSDK({ signer, network: 'perseverance' }); // Fund a validator account const amount = ethers.parseUnits('1000', 18); // 1000 FLIP const txHash = await fundingSDK.fundStateChainAccount(accountId, amount); ``` -------------------------------- ### Initialize FundingSDK Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/02-funding-sdk.md Initializes a FundingSDK instance for interacting with the Ethereum-based state chain gateway contract. Requires an ethers v6 signer. ```typescript import { FundingSDK } from '@chainflip/sdk/funding'; import { ethers } from 'ethers'; // Using ethers v6 wallet const provider = new ethers.JsonRpcProvider('https://eth-rpc.chainflip.io'); const signer = new ethers.Wallet(privateKey, provider); const fundingSDK = new FundingSDK({ signer, network: 'perseverance', }); ``` -------------------------------- ### Initialize SwapSDK with Explicit Network Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/05-configuration.md Configure the SwapSDK to target a specific Chainflip network, such as 'sisyphos'. ```typescript import { SwapSDK } from '@chainflip/sdk/swap'; // Explicit network const sdk = new SwapSDK({ network: 'sisyphos', }); ``` -------------------------------- ### Swap SDK - Get Quote Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/00-index.md Retrieves a quote for a swap operation, specifying source and destination chains and assets, along with the amount. ```APIDOC ## getQuoteV2 ### Description Retrieves a quote for a swap operation. ### Method `sdk.getQuoteV2(params)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **srcChain** (string) - Required - The source chain (e.g., 'Bitcoin'). - **srcAsset** (string) - Required - The source asset (e.g., 'BTC'). - **destChain** (string) - Required - The destination chain (e.g., 'Ethereum'). - **destAsset** (string) - Required - The destination asset (e.g., 'ETH'). - **amount** (string) - Required - The amount to swap. ### Request Example ```json { "srcChain": "Bitcoin", "srcAsset": "BTC", "destChain": "Ethereum", "destAsset": "ETH", "amount": "0.5" } ``` ### Response #### Success Response (200) - **quotes** (array) - An array of available quotes. - **recommendedSlippageTolerancePercent** (string) - The recommended slippage tolerance. #### Response Example ```json { "quotes": [ { "recommendedSlippageTolerancePercent": "0.5" } ] } ``` ``` -------------------------------- ### FundingSDK Constructor Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/02-funding-sdk.md Initializes a FundingSDK instance for interacting with the Ethereum-based state chain gateway contract. ```APIDOC ## FundingSDK Constructor ### FundingSDK ```typescript constructor(options: FundingSDKOption): FundingSDK ``` Initializes a FundingSDK instance for interacting with the Ethereum-based state chain gateway contract. **Parameters:** | Property | Type | Required | Default | Description | |----------|------|----------|---------|-------------| | signer | `ethers.Signer` | Yes | — | Ethers v6 signer (for signing transactions) | | network | `ChainflipNetwork` | No | `'perseverance'` | Chainflip network: `'perseverance'`, `'sisyphos'`, `'berghain'`, `'backspin'`, or `'mainnet'` | | rpcUrl | `string` | No | Network-specific default | Custom RPC URL for state chain | **Example:** ```typescript import { FundingSDK } from '@chainflip/sdk/funding'; import { ethers } from 'ethers'; // Using ethers v6 wallet const provider = new ethers.JsonRpcProvider('https://eth-rpc.chainflip.io'); const signer = new ethers.Wallet(privateKey, provider); const fundingSDK = new FundingSDK({ signer, network: 'perseverance', }); ``` ``` -------------------------------- ### Initialize FundingSDK with Custom RPC Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/05-configuration.md Configure the FundingSDK to use a custom RPC URL for a specific network, such as 'mainnet'. ```typescript import { FundingSDK } from '@chainflip/sdk/funding'; import { ethers } from 'ethers'; // With custom RPC const fundingSDK = new FundingSDK({ signer, network: 'mainnet', rpcUrl: 'https://custom-rpc.example.com', }); ``` -------------------------------- ### Get Asset by Chain and Symbol Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/06-constants-assets-chains.md Retrieves the Chainflip ID for a given asset on a specific chain. This is useful for internal SDK operations. ```APIDOC ## getChainflipId ### Description Retrieves the Chainflip ID for a given asset on a specific chain. ### Method Signature ```typescript getChainflipId({ chain: string, asset: string }): string ``` ### Parameters #### Path Parameters - **chain** (string) - Required - The name of the chain (e.g., 'Ethereum'). - **asset** (string) - Required - The symbol of the asset (e.g., 'USDC'). ### Response - **string** - The Chainflip ID for the asset (e.g., 'Usdc'). ### Example ```typescript import { getChainflipId } from '@chainflip/sdk/swap'; const asset = getChainflipId({ chain: 'Ethereum', asset: 'USDC', }); // Returns: 'Usdc' ``` ``` -------------------------------- ### Get Redemption Delay Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/02-funding-sdk.md Retrieves the required delay in seconds that must pass after requesting a redemption before it can be executed. This value is returned as a bigint. ```typescript const delay = await fundingSDK.getRedemptionDelay(); console.log('Redemption delay:', Number(delay), 'seconds'); console.log('Redemption delay:', Number(delay) / 86400, 'days'); ``` -------------------------------- ### Retrieve All Assets and Filter by Chain/Capability Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/_autodocs/06-constants-assets-chains.md Instantiate `SwapSDK` to fetch all available assets, filter them by a specific chain, or by their capabilities like 'deposit' or 'destination'. ```typescript const sdk = new SwapSDK(); // Get all assets with their capabilities const assets = await sdk.getAssets(); // Get assets by chain const ethAssets = await sdk.getAssets('Ethereum'); // Filter by capability const depositAssets = await sdk.getAssets(undefined, 'deposit'); const destinationAssets = await sdk.getAssets(undefined, 'destination'); const boostAssets = await sdk.getAssets(undefined, 'deposit').then( a => a.filter(asset => /* check networkInfo.boostDepositsEnabled */) ) ``` -------------------------------- ### Get Account Balances Source: https://github.com/chainflip-io/chainflip-sdk-monorepo/blob/main/packages/lending-sdk/sdk-api-reference.md Retrieve the free and collateral balances for a given account address. This function queries the `cf_account_info` RPC endpoint. ```typescript getBalances(address: string) ```