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

# 配置 Widget

> 触手可及的灵活性

LI.FI Widget 支持一系列配置选项，让你能够：

* 允许或拒绝特定的链、代币、桥和交易所。
* 按生态系统类型（EVM、SVM、UTXO、MVM、TVM）筛选链。
* 预选默认的源链和目标链。
* 为源链和目标链选择默认代币。
* 设置源代币或目标代币的金额。
* 指定目标地址。
* 使用静态或动态费用计算配置集成方费用。
* 为符合条件的交易启用无 gas/relayer 路由。
* 为 Ethereum、Solana、Bitcoin、Sui 和 Tron 生态系统配置区块链提供者。
* 通过 `sdkConfig` 配置自定义各种 LI.FI SDK 设置。

这些选项能让你精确控制 widget 的行为，并通过针对具体需求和偏好进行调整来改善用户体验。

## LI.FI SDK 配置

LI.FI Widget 构建于 LI.FI SDK 之上，借助其强大的功能实现跨链交换与桥接。sdkConfig 选项允许你直接在 widget 内配置 SDK 的各个方面。

让我们看一个使用 sdkConfig 选项配置私有 RPC 端点的示例。

```typescript theme={"system"}
import { LiFiWidget, WidgetConfig, ChainId } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  sdkConfig: {
    rpcUrls: {
      [ChainId.ARB]: ["https://arbitrum-example.node.com/"],
      [ChainId.SOL]: ["https://solana-example.node.com/"],
    },
  },
};

export const WidgetPage = () => {
  return (
    <LiFiWidget integrator="Your dApp/company name" config={widgetConfig} />
  );
};
```

> [!WARNING]
>
> 在生产应用中，建议传入你自己经过身份验证的 RPC 提供商 URL（Alchemy、Infura、Ankr 等）。
>
> 如果未提供 RPC URL，LI.FI Widget 将默认使用公共 RPC 提供商。
>
> 公共 RPC 端点（尤其是 Solana）有时会根据地理位置或在高负载时段对用户进行速率限制，从而导致余额显示错误或交易模拟出错等问题。

