Skip to content

Typed reads for order slots; DecodeError on decode failures - #1

Open
ola196 wants to merge 130 commits into
mainfrom
ola196-typed-order-slot-reads
Open

Typed reads for order slots; DecodeError on decode failures#1
ola196 wants to merge 130 commits into
mainfrom
ola196-typed-order-slot-reads

Conversation

@ola196

@ola196 ola196 commented Aug 29, 2026

Copy link
Copy Markdown
Owner

Why

Reading order slots for accounts with no orders or unfunded subaccounts previously surfaced raw XDR or threw, making it impossible for consumers to distinguish an empty slot from a decode error.

What changed

  • Adds a DecodeError (src/errors.ts) that includes slot context when decoding fails.
  • Updates StopLossModule.getStopLossOrders (src/modules/stop-loss.ts) to:
    • Treat empty/missing slots as empty (ignored in final list).
    • Decode each slot safely (handles base64 XDR and native values).
    • Raise DecodeError with slot info for per-slot decode failures and for top-level decode failures.

Notes for reviewers

  • Other modules that read slot arrays should adopt the same pattern to get the same safety.
  • No behavior changes for successfully-decoded orders.

Closes CoralSwap-Finance#676

Arome8240 and others added 30 commits June 29, 2026 09:49
Adds a new PortfolioModule that computes per-position and aggregate
PnL for LP holders by replaying on-chain add/remove liquidity events
against the current pool state.

- PositionPnL and PortfolioPnL types in src/types/positions.ts
- PortfolioModule in src/modules/portfolio.ts with getPortfolioPnL(address, opts)
- Decomposes netPnL into feeEarnedUSD and ilUSD components
- Accepts optional tokenPricesUSD map; gracefully returns 0 USD values
  when prices are unavailable
- Handles multiple add/remove events, partial removals, and multi-pair
  portfolios via Promise.allSettled for resilience
- 16 unit tests covering all acceptance criteria

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Adds a new PortfolioModule that computes per-position and aggregate
PnL for LP holders by replaying on-chain add/remove liquidity events
against the current pool state.

- PositionPnL and PortfolioPnL types in src/types/positions.ts
- PortfolioModule in src/modules/portfolio.ts with getPortfolioPnL(address, opts)
- Decomposes netPnL into feeEarnedUSD and ilUSD components
- Accepts optional tokenPricesUSD map; gracefully returns 0 USD values
  when prices are unavailable
- Handles multiple add/remove events, partial removals, and multi-pair
  portfolios via Promise.allSettled for resilience
