Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

tokenchain/lifi-adapter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

9 Commits

Repository files navigation

LI.FI Adapter - Go SDK

A comprehensive Go implementation of the LI.FI SDK for cross-chain swaps and bridging. This SDK provides a robust, modular interface to LI.FI's routing service, enabling seamless cross-chain token transfers and swaps with enterprise-grade error handling and monitoring.

๐Ÿš€ Features

  • Cross-chain Support: Support for EVM chains (Ethereum, Arbitrum, Optimism, Polygon, BSC, Avalanche, Base, Linea, Scroll, Mantle, Blast) and non-EVM chains (Solana, Bitcoin, Litecoin, Dogecoin, Sui)
  • Quote & Route Discovery: Get quotes and routes for cross-chain swaps with intelligent routing
  • Transaction Execution: Execute transactions on supported chains with comprehensive error handling
  • Token Management: Get supported tokens for each chain with validation
  • Tool Integration: Access to various bridges, DEXs, and other DeFi tools
  • Modular Architecture: Clean separation of concerns with services-based design
  • Comprehensive Error Handling: Structured error types with context and severity levels
  • Configurable: Custom RPC endpoints, API keys, and timeout settings
  • Production Ready: Built-in monitoring, retry logic, and error analysis

๐Ÿ“ฆ Installation

Prerequisites

  • Go 1.21 or later
  • Make (for build automation)
  • Git

Install the SDK

go get github.com/morpheum-labs/lifi-adapter

Development Setup

# Clone the repository
git clone https://github.com/morpheum-labs/lifi-adapter.git
cd lifi-adapter
# Install dependencies
make deps
# Setup development environment
make dev-setup
# Run tests
make test

๐Ÿš€ Quick Start

Basic Usage

package main
import (
 "context"
 "fmt"
 "log"
 
 "github.com/morpheum-labs/lifi-adapter/core"
)
func main() {
 // Create configuration
 config := core.NewConfig("your-app-name")
 config.SetAPIKey("your-api-key") // Optional for higher rate limits
 
 // Create client
 client := core.NewClient(config)
 
 // Get a quote
 quoteReq := core.QuoteRequest{
 FromAddress: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
 FromChain: core.ChainIDArbitrum,
 ToChain: core.ChainIDOptimism,
 FromToken: "0x0000000000000000000000000000000000000000", // ETH
 ToToken: "0x0000000000000000000000000000000000000000", // ETH
 FromAmount: "1000000000000000000", // 1 ETH in wei
 Slippage: 0.005, // 0.5%
 Order: core.OrderCheapest,
 }
 
 ctx := context.Background()
 quote, err := client.GetQuote(ctx, quoteReq)
 if err != nil {
 log.Fatal(err)
 }
 
 fmt.Printf("Quote: %+v\n", quote)
}

Using Services Architecture

package main
import (
 "context"
 "fmt"
 "log"
 
 "github.com/morpheum-labs/lifi-adapter/services"
 "github.com/morpheum-labs/lifi-adapter/util"
)
func main() {
 // Create configuration
 config := util.NewConfig("your-app-name")
 config.SetAPIKey("your-api-key")
 
 // Create services client
 servicesClient := services.NewServicesClient(config)
 
 // Get quote using services
 quoteReq := services.QuoteRequest{
 FromAddress: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
 FromChain: util.ChainIDArbitrum,
 ToChain: util.ChainIDOptimism,
 FromToken: "0x0000000000000000000000000000000000000000",
 ToToken: "0x0000000000000000000000000000000000000000",
 FromAmount: "1000000000000000000",
 Slippage: 0.005,
 Order: services.OrderCheapest,
 }
 
 ctx := context.Background()
 quote, err := servicesClient.GetQuote(ctx, quoteReq)
 if err != nil {
 log.Fatal(err)
 }
 
 fmt.Printf("Quote: %+v\n", quote)
}

Configuration

Basic Configuration

config := lifi.NewConfig("your-app-name")

With API Key

config := lifi.NewConfig("your-app-name")
config.SetAPIKey("your-lifi-api-key")

Custom RPC Endpoints

config := lifi.NewConfig("your-app-name")
config.SetRPC(lifi.ChainIDEthereum, "https://mainnet.infura.io/v3/your-project-id")
config.SetRPC(lifi.ChainIDArbitrum, "https://arb1.arbitrum.io/rpc")

