Skip to content

Commit 84934e9

Browse files
authored
Merge pull request #200 from ryzen-xp/docs/DeFi-protocols
[DOCS]: DeFi protocols — DEX aggregator and Soroswap integration guide
2 parents 32dda93 + 18f87c3 commit 84934e9

File tree

3 files changed

+103
-0
lines changed

3 files changed

+103
-0
lines changed

docs/defi/aggregator-guide.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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.

docs/defi/soroswap-integration.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Soroswap Protocol Integration
2+
3+
## Overview
4+
Soroswap is integrated as a primary AMM liquidity source in the `DexAggregatorService`. It leverages the `@galaxy-kj/core-defi-protocols` package to interface with Soroswap smart contracts.
5+
6+
## How it is Integrated
7+
1. **Pricing:** The `fetchSoroswapQuote` method initializes the protocol via `ProtocolFactory` and calls `getSwapQuote(assetIn, assetOut, amountIn)`.
8+
2. **Execution:** The `buildSoroswapSwapTransaction` calls the `swap` method on the protocol, returning the transaction hash (XDR) ready for signing.
9+
10+
Docs for Soroswap: [Soroswap Documentation](https://docs.soroswap.finance/).
11+
12+
## Adding New Protocol Sources
13+
To add a new protocol source (e.g., Aquarius):
14+
1. **Types:** Add the Source ID to the `LiquiditySource` union in `aggregator.types.ts`.
15+
2. **Quoting:** Implement a `fetch<Protocol>Quote(params)` method in `DexAggregatorService` that conforms to `RouteQuote`.
16+
3. **Execution:** Implement a `build<Protocol>SwapTransaction(params)` method to return an unsigned XDR string.
17+
4. **Registration:** Update the switch-cases inside `fetchQuoteFromSource` and `buildSwapTransaction`.
18+
19+
## Testing and Mocking Protocal Responses
20+
To unit test the aggregator without hitting real networks, mock the `ProtocolFactory` in Jest:
21+
22+
```typescript
23+
import { ProtocolFactory } from '@galaxy-kj/core-defi-protocols';
24+
25+
jest.mock('@galaxy-kj/core-defi-protocols', () => ({
26+
...jest.requireActual('@galaxy-kj/core-defi-protocols'),
27+
ProtocolFactory: {
28+
getInstance: jest.fn().mockReturnValue({
29+
createProtocol: jest.fn().mockReturnValue({
30+
initialize: jest.fn().mockResolvedValue(true),
31+
getSwapQuote: jest.fn().mockResolvedValue({
32+
amountOut: '99',
33+
priceImpact: '0.1',
34+
path: []
35+
}),
36+
swap: jest.fn().mockResolvedValue({ hash: 'AAAA...' })
37+
})
38+
})
39+
}
40+
}));
41+
```

packages/core/defi/README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# @galaxy-kj/core-defi
2+
3+
## Overview
4+
The `defi` package provides decentralized finance capabilities for the Galaxy DevKit. Its core feature is the `DexAggregatorService`, which coordinates price discovery across SDEX (Horizon path payments) and AMM protocols to find the best swap route for any asset pair.
5+
6+
## Structure
7+
- `src/services/DexAggregatorService.ts`: Core aggregator service for routing and quotes.
8+
- `src/types/aggregator.types.ts`: Typings for liquidity sources, quotes, and swaps.
9+
10+
For detailed integration guides, see:
11+
- [DEX Aggregator Guide](../../../docs/defi/aggregator-guide.md)
12+
- [Soroswap Integration Guide](../../../docs/defi/soroswap-integration.md)

0 commit comments

Comments
 (0)