请在 [配置 SDK](https://docs.li.fi/sdk/configure-sdk.md) 部分查看其他 SDK 配置选项。

## 区块链提供者配置

LI.FI Widget 通过专用的提供者包支持多个区块链生态系统。你可以为 Ethereum（EVM）、Solana（SVM）、Bitcoin（UTXO）、Sui（MVM）和 Tron（TVM）链配置提供者。

```typescript theme={"system"}
import { LiFiWidget } from "@lifi/widget";
import type { WidgetConfig } from "@lifi/widget";
import { EthereumProvider } from "@lifi/widget-provider-ethereum";
import { SolanaProvider } from "@lifi/widget-provider-solana";
import { BitcoinProvider } from "@lifi/widget-provider-bitcoin";
import { SuiProvider } from "@lifi/widget-provider-sui";
import { TronProvider } from "@lifi/widget-provider-tron";

const widgetConfig: WidgetConfig = {
  providers: [
    EthereumProvider(),
    SolanaProvider(),
    BitcoinProvider(),
    SuiProvider(),
    TronProvider(),
  ],
};

export const WidgetPage = () => {
  return (
    <LiFiWidget integrator="Your dApp/company name" config={widgetConfig} />
  );
};
```

每个提供者都可以使用特定配置进行自定义。例如，Ethereum 提供者支持配置 WalletConnect、Coinbase、MetaMask、Porto 和 Base Account 连接器。详情请参阅 [钱包管理](https://docs.li.fi/widget/wallet-management.md) 页面。

## 初始化表单值

LI.FI Widget 使用若干表单值来获取和执行路由。

这些值包括 `fromAmount`、`fromChain`、`fromToken`、`toChain`、`toToken`、`toAmount` 和 `toAddress`。

它们通常通过 Widget UI 设置，但也可以通过编程方式初始化和更新。

通过配置这些选项，你可以简化用户体验，确保 widget 预加载所需的链、代币、金额和地址以进行交换或桥接。这减少了手动输入的需要，并有助于引导用户完成预期的流程。

你可以通过以下任一方式初始化这些值：

* Widget 配置 - 通过在 widget 配置中添加 `fromAmount`、`fromChain`、`fromToken`、`toChain`、`toToken`、`toAmount` 或 `toAddress` 值。

* URL 查询参数 - 当 widget 配置中的 `buildUrl` 设为 `true` 时，通过将它们添加到 widget 所在页面 URL 的查询参数中。

当通过配置或 URL 查询参数设置表单值时，你会看到相应的表单字段 UI 更新以反映这些值。

## 通过 widget 配置初始化

LI.FI Widget 允许你预配置默认的链和代币，从而可以从一开始就轻松设置所需的交换或桥接参数。以下是如何使用特定的默认链、代币、金额和转账地址值配置 widget 的示例。

```typescript theme={"system"}
import type { WidgetConfig } from "@lifi/widget";
import { ChainType } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  // set source chain to Polygon
  fromChain: 137,
  // set destination chain to Optimism
  toChain: 10,
  // set source token to USDC (Polygon)
  fromToken: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",
  // set source token to USDC (Optimism)
  toToken: "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",
  // set source token amount to 10 USDC (Polygon)
  fromAmount: 10,
  // set the destination wallet address
  toAddress: {
    address: "0x29DaCdF7cCaDf4eE67c923b4C22255A4B2494eD7",
    chainType: ChainType.EVM,
  },
};

export const WidgetPage = () => {
  return (
    <LiFiWidget integrator="Your dApp/company name" config={widgetConfig} />
  );
};
```

你还可以使用 `minFromAmountUSD` 参数（数字）设置以美元等值计的最小金额，以确保用户满足最低交易要求。

## 通过 URL 查询参数初始化

要使用 URL 查询参数初始化 widget 中的表单值，你需要确保 widget 配置中的 `buildUrl` 设为 `true`。

```typescript theme={"system"}
import type { WidgetConfig } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  // instruct the widget to use and build url search params
  buildUrl: true,
};
```

然后，你可以在导航到包含 widget 的页面时，在 URL 中加入这些查询参数。

```
https://playground.li.fi/?fromAmount=20&fromChain=42161&fromToken=0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9&toAddress=0x29DaCdF7cCaDf4eE67c923b4C22255A4B2494eD7&toChain=42161&toToken=0xaf88d065e77c8cC2239327C5EDb3A432268e5831
```

需要理解的是，这只对 widget 的初始化生效——在不重新加载页面的情况下动态更改 URL 中的查询参数，不会导致 widget 中表单值的更新。

> [!NOTE]
>
> 配置值会覆盖 URL 查询参数
>
> 如果你想使用 URL 查询参数在初始化（或页面加载）时填充 widget 的表单值，重要的是这些表单值不要出现在用于初始化 widget 的配置对象中。fromAmount、fromChain、fromToken、toAddress、toChain 和 toToken 不应在 widget 配置中设置，以便允许 URL 执行 widget 状态的初始设置。
>
> 在首次页面加载时，如果你在配置和 URL 中都设置了表单值，那么 URL 查询参数将被重写以匹配配置值，并且 widget 表单将填充配置中呈现的值。

## 更新表单值

在 widget 初始化之后，有两种方式可以更新 widget 中的表单值

* 使用 widget 配置 - 这利用配置中的响应式值，需要对这些值进行一定的管理以进行更新

* 使用 formRef - 这提供了一个函数调用，你可以用它来更新 widget 表单存储中的值。

> [!NOTE]
>
> 请注意，当 widget 配置中的 `buildUrl` 设为 `true` 时，两种方法都应同时更新
> URL 查询参数以及 widget 本身显示的值。

## 通过 widget 配置更新

一旦 widget 完成初始化，你可以通过更新 widget 配置来更新 widget 中的表单值。

要执行更新，你应该只在配置中包含想要更改的表单值，并确保这些更改被传递给 Widget。

例如，如果你只想更改 fromChain 和 fromToken 而不改动其他内容，那么你应该只包含这些值。

除了想要更改的表单值之外，你还应该设置一个 formUpdateKey。它需要是一个唯一的、随机生成的字符串，用于确保 widget 中的表单值得到更新——本质上是强制执行一次更新。这可以避免在通过配置和用户在 widget UI 上的操作混合设置值时可能出现的一些边界情况问题。

以下是你的配置的示例。

```typescript theme={"system"}
import type { WidgetConfig } from '@lifi/widget';

const widgetConfig: WidgetConfig = {
    fromChain: 10,
    fromToken: '0x94b008aA00579c1307B0EF2c499aD98a8ce58e58',
    // use the date object to generate a unique value
    formUpdateKey: new Date().valueOf().toString()
    // config may still feature other config values but
    // should not include other form values…
}
```

你还可以使用 `undefined` 将表单值及其字段重置为空状态。以下示例仅重置 fromChain 和 fromToken 表单值。

```typescript theme={"system"}
import type { WidgetConfig } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  fromChain: undefined,
  fromToken: undefined,
  // use the date object to generate a unique value
  formUpdateKey: new Date().valueOf().toString(),
  // config may still feature other config values but
  // should not include other form values…
};
```

这里使用 `undefined` 将 widget 的表单值重置为空状态。widget 配置对象中缺少某个属性意味着该属性将保持不变。

### 使用 widget 配置进行状态管理

在使用配置更新 widget 表单值时，考虑使用应用状态管理库来存储你的 widget 配置通常是一个不错的选择。有许多选项可供选择，例如 Zustand、MobX、Redux，甚至 React context。

例如，如果你使用 Zustand 作为状态管理工具，你可以使用 Zustand 的 API 从应用的任何部分访问并设置配置中的值。此外，你还可以使用 Zustand 的相等性功能，例如内置的 `shallow` 函数，来确保只有在必要时才用你的 widget 配置更新 LiFi Widget 的实例。这有助于优化重新渲染。

你可以在 widget 仓库中找到一个使用 [Zustand 管理 widget 配置](https://github.com/lifinance/widget/tree/main/examples/zustand-widget-config) 的示例。

## 通过 form ref 更新

此方法为开发者提供了一种直接在 widget 中设置表单值的方式，而无需更改 widget 配置。通过向 widget 传递一个 ref 对象，你可以访问一个函数来直接在 widget 的表单状态上设置值。请参阅下面的示例。

```typescript theme={"system"}
import type { FormState } from '@lifi/widget';
import { LiFiWidget } from '@lifi/widget';

export const WidgetPage = () => {
  const widgetConfig: WidgetConfig = {
    buildUrl: true,
  };

  const formRef = useRef<FormState>(null);

  const handleClick = () => {
    formRef.current?.setFieldValue( 'fromChain', 10, { setUrlSearchParam: true });
  };

  return (
    <>
      <LiFiWidget
        integrator="Your dApp/company name"
        config={widgetConfig}
        formRef={formRef}
      />
      <button onClick={handleClick} type="button">Set fromChain to Optimism</button>
    </>
  )
}
```

注意 `setFieldValue` 函数的使用。

```typescript theme={"system"}
formRef.current?.setFieldValue( 'fromChain', 10, { setUrlSearchParam: true });
```

初始化之后，可以调用 `setFieldValue` 函数来设置表单值，请注意，如果你在 widget 配置中将 `buildUrl` 设为 `true`，则 `setUrlSearchParam` 将确保 URL 得到更新。

以下是一些使用示例。

```typescript fromChain & fromToken theme={"system"}

// fromChain and fromToken can be set independently but you might also find that you want to set them at the same time
formRef.current?.setFieldValue(
    'fromChain',
    10,
    { setUrlSearchParam: true }
);
formRef.current?.setFieldValue(
    'fromToken',
    '0x94b008aA00579c1307B0EF2c499aD98a8ce58e58',
    { setUrlSearchParam: true }
);

// To reset fromChain and fromToken
formRef.current?.setFieldValue(
    'fromChain',
    undefined,
    { setUrlSearchParam: true }
);
formRef.current?.setFieldValue(
    'fromToken',
    undefined,
    { setUrlSearchParam: true }
);
```

```typescript fromAmount theme={"system"}
formRef.current?.setFieldValue(
   'fromAmount',
    '10',
    { setUrlSearchParam: true }
);

// To reset fromAmount
formRef.current?.setFieldValue(
    'fromAmount',
    undefined,
    { setUrlSearchParam: true }
);
```

```typescript toAddress theme={"system"}
import { ChainType } from '@lifi/widget';

formRef.current?.setFieldValue(
    'toAddress',
    {
      name: 'Lenny',
      address: '0x552008c0f6870c2f77e5cC1d2eb9bdff03e30Ea9',
      chainType: ChainType.EVM,
    },
    { setUrlSearchParam: true }
);

// To reset toAddress
formRef.current?.setFieldValue(
    'toAddress',
    undefined,
    { setUrlSearchParam: true }
);
```

## 配置路由选项

widget 提供了若干选项来控制路由的获取和选择行为。

```typescript theme={"system"}
import type { WidgetConfig } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  // Set default route priority (RECOMMENDED, FASTEST, CHEAPEST, SAFEST)
  routePriority: "RECOMMENDED",
  // Set default slippage (0.03 = 3%)
  slippage: 0.03,
  // Show only the recommended route and hide the route selector
  showSingleRoute: true,
  // Enable gasless/relayer routes for eligible transactions
  useRelayerRoutes: true,
};

export const WidgetPage = () => {
  return (
    <LiFiWidget integrator="Your dApp/company name" config={widgetConfig} />
  );
};
```

## 配置集成方费用

你可以配置在每笔交易上收取的费用。有两种方式：

### 静态费用

使用 `feeConfig` 为所有交易设置固定的费用百分比：

```typescript theme={"system"}
import type { WidgetConfig } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  feeConfig: {
    fee: 0.01, // 1% fee
    name: "DApp fee",
    showFeePercentage: true,
    showFeeTooltip: true,
  },
};
```

### 动态费用计算

使用 `calculateFee` 函数根据路由参数进行动态费用计算：

```typescript theme={"system"}
import type { WidgetConfig, CalculateFeeParams } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  feeConfig: {
    name: "Platform fee",
    showFeePercentage: true,
    calculateFee: async (params: CalculateFeeParams) => {
      // params includes: fromChain, toChain, fromToken, toToken,
      // fromAddress, toAddress, fromAmount, toAmount, slippage
      
      // Return fee as a number (e.g., 0.03 for 3%)
      if (params.fromChain.id === params.toChain.id) {
        return 0.01; // 1% for same-chain swaps
      }
      return 0.03; // 3% for cross-chain transfers
    },
  },
};
```

> [!NOTE]
>
> 只使用 `fee` 或 `calculateFee` 之一，而不要同时使用。如果提供了 `calculateFee`，它将优先于静态的 `fee` 值。

## 配置 allow 和 deny 选项

我们提供了 `allow` 和 `deny` 配置选项，用于控制在你的应用中可以使用哪些链、代币、桥和交易所。以下是设置和使用这些选项的方法：

```typescript theme={"system"}
import { LiFiWidget, WidgetConfig } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  // disable BSC from being shown in the chains list
  chains: {
    deny: [56],
  },
  // allow bridging through Stargate bridge only
  bridges: {
    allow: ["stargateV2"],
  },
};

export const WidgetPage = () => {
  return (
    <LiFiWidget integrator="Your dApp/company name" config={widgetConfig} />
  );
};
```

### 按生态系统类型筛选链

你还可以按链的生态系统类型（EVM、SVM、UTXO、MVM、TVM）筛选链：

```typescript theme={"system"}
import { LiFiWidget, WidgetConfig, ChainType } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  chains: {
    // Only show EVM and Solana chains
    types: {
      allow: [ChainType.EVM, ChainType.SVM],
    },
  },
};

export const WidgetPage = () => {
  return (
    <LiFiWidget integrator="Your dApp/company name" config={widgetConfig} />
  );
};
```

### 分别配置源链/目标链筛选器

你可以对源链列表和目标链列表应用不同的筛选器：

```typescript theme={"system"}
import { LiFiWidget, WidgetConfig } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  chains: {
    // Apply to both from and to lists
    deny: [56],
    // Only for source chain selection
    from: {
      allow: [1, 137, 10],
    },
    // Only for destination chain selection
    to: {
      allow: [42161, 8453],
    },
  },
};
```

### 代币筛选

要控制哪些代币出现在 **from** 和 **to** 列表中，请使用 `allow` 和 `deny` 选项：

* 如果定义在 `tokens` 对象的顶层，它们将同时应用于**两个**列表。
* 如果定义在 `from` 或 `to` 对象内部，它们将**仅**应用于该特定列表。
* 如果定义了 `allow` 列表，则只允许其中包含的代币。如果未定义 `allow` 列表，则允许所有代币，除非它们被明确包含在 `deny` 中。如果某个代币同时出现在 `allow` 和 `deny` 中，则 `allow` 列表优先。
* 一个代币必须同时通过顶层的 `allow`/`deny` 检查以及当前列表（`from` 或 `to`）的检查，才会被视为允许。
* 代币筛选是按链应用的。当为特定链允许/拒绝代币时，只有该链的代币会受到影响。其他链保持不受筛选，显示所有可用代币。

```typescript theme={"system"}
import { LiFiWidget, WidgetConfig } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  tokens: {
    // Top-level allow/deny apply to BOTH 'from' and 'to' lists
    allow: [
      {
        address: "0x0000000000000000000000000000000000000000",
        chainId: 1,
      },
    ],
    deny: [
      {
        address: "0x0000000000000000000000000000000000000000",
        chainId: 137,
      },
    ],
    // 'from' list-specific allow/deny complements top-level settings
    from: {
      allow: [
        {
          address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
          chainId: 1,
        },
      ],
      deny: [
        {
          address: "0x0000000000000000000000000000000000000000",
          chainId: 1,
        },
      ],
    },
    // 'to' list-specific allow/deny
    to: {
      allow: [
        {
          address: "0x0000000000000000000000000000000000000000",
          chainId: 137,
        },
      ],
      deny: [
        {
          address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
          chainId: 1,
        },
      ],
    },
  },
};

export const WidgetPage = () => {
  return (
    <LiFiWidget integrator="Your dApp/company name" config={widgetConfig} />
  );
};
```

### 精选代币、热门代币和包含的代币

除了 `allow` 和 `deny` 选项之外，`tokens` 选项还可以配置为包含其他代币、精选代币或热门代币，它们将出现在相应代币列表的顶部。

```typescript theme={"system"}
import { LiFiWidget, WidgetConfig } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  tokens: {
    // Featured tokens will appear on top of the list
    featured: [
      {
        address: "0x2fd6c9b869dea106730269e13113361b684f843a",
        symbol: "CHH",
        decimals: 9,
        chainId: 56,
        name: "Chihuahua",
        logoURI:
          "https://s2.coinmarketcap.com/static/img/coins/64x64/21334.png",
      },
    ],
    // Popular tokens will appear in a separate "Popular tokens" section
    popular: [
      {
        address: "0xdac17f958d2ee523a2206206994597c13d831ec7",
        symbol: "USDT",
        decimals: 6,
        chainId: 1,
        name: "Tether USD",
      },
    ],
    // Include any token to the list
    include: [
      {
        address: "0xba98c0fbebc892f5b07a42b0febd606913ebc981",
        symbol: "MEH",
        decimals: 18,
        chainId: 1,
        name: "meh",
        logoURI:
          "https://s2.coinmarketcap.com/static/img/coins/64x64/22158.png",
      },
    ],
  },
};

export const WidgetPage = () => {
  return (
    <LiFiWidget integrator="Your dApp/company name" config={widgetConfig} />
  );
};
```

> [card] With featured tokens

> [card] Without featured tokens

## 目标地址

在某些使用场景中，用户需要使用不同的目标地址。通常，他们可以独立输入目标地址。

不过，widget 也提供了配置选项，可以预先配置目标地址，或创建一个精选的钱包地址列表供选择。

> [card] Send to wallet button

> [card] Send to wallet view

## 配置单个目标地址

开发者可以使用 `toAddress` 选项配置单个目标地址。`address` 和 `chainType` 属性是必需的，而 `name` 和 `logoURI` 属性是可选的。

```typescript theme={"system"}
import { ChainType, LiFiWidget, WidgetConfig } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  toAddress: {
    name: "Vault Deposit",
    address: "0x0000000000000000000000000000000000000000",
    chainType: ChainType.EVM,
    logoURI: "https://example.com/image.svg",
  },
};

export const WidgetPage = () => {
  return (
    <LiFiWidget integrator="Your dApp/company name" config={widgetConfig} />
  );
};
```

![](https://mintcdn.com/lifi/08FOM1AsMmrVbIEl/images/dest_address_ex.png?fit=max\&auto=format\&n=08FOM1AsMmrVbIEl\&q=85\&s=acc2f4c0f467754fc6c36a58f3eb9f09)

## 配置精选的钱包地址列表

开发者可以使用 `toAddresses` 选项配置一个精选的钱包地址列表。

```typescript theme={"system"}
import { ChainType, LiFiWidget, WidgetConfig } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  toAddresses: [
    {
      name: "Lenny",
      address: "0x552008c0f6870c2f77e5cC1d2eb9bdff03e30Ea9",
      chainType: ChainType.EVM,
      logoURI: "https://example.com/image.svg",
    },
    {
      address: "0x4577a46A3eCf44E0ed44410B7793977ffbe22CE0",
      chainType: ChainType.EVM,
    },
    {
      name: "My sweet solami",
      address: "6AUWsSCRFSCbrHKH9s84wfzJXtD6mNzAHs11x6pGEcmJ",
      chainType: ChainType.SVM,
    },
  ],
};

export const WidgetPage = () => {
  return (
    <LiFiWidget integrator="Your dApp/company name" config={widgetConfig} />
  );
};
```

使用此配置，当用户点击 `Send to wallet` 按钮时，将打开一个预先配置的地址列表供其选择，从而跳过他们手动输入地址的步骤。

在配置钱包列表的同时，开发者可以将填写目标地址设为必需。详情请参阅"必填目标地址"。

> [card] Optional destination address

> [card] A curated list of wallet addresses

## 浏览器 URL

在 widget 中有许多用户可以点击的地方，用于在单独的浏览器标签页中打开区块浏览器，以了解有关某笔交易或某个地址的更多信息。widget 中任何显示此图标的按钮或链接都会将用户引导至浏览器。

我们在打开浏览器方面有默认行为，同时也可以使用 widget 配置来覆盖和更改这些行为。

### 链的默认行为

通常，当尝试将用户引导至浏览器时，widget 会知道哪条链与某笔交易或地址相关，并会提供与该链匹配的浏览器。

例如，在用户执行交易后，在交易详情页面上，他们可以点击"Token allowance approved"浏览器按钮，以查看有关该授权的更多详情。如果该授权是使用 Optimism 链完成的，那么会打开一个新标签页，将用户带到 optimistic.etherscan.io，向他们展示有关该授权的更多信息。

如果找不到与某条链相关的浏览器，则用户将被引导至 LiFi 的浏览器。

### 内部浏览器的默认行为

内部浏览器是使用 widget 构建应用的组织所偏好选择的浏览器。在 widget 的某些部分，我们使用内部浏览器，而不是尝试为特定链查找浏览器。

例如，一旦用户完成交易并进入交易详情页面，他们会看到一个 transfer ID（见下文）。随附一个链接，允许用户打开浏览器以查找有关该交易的更多信息。这里不会尝试查找特定链的浏览器。使用的默认浏览器是 LI.FI 自己的内部浏览器，用户将被引导至 [https://scan.li.fi](https://scan.li.fi/)

### 覆盖浏览器 URL

可以通过 widget 配置覆盖 widget 使用的浏览器 URL。我们可以针对特定链和内部浏览器执行此操作。你可以为多条链使用自己的浏览器 URL，同时也可以为内部浏览器指定你自己的替代方案。

#### 覆盖某条链的浏览器

在 widget 配置中，你可以通过向 explorerUrls 对象添加条目来覆盖链：将链 ID 作为键，将浏览器的基础 URL 作为值。

```typescript theme={"system"}
import type { WidgetConfig } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  explorerUrls: {
    42161: ["https://scan.li.fi"],
  },
};
```

上面指定的浏览器将只用于该链，在上述示例中即 Arbitrum。对于未在 explorerUrls 对象中指定的其他链，widget 仍将呈现默认行为（如上所述）。

#### 自定义浏览器路径

对于不遵循标准 `/address/:address` 和 `/tx/:hash` 约定的浏览器，你可以指定自定义路径：

```typescript theme={"system"}
import type { WidgetConfig } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  explorerUrls: {
    42161: [
      {
        url: "https://custom-explorer.com",
        txPath: "/transaction/",  // Custom transaction path
        addressPath: "/account/", // Custom address path
      },
    ],
  },
};
```

#### 覆盖内部浏览器

在 widget 配置中，你可以通过向 explorerUrls 对象添加条目来覆盖内部浏览器：将 `internal` 作为键，将浏览器的基础 URL 作为值。

```typescript theme={"system"}
import type { WidgetConfig } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  explorerUrls: {
    internal: ["https://jumper.exchange/scan"],
  },
};
```

widget 中任何使用内部浏览器的地方现在都将使用配置中指定的 URL，而不是默认值。

### 地址和交易页面

widget 假定浏览器会在 `/address/:address` 提供地址页面，在 `/tx/:hash` 提供交易页面，并会在用户点击相关按钮时尝试将用户导航到这些页面。

指向钱包地址的链接看起来像：

```
https://scan.li.fi/address/0xb9c0dE368BECE5e76B52545a8E377a4C118f597B
```

指向交易的链接看起来像：

```
https://scan.li.fi/tx/0x05dbd8d3be79ad466e7d2898f719cc47b1b3b545cf4782aece16e11849ddd24b
```

widget 假定与 widget 一起使用的任何浏览器都将遵循此约定，除非指定了自定义路径。

## 添加路由标签

Widget 允许你通过添加路由标签（带有可自定义文本和外观的样式徽章）来在视觉上强化特定路由。
要动态显示路由标签，请在你的 `WidgetConfig` 中配置 `routeLabels: RouteLabelRule[]` 数组。

```typescript theme={"system"}
interface RouteLabelRule {
  label: RouteLabel; // The label to display if conditions match
  bridges?: AllowDeny<string>; // Optional: Filter by bridge(s)
  exchanges?: AllowDeny<string>; // Optional: Filter by exchange(s)
  fromChainId?: number[]; // Optional: Filter by source chain ID(s)
  toChainId?: number[]; // Optional: Filter by destination chain ID(s)
  fromTokenAddress?: string[]; // Optional: Filter by source token address(es)
  toTokenAddress?: string[]; // Optional: Filter by destination token address(es)
  match?: (route: Route) => boolean; // Optional: Custom predicate evaluated against the route
}
interface RouteLabel {
  text: string; // Text to show on the label
  sx?: SxProps<Theme>; // Optional: Style object (MUI-style)
}
```

每条标签规则定义了匹配条件和一个标签配置，当满足条件时将应用该配置。
标签配置包括 `text` 以及以 MUI 风格 CSS-in-JS 方式定义的徽章 `sx` 样式。

其余字段根据路由条件确定何时以及在何处应用标签。
你可以组合多个条件，例如 `fromChainId`、`exchanges`、`tokens` 等。
对于桥和交易所，请使用 `allow` 和 `deny` 字段进行细粒度控制，方式与 [配置 allow 和 deny 选项](#configure-allow-and-deny-options) 中所述类似。

对于内置字段无法表达的匹配逻辑——gas 成本、步骤数量、路由标签，或 `Route` 对象上的任何其他属性——请提供一个自定义的 `match` 谓词。
它的结果会与规则上的其他条件进行 AND 运算，因此必须满足所有指定条件，标签才会应用。
一条规则也可以单独使用 `match`，而不带任何其他字段。

> [!NOTE]
>
> `match` 谓词在 `@lifi/widget-light` 中不受支持，因为函数无法通过 `postMessage` 跨 iframe 边界传输。

配置示例：

```typescript theme={"system"}
import { ChainId } from "@lifi/sdk";
import type { WidgetConfig } from "@lifi/widget";

const widgetConfig: WidgetConfig = {
  routeLabels: [
    {
      label: {
        text: "OP Reward",
        sx: {
          background: "linear-gradient(90deg, #ff0404, #ff04c8)",
          "@keyframes gradient": {
            "0%": { backgroundPosition: "0% 50%" },
            "50%": { backgroundPosition: "100% 50%" },
            "100%": { backgroundPosition: "0% 50%" },
          },
          animation: "gradient 3s ease infinite",
          backgroundSize: "200% 200%",
          color: "#ffffff",
        },
      },
      fromChainId: [ChainId.OPT], // Applies to routes from Optimism
    },
    {
      label: {
        text: "LI.FI Bonus",
        sx: {
          display: "flex",
          alignItems: "center",
          position: "relative",
          overflow: "hidden",
          marginLeft: "auto",
          order: 1,
          backgroundImage:
            "url(https://raw.githubusercontent.com/lifinance/types/main/src/assets/icons/exchanges/lifidexaggregator.svg)",
          backgroundPosition: "left center",
          backgroundRepeat: "no-repeat",
          backgroundSize: "24px",
          paddingLeft: "12px",
          backgroundColor: "#f5b5ff",
        },
      },
      fromChainId: [ChainId.OPT], // Applies to routes from Optimism
      exchanges: {
        allow: ["relay"], // Only show for Relay routes
      },
    },
    {
      label: { text: "Single Tx" },
      // Highlight routes that complete in one transaction — no extra
      // approvals or intermediate steps, so they're faster and less
      // likely to fail mid-execution.
      match: (route) => route.steps.length === 1,
    },
  ],
};
```

配置好的路由标签的渲染示例：

![](https://mintcdn.com/lifi/08FOM1AsMmrVbIEl/images/route-labels-example.png?fit=max\&auto=format\&n=08FOM1AsMmrVbIEl\&q=85\&s=24ce72146b1efbdc362875fb632f5744)

Route labels example

只有当路由满足\_所有\_指定条件时，标签才会出现。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.