Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions docs/defi/aggregator-guide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# DEX Aggregator Guide

## Overview
`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.

## Routing Strategies and Quote Flow
When `getAggregatedQuote` is called:
1. **Request:** The service takes an `assetIn`, `assetOut`, and `amountIn`.
2. **Route:** It concurrently queries all configured `LiquiditySource`s (`sdex`, `soroswap`).
3. **Selection:** Results are filtered and sorted best-first (highest `amountOut`), returning an `AggregatedQuote`.

### Quote Example
```typescript
import { DexAggregatorService } from '@galaxy-kj/core-defi';

const aggregator = new DexAggregatorService(horizonServer, soroswapConfig);

const quote = await aggregator.getAggregatedQuote({
assetIn: { code: 'XLM', type: 'native' },
assetOut: { code: 'USDC', issuer: 'GA...', type: 'credit_alphanum4' },
amountIn: '100',
});

console.log('Best source:', quote.bestRoute.source);
console.log('Expected out:', quote.bestRoute.amountOut);
```

## Executing a Swap
From a quote, you can construct an unsigned transaction using `executeAggregatedSwap`.

```typescript
const swapResult = await aggregator.executeAggregatedSwap({
signerPublicKey: 'GA...',
assetIn: { code: 'XLM', type: 'native' },
assetOut: { code: 'USDC', issuer: 'GA...', type: 'credit_alphanum4' },
amountIn: '100',
minAmountOut: '95', // Slippage protection
});

console.log('XDR to sign:', swapResult.xdr);
```

### Smart Wallet Integration
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.

## Error Handling
The aggregator manages several constraints:
- **Price Impact:** `highImpactWarning` is flagged if the chosen route has a price impact >= 5%.
- **Slippage Exceeded:** Controlled by passing `minAmountOut` during execution. If the actual return is lower, the transaction fails on-chain.
- **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.
41 changes: 41 additions & 0 deletions docs/defi/soroswap-integration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Soroswap Protocol Integration

## Overview
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.

## How it is Integrated
1. **Pricing:** The `fetchSoroswapQuote` method initializes the protocol via `ProtocolFactory` and calls `getSwapQuote(assetIn, assetOut, amountIn)`.
2. **Execution:** The `buildSoroswapSwapTransaction` calls the `swap` method on the protocol, returning the transaction hash (XDR) ready for signing.
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟑 Minor

Clarify terminology: "transaction hash" vs XDR.

The phrase "returning the transaction hash (XDR)" is misleading. A transaction hash is typically a cryptographic identifier, while XDR is the serialized transaction envelope. Based on the implementation and usage in aggregator-guide.md, this should be "returning the unsigned transaction XDR" or "returning the XDR envelope".

πŸ“ Proposed fix for clarity
-2. **Execution:** The `buildSoroswapSwapTransaction` calls the `swap` method on the protocol, returning the transaction hash (XDR) ready for signing.
+2. **Execution:** The `buildSoroswapSwapTransaction` calls the `swap` method on the protocol, returning the unsigned transaction XDR ready for signing.
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
2. **Execution:** The `buildSoroswapSwapTransaction` calls the `swap` method on the protocol, returning the transaction hash (XDR) ready for signing.
2. **Execution:** The `buildSoroswapSwapTransaction` calls the `swap` method on the protocol, returning the unsigned transaction XDR ready for signing.
πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/defi/soroswap-integration.md` at line 8, Update the wording in the docs
where buildSoroswapSwapTransaction is described: replace "returning the
transaction hash (XDR)" with a clear term such as "returning the unsigned
transaction XDR" or "returning the XDR envelope" to reflect that
buildSoroswapSwapTransaction calls the protocol's swap method and returns the
serialized transaction XDR (not a cryptographic hash); reference
buildSoroswapSwapTransaction and the protocol.swap usage and align with
terminology used in aggregator-guide.md.


Docs for Soroswap: [Soroswap Documentation](https://docs.soroswap.finance/).

## Adding New Protocol Sources
To add a new protocol source (e.g., Aquarius):
1. **Types:** Add the Source ID to the `LiquiditySource` union in `aggregator.types.ts`.
2. **Quoting:** Implement a `fetch<Protocol>Quote(params)` method in `DexAggregatorService` that conforms to `RouteQuote`.
3. **Execution:** Implement a `build<Protocol>SwapTransaction(params)` method to return an unsigned XDR string.
4. **Registration:** Update the switch-cases inside `fetchQuoteFromSource` and `buildSwapTransaction`.

## Testing and Mocking Protocal Responses
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟑 Minor

Fix typo in section heading.

The word "Protocal" should be "Protocol".

πŸ“ Proposed fix
-## Testing and Mocking Protocal Responses
+## Testing and Mocking Protocol Responses
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
## Testing and Mocking Protocal Responses
## Testing and Mocking Protocol Responses
🧰 Tools
πŸͺ› LanguageTool

[grammar] ~19-~19: Ensure spelling is correct
Context: ...apTransaction`. ## Testing and Mocking Protocal Responses To unit test the aggregator w...

(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)

πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/defi/soroswap-integration.md` at line 19, Fix the typo in the section
heading "## Testing and Mocking Protocal Responses" by updating the word
"Protocal" to "Protocol" so the heading reads "## Testing and Mocking Protocol
Responses"; locate and edit that heading in docs/defi/soroswap-integration.md
(the heading text string "Testing and Mocking Protocal Responses").

To unit test the aggregator without hitting real networks, mock the `ProtocolFactory` in Jest:

```typescript
import { ProtocolFactory } from '@galaxy-kj/core-defi-protocols';

jest.mock('@galaxy-kj/core-defi-protocols', () => ({
...jest.requireActual('@galaxy-kj/core-defi-protocols'),
ProtocolFactory: {
getInstance: jest.fn().mockReturnValue({
createProtocol: jest.fn().mockReturnValue({
initialize: jest.fn().mockResolvedValue(true),
getSwapQuote: jest.fn().mockResolvedValue({
amountOut: '99',
priceImpact: '0.1',
path: []
}),
swap: jest.fn().mockResolvedValue({ hash: 'AAAA...' })
})
})
}
}));
```
12 changes: 12 additions & 0 deletions packages/core/defi/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# @galaxy-kj/core-defi

## Overview
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.

## Structure
- `src/services/DexAggregatorService.ts`: Core aggregator service for routing and quotes.
- `src/types/aggregator.types.ts`: Typings for liquidity sources, quotes, and swaps.

For detailed integration guides, see:
- [DEX Aggregator Guide](../../../docs/defi/aggregator-guide.md)
- [Soroswap Integration Guide](../../../docs/defi/soroswap-integration.md)
Loading