Skip to main content

Client Example

Basic implementation steps for building a cross-chain bridge using the Metalayer client directly.

1. Initialize Client

Set up the Metalayer client with your API key to access bridge functionality.
import { MetalayerClient, OrderStatus } from '@metalayer/sdk';

const client = MetalayerClient.init({
  apiKey: process.env.METALAYER_API_KEY!,
  environment: 'production',
});

2. Get Supported Chains

Fetch available chains to determine valid bridge routes for your application.
const { chains } = await client.getSupportedChains();
console.log('Available chains:', chains);

3. Get Tokens

Retrieve token information for the chains you want to support in your bridge interface.
const { tokensByChain } = await client.getTokens();
const ethereumTokens = tokensByChain[1] || [];

4. Request Quote

Get bridge quotes based on user selections to show routing options and fees.
const quoteResponse = await client.quote({
  sourceChainId: 1, // Ethereum Mainnet
  sourceTokenAddress: '0x0000000000000000000000000000000000000000', // ETH
  destinationChainId: 33139, // ApeChain
  destinationTokenAddress: '0x0000000000000000000000000000000000000000', // ETH
  amount: BigInt('1000000000000000000'), // 1 ETH
  senderAddress: '0xYourWalletAddress',
});

const bestQuote = quoteResponse.quotes[0];

5. Execute Transaction

Execute the bridge transaction by processing each step in the quote with your wallet client.
for (const step of bestQuote.steps) {
  switch (step.action.case) {
    case 'transactionRequest':
      const hash = await walletClient.sendTransaction({
        to: step.action.value.to,
        data: step.action.value.data,
        value: step.action.value.value,
      });
      break;
    case 'eip712Data':
      await walletClient.signTypedData(step.action.value);
      break;
  }
}

6. Monitor Status

Track the bridge transaction progress to provide status updates to users.
const order = await client.getOrder({
  sourceTransactionHash: '0xTxHash',
  sourceChainId: 1,
});

if (order.status === OrderStatus.FULFILLED) {
  console.log('Bridge completed successfully!');
} else if (order.status === OrderStatus.FAILED) {
  console.log('Bridge failed');
} else if (order.status === OrderStatus.PENDING) {
  console.log('Bridge in progress...');
}

React Hook Example

Basic implementation steps for building a cross-chain bridge using Metalayer SDK hooks. For detailed hook configuration and provider setup, see Hooks.

1. Get Supported Chains

Fetch the list of supported chains to populate source and destination chain selectors in your UI. This data enables users to choose which networks they want to bridge between.
import { useSupportedChains } from '@metalayer/sdk';

const { data: chainsData } = useSupportedChains();
const chains = chainsData?.chains || [];

2. Get Tokens

Retrieve available tokens organized by chain to build token selection lists. Use this data to create filtered token dropdowns that update based on the user’s selected source and destination chains.
import { useTokens } from '@metalayer/sdk';

const { data: tokensData } = useTokens();
const tokens = tokensData?.tokensByChain || {};

3. Get Quote

Request bridge quotes based on user selections from your UI. This provides routing options, fees, and estimated completion times for the bridge transaction.
import { useQuote } from '@metalayer/sdk';

const { data: quoteData, isLoading } = useQuote({
  sourceChainId: 1, // Ethereum Mainnet
  sourceTokenAddress: '0x0000000000000000000000000000000000000000', // ETH
  destinationChainId: 33139, // ApeChain
  destinationTokenAddress: '0x0000000000000000000000000000000000000000', // ETH
  amount: BigInt('1000000000000000000'), // 1 ETH
  senderAddress: '0xYourWalletAddress',
});

const bestQuote = quoteData?.quotes[0];

4. Execute Transaction

Execute the bridge transaction using the selected quote. This typically involves multiple steps like token approvals followed by the actual bridge transaction, with each step requiring user wallet confirmation.
// Execute quote steps
for (const step of bestQuote.steps) {
  switch (step.action.case) {
    case 'transactionRequest':
      await walletClient.sendTransaction({
        to: step.action.value.to,
        data: step.action.value.data,
        value: step.action.value.value,
      });
      break;
    case 'eip712Data':
      await walletClient.signTypedData(step.action.value);
      break;
  }
}

5. Monitor Status

Track the bridge transaction progress to provide real-time status updates to users. Use this to display progress indicators, completion confirmations, or error states in your UI.
import { useOrderPolling, OrderStatus } from '@metalayer/sdk';

const { data: order } = useOrderPolling({
  sourceTransactionHash: '0xTxHash',
  sourceChainId: 1,
});

// Check order status - see OrderStatus Values section for all possible values
if (order?.status === OrderStatus.FULFILLED) {
  console.log('Bridge completed successfully!');
} else if (order?.status === OrderStatus.FAILED) {
  console.log('Bridge failed');
} else if (order?.status === OrderStatus.PENDING) {
  console.log('Bridge in progress...');
}