Skip to content

Spike 574: flag-gated liquidity pools (phase-182) - #603

Merged
Darkvader-ship-it merged 2 commits into
PHASE-STELLAR:mainfrom
shekwolonathanielbala-cyber:main
Oct 21, 2026
Merged

Darkvader-ship-it merged 2 commits into
PHASE-STELLAR:mainfrom
shekwolonathanielbala-cyber:main

Conversation

@shekwolonathanielbala-cyber

Copy link
Copy Markdown
Contributor

#438 Spike 574: Integrate Soroswap and Classic DEX Liquidity Pools

Summary

Implement a feature-flagged liquidity pool integration supporting Soroswap and Stellar's classic liquidity pool operations, including PHASELQ-XLM pools and Chamber swaps. This spike establishes a secure, idempotent, and observable end-to-end flow covering funding, pool interactions, settlement, indexing, and UI display.

The implementation addresses existing architectural gaps in settlement accounting, liquidity pool balance handling, trustline preflight checks, reserve and quote retrieval, market pricing, wash-trading detection, and pool seed capital management.

Changes

  • Smart Contracts: Extend the Phase Protocol to support liquidity-related operations, settlement safeguards, and the required contract-level invariants.
  • Stellar Integration: Add and update Soroswap and classic DEX helpers for pool discovery, quotes, deposits, withdrawals, swaps, and asset resolution.
  • API Routes: Integrate classic liquidity operations and update market and offer endpoints to support pool-aware trading and settlement.
  • Market Storage: Extend market persistence and concurrency controls to prevent silent overwrites and preserve consistent state during overlapping requests.
  • Wash-Trading Prevention: Detect and flag self-provisioning, self-swapping, replay attempts, and suspicious volume manipulation; exclude invalid activity from aggregates.
  • Distributor Accounting: Update distributor ledger, refill, and issuer-payment flows to support safe liquidity pool funding and preserve accounting invariants.
  • Idempotency and Concurrency: Enforce appropriate replay protection, version-guarded writes, and deterministic behavior under retries and concurrent operations.
  • Resilience: Add or integrate safeguards for RPC, Horizon, and gateway failures, including failover, stale-on-error handling, and appropriate retry behavior.
  • Feature Flags: Introduce dedicated "phase-*" flags, defaulting to off, with documented rollback procedures and no regression when disabled.
  • Internationalization: Route all user-facing strings and errors through "lib/phase-copy.ts" and "pickCopy(lang)", supporting English and Spanish.
  • Documentation: Update the liquidity rewards terminal documentation, architecture records, technical documentation, environment configuration, and relevant API contracts.

Security and Reliability

  • Preserve client-side wallet signing through Freighter and Stellar Wallet Kit.
  • Keep privileged and issuer keys within their existing authorized server-side boundaries.
  • Validate pool assets, trustlines, quotes, slippage, and contract configuration before executing operations.
  • Prevent duplicate processing and unsafe settlement through layered idempotency and concurrency controls.
  • Use closed-label metrics without wallet addresses, signal identifiers, or user-generated text.
  • Preserve normalized domain errors, including the existing biometric trust gate error mapping.
  • Keep testnet-specific assumptions explicitly fenced from mainnet behavior.

Testing and Validation

  • Verify the complete testnet flow: Friendbot funding → trustline setup → asset funding → pool operation or swap → transaction verification → indexing → UI display.
  • Record transaction hashes and contract IDs, with configuration sourced from environment variables and synchronized documentation.
  • Test Soroswap and classic liquidity pool paths independently.
  • Verify replay protection, duplicate submissions, expired requests, and retries following serverless timeouts.
  • Validate concurrent writes, version conflicts, deterministic queue behavior, and CRDT merge semantics.
  • Test self-deal, sybil, wash-trading, tampered-input, and volume-drift detection.
  • Verify RPC, gateway, and Horizon failover, stale-on-error behavior, circuit breakers, and "Retry-After" propagation.
  • Confirm English and Spanish translations and normalized error handling.
  • Update and verify feature-flag documentation and rollback behavior.
  • Run existing tests, "tsc --noEmit", and Vitest with all new flags disabled to confirm no regressions.

