# Cross-Chain Bridges

## Overview

Lexari AI integrates with LiFi (Liquidity Finance) to provide seamless DeFi operations including token swaps and cross-chain bridging. The integration enables users to execute complex DeFi transactions through natural language commands.

## Supported Operations

### Token Swaps

* **Same-chain swaps**: Exchange tokens within the same blockchain
* **DEX aggregation**: Best routes across multiple decentralized exchanges
* **Gas optimization**: Optimal gas strategies and timing
* **Slippage management**: Professional guidance on slippage settings

### Cross-Chain Bridging

* **Multi-chain transfers**: Move tokens between different blockchains
* **Bridge aggregation**: Best bridge routes and protocols
* **Security assessment**: Bridge security and risk evaluation
* **Route optimization**: Fastest and most cost-effective routes

## Supported Networks

### Layer 1 Networks

* **Ethereum (1)**: Primary blockchain with full DeFi ecosystem
* **BNB Smart Chain (56)**: High-performance blockchain with low fees
* **Avalanche C-Chain (43114)**: Fast and scalable blockchain

### Layer 2 Networks

* **Arbitrum One (42161)**: High-throughput Ethereum L2
* **Optimism (10)**: Fast and cheap Ethereum L2
* **Polygon (137)**: Scalable Ethereum sidechain
* **Base (8453)**: Coinbase's Ethereum L2

## Supported Tokens

### Major Tokens

* **ETH**: Native Ethereum token
* **USDC**: USD Coin stablecoin
* **USDT**: Tether stablecoin
* **DAI**: Decentralized stablecoin
* **WETH**: Wrapped Ethereum

### Chain-Specific Tokens

* **BNB**: BNB Smart Chain native token
* **MATIC**: Polygon native token
* **AVAX**: Avalanche native token

## Technical Implementation

### LiFi SDK Integration

#### Installation

```bash
npm install @lifi/sdk
```

#### Basic Setup

```typescript
import { LiFi } from '@lifi/sdk';

const lifi = new LiFi({
  integrator: 'lexari-ai',
  version: '3.0.0'
});
```

### Swap Implementation

#### Quote Generation

```typescript
const swapQuote = await lifi.getQuote({
  fromChain: 1, // Ethereum
  toChain: 1,   // Ethereum
  fromToken: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
  toToken: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',   // WETH
  fromAmount: '1000000000', // 1000 USDC (6 decimals)
  fromAddress: '0x...',
  toAddress: '0x...'
});
```

#### Route Execution

```typescript
const route = await lifi.executeRoute({
  route: swapQuote.route,
  signer: wallet,
  onRouteExecution: (route) => {
    console.log('Route executed:', route);
  }
});
```

### Bridge Implementation

#### Bridge Quote

```typescript
const bridgeQuote = await lifi.getQuote({
  fromChain: 1,    // Ethereum
  toChain: 8453,   // Base
  fromToken: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
  toToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',   // USDC on Base
  fromAmount: '1000000000', // 1000 USDC
  fromAddress: '0x...',
  toAddress: '0x...'
});
```

#### Bridge Execution

```typescript
const bridgeRoute = await lifi.executeRoute({
  route: bridgeQuote.route,
  signer: wallet,
  onRouteExecution: (route) => {
    console.log('Bridge executed:', route);
  }
});
```

## Route Optimization

### DEX Aggregation

* **Uniswap**: Primary DEX for Ethereum
* **Sushiswap**: Alternative DEX with liquidity
* **PancakeSwap**: BNB Smart Chain DEX
* **Trader Joe**: Avalanche DEX
* **1inch**: DEX aggregator integration

### Bridge Protocols

* **Symbiosis**: Cross-chain liquidity protocol
* **Stargate**: LayerZero-based bridging
* **Hop**: Fast Ethereum L2 bridging
* **Across**: Optimistic bridging
* **Celer**: Multi-chain bridging

### Route Selection Criteria

* **Liquidity**: Available liquidity for the trade
* **Fees**: Total fees including gas and protocol fees
* **Speed**: Transaction confirmation time
* **Security**: Protocol security assessment
* **Slippage**: Expected price impact

## Error Handling

### Common Errors

* **Insufficient Liquidity**: No available routes
* **High Slippage**: Price impact too high
* **Gas Estimation**: Gas estimation failures
* **Bridge Delays**: Cross-chain transaction delays
* **Token Approval**: Missing token approvals

