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

# Components & API

> Complete API reference for the Metalayer Bridge Widget components

## WidgetProvider

The provider component that sets up the widget context and configuration.

### Props

| Prop                    | Type                                                                 | Description                                                            | Default     | Required |
| ----------------------- | -------------------------------------------------------------------- | ---------------------------------------------------------------------- | ----------- | -------- |
| `sdkConfig`             | **[MetalayerConfig](/metalayer/sdk/client-methods#metalayerconfig)** | SDK configuration                                                      | -           | ✅        |
| `theme`                 | **[WidgetTheme](/metalayer/widget/theming#widgettheme)**             | Theme configuration for customizing colors, corners, shadows, and more | `undefined` | ❌        |
| `defaultSource`         | **[DefaultChainToken](#defaultchaintoken)**                          | Default source chain and token                                         | `undefined` | ❌        |
| `defaultDestination`    | **[DefaultChainToken](#defaultchaintoken)**                          | Default destination chain and token                                    | `undefined` | ❌        |
| `enabledChains`         | **[Chain](/metalayer/sdk/api-reference#chain)\[]**                   | Pre-loaded chains (bypasses fetching)                                  | `undefined` | ❌        |
| `onSupportedChainsLoad` | `(chains: Chain[]) => void`                                          | Callback when chains are loaded                                        | `undefined` | ❌        |
| `onError`               | `(error: Error) => void`                                             | Error handling callback                                                | `undefined` | ❌        |
| `debugEnabled`          | `boolean`                                                            | Enable debug logging                                                   | `false`     | ❌        |

### SDK Configuration

<CodeGroup>
  ```tsx Basic Configuration theme={null}
  <WidgetProvider
    sdkConfig={{
      apiKey: 'your-api-key',
      environment: 'mainnet', // or 'testnet'
    }}
  >
  ```

  ```tsx With Custom Options theme={null}
  <WidgetProvider
    sdkConfig={{
      apiKey: 'your-api-key',
      environment: 'mainnet', // or 'testnet'
      defaultOptions: {
        quotePreference: 'fastest', // Options: 'fastest' | 'bestReturn'
        chainIds: [1, 33139, 42161], // Filter for specific chains
      },
    }}
  >
  ```
</CodeGroup>

<Note>
  The `defaultOptions` configuration is optional. When not specified, the widget will display all supported chains and use default quote preference.
</Note>

### Default Source and Destination

```tsx theme={null}
<WidgetProvider
  defaultSource={{
    chainId: 1, // Ethereum Mainnet
    tokenAddress: '0x0000000000000000000000000000000000000000', // ETH
  }}
  defaultDestination={{
    chainId: 33139, // ApeChain
    tokenAddress: '0x0000000000000000000000000000000000000000', // ETH
  }}
>
```

### Chain Loading Callback

`onSupportedChainsLoad` receives Metalayer [Chain](/metalayer/sdk/api-reference#chain) values from the SDK. Convert them with **[chainsToViemChains](/metalayer/sdk/utilities#chainstoviem)** or **[chainToViemChain](/metalayer/sdk/utilities#chaintoviem)** before passing them to wagmi, viem, or the [RPC transport helpers](#rpc-transport-helpers) below.

```tsx theme={null}
import { chainsToViemChains } from '@metalayer/sdk';
import { WidgetProvider } from '@metalayer/widget';

<WidgetProvider
  onSupportedChainsLoad={(chains) => {
    const viemChains = chainsToViemChains(chains);
    updateWalletConfig(viemChains);
  }}
>
```

#### Wagmi client callback (recommended)

Use **[createWidgetClient](#createwidgetclient-chain)** so each chain’s public client uses Metalayer’s RPC ordering and fallbacks. Build a non-empty viem chain tuple from `chainsToViemChains(metalayerChains)` (or a filtered list). Below, `ViemChain` is viem’s `Chain` type under an alias so it is not confused with the Metalayer `Chain` from the SDK.

```tsx theme={null}
import { chainsToViemChains } from '@metalayer/sdk';
import { createWidgetClient } from '@metalayer/widget';
import type { Chain as ViemChain } from 'viem';
import { createConfig } from 'wagmi';

function createWagmiConfig(chains: [ViemChain, ...ViemChain[]]) {
  return createConfig({
    chains,
    multiInjectedProviderDiscovery: false,
    client({ chain }) {
      return createWidgetClient(chain);
    },
  });
}
```

> **📋 Note**: The widget requires an external `WagmiProvider` — it does not create its own. Use `onSupportedChainsLoad` to update your wagmi config with the widget's supported chains.

### RPC transport helpers

These helpers take **viem [`Chain`](https://viem.sh/docs/glossary/types#chain)** objects—the same shape returned by **`chainToViemChain`** / **`chainsToViemChains`** in `@metalayer/sdk`. Internally, **`createWidgetTransport`** calls **`collectChainHttpRpcUrls`** (see [SDK utilities](/metalayer/sdk/utilities#collectchainhttprpcurls-chain)) and builds a viem **`fallback`** transport over those HTTP URLs: Metalayer **default RPC** first, then **`rpc-0`**, **`rpc-1`**, … slots that **`chainToViemChain`** fills from **`alternativeRpcs`**. If no URLs are present, it falls back to viem’s default **`http()`** behavior.

#### `createWidgetTransport(chain)`

Returns a viem **`Transport`** for a single chain. It reads every HTTP RPC URL from the chain via **[`collectChainHttpRpcUrls`](/metalayer/sdk/utilities#collectchainhttprpcurls-chain)** and wraps them in a viem **`fallback()`** transport, so requests automatically retry on the next endpoint when one is rate-limited or unavailable. If no URLs are present it returns a plain `http()` transport.

Most integrations should use **[`createWidgetClient`](#createwidgetclient-chain)** (wagmi `client` callback) or **[`createWidgetTransportsRecord`](#createwidgettransportsrecord-chains)** (wagmi `transports` map) instead of calling this directly. Use `createWidgetTransport` when you need the raw transport for a custom viem client or want to compose it with other transports:

```typescript theme={null}
import { createWidgetTransport } from '@metalayer/widget';
import { createClient } from 'viem';

const client = createClient({
  chain: viemChain,
  transport: createWidgetTransport(viemChain),
});
```

#### `createWidgetClient(chain)`

Convenience wrapper: creates a viem **`Client`** with `createWidgetTransport` already wired in. This is the recommended way to configure wagmi via the **`client`** callback (see [Wagmi client callback](#wagmi-client-callback-recommended) above).

```typescript theme={null}
import { createWidgetClient } from '@metalayer/widget';

const client = createWidgetClient(viemChain);
```

#### `createWidgetTransportsRecord(chains)`

Builds **`Record<number, Transport>`** keyed by chain id. Useful with RainbowKit’s `getDefaultConfig` or any wagmi setup that takes a `transports` map instead of a `client` callback:

```typescript theme={null}
import { createWidgetTransportsRecord } from '@metalayer/widget';
import { getDefaultConfig } from '@rainbow-me/rainbowkit';

const config = getDefaultConfig({
  appName: 'My App',
  projectId: 'your-walletconnect-project-id',
  chains: supportedChains as unknown as readonly [Chain, ...Chain[]],
  transports: createWidgetTransportsRecord(supportedChains),
});
```

For custom transport stacks (for example viem **`fallback()`**), you can read ordered HTTP URLs from a viem chain with **[collectChainHttpRpcUrls](/metalayer/sdk/utilities#collectchainhttprpcurls-chain)** in `@metalayer/sdk`.

### Theme Configuration

The widget supports extensive theming options including predefined themes, custom colors, fonts, and advanced overrides.

See the **[Theming](/metalayer/widget/theming)** page for complete customization options and visual examples.

## Widget

The main UI component that renders the bridge interface.

### Props

See **[WidgetProps](#widgetprops)** for the complete props reference.

```tsx theme={null}
<Widget
  onConnectClick={() => openWalletModal()}
  onDisconnectClick={() => disconnect()}
  solanaSigner={solanaSigner}
/>
```

## Type Definitions

### MetalayerConfig

SDK configuration object. See **[MetalayerConfig](/metalayer/sdk/client-methods#metalayerconfig)** in the SDK documentation for full details.

### WidgetProps

| Property                 | Type                                                                                    | Description                                                                                      | Default     | Required |
| ------------------------ | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ----------- | -------- |
| `onConnectClick`         | `() => void`                                                                            | Callback when user clicks connect                                                                | -           | ✅        |
| `onDisconnectClick`      | `() => void`                                                                            | Callback when user clicks disconnect. When provided, widget manages wallet connection internally | `undefined` | ❌        |
| `onTransactionSubmitted` | `(sourceChainId?: number, destChainId?: number, amount?: string) => void`               | Callback when user submits a transaction                                                         | `undefined` | ❌        |
| `onTokenSelected`        | `(direction: 'source' \| 'destination', chainId: number, tokenAddress: string) => void` | Callback when user selects a token                                                               | `undefined` | ❌        |
| `source`                 | `{ chainId: number; tokenAddress?: string }`                                            | Controlled source chain and token                                                                | `undefined` | ❌        |
| `destination`            | `{ chainId: number; tokenAddress?: string }`                                            | Controlled destination chain and token                                                           | `undefined` | ❌        |
| `isConnecting`           | `boolean`                                                                               | Whether a wallet is connecting                                                                   | `false`     | ❌        |
| `solanaSigner`           | **[WidgetSolanaSigner](#widgetsolanasigner)**                                           | Solana wallet signer for Solana transactions                                                     | `undefined` | ❌        |
| `className`              | `string`                                                                                | CSS class name for custom styling                                                                | `undefined` | ❌        |

<Note>
  When `onDisconnectClick` is provided, the widget manages wallet connection state internally and displays wallet info in the settings tab. If your page already handles wallet connect/disconnect logic, you don't need to set this prop; the widget will work with your existing wallet connection management.
</Note>

```tsx theme={null}
import type { WidgetProps } from '@metalayer/widget';
```

### WidgetSolanaSigner

<Note>
  Solana support is currently in beta and requires additional dependencies. See the [EVM + Solana installation](/metalayer/widget/getting-started#evm--solana-beta) for setup instructions.
</Note>

| Property          | Type                                                 | Description                                           | Default | Required |
| ----------------- | ---------------------------------------------------- | ----------------------------------------------------- | ------- | -------- |
| `address`         | `string`                                             | Solana wallet address                                 | -       | ✅        |
| `isConnected`     | `() => boolean`                                      | Function that returns whether the wallet is connected | -       | ✅        |
| `signTransaction` | `(transaction: Transaction) => Promise<Transaction>` | Function to sign a Solana transaction                 | -       | ✅        |

```tsx theme={null}
const solanaSigner = {
  address: wallet.publicKey.toString(),
  isConnected: () => wallet.connected,
  signTransaction: async (transaction) => await wallet.signTransaction(transaction),
};
```

### DefaultChainToken

```tsx theme={null}
interface DefaultChainToken {
  chainId: number;
  tokenAddress: string;
}
```

| Property       | Type     | Description                     | Default | Required |
| -------------- | -------- | ------------------------------- | ------- | -------- |
| `chainId`      | `number` | Chain ID of the default network | -       | ✅        |
| `tokenAddress` | `string` | Token contract address          | -       | ✅        |

## Utility Functions

* **RPC transport helpers** — [`createWidgetTransport`](#createwidgettransport-chain), [`createWidgetClient`](#createwidgetclient-chain), and [`createWidgetTransportsRecord`](#createwidgettransportsrecord-chains) (see [above](#rpc-transport-helpers)).
* **Chain conversion** (from `@metalayer/sdk`) feeds those helpers; see [SDK Utilities](/metalayer/sdk/utilities):

  * **[chainsToViemChains](/metalayer/sdk/utilities#chainstoviem)** — batch convert; skips invalid / non-EVM chains
  * **[chainToViemChain](/metalayer/sdk/utilities#chaintoviem)** — single Metalayer chain → viem `Chain`
  * **[collectChainHttpRpcUrls](/metalayer/sdk/utilities#collectchainhttprpcurls-chain)** — ordered HTTP RPC URLs on a viem `Chain` (for custom transports)

## CSS Styling

The widget requires a CSS import for proper styling:

```tsx theme={null}
import '@metalayer/widget/styles.css';
```

## Error Handling

### Error Callback

Handle errors in the widget through the `onError` callback:

```tsx theme={null}
<WidgetProvider
  onError={(error) => {
    console.error('Widget error:', error);
    // Handle error (show toast, log to service, etc.)
  }}
>
```