API Methods

Get Quote

quote, err := client.GetQuote(ctx, lifi.QuoteRequest{
 FromChain: lifi.ChainIDArbitrum,
 ToChain: lifi.ChainIDOptimism,
 FromToken: "0x0000000000000000000000000000000000000000",
 ToToken: "0x0000000000000000000000000000000000000000",
 FromAmount: "1000000000000000000",
 Slippage: 0.005,
 Order: "CHEAPEST",
})

Get Routes

routes, err := client.GetRoutes(ctx, quoteReq)

Get Supported Tokens

tokens, err := client.GetTokens(ctx, lifi.ChainIDEthereum)

Get Supported Chains

chains, err := client.GetChains(ctx)

Get Available Tools

tools, err := client.GetTools(ctx)

Transaction Execution

Execute Quote

// Create executor
executor := lifi.NewExecutor(client)
// Execute quote
result, err := executor.ExecuteQuote(ctx, quote, privateKey)

Execute Route

// Execute complete route
results, err := executor.ExecuteRoute(ctx, route, privateKey)

Wait for Confirmation

// Wait for transaction confirmation
result, err := executor.WaitForConfirmation(ctx, txHash, chainID)

Supported Chains

EVM Chains

  • Ethereum (1)
  • Arbitrum (42161)
  • Optimism (10)
  • Polygon (137)
  • BSC (56)
  • Avalanche (43114)
  • Base (8453)
  • Linea (59144)
  • Scroll (534352)
  • Mantle (5000)
  • Blast (81457)

Non-EVM Chains

  • Solana (501)
  • Bitcoin (0)
  • Litecoin (2)
  • Dogecoin (3)
  • Sui (502)

Building and Testing

Prerequisites

  • Go 1.21 or later
  • Make (for build automation)

Build

make build

Run Tests

make test

Run Demo

make demo

Run with API Key

LIFI_API_KEY=your-api-key make demo

Run Integration Tests

LIFI_API_KEY=your-api-key make integration-test

Makefile Targets

  • make all - Run deps, build, and test
  • make build - Build the project
  • make test - Run tests
  • make test-coverage - Run tests with coverage report
  • make demo - Run the demo application
  • make demo-quote - Run quote demo with API key
  • make deps - Install dependencies
  • make install - Install binary to /usr/local/bin
  • make lint - Run linter
  • make format - Format code
  • make clean - Clean build artifacts
  • make bench - Run benchmarks
  • make race - Run race detection
  • make docs - Generate documentation
  • make integration-test - Run integration tests
  • make build-linux - Build for Linux
  • make build-windows - Build for Windows
  • make build-darwin - Build for macOS
  • make build-all - Build for all platforms
  • make dev-setup - Setup development environment
  • make update-deps - Update dependencies
  • make security - Run security scan

Environment Variables

  • LIFI_API_KEY - LI.FI API key for higher rate limits
  • PRIVATE_KEY - Private key for transaction execution (hex format)

Examples

Basic Quote

package main
import (
 "context"
 "fmt"
 "log"
 
 "github.com/morpheum-labs/lifi-adapter"
)
func main() {
 config := lifi.NewConfig("my-app")
 client := lifi.NewClient(config)
 
 quoteReq := lifi.QuoteRequest{
 FromChain: lifi.ChainIDArbitrum,
 ToChain: lifi.ChainIDOptimism,
 FromToken: "0x0000000000000000000000000000000000000000",
 ToToken: "0x0000000000000000000000000000000000000000",
 FromAmount: "1000000000000000000",
 Slippage: 0.005,
 }
 
 quote, err := client.GetQuote(context.Background(), quoteReq)
 if err != nil {
 log.Fatal(err)
 }
 
 fmt.Printf("Quote: %+v\n", quote)
}

Multiple Routes

routes, err := client.GetRoutes(ctx, quoteReq)
if err != nil {
 log.Fatal(err)
}
for i, route := range routes {
 fmt.Printf("Route %d: %s -> %s (%d steps)\n", 
 i+1, route.FromAmount, route.ToAmount, len(route.Steps))
}

Transaction Execution

