> ## 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 Integration

> Use the LI.FI TypeScript SDK for managed Composer execution with automatic allowance handling, status tracking, hooks, and events.

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

<Note>
  **前置条件：** 你应已安装并配置好 LI.FI SDK。如果没有，参见 [Installing the SDK](/sdk/installing-the-sdk) 与 [Configure
  SDK](/sdk/configure-sdk)。
</Note>

***

## Quick Example

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

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

// 1. Configure the SDK (once, at app startup)
const client = createClient({
  integrator: "YourAppName",
});

// 2. Get a Composer quote
const quote = await getQuote(client, {
  fromChain: 8453, // Base
  toChain: 8453, // Base
  fromToken: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC on Base
  toToken: "0x7BfA7C4f149E7415b73bdeDfe609237e29CBF34A", // Morpho vault token
  fromAmount: "1000000", // 1 USDC
  fromAddress: "0xYOUR_WALLET_ADDRESS",
});

// 3. Convert quote to route and execute - SDK handles allowance, submission, and tracking
const route = convertQuoteToRoute(quote);
const executedRoute = await executeRoute(client, route, {
  updateRouteHook(updatedRoute) {
    console.log("Route updated:", updatedRoute);
  },
});

console.log("Done!", executedRoute);
```

就是这样。SDK 在内部管理：

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

***

## Step-by-Step Guide

### 1. Configure the SDK

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

```ts theme={"system"}
import { createClient } from "@lifi/sdk";
import { EthereumProvider } from "@lifi/sdk-provider-ethereum";

const client = createClient({
  integrator: "YourAppName",
});

client.setProviders([
  EthereumProvider({
    getWalletClient: () => Promise.resolve(walletClient),
  }),
]);
```

如需完整的 provider 配置，参见 [Configure SDK Providers](/sdk/configure-sdk-providers)。

### 2. Request a Composer Quote

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

#### Using `getQuote`

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

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

#### Using `getRoutes`

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

const result = await getRoutes(client, {
  fromChainId: 8453,
  toChainId: 8453,
  fromTokenAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
  toTokenAddress: "0x7BfA7C4f149E7415b73bdeDfe609237e29CBF34A",
  fromAmount: "1000000",
  fromAddress: "0xYOUR_WALLET_ADDRESS",
});

const route = result.routes[0]; // Select the best route
```

<Tip>
  `toToken` / `toTokenAddress` 始终是目标协议的 **vault 代币地址**。这正是触发 Composer 的原因。你可以在协议自己的应用或文档中找到 vault 代币地址。
</Tip>

### 3. Execute the Route

`executeRoute` 函数处理整个执行生命周期：

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

const executedRoute = await executeRoute(client, route, {
  // Called whenever the route object is updated during execution
  updateRouteHook(updatedRoute) {
    const step = updatedRoute.steps[0];
    const actions = step?.execution?.actions;
    const lastAction = actions?.[actions.length - 1];

    console.log(`Step: ${step?.tool}`);
    console.log(`Status: ${lastAction?.status}`);
    console.log(`Tx: ${lastAction?.txHash || "pending"}`);
  },
});
```

### 4. Monitor Execution

`updateRouteHook` 回调会在每次状态变更时触发。用它来更新你的 UI：

```ts theme={"system"}
const executedRoute = await executeRoute(client, route, {
  updateRouteHook(updatedRoute) {
    for (const step of updatedRoute.steps) {
      if (!step.execution) continue;

      for (const action of step.execution.actions) {
        switch (action.status) {
          case "STARTED":
            console.log(`${action.type} started`);
            break;
          case "PENDING":
            console.log(`${action.type} pending - tx: ${action.txHash}`);
            break;
          case "DONE":
            console.log(`${action.type} complete`);
            break;
          case "FAILED":
            console.error(`${action.type} failed: ${action.error?.message}`);
            break;
        }
      }
    }
  },
});
```

***

## Cross-Chain Composer via SDK

跨链 Composer 可在 EVM 链之间工作。集成与同链完全相同：只需使用不同的 `fromChain` 与 `toChain` 值。SDK 会自动处理桥接路由、链切换与状态跟踪。

### ETH (Ethereum) → Morpho vault (Base)

```ts theme={"system"}
const crossChainQuote = await getQuote(client, {
  fromChain: 1, // Ethereum
  toChain: 8453, // Base
  fromToken: "0x0000000000000000000000000000000000000000", // ETH (native)
  toToken: "0x7BfA7C4f149E7415b73bdeDfe609237e29CBF34A", // Morpho vault on Base
  fromAmount: "100000000000000000", // 0.1 ETH
  fromAddress: "0xYOUR_WALLET_ADDRESS",
});

