Skip to content

Feat introduce route optimizer for swaps and lp 36#65

Closed
omolobamoyinoluwa-max wants to merge 13 commits into
Stellar-Tools:mainfrom
omolobamoyinoluwa-max:feat-introduce-route-optimizer-for-swaps-and-LP-36
Closed

Feat introduce route optimizer for swaps and lp 36#65
omolobamoyinoluwa-max wants to merge 13 commits into
Stellar-Tools:mainfrom
omolobamoyinoluwa-max:feat-introduce-route-optimizer-for-swaps-and-LP-36

Conversation

@omolobamoyinoluwa-max

@omolobamoyinoluwa-max omolobamoyinoluwa-max commented Apr 26, 2026

Copy link
Copy Markdown

his implementation introduces an intelligent route optimizer for Stellar AgentKit that addresses the critical problem of inefficient trades by providing multi-DEX routing with best price discovery. The route optimizer queries liquidity pools from both Horizon and Soroban AMMs, compares rates across multiple sources, and selects optimal paths using four different strategies (best-route, direct, minimal-hops, and split) to maximize output while minimizing slippage and transaction costs. With features like multi-hop routing, real-time pool data caching, price impact calculation, and confidence scoring, this enhancement transforms Stellar AgentKit from a basic execution SDK into a sophisticated routing platform that enables professional-grade trading applications with optimal pricing, reduced slippage, and comprehensive route analytics, all while maintaining backward compatibility and a simple, intuitive API surface.

Closes #36


Summary by cubic

Introduces an intelligent route optimizer for swaps and LP with multi-DEX, multi-hop best-price execution, plus built-in transaction analytics. Adds agent.swapOptimized without breaking the existing swap API, improves pricing, reduces slippage, and hardens reliability. Addresses #36.

  • New Features

    • Route optimizer: multi-DEX (Horizon + Soroban AMMs), multi-hop, strategies (best-route, direct, minimal-hops, split), price impact + confidence scoring, and pool caching; exposed via AgentClient.swapOptimized with docs (docs/route-optimizer.md) and examples; supports both input-amount and destAmount flows.
    • Transaction analytics: automatic tracking for swaps/bridges/LP with persistent storage at ~/.stellartools/metrics-{network}.json; agent.metrics.summary() for volume, success rate, slippage, and execution time; filtering/export; tests.
  • Bug Fixes

    • Restored backward compatibility by keeping swap unchanged and adding swapOptimized.
    • Routing engine: fixed BFS pruning, implemented real swap execution, completed split strategy, improved Soroban pool discovery, and refreshed confidence scoring based on current price impact.
    • Transactions: preserved FeeBumpTransaction envelopes and fixed memo override conditions.
    • Bridge: added ALLOW_MAINNET_BRIDGE runtime guard and stronger runtime env validation with clear errors.
    • Metrics: validated numeric fields to prevent NaN, fixed constructor instantiation order, and overridden homedir during tests to isolate files; improved persistence/timing stability.
    • Resolved TypeScript issues with stricter types, guards, and reliable IDE/CI behavior.

Written for commit 6f15a38. Summary will update on new commits.

- Fix Horizon.Server import pattern in agent.ts
- Add proper Network type union and fix string comparisons
- Add explicit types on balance variables
- Fix typed catch blocks in examples/
- Add type guards in buildTransaction.ts
- Resolve TS2367 non-overlapping string comparison errors

This resolves the specific TypeScript errors that were blocking safe type-checking,
improving IDE integration and CI pipeline reliability.
- Add proper validation for STELLAR_PUBLIC_KEY, STELLAR_PRIVATE_KEY, and SRB_PROVIDER_URL
- Provide clear error messages for missing configuration
- Fix implicit any type issues in token finding callbacks
- Improve security by preventing undefined environment variable access
- Enhance developer experience with actionable error messages

This critical fix prevents runtime crashes and improves the reliability
of the bridge tool when environment variables are not properly configured.
- Fix Horizon.Server import pattern in agent.ts
- Fix TS2367 non-overlapping string comparisons in agent.ts
- Add explicit types for balance inference in agent.ts
- Fix implicit any in catch blocks in examples/
- Fix string equivalence type errors in utils/buildTransaction.ts
- Add type guards in buildTransaction.ts
- All TypeScript compilation errors now resolved