// Parse private key
privateKeyBytes, err := hex.DecodeString("your-private-key-hex")
if err != nil {
 log.Fatal(err)
}
privateKey, err := crypto.ToECDSA(privateKeyBytes)
if err != nil {
 log.Fatal(err)
}
// Create executor
executor := lifi.NewExecutor(client)
// Execute quote
result, err := executor.ExecuteQuote(ctx, quote, privateKey)
if err != nil {
 log.Fatal(err)
}
fmt.Printf("Transaction Hash: %s\n", result.TransactionHash)

๐Ÿ›ก๏ธ Error Handling

The SDK provides comprehensive, structured error handling with context and severity levels:

Basic Error Handling

quote, err := client.GetQuote(ctx, req)
if err != nil {
 // Handle API errors, network errors, etc.
 log.Printf("Error getting quote: %v", err)
 return
}

Structured Error Types

import "github.com/morpheum-labs/lifi-adapter/errors"
// Check error types
if lifiErr, ok := err.(*errors.LiFiError); ok {
 switch lifiErr.Code {
 case errors.ErrorCodeNoRouteFound:
 log.Printf("No route found: %s", lifiErr.Message)
 case errors.ErrorCodeQuoteExpired:
 log.Printf("Quote expired: %s", lifiErr.Message)
 case errors.ErrorCodeSlippageExceeded:
 log.Printf("Slippage exceeded: %s", lifiErr.Message)
 default:
 log.Printf("Error: %s (Code: %s, Severity: %s)", 
 lifiErr.Message, lifiErr.Code, lifiErr.Severity)
 }
}

Error Context and Analysis

// Create error with context
err := errors.NewLiFiErrorWithContext(
 errors.ErrorCodeInvalidInput,
 "Invalid amount provided",
 map[string]interface{}{
 "field": "amount",
 "value": "invalid",
 "chain": "ethereum",
 },
)
// Check if error is retryable
if err.IsRetryable() {
 // Implement retry logic
 time.Sleep(time.Second)
 // Retry operation
}
// Get error severity
if err.GetSeverity() == errors.SeverityCritical {
 // Handle critical error
 alerting.SendAlert(err)
}

Error Collection and Analysis

// Create error collection
collection := errors.NewErrorCollection()
// Add errors
collection.AddError(err1)
collection.AddError(err2)
// Analyze errors
analyzer := errors.NewErrorAnalyzer(collection.GetErrors())
analysis := analyzer.Analyze()
// Get error statistics
fmt.Printf("Total errors: %d\n", analysis.GetTotalErrors())
fmt.Printf("Critical rate: %.2f%%\n", analysis.GetCriticalErrorRate())
fmt.Printf("Most common error: %s\n", analysis.GetMostCommonError())

Error Formatting

// Default formatting
fmt.Println(errors.FormatError(err))
// JSON formatting for APIs
jsonFormatter := errors.GetJSONFormatter()
jsonOutput := jsonFormatter.Format(err)
// Detailed formatting for logs
detailedFormatter := errors.GetDetailedFormatter()
logOutput := detailedFormatter.Format(err)

Error Types by Category

Chain Errors

  • UnsupportedChainError: Chain not supported
  • RPCError: RPC connection issues
  • ChainNotReadyError: Chain not ready

Token Errors

  • UnsupportedTokenError: Token not supported
  • InsufficientBalanceError: Insufficient balance
  • TokenValidationError: Token validation failed

Transaction Errors

  • TransactionFailedError: Transaction failed
  • GasEstimationFailedError: Gas estimation failed
  • TransactionTimeoutError: Transaction timeout

Quote Errors

  • NoRouteFoundError: No route found
  • QuoteExpiredError: Quote expired
  • SlippageExceededError: Slippage exceeded

๐Ÿ—๏ธ Architecture

The SDK follows a modular, services-based architecture with clear separation of concerns:

Core Components

lifi-adapter/
โ”œโ”€โ”€ core/ # Core client and types
โ”œโ”€โ”€ services/ # Service layer (quotes, execution, etc.)
โ”œโ”€โ”€ errors/ # Comprehensive error handling
โ”œโ”€โ”€ util/ # Utilities and validation
โ”œโ”€โ”€ types/ # Shared type definitions
โ””โ”€โ”€ core/
 โ”œโ”€โ”€ evm/ # EVM chain implementations
 โ”œโ”€โ”€ sui/ # Sui chain implementation
 โ”œโ”€โ”€ svm/ # Solana implementation
 โ””โ”€โ”€ utxo/ # UTXO chains (Bitcoin, Litecoin, Dogecoin)