const route = convertQuoteToRoute(crossChainQuote);
const executedRoute = await executeRoute(client, route, {
  updateRouteHook(updatedRoute) {
    console.log(
      "Route updated:",
      updatedRoute.steps.map((s) => s.tool),
    );
  },
});
```

### USDC (Ethereum) → Morpho Vault (Base)

```ts theme={"system"}
const crossChainQuote = await getQuote(client, {
  fromChain: 1, // Ethereum
  toChain: 8453, // Base
  fromToken: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC on Ethereum
  toToken: "0x7BfA7C4f149E7415b73bdeDfe609237e29CBF34A", // Morpho vault on Base
  fromAmount: "1000000000", // 1000 USDC
  fromAddress: "0xYOUR_WALLET_ADDRESS",
  slippage: 0.01,
});

const route = convertQuoteToRoute(crossChainQuote);
const executedRoute = await executeRoute(client, route, {
  updateRouteHook(updatedRoute) {
    console.log(
      "Route updated:",
      updatedRoute.steps.map((s) => s.tool),
    );
  },
});
```

SDK 会自动处理：

* 桥接选择与执行
* 等待桥接完成
* 切换到目标链
* 在目标链上执行 Composer 存入
* 全程状态跟踪

***

## Execution Options

所有执行选项都是可选的，但对高级用例可能很有用：

| Option                         | Type                           | Description                     |
| ------------------------------ | ------------------------------ | ------------------------------- |
| `updateRouteHook`              | `(route) => void`              | 在每次路由状态变更时调用。用于 UI 更新。          |
| `updateTransactionRequestHook` | `(txRequest) => Promise<tx>`   | 在提交前修改交易请求（例如自定义 gas）。          |
| `acceptExchangeRateUpdateHook` | `(params) => Promise<boolean>` | 如果执行期间汇率发生变化则调用。返回 `true` 表示接受。 |
| `getContractCalls`             | `(params) => Promise<result>`  | 根据实际桥接金额在执行期间动态提供合约调用。          |
| `executeInBackground`          | `boolean`                      | 若为 `true`，即使用户离开页面执行也会继续。       |

如需完整的执行选项参考，参见 [Execute Routes/Quotes](/sdk/execute-routes)。

***

## Error Handling

SDK 会抛出你可以捕获并处理的错误：

```ts theme={"system"}
try {
  const executedRoute = await executeRoute(client, route, {
    updateRouteHook(updatedRoute) {
      // Track progress
    },
  });
} catch (error) {
  console.error("Execution failed:", error.message);

  // Check the route's step execution for detailed failure info
  for (const step of route.steps) {
    if (step.execution) {
      for (const action of step.execution.actions) {
        if (action.status === "FAILED") {
          console.error(`Step ${step.tool} failed:`, action.error?.message);
        }
      }
    }
  }
}
```

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Cross-Chain Patterns" icon="bridge" href="/composer/lifi-api/guides/cross-chain-compose">
    高级跨链 Composer flow
  </Card>

  <Card title="Widget Integration" icon="window" href="/composer/lifi-api/guides/widget-integration">
    通过即插即用的 Widget 实现零代码 Composer
  </Card>

  <Card title="SDK Configuration" icon="gear" href="/sdk/configure-sdk">
    完整的 SDK 配置参考
  </Card>

  <Card title="Vault Deposit Recipes" icon="book" href="/composer/lifi-api/recipes/vault-deposits">
    常见协议的可复制粘贴 recipe
  </Card>
</CardGroup>
