> ## Documentation Index
> Fetch the complete documentation index at: https://docs.li.fi/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK 集成

> 使用 LI.FI TypeScript SDK 进行托管 Composer 执行，包含自动授权处理、状态跟踪、钩子和事件。

LI.FI SDK 处理完整的 Composer 生命周期（授权检查、链切换、交易提交和状态跟踪），让您可以专注于应用逻辑。本指南展示如何通过 SDK 使用 Composer。

<Note>
  **先决条件：** 您应该已经安装并配置了 LI.FI SDK。如果没有，请参见 [安装 SDK](/sdk/installing-the-sdk) 和 [配置 SDK](/sdk/configure-sdk)。
</Note>

***

## 快速示例

使用 SDK 将 USDC 存入 Base 上的 Morpho 金库：

```ts theme={"system"}
import { createConfig, getQuote, convertQuoteToRoute, executeRoute } from '@lifi/sdk';

// 1. 配置 SDK（在应用启动时一次）
createConfig({
  integrator: 'YourAppName',
});

// 2. 获取 Composer 报价
const quote = await getQuote({
  fromChain: 8453,                                              // Base
  toChain: 8453,                                                // Base
  fromToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',     // Base 上的 USDC
  toToken: '0x7BfA7C4f149E7415b73bdeDfe609237e29CBF34A',       // Morpho 金库代币
  fromAmount: '1000000',                                        // 1 USDC
  fromAddress: '0xYOUR_WALLET_ADDRESS',
});

// 3. 转换报价为路由并执行 - SDK 处理授权、提交和跟踪
const route = convertQuoteToRoute(quote);
const executedRoute = await executeRoute(route, {
  updateRouteHook(updatedRoute) {
    console.log('路由已更新：', updatedRoute);
  },
});

console.log('完成！', executedRoute);
```

就这样。SDK 内部管理：

* **授权检查和批准**
* **交易数据检索**（如果使用 `/advanced/routes`）
* **交易提交**
* **状态跟踪和轮询**
* **链切换**（用于跨链流程）

***

## 分步指南

### 1. 配置 SDK