Services Architecture

// Services provide modular functionality
servicesClient := services.NewServicesClient(config)
// Quote service
quote, err := servicesClient.GetQuote(ctx, quoteReq)
// Execution service
result, err := servicesClient.ExecuteQuote(ctx, quote, privateKey)
// Status service
status, err := servicesClient.GetStatus(ctx, txHash, chainID)
// Chains service
chains, err := servicesClient.GetChains(ctx)
// Tokens service
tokens, err := servicesClient.GetTokens(ctx, chainID)
// Tools service
tools, err := servicesClient.GetTools(ctx)

Chain-Specific Implementations

EVM Chains

// Ethereum, Arbitrum, Optimism, Polygon, BSC, etc.
evmClient, err := core.NewEVMClientFromConfig(chainID, config)

Sui Chain

// Sui blockchain support
suiClient, err := core.NewSuiClient(config)

Solana (SVM)

// Solana support
svmClient, err := core.NewSVMClient(config)

UTXO Chains

// Bitcoin, Litecoin, Dogecoin
bitcoinClient := utxo.NewBitcoinClient(config)
litecoinClient := utxo.NewLitecoinClient(config)
dogecoinClient := utxo.NewDogecoinClient(config)

๐Ÿ“Š Rate Limits

  • Free tier: 100 requests per minute
  • With API key: 1000 requests per minute
  • Enterprise: Custom limits available

๐Ÿ› ๏ธ Development

Development Workflow

# Setup development environment
make dev-setup
# Install dependencies
make deps
# Run tests
make test
# Run tests with coverage
make test-coverage
# Run linting
make lint
# Format code
make format
# Run security scan
make security
# Build for all platforms
make build-all

Testing

# Run all tests
make test
# Run tests with coverage
make test-coverage
# Run integration tests (requires API key)
LIFI_API_KEY=your-key make integration-test
# Run race detection
make race
# Run benchmarks
make bench

Code Quality

# Lint code
make lint
# Format code
make format
# Security scan
make security
# Update dependencies
make update-deps

Building

# Build for current platform
make build
# Build for specific platforms
make build-linux
make build-windows
make build-darwin
# Build for all platforms
make build-all

๐Ÿค Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes with proper tests
  4. Run quality checks: make lint && make test
  5. Commit your changes: git commit -m 'Add amazing feature'
  6. Push to the branch: git push origin feature/amazing-feature
  7. Open a Pull Request

Development Guidelines

  • Follow Go best practices and conventions
  • Add comprehensive tests for new features
  • Update documentation for API changes
  • Use structured error handling from the errors package
  • Ensure all tests pass before submitting PR
  • Use meaningful commit messages

Code Style

  • Use gofmt and goimports for formatting
  • Follow Go naming conventions
  • Add comprehensive comments for public APIs
  • Use structured error handling
  • Write tests for all new functionality

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

For support and questions:

๐Ÿ“ Changelog

v1.1.0 (Latest)

  • Enhanced Error Handling: Comprehensive structured error system with context and severity levels
  • Modular Architecture: Services-based design with clear separation of concerns
  • Improved Chain Support: Enhanced EVM, Sui, Solana, and UTXO chain implementations
  • Production Ready: Built-in monitoring, retry logic, and error analysis
  • Developer Experience: Enhanced development workflow with comprehensive tooling
  • Documentation: Comprehensive documentation with examples and best practices

v1.0.0

  • Initial release
  • Support for EVM and non-EVM chains
  • Quote and route discovery
  • Transaction execution
  • Comprehensive test suite
  • Makefile for build automation

๐Ÿ”ฎ Roadmap

  • v1.2.0: Enhanced monitoring and observability
  • v1.3.0: Additional chain support (Cosmos, Polkadot)
  • v1.4.0: Advanced routing algorithms
  • v2.0.0: Major architecture improvements

About

The same SDK from the offiical LIFI

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Go 99.1%
  • Makefile 0.9%

AltStyle ใซใ‚ˆใฃใฆๅค‰ๆ›ใ•ใ‚ŒใŸใƒšใƒผใ‚ธ (->ใ‚ชใƒชใ‚ธใƒŠใƒซ) /