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.
- 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
- Go 1.21 or later
- Make (for build automation)
- Git
go get github.com/morpheum-labs/lifi-adapter
# 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
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) }
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) }
config := lifi.NewConfig("your-app-name")
config := lifi.NewConfig("your-app-name") config.SetAPIKey("your-lifi-api-key")
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")
quote, err := client.GetQuote(ctx, lifi.QuoteRequest{ FromChain: lifi.ChainIDArbitrum, ToChain: lifi.ChainIDOptimism, FromToken: "0x0000000000000000000000000000000000000000", ToToken: "0x0000000000000000000000000000000000000000", FromAmount: "1000000000000000000", Slippage: 0.005, Order: "CHEAPEST", })
routes, err := client.GetRoutes(ctx, quoteReq)
tokens, err := client.GetTokens(ctx, lifi.ChainIDEthereum)
chains, err := client.GetChains(ctx)
tools, err := client.GetTools(ctx)
// Create executor executor := lifi.NewExecutor(client) // Execute quote result, err := executor.ExecuteQuote(ctx, quote, privateKey)
// Execute complete route results, err := executor.ExecuteRoute(ctx, route, privateKey)
// Wait for transaction confirmation result, err := executor.WaitForConfirmation(ctx, txHash, chainID)
- Ethereum (1)
- Arbitrum (42161)
- Optimism (10)
- Polygon (137)
- BSC (56)
- Avalanche (43114)
- Base (8453)
- Linea (59144)
- Scroll (534352)
- Mantle (5000)
- Blast (81457)
- Solana (501)
- Bitcoin (0)
- Litecoin (2)
- Dogecoin (3)
- Sui (502)
- Go 1.21 or later
- Make (for build automation)
make build
make testmake demo
LIFI_API_KEY=your-api-key make demo
LIFI_API_KEY=your-api-key make integration-test
make all- Run deps, build, and testmake build- Build the projectmake test- Run testsmake test-coverage- Run tests with coverage reportmake demo- Run the demo applicationmake demo-quote- Run quote demo with API keymake deps- Install dependenciesmake install- Install binary to /usr/local/binmake lint- Run lintermake format- Format codemake clean- Clean build artifactsmake bench- Run benchmarksmake race- Run race detectionmake docs- Generate documentationmake integration-test- Run integration testsmake build-linux- Build for Linuxmake build-windows- Build for Windowsmake build-darwin- Build for macOSmake build-all- Build for all platformsmake dev-setup- Setup development environmentmake update-deps- Update dependenciesmake security- Run security scan
LIFI_API_KEY- LI.FI API key for higher rate limitsPRIVATE_KEY- Private key for transaction execution (hex format)
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) }
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)) }
// 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)
The SDK provides comprehensive, structured error handling with context and severity levels:
quote, err := client.GetQuote(ctx, req) if err != nil { // Handle API errors, network errors, etc. log.Printf("Error getting quote: %v", err) return }
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) } }
// 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) }
// 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())
// 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)
UnsupportedChainError: Chain not supportedRPCError: RPC connection issuesChainNotReadyError: Chain not ready
UnsupportedTokenError: Token not supportedInsufficientBalanceError: Insufficient balanceTokenValidationError: Token validation failed
TransactionFailedError: Transaction failedGasEstimationFailedError: Gas estimation failedTransactionTimeoutError: Transaction timeout
NoRouteFoundError: No route foundQuoteExpiredError: Quote expiredSlippageExceededError: Slippage exceeded
The SDK follows a modular, services-based architecture with clear separation of concerns:
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 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)
// Ethereum, Arbitrum, Optimism, Polygon, BSC, etc. evmClient, err := core.NewEVMClientFromConfig(chainID, config)
// Sui blockchain support suiClient, err := core.NewSuiClient(config)
// Solana support svmClient, err := core.NewSVMClient(config)
// Bitcoin, Litecoin, Dogecoin bitcoinClient := utxo.NewBitcoinClient(config) litecoinClient := utxo.NewLitecoinClient(config) dogecoinClient := utxo.NewDogecoinClient(config)
- Free tier: 100 requests per minute
- With API key: 1000 requests per minute
- Enterprise: Custom limits available
# 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
# 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
# Lint code make lint # Format code make format # Security scan make security # Update dependencies make update-deps
# 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
We welcome contributions! Please follow these steps:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes with proper tests
- Run quality checks:
make lint && make test - Commit your changes:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
- Follow Go best practices and conventions
- Add comprehensive tests for new features
- Update documentation for API changes
- Use structured error handling from the
errorspackage - Ensure all tests pass before submitting PR
- Use meaningful commit messages
- Use
gofmtandgoimportsfor formatting - Follow Go naming conventions
- Add comprehensive comments for public APIs
- Use structured error handling
- Write tests for all new functionality
This project is licensed under the MIT License - see the LICENSE file for details.
For support and questions:
- GitHub Issues: Create an issue
- Documentation: LI.FI Docs
- API Reference: LI.FI API
- 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
- Initial release
- Support for EVM and non-EVM chains
- Quote and route discovery
- Transaction execution
- Comprehensive test suite
- Makefile for build automation
- 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