- 16 unit tests covering all acceptance criteria

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Adds tests/portfolio.test.ts covering getPortfolio(), getPortfolioValue(),
and getPortfolioPnL() with mocked RPC and price feeds. Extends portfolio.ts
with getPortfolio() and getPortfolioValue() methods, adds Portfolio/PortfolioValue
types, and wires up all public exports.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…ules (CoralSwap-Finance#315)

- Add AlertModule with CRUD, lifecycle transitions (active/fired/acknowledged/resolved/paused/archived), event subscriptions, and summary aggregation
- Add WebhookModule with endpoint registration, HMAC-SHA256 signature verification, delivery with retry/exponential backoff, endpoint health tracking, and delivery history
- Add MonitoringModule with pool health checks, system health checks, protocol summary, metric querying, and built-in metric definitions
- Add TSDoc with @PARAM, @returns, @throws, and @example tags on all public methods
- Document alert lifecycle and alert type thresholds
- Document webhook delivery guarantees and HMAC security
- Add module-level documentation for all three modules
Closes CoralSwap-Finance#318

- Comprehensive migration guide covering all 7 breaking change areas
- Before/after code examples for every breaking API change
- Step-by-step upgrade instructions (6 testable steps)
- FAQ section addressing common migration issues
- Linked from README.md and CHANGELOG.md
…oring modules

- Add comprehensive TSDoc to AlertsModule with @PARAM, @returns, @throws, @example
- Add comprehensive TSDoc to WebhooksModule with HMAC security documentation
- Add comprehensive TSDoc to MonitoringModule with metric category documentation
- Add module-level documentation for each module with lifecycle and type docs
- Add type definitions (AlertConfig, WebhookConfig, MetricConfig, etc.)
- Update typedoc.json navigation link to fork origin
- Add MissingPriceFeedError with tokenAddress and fallbackUsed context
- Add AddressNotFoundError with address and network context
- Add PortfolioCalculationError with failedPool and reason context
- Replace generic Error throws in PortfolioModule with typed SDK errors
- Add protected stableAddresses getter to TreasuryModule for subclass access
- Export new error classes and PortfolioModule from package index
…erts-monitoring

Add MIGRATION.md guide for upgrading from v1 to v2
…ert-monitoring-docs

feat: add API reference docs for alerts, webhooks, and monitoring modules
Resolve merge conflicts in src/errors.ts, src/index.ts, and
src/modules/index.ts by including changes from both branches:
- Portfolio module error classes (MissingPriceFeedError, AddressNotFoundError, PortfolioCalculationError)
- Webhook module classes (WebhookError, WebhookDisabledError, WebhookDeliveryError)
- Alert module exports (AlertsModule, AlertModule, WebhookModule, MonitoringModule)
…Finance#283)

Add src/modules/health-check.ts exporting:
- checkRPCHealth() — probe RPC endpoints for health status
- getRPCLatency() — compute p50/p95/p99 + error rate
- getContractStatus() — verify deployment and TTL expiry
- getBestEndpoint() — rank and pick the lowest-latency healthy RPC
- percentile() — linear-interpolation percentile utility
- HealthCheckModule — class wrapper for container registration

	ests/health-check.test.ts adds 28 tests covering all four probe
functions with SorobanRpc.Server mocked so no real network calls
are made. Percentile math is verified against a known 0..100 dataset.
Minimum acceptance: 15+ test cases — met (28).
Feat/issue 268 leaderboard module
[SDK] Fix missing error context in portfolio module exceptions
feat(health-check): add HealthCheckModule with unit tests (CoralSwap-Finance#283)
feat: add validation guards to GovernanceModule methods
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 7.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](actions/checkout@v4...v7)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 4 to 8.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](actions/download-artifact@v4...v8)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '8'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4 to 7.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](actions/upload-artifact@v4...v7)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Bumps [actions/github-script](https://github.com/actions/github-script) from 7 to 9.
- [Release notes](https://github.com/actions/github-script/releases)
- [Commits](actions/github-script@v7...v9)

---
updated-dependencies:
- dependency-name: actions/github-script
  dependency-version: '9'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
larryjay007 and others added 30 commits August 7, 2026 12:13
* feat: add transaction composer workflow

* feat: compose add liquidity and stake flow

* refactor(liquidity): migrate validation to zod schemas

* refactor: remove zod validation from limit orders

* fix: restore limit order validation type references

* feat: add transaction composer workflow

* fix: resolve TypeScript compiler errors, Zod schema refine syntax, and unused imports

* fix(staking): restore StakingError import and fix client test mock

* fix(client): use server setter in executeWithFallback for mock server support

* fix(lint): resolve all ESLint errors across modules

* test(integration): guard integration suites against missing secrets on fork PRs

* fix(integration): update RwaModule import to RWAModule in rwa.integration.test.ts

* fix(integration): update rwa.integration.test.ts for RWAModule class and methods

* ci: trigger fresh build
…alSwap-Finance#555)

* fix(alerts): use TWAP-backed price source to resist manipulation (Closes CoralSwap-Finance#501)

- Add OracleModule instance to both AlertsModule and AlertModule
- Update fetchPrice() to use TWAP when available, fallback to spot
- Update getPoolPrice() to prioritize TWAP over raw spot reserves
- Update checkILAlert() to use TWAP for IL calculations
- Add fallback mechanism when TWAP not yet available (needs MIN_TWAP_WINDOW_SECONDS)
- Add comprehensive tests for flash loan attack resistance
- Add tests documenting fallback behavior and TWAP protection
- Tests verify manipulated reserves don't trigger false alerts with TWAP

* fix(tests): add getCumulativePrices mock and fix TWAP test observations
…net (CoralSwap-Finance#586)

Add integration test for PositionsModule.getPosition(), getPositions(),
and hasPosition() using real Stellar Testnet data. Tests verify:
- Enriched LP position data consistency (balances, reserves, share)
- PositionSummary filtering and empty-case handling
- hasPosition true/false for known addresses

All tests are guarded by the STELLAR_TESTNET env var skip gate.

Adds npm run test:integration:positions script.

Closes CoralSwap-Finance#450

Co-authored-by: OpadijoIdris <opadijoidris@branda.com.ng>
…-Finance#579)

Verifies getLeaderboard()/getTopTraders() against real on-chain swap
and add-liquidity events on a known A/B testnet pool, and checks the
empty/new-pool path (untouched B/C pool) returns gracefully instead
of throwing.
…nce#581)

- Add comprehensive integration tests for RouterModule against Stellar Testnet
- Test multi-hop route quoting with real pool reserves
- Test EXACT_IN pathfinding for optimal route selection
- Test EXACT_OUT pathfinding with target output amounts
- Verify quote consistency against real on-chain reserves
- Test edge cases: no path exists, zero-liquidity filtering, cache behavior
- Add npm script 'test:integration:router' for isolated test execution
- Follow existing integration test conventions (env vars, STELLAR_TESTNET skip gate)
- Include liquidity setup and cleanup utilities for test idempotence

Tests cover issue CoralSwap-Finance#453 acceptance criteria:
- Multi-hop quote verified against real Testnet pool reserves
- EXACT_OUT path verified to produce a route satisfying target output amount
…ralSwap-Finance#522)

Implements checkRPCHealth, checkAllEndpoints, and getBestEndpoint per issue CoralSwap-Finance#280.
…et (CoralSwap-Finance#305) (CoralSwap-Finance#425)

Co-authored-by: alexatsejames-alt <alexatsejames@gmail.comgit config --global user.email alexatsejames@gmail.com>
…ss (CoralSwap-Finance#521)

Rebased onto main's newly-merged TransactionComposer (src/transaction-composer.ts)
and reimplemented on top of it, since main had already gained its own
composer plus a first composed flow (addLiquidityAndStake) since this
branch was created.

- createStopLoss() now rejects order creation against a stale RedStone
  oracle read, using the same freshness guard as enrichOrder()/
  isStopLossTriggered() (CoralSwap-Finance#500).
- StopLossModule.swapAndCreateStopLoss() composes a swap with a protective
  stop-loss placement into one atomic transaction via the shared
  TransactionComposer (CoralSwap-Finance#496).
- LimitOrderModule.cancelAndReplaceLimitOrder() composes cancel + place
  atomically, reusing the module's existing idempotent-resubmission
  safety net (CoralSwap-Finance#467) since both legs move escrowed funds (CoralSwap-Finance#497).
- StakingModule.unstakeAndWithdraw() composes unstake + liquidity
  withdrawal atomically once cooldown has elapsed (CoralSwap-Finance#498).
…ns (CoralSwap-Finance#532)

* feat(blend): adopt idempotent resubmission for LP-collateral operations

- Add shared idempotent-resubmission utility (CoralSwap-Finance#464 companion)
- Implement deposit/withdraw collateral with safe retry in blend module
- Add tests covering timed-out-but-landed and genuine failure paths

Closes CoralSwap-Finance#475

* fix(blend): remove unused imports

* feat(blend): adopt idempotent resubmission

---------

Co-authored-by: poaspergillus <poaspergillus@users.noreply.github.com>
…alSwap-Finance#562)

Co-authored-by: olatechy0 <olatechy0@users.noreply.github.com>
…0-order-book-event-cursor

Document order book EventCursor audit
…dabot/npm_and_yarn/zod-4.4.3

build(deps): bump zod from 3.25.76 to 4.4.3
…at/webhooks-integration-test

feat(webhooks): add testnet integration tests for webhook registration, delivery, and retry behavior
dependabot bump stellar-sdk 12 to 17 plus migrations
…ilures raise DecodeError; closes CoralSwap-Finance#676

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
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.

[SDK] limit-orders: empty/unfunded order-slot reads should surface typed order state, not raw XDR decode failures