Migration and Rollback

All new functionality remains disabled by default until the end-to-end testnet proof and required validation are complete.

Contract upgrades or redeployments, contract ID changes, database migrations, environment updates, and associated documentation must be coordinated. Additive database migrations should preserve existing data, while JSON sidecar data must remain inert when the feature is disabled.

Rollback consists of disabling the new feature flags and reverting the relevant documentation changes. Any on-chain changes, stranded assets, or contract state require an explicit recovery plan because disabling application flags does not reverse blockchain transactions or contract upgrades.

Scope and Limitations

  • Testnet validation only.
  • No production facilitator keys or mainnet deployment.
  • No shared-database migration.
  • Any expansion beyond the defined 16-file scope requires a separate issue or spike.

Issue Closure

Closes #438

Add the classic PHASELQ/XLM pool and Soroswap router adapter for spike PHASE-STELLAR#438.

What ships now:
- lib/liquidity-pool.ts: pool id derived from the pair, Horizon pool
  record parsing, a constant-product quote with fee/impact/min-out/
  quote-hash, a 409 QUOTE_STALE / QUOTE_MISMATCH gate, deposit /
  withdraw / pool-share trustline builders, a path-payment swap
  builder, Soroswap config with no default router and router-drift
  detection, quote-hash intent idempotency, and a pool activity table
  that labels + excludes self-provision and self-swap volume.
- app/api/liquidity-pools/route.ts: quote + prepare (deposit /
  withdraw / swap / trustline) and a Horizon-verified record action so
  pool volume can only count after a real successful settlement.
- Market reads and offers read pick up spot+execution price in XLM
  advisory; fails the pool open when the pool is down.
- Wash: detectSelfProvisionedPools, detectSelfSwaps, pool counters,
  getPoolVolumeExcludingWash.
- Distributor ledger: additive pool_seed_stroops that is subtracted
  from availableBalance and from reserveFunds.
- distributor-trust-and-payment.ts: pool-share trustline step when
  LP_POOL_SEED_ENABLED=1.
- phase-protocol: set_pool_leg / get_pool_leg / clear_pool_leg plus
  PoolLegConfig storage (Rust on disk here; not compiled in this env).
- i18n, closed-label counters, the feature-flag/security-counter rows,
  sidecar key, docs/TECHNICAL.md 28, PROJECT_ARCHITECTURE.md §10, and
  the spike record docs/spikes/574-liquidity-pools-findings.md.
- lib/__tests__/liquidity-pool.test.ts: 28 tests.

Verification this turn:
- tsc --noEmit green.
- 56 tests green across liquidity-pool, feature-flag-ops, funnel-
  retention, xbull-adapter, viewer-signature.
- Pre-existing failures remain pre-existing only: client-only browser-
  module collection failures plus two old assertion-drift bugs (moderation
  audit redaction, biometric unlock, wallet-history stale-on-error,
  walletconnect-resilience session persistence).

Rollback (from docs/PROJECT_ARCHITECTURE.md §10):
unset NEXT_PUBLIC_FEATURE_PHASE_182 / FEATURE_PHASE_182 and restart;
liquidity-pool-intents.json, pool_activity, distributor_pool_seed_stroops,
and PoolLegConfig stay inert.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
@drips-wave

drips-wave Bot commented Oct 21, 2026

Copy link
Copy Markdown

@shekwolonathanielbala-cyber Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

@shekwolonathanielbala-cyber

Copy link
Copy Markdown
Contributor Author

Please merge

@Darkvader-ship-it
Darkvader-ship-it merged commit 14a0e34 into PHASE-STELLAR:main Oct 21, 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.

# Spike 574 — Liquidity pools: Soroswap plus classic DEX with PHASELQ-XLM pool and Chamber swaps

2 participants