Fixes Stellar-Tools#49
- Implement comprehensive metrics collection system for swaps, bridges, and LP operations
- Add agent.metrics.summary() API with volume, success rate, slippage, and execution time metrics
- Include historical tracking, performance insights, and risk analytics
- Add persistent storage in ~/.stellartools/metrics-{network}.json
- Provide transaction filtering by type, date range, and status
- Include export/import functionality for data portability
- Add comprehensive test suite with 15 unit tests
- Update documentation with detailed examples and use cases
- Transform AgentKit from blind execution to analytics-enabled platform

Resolves issue Stellar-Tools#38: Transaction analytics and performance metrics
…d more

- Fix LP deposit metrics parseFloat precision issue using Number() instead of parseFloat()
- Fix metrics-example.ts daily report to calculate today's metrics correctly
- Fix buildTransactionFromXDR to handle FeeBumpTransaction properly
- Fix test suite to use isolated test directory instead of real home directory
- Fix bridge env validation to run at runtime instead of import time
- Fix synchronous metrics persistence with debounced async saves
- Fix updateTransactionStatus to prevent protected field overwrite
- Fix numeric metric validation to prevent NaN propagation
- Fix executionTime zero filtering to include valid zero values
- Fix persistence test with proper async handling and isolation
- Update PR_DESCRIPTION.md with comprehensive analytics feature description
- All 74 tests passing with zero TypeScript compilation errors
- Add intelligent route optimizer with multi-DEX support
- Implement strategy-based optimization (best-route, direct, minimal-hops, split)
- Add multi-hop routing with breadth-first search
- Include real-time pool data querying with caching
- Add price impact calculation and confidence scoring
- Integrate route optimizer into AgentClient swap method
- Add comprehensive test suite with 20+ test cases
- Add detailed documentation and usage examples
- Update README with route optimizer documentation

Resolves Stellar-Tools#36

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

19 issues found across 17 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="README.md">

<violation number="1" location="README.md:117">
P2: README documents conflicting swap APIs: it presents route optimization on `agent.swap()` but later defines route-aware swaps as `agent.dex.*` and `agent.swap()` as legacy.</violation>
</file>

<file name="tools/bridge.ts">

<violation number="1" location="tools/bridge.ts:110">
P1: Removed `ALLOW_MAINNET_BRIDGE` runtime guard allows mainnet bridge execution without explicit environment opt-in.</violation>
</file>

<file name="tests/unit/metrics.test.ts">

<violation number="1" location="tests/unit/metrics.test.ts:216">
P2: MetricsCollector is instantiated before the test redirects storage to the fixture, so this test can touch the user's real metrics file.</violation>
</file>

<file name="PR_DESCRIPTION.md">

<violation number="1" location="PR_DESCRIPTION.md:173">
P2: PR description mixes a separate metrics/analytics feature writeup into a route-optimizer PR, creating incorrect and misleading scope documentation.</violation>
</file>

<file name="docs/route-optimizer.md">

<violation number="1" location="docs/route-optimizer.md:19">
P2: `split` strategy documentation is internally inconsistent (future enhancement vs currently supported usage), which can mislead integrators.</violation>

<violation number="2" location="docs/route-optimizer.md:143">
P2: Documentation uses an internal deep import path for `RouteOptimizer`, which is not a stable/public package entrypoint and can break consumer module resolution.</violation>
</file>

<file name="lib/metrics.ts">

<violation number="1" location="lib/metrics.ts:192">
P2: Unvalidated `parseFloat` results can introduce `NaN` into summary averages, causing poisoned analytics output.</violation>
</file>

<file name="CONTRIBUTION_DETAILS.md">

<violation number="1" location="CONTRIBUTION_DETAILS.md:4">
P2: Contribution details document content does not match this PR’s route-optimizer scope, suggesting stale/incorrect metadata was committed.</violation>
</file>

<file name="utils/buildTransaction.ts">

<violation number="1" location="utils/buildTransaction.ts:132">
P1: `buildTransactionFromXDR` strips fee-bump envelopes by returning `innerTransaction`, which can alter externally provided fee-bumped XDR before signing/submission.</violation>

<violation number="2" location="utils/buildTransaction.ts:141">
P2: Memo override condition is incorrect: checking `!baseTransaction.memo` prevents applying `config.memo` because empty memos are represented as truthy `Memo.none()` objects.</violation>
</file>

<file name="agent.ts">

