LI.FI SDK

repository·main·Indexed 42 days ago

https://github.com/lifinance/sdk

A modular toolkit for implementing cross-chain and on-chain swaps and bridging across EVM, Solana, Bitcoin, Sui, Tron, and Stellar. Version 4.0.0-beta.11 provides a core SDK (@lifi/sdk) and ecosystem-specific providers to manage communication between smart routing APIs and smart contracts, supporting features like multi-hop bridges, reverse quotes, and arbitrary contract calls on destination chains.

Tokens
22.4K
Snippets
75
Records
108
Agent score
53%

What's inside LI.FI SDK

  1. Understand Solana E2E coverage and limitations

    main

    The Solana E2E harness is designed to validate specific execution paths and reliability features.

    What is covered:

    • Jito Bundle Path: Includes sendAndConfirmBundle, confirmBundle, and SolanaJitoWaitForTransactionTask.
    • Standard Path: Validated across 12 different asset pairs.
    • Ordering: Validates txHash-then-txLink sequence.
    • Resiliency: Tests raceRpcs against multiple live endpoints.

    What is NOT covered:

    • Multi-blockhash bundles: Bundles shared across different blockhashes.
    • 90s Ceiling: The harness does not test the 90s timeout as mainnet typically confirms much faster.
    • rpc-unavailable error: To test this manually, disable networking mid-run; expect error code 1027 (not 1018).

    Known Behavior & Failures

    • Slippage Failures: It is expected that many legs fail during simulation with InstructionError Custom: 25 (slippage). This is often due to Titan aggregator quote defects (e.g., quoting a significant premium for SOL→USDT or USDC→USDT) and is not considered an SDK defect.
    • Jito Bundle Requirement: For the bundle phase to work, the backend must return a Perena route for PENGU → USD* when jitoBundle: true is set in the routes options. Note that this must be in the routes options, not as a query parameter on /v1/quote or on stepTransaction.
  2. How the LI.FI SDK modular architecture works

    main

    The SDK is split into two main layers to optimize bundle size and maintain clean separation of concerns:

    1. @lifi/sdk (Core SDK): Contains shared functionality, actions, and the central execution logic.
    2. Provider Packages: Ecosystem-specific packages (e.g., @lifi/sdk-provider-ethereum) that handle wallet interactions and transaction execution for specific blockchain types.

    This allows developers to install only the providers they need, reducing bundle size and allowing the use of ecosystem-specific libraries optimized for each blockchain.

  3. Set up the LI.FI SDK client

    main

    To initialize the SDK, use createClient. You must provide an integrator string and an array of providers. Each provider is initialized with a configuration object that typically includes a function to retrieve a wallet or client (e.g., getWalletClient).

    Example for EVM chains using viem:

    import { createClient } from '@lifi/sdk'
    import { EthereumProvider } from '@lifi/sdk-provider-ethereum'
    import { createWalletClient, http } from 'viem'
    import { mainnet } from 'viem/chains'
    
    // You must construct your own wallet client
    const walletClient = createWalletClient({
      account,
      chain: mainnet,
      transport: http(),
    })
    
    const client = createClient({
      integrator: 'Your dApp/company name',
      providers: [
        EthereumProvider({
          getWalletClient: () => Promise.resolve(walletClient),
        }),
      ],
    })
    import { createClient } from '@lifi/sdk'
    import { EthereumProvider } from '@lifi/sdk-provider-ethereum'
    import { createWalletClient, http } from 'viem'
    import { mainnet } from 'viem/chains'
    
    const walletClient = createWalletClient({
      account,
      chain: mainnet,
      transport: http(),
    })
    
    const client = createClient({
      integrator: 'Your dApp/company name',
      providers: [
        EthereumProvider({
          getWalletClient: () => Promise.resolve(walletClient),
        }),
      ],
    })
  4. Install the LI.FI SDK Core

    main

    Install the core SDK package which contains the shared functionality, actions, and execution logic. This is required for all implementations.

    pnpm add @lifi/sdk
    # or
    npm install --save @lifi/sdk
  5. Install Provider Packages for different ecosystems

    main

    The LI.FI SDK uses a modular architecture. You must install the specific provider packages for the blockchain ecosystems you want to support. Note that most providers require you to install the underlying ecosystem library alongside the provider so you can construct and pass the wallet/client objects yourself.

    # EVM Chains (Ethereum, Polygon, Arbitrum, Optimism, etc.)
    pnpm add @lifi/sdk-provider-ethereum viem
    
    # Solana
    pnpm add @lifi/sdk-provider-solana @wallet-standard/base
    
    # Bitcoin
    pnpm add @lifi/sdk-provider-bitcoin @bigmi/core
    
    # Sui
    pnpm add @lifi/sdk-provider-sui @mysten/sui
    
    # Tron
    pnpm add @lifi/sdk-provider-tron @tronweb3/tronwallet-abstract-adapter
    
    # Stellar
    pnpm add @lifi/sdk-provider-stellar
  6. Set up the Solana E2E harness

    main

    The Solana E2E harness executes real swaps on Solana mainnet. Warning: This spends real money.

    To set up the environment, add the following variables to a .env file in your repository root. Ensure this file is gitignored and never committed.

    Required Environment Variables

    • SOLANA_PK: Your Solana base58 private key.
    • SOLANA_RPC_URLS: A comma-separated list of RPC URLs (e.g., https://your-quicknode-url/,https://your-helius-url/). At least one RPC must support getBundleStatuses for the Jito phase to function. For ChainId.SOL, these URLs replace LI.FI defaults.
    • LIFI_API_URL: The LI.FI API endpoint. Use https://staging.li.quest/v1 to avoid production quota exhaustion during matrix runs.
    • API_KEY: Your LI.FI API key (sent via the x-lifi-api-key header).

    Optional Environment Variables

    • MAX_SPEND_USD: The maximum total USD amount to spend for the entire run (default: 10). This is asserted before any tests run.
    • E2E_USD_PER_LEG: The USD amount to spend per leg (default: 0.5).
    • E2E_EXECUTE: Controls whether swaps are real or dry runs (see Running section).
    SOLANA_PK=<base58 private key>
    SOLANA_RPC_URLS=https://your-quicknode-url/,https://your-helius-url/
    LIFI_API_URL=https://staging.li.quest/v1
    API_KEY=<staging key>
  7. Setup the LI.FI SDK Node.js Examples

    main

    To run the example scripts in the lifi-sdk-node-sample directory, follow these steps:

    1. Configure Environment Variables: Copy the template to a .env file and add your private key.
      cp .env-template .env
    2. Install Dependencies: Use pnpm to install the required packages.
      pnpm install
    3. Wallet Preparation: Ensure your wallet contains small amounts of tokens on the chains used in the examples (e.g., Optimism, Arbitrum, Polygon).

    ⚠️ Safety Warning: These examples execute REAL transactions on mainnet chains. Use a dedicated test wallet with minimal funds and review all route details before confirming.

    cp .env-template .env
    pnpm install
  8. Run Solana E2E tests

    main

    Use pnpm to execute the E2E harness. By default, the command performs a dry run. To perform real swaps on mainnet, you must explicitly set the E2E_EXECUTE environment variable to true.

    Safety Notes:

    • Only E2E_EXECUTE=true triggers real swaps. Values like 1, yes, or TRUE are treated as dry runs.
    • The standard pnpm test command excludes E2E spec files (**/*.e2e.spec.ts). To run all specs including E2E, you must use vitest --run.
    • Legs run sequentially.
    • MAX_SPEND_USD is checked against the total planned run at collection time, before any test execution begins.
    # Dry run (no real money spent)
    pnpm --filter @lifi/sdk-provider-solana test:e2e
    
    # Real swaps (spends real money)
    E2E_EXECUTE=true pnpm --filter @lifi/sdk-provider-solana test:e2e
  9. Understand Execution status and actions

    main

    The SDK tracks the progress of a transaction through an Execution object.

    Execution Statuses:

    • ACTION_REQUIRED: User intervention is needed (e.g., signing a permit).
    • PENDING: The transaction is in progress.
    • FAILED: The execution encountered an error.
    • DONE: The execution completed successfully.

    Execution Actions: An Execution contains an array of ExecutionAction objects. Each action has a type (e.g., SWAP, CROSS_CHAIN, PERMIT, CHECK_ALLOWANCE) and a status (e.g., STARTED, MESSAGE_REQUIRED, CANCELLED). Actions also provide metadata like txHash, txLink, and error details if they fail.

  10. Bridge with an Exact Output Amount (Reverse Quote)

    main

    If you need to receive a specific amount of tokens on the destination chain, use getContractCallsQuote with the toAmount parameter. The SDK will automatically calculate the required input amount.

    Key SDK features:

    • getContractCallsQuote({ toAmount }): Performs a reverse quote calculation.
    • Token allowance checking and setting.

    Run command:

    pnpm example:toAmount
  11. Execute Multi-Hop Bridges and Manual Transactions

    main

    For complex bridging scenarios involving multiple intermediate chains, use getContractCallsQuote to chain bridges and contract calls together. This pattern requires manual transaction execution and status polling.

    Workflow:

    1. Use getQuote() for single-step quotes.
    2. Use getContractCallsQuote() to create a quote that includes destination contract calls (e.g., bridging to a chain AND executing a second bridge leg).
    3. Manually send the transaction.
    4. Use getStatus() to poll for the transaction status.

    Run command:

    pnpm example:multihop
  12. Execute Arbitrary Contract Calls on Destination

    main

    The SDK allows you to execute arbitrary contract calls on the destination chain as part of a bridge transaction. This is useful for DeFi integrations like carbon offsetting or vault deposits.

    Workflow:

    1. Encode the target function call (e.g., using retireExactCarbonDefault for Klima DAO or deposit for Yearn).
    2. Create a quote using getContractCallsQuote({ contractCalls }) that includes the bridge and the encoded call.
    3. Execute and monitor the transaction.

    Examples:

    • Klima DAO: klimaRetireExactCarbon.ts (Optimism → Polygon)
    • Polynomial: polynomialDeposit.ts (Arbitrum → Optimism)
    • Yearn: yearnDeposit.ts (Arbitrum → Polygon)

    Run commands:

    pnpm example:klima
    pnpm example:polynomial
    pnpm example:yearn