|
| 1 | +# DEX Aggregator Guide |
| 2 | + |
| 3 | +## Overview |
| 4 | +`DexAggregatorService` queries multiple liquidity sources (SDEX via Horizon, Soroswap AMM) simultaneously to find the best execution price for a given asset pair. It currently supports routing and price comparison, culminating in an unsigned XDR transaction for client-side signing. |
| 5 | + |
| 6 | +## Routing Strategies and Quote Flow |
| 7 | +When `getAggregatedQuote` is called: |
| 8 | +1. **Request:** The service takes an `assetIn`, `assetOut`, and `amountIn`. |
| 9 | +2. **Route:** It concurrently queries all configured `LiquiditySource`s (`sdex`, `soroswap`). |
| 10 | +3. **Selection:** Results are filtered and sorted best-first (highest `amountOut`), returning an `AggregatedQuote`. |
| 11 | + |
| 12 | +### Quote Example |
| 13 | +```typescript |
| 14 | +import { DexAggregatorService } from '@galaxy-kj/core-defi'; |
| 15 | + |
| 16 | +const aggregator = new DexAggregatorService(horizonServer, soroswapConfig); |
| 17 | + |
| 18 | +const quote = await aggregator.getAggregatedQuote({ |
| 19 | + assetIn: { code: 'XLM', type: 'native' }, |
| 20 | + assetOut: { code: 'USDC', issuer: 'GA...', type: 'credit_alphanum4' }, |
| 21 | + amountIn: '100', |
| 22 | +}); |
| 23 | + |
| 24 | +console.log('Best source:', quote.bestRoute.source); |
| 25 | +console.log('Expected out:', quote.bestRoute.amountOut); |
| 26 | +``` |
| 27 | + |
| 28 | +## Executing a Swap |
| 29 | +From a quote, you can construct an unsigned transaction using `executeAggregatedSwap`. |
| 30 | + |
| 31 | +```typescript |
| 32 | +const swapResult = await aggregator.executeAggregatedSwap({ |
| 33 | + signerPublicKey: 'GA...', |
| 34 | + assetIn: { code: 'XLM', type: 'native' }, |
| 35 | + assetOut: { code: 'USDC', issuer: 'GA...', type: 'credit_alphanum4' }, |
| 36 | + amountIn: '100', |
| 37 | + minAmountOut: '95', // Slippage protection |
| 38 | +}); |
| 39 | + |
| 40 | +console.log('XDR to sign:', swapResult.xdr); |
| 41 | +``` |
| 42 | + |
| 43 | +### Smart Wallet Integration |
| 44 | +The resulting `xdr` is left unsigned by design. It can be passed to the Smart Wallet integration (via passkey signatures) to authorize the swap transaction safely on behalf of the user. |
| 45 | + |
| 46 | +## Error Handling |
| 47 | +The aggregator manages several constraints: |
| 48 | +- **Price Impact:** `highImpactWarning` is flagged if the chosen route has a price impact >= 5%. |
| 49 | +- **Slippage Exceeded:** Controlled by passing `minAmountOut` during execution. If the actual return is lower, the transaction fails on-chain. |
| 50 | +- **Insufficient Liquidity / Network Errors:** Individual source quote failures are swallowed during aggregation, allowing the service to fallback to the remaining functioning sources. If no sources succeed, it throws an error. |
0 commit comments