### Error Recovery

* **Route Retry**: Attempt alternative routes
* **Amount Adjustment**: Reduce trade amount
* **Token Validation**: Verify token addresses
* **Network Switching**: Try different networks
* **Fallback Routes**: Use backup protocols

## Security Considerations

### Bridge Security

* **Protocol Audits**: Verified smart contract audits
* **Liquidity Depth**: Sufficient liquidity for large trades
* **Time Locks**: Bridge transaction timeouts
* **Multi-sig**: Multi-signature security measures
* **Insurance**: Bridge insurance coverage

### Transaction Security

* **Slippage Protection**: Maximum slippage limits
* **Deadline Protection**: Transaction timeout protection
* **Gas Estimation**: Accurate gas cost estimation
* **Route Validation**: Verify route parameters
* **User Confirmation**: Require user approval

## Performance Optimization

### Caching Strategy

* **Quote Caching**: Cache quotes for 30 seconds
* **Route Caching**: Cache routes for 5 minutes
* **Token Caching**: Cache token metadata
* **Price Caching**: Cache token prices

### Rate Limiting

* **API Limits**: Respect LiFi API rate limits
* **Request Throttling**: Implement request throttling
* **Queue Management**: Manage concurrent requests
* **Error Backoff**: Exponential backoff on errors

## Monitoring & Analytics

### Transaction Tracking

* **Route Success Rate**: Track successful routes
* **Gas Usage**: Monitor gas consumption
* **Slippage Analysis**: Analyze price impact
* **Bridge Performance**: Track bridge completion times

### Error Monitoring

* **Failed Transactions**: Track failed transactions
* **Error Patterns**: Identify common error patterns
* **User Feedback**: Collect user feedback on routes
* **Performance Metrics**: Monitor response times

## Widget Integration

### Frontend Widget

```typescript
import { LiFiWidget } from '@lifi/widget';

<LiFiWidget
  integrator="lexari-ai"
  config={{
    appearance: 'dark',
    containerStyle: {
      border: '1px solid rgb(234, 234, 234)',
      borderRadius: '16px',
    },
  }}
  onRouteExecution={(route) => {
    console.log('Route executed:', route);
  }}
/>
```

### Widget Configuration

* **Theme**: Dark/light theme support
* **Customization**: Brand colors and styling
* **Functionality**: Swap and bridge operations
* **Integration**: Seamless chat integration

## API Reference

### Core Functions

#### getQuote

```typescript
getQuote(params: {
  fromChain: number;
  toChain: number;
  fromToken: string;
  toToken: string;
  fromAmount: string;
  fromAddress: string;
  toAddress: string;
}): Promise<Quote>
```

#### executeRoute

```typescript
executeRoute(params: {
  route: Route;
  signer: Signer;
  onRouteExecution?: (route: Route) => void;
}): Promise<Route>
```

#### getRoutes

```typescript
getRoutes(params: {
  fromChain: number;
  toChain: number;
  fromToken: string;
  toToken: string;
  fromAmount: string;
}): Promise<Route[]>
```

### Response Types

#### Quote

```typescript
interface Quote {
  id: string;
  fromChain: number;
  toChain: number;
  fromToken: Token;
  toToken: Token;
  fromAmount: string;
  toAmount: string;
  route: Route;
  estimatedGas: string;
  fee: Fee;
}
```

#### Route

```typescript
interface Route {
  id: string;
  fromChain: number;
  toChain: number;
  fromToken: Token;
  toToken: Token;
  fromAmount: string;
  toAmount: string;
  steps: Step[];
  estimatedGas: string;
  fee: Fee;
}
```

## Best Practices

### User Experience

* **Clear Communication**: Explain route details clearly
* **Progress Updates**: Provide transaction progress updates
* **Error Messages**: User-friendly error messages
* **Confirmation**: Require user confirmation for large trades

### Technical Implementation

* **Error Handling**: Comprehensive error handling
* **Validation**: Validate all input parameters
* **Testing**: Thorough testing of all routes
* **Monitoring**: Continuous monitoring and alerting

### Security

* **Input Validation**: Validate all user inputs
* **Route Verification**: Verify route parameters
* **Gas Estimation**: Accurate gas estimation
* **Slippage Protection**: Protect against high slippage


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lexari-1.gitbook.io/lexari/defi-operations/lifi-integration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