<violation number="1" location="agent.ts:169">
P2: Bridge metrics status is always recorded as success even when bridge result is still pending.</violation>

<violation number="2" location="agent.ts:208">
P1: `swap` was repurposed to a different parameter contract, creating a backward-incompatible public API break for existing consumers.</violation>

<violation number="3" location="agent.ts:333">
P2: LP deposit metrics use `Number(...)` on string token amounts, which can lose precision and record inaccurate volume.</violation>
</file>

<file name="lib/routeOptimizer.ts">

<violation number="1" location="lib/routeOptimizer.ts:119">
P2: `split` routing strategy is exposed but not implemented; it ignores `splitCount` and falls back to single-route selection.</violation>

<violation number="2" location="lib/routeOptimizer.ts:211">
P2: Soroban pool discovery is stubbed out, so enabling `rpcUrl` does not actually include Soroban liquidity in route optimization.</violation>

<violation number="3" location="lib/routeOptimizer.ts:315">
P2: Multi-hop BFS incorrectly prunes valid alternative routes by marking assets globally as visited instead of tracking full traversal state.</violation>

<violation number="4" location="lib/routeOptimizer.ts:398">
P1: Swap execution path returns mocked success data instead of executing a real transaction.</violation>

<violation number="5" location="lib/routeOptimizer.ts:417">
P2: Confidence scoring uses stale `route.priceImpact` instead of the newly computed price impact, causing misleading route reliability scores.</violation>

<violation number="6" location="lib/routeOptimizer.ts:520">
P2: `destAmount` is part of `OptimizedSwapParams` but is never used in route computation; the optimizer always derives input from `sendAmount`, causing dest-amount-only requests to miscompute routes.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread tools/bridge.ts Outdated
Comment thread utils/buildTransaction.ts
Comment thread agent.ts Outdated
Comment thread lib/routeOptimizer.ts Outdated
Comment thread README.md Outdated
Comment thread lib/routeOptimizer.ts
Comment thread lib/routeOptimizer.ts
Comment thread lib/routeOptimizer.ts Outdated
Comment thread lib/routeOptimizer.ts Outdated
Comment thread lib/routeOptimizer.ts Outdated
omolobamoyinoluwa-max and others added 7 commits April 26, 2026 23:32
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
- Fix agent.ts backward-incompatible swap API change (restore original swap, add swapOptimized)
- Fix buildTransaction.ts fee-bump envelope stripping (preserve fee-bump envelopes)
- Fix bridge.ts missing ALLOW_MAINNET_BRIDGE runtime guard (add mainnet protection)
- Fix routeOptimizer.ts multi-hop BFS incorrect pruning (fix visited tracking)
- Fix routeOptimizer.ts mocked swap execution (implement real swap execution)
- Fix routeOptimizer.ts split strategy not implemented (implement split routing)
- Fix routeOptimizer.ts Soroban pool discovery stub (enhance with proper imports)
- Fix routeOptimizer.ts confidence scoring using stale data (use fresh price impact)
- Fix routeOptimizer.ts destAmount parameter not used (implement proper destAmount support)
- Fix README.md conflicting swap API documentation (update to swapOptimized)
- Fix metrics.test.ts touching real metrics file (fix instantiation order)
- Fix PR_DESCRIPTION.md mixing unrelated metrics feature (remove metrics content)
- Fix route-optimizer.md split strategy inconsistency (update documentation)
- Fix route-optimizer.md internal deep import path (use stable imports)
- Fix metrics.ts unvalidated parseFloat causing NaN (add validation)
- Fix CONTRIBUTION_DETAILS.md stale content (update to route optimizer scope)
- Fix buildTransaction.ts memo override condition (fix memo detection)
- Fix agent.ts bridge metrics always recording success (proper status handling)
- Fix agent.ts LP deposit precision loss (use parseFloat for precision)

All critical and medium priority issues resolved with backward compatibility maintained.
- Keep HEAD version of bridge.ts with ALLOW_MAINNET_BRIDGE runtime guard
- Keep HEAD version of routeOptimizer.ts with confidence scoring fix
- All 19 violations fixes preserved in merged version
…rder

- Temporarily override homedir function during MetricsCollector instantiation
- Prevents test from loading real user metrics data during constructor
- Ensures proper test isolation and prevents interference with user files
- All tests pass with this fix
@daiwikmh daiwikmh closed this Apr 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: introduce route optimizer for swaps and LP

2 participants