在应用启动时设置 SDK 一次。您必须为您想使用的链配置 [EVM 提供者](/sdk/configure-sdk-providers#setup-evm-provider)。

```ts theme={"system"}
import { createConfig } from '@lifi/sdk';
import { createWalletClient, http } from 'viem';
import { base } from 'viem/chains';

createConfig({
  integrator: 'YourAppName',
  providers: [
    // 配置您的 EVM 提供者 - 完整设置请参见 SDK 文档
  ],
});
```

完整的提供者配置，请参见 [配置 SDK 提供者](/sdk/configure-sdk-providers)。

### 2. 请求 Composer 报价

使用 `getQuote` 获取单个最佳路由（包含交易数据）或 `getRoutes` 获取多个选项。

#### 使用 `getQuote`

```ts theme={"system"}
import { getQuote } from '@lifi/sdk';

const quote = await getQuote({
  fromChain: 8453,
  toChain: 8453,
  fromToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
  toToken: '0x7BfA7C4f149E7415b73bdeDfe609237e29CBF34A',
  fromAmount: '1000000',
  fromAddress: '0xYOUR_WALLET_ADDRESS',
});
```

#### 使用 `getRoutes`

```ts theme={"system"}
import { getRoutes } from '@lifi/sdk';

const routes = await getRoutes({
  fromChain: 8453,
  toChain: 8453,
  fromToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
  toToken: '0x7BfA7C4f149E7415b73bdeDfe609237e29CBF34A',
  fromAmount: '1000000',
  fromAddress: '0xYOUR_WALLET_ADDRESS',
});

// 选择最佳路由
const selectedRoute = routes.routes[0];
```

### 3. 转换并执行路由

SDK 提供了 `convertQuoteToRoute` 和 `executeRoute` 函数来处理整个执行流程。

```ts theme={"system"}
import { convertQuoteToRoute, executeRoute } from '@lifi/sdk';

// 如果使用 getQuote
const route = convertQuoteToRoute(quote);

// 如果使用 getRoutes，直接使用选定的路由
const route = selectedRoute;

// 执行路由
const executedRoute = await executeRoute(route, {
  // 可选钩子
  updateRouteHook(updatedRoute) {
    console.log('路由更新：', updatedRoute);
  },
  onChainSwitch(chainId) {
    console.log('切换到链：', chainId);
  },
});
```

### 4. 处理执行事件

SDK 发出事件来跟踪执行进度：

```ts theme={"system"}
const executedRoute = await executeRoute(route, {
  updateRouteHook(updatedRoute) {
    console.log('路由更新：', updatedRoute);
  },
  onChainSwitch(chainId) {
    console.log('切换到链：', chainId);
  },
  gasCosts: (gasCosts) => {
    console.log('Gas 成本：', gasCosts);
  },
});

console.log('执行完成：', executedRoute);
```

***

## 跨链 Composer

SDK 自动处理跨链 Composer 流程的复杂性：

```ts theme={"system"}
const crossChainQuote = await getQuote({
  fromChain: 1,                                                 // Ethereum
  toChain: 8453,                                                // Base
  fromToken: '0x0000000000000000000000000000000000000000',       // ETH (原生)
  toToken: '0x7BfA7C4f149E7415b73bdeDfe609237e29CBF34A',       // Morpho 金库代币
  fromAmount: '100000000000000000',                             // 0.1 ETH
  fromAddress: '0xYOUR_WALLET_ADDRESS',
});

const route = convertQuoteToRoute(crossChainQuote);
const executedRoute = await executeRoute(route);

// SDK 自动处理：
// - 源链交易（兑换 + 跨链）
// - 等待跨链完成
// - 目标链交易（Composer 存款）
// - 状态跟踪
```

***

## 错误处理

SDK 提供结构化错误处理：

```ts theme={"system"}
import { LiFiErrorCode } from '@lifi/sdk';

try {
  const executedRoute = await executeRoute(route);
} catch (error) {
  if (error.code === LiFiErrorCode.TransactionFailed) {
    console.error('交易失败：', error.message);
  } else if (error.code === LiFiErrorCode.InsufficientBalance) {
    console.error('余额不足');
  } else if (error.code === LiFiErrorCode.GasLimitChanged) {
    console.error('Gas 限制已更改，请重试');
  }
}
```

***

## 高级配置

### 自定义提供者

为不同链配置特定提供者：

```ts theme={"system"}
import { createConfig } from '@lifi/sdk';
import { createWalletClient, http } from 'viem';
import { mainnet, base, arbitrum } from 'viem/chains';

createConfig({
  integrator: 'YourAppName',
  providers: [
    createWalletClient({
      chain: mainnet,
      transport: http('https://mainnet.infura.io/v3/YOUR_PROJECT_ID'),
      account: 'YOUR_WALLET_ADDRESS',
    }),
    createWalletClient({
      chain: base,
      transport: http('https://mainnet.base.org'),
      account: 'YOUR_WALLET_ADDRESS',
    }),
    createWalletClient({
      chain: arbitrum,
      transport: http('https://arbitrum.infura.io/v3/YOUR_PROJECT_ID'),
      account: 'YOUR_WALLET_ADDRESS',
    }),
  ],
});
```

### 执行选项

自定义执行行为：

```ts theme={"system"}
const executedRoute = await executeRoute(route, {
  // 控制执行
  executeInBackground: false,  // 在前台执行
  
  // 钩子
  updateRouteHook(updatedRoute) {
    // 路由更新时的回调
  },
  onChainSwitch(chainId) {
    // 链切换时的回调
  },
  
  // 选项
  gasCosts: (gasCosts) => {
    // Gas 成本估算
  },
  infiniteApproval: true,  // 无限授权
});
```

***

## 完整示例

这是一个完整的 Composer SDK 集成示例：

```ts theme={"system"}
import { 
  createConfig, 
  getQuote, 
  convertQuoteToRoute, 
  executeRoute,
  LiFiErrorCode 
} from '@lifi/sdk';
import { createWalletClient, http } from 'viem';
import { base, mainnet } from 'viem/chains';

// 1. 配置 SDK
createConfig({
  integrator: 'YourAppName',
  providers: [
    createWalletClient({
      chain: base,
      transport: http('https://mainnet.base.org'),
      account: '0xYOUR_WALLET_ADDRESS',
    }),
    createWalletClient({
      chain: mainnet,
      transport: http('https://mainnet.infura.io/v3/YOUR_PROJECT_ID'),
      account: '0xYOUR_WALLET_ADDRESS',
    }),
  ],
});

// 2. Composer 执行函数
async function executeComposerDeposit() {
  try {
    // 获取报价
    const quote = await getQuote({
      fromChain: 1,                                                 // Ethereum
      toChain: 8453,                                                // Base
      fromToken: '0x0000000000000000000000000000000000000000',       // ETH
      toToken: '0x7BfA7C4f149E7415b73bdeDfe609237e29CBF34A',       // Morpho 金库
      fromAmount: '100000000000000000',                             // 0.1 ETH
      fromAddress: '0xYOUR_WALLET_ADDRESS',
    });

    console.log('收到报价，工具：', quote.tool);

    // 转换并执行
    const route = convertQuoteToRoute(quote);
    const executedRoute = await executeRoute(route, {
      updateRouteHook(updatedRoute) {
        console.log('路由更新：', updatedRoute.steps.length, '步骤');
      },
      onChainSwitch(chainId) {
        console.log('切换到链：', chainId);
      },
    });

    console.log('执行完成！');
    console.log('最终状态：', executedRoute.status);
    
  } catch (error) {
    console.error('执行失败：', error);
    
    if (error.code === LiFiErrorCode.TransactionFailed) {
      console.error('交易失败，请重试');
    } else if (error.code === LiFiErrorCode.InsufficientBalance) {
      console.error('余额不足');
    }
  }
}

// 执行
executeComposerDeposit();
```

***

## 下一步

<CardGroup cols={2}>
  <Card title="API 集成" icon="code" href="/composer/guides/api-integration">
    直接 REST API 集成
  </Card>

  <Card title="Widget 集成" icon="window" href="/composer/guides/widget-integration">
    使用 LI.FI Widget
  </Card>

  <Card title="跨链模式" icon="bridge" href="/composer/guides/cross-chain-compose">
    跨链 Composer 流程
  </Card>

  <Card title="SDK 文档" icon="cube" href="/sdk/overview">
    完整 SDK 参考
  </Card>
</CardGroup>
