Skip to content

feat(pricing): add staleness-aware median pricing with priority source fallback (#81) - #628

Open
phatloi0010 wants to merge 1 commit into
Divinity-Labs:mainfrom
phatloi0010:feat/staleness-aware-median-pricing-81
Open

phatloi0010 wants to merge 1 commit into
Divinity-Labs:mainfrom
phatloi0010:feat/staleness-aware-median-pricing-81

Conversation

@phatloi0010

Copy link
Copy Markdown

Summary

Implements staleness-aware median pricing across multiple price sources with priority fallback chain and source inclusion/exclusion annotations.

Closes #81

Changes

  1. src/pricing/median.ts:
    • Implemented calculateMedian (returning number | null, never 0 on empty input), clampFreshnessThreshold (bounded to [5, 86400] seconds, default 300s), computeStalenessAwareMedian, and getStalenessAwareMedianPrice.
    • Filters out sources older than freshnessThresholdSeconds (recording them in excludedSources with reason: 'stale' and ageSeconds) as well as non-positive/non-finite quotes (reason: 'invalid_price' | 'invalid_timestamp').
    • Computes the median strictly across fresh sources when available.
    • Engages a priority fallback chain (['SDEX', 'AMM', 'SOROSWAP', 'PHOENIX', 'AQUARIUS', 'REFLECTOR', 'DEFINDEX'], falling back to the freshest valid stale source when none match the priority list) when all valid sources are stale, annotating fallbackUsed: true, fallbackSource, and fallbackAgeSeconds.
    • Distinguishes empty input (reason: 'no_price_data') from all-invalid input (reason: 'all_sources_invalid'), returning medianPrice: null in both cases.
  2. src/api/rest.ts, openapi.yaml, openapi.json, README.md, docs/what-lens-knows.md, clients/typescript/src/schema.d.ts:
    • Added GET /price/:assetA/:assetB/median (and /v1/price/{assetA}/{assetB}/median in OpenAPI + generated artifacts) with freshness validation in [5, 86400] seconds (HTTP 400 when out of bounds) and HTTP 404 when medianPrice === null.
  3. src/__tests__/medianPricing.test.ts:
    • Added 14 unit and route tests covering odd/even medians, empty vs all-invalid inputs, fresh source median calculation with stale outlier exclusion, priority fallback chain with fallbackAgeSeconds, freshness parameter bounds, and database/REST integration.

Verification

  • npx tsc --noEmit: PASS (0 errors)
  • npm run client:typecheck & npm run readme:check: PASS
  • npx vitest run src/__tests__/medianPricing.test.ts tests/openapi.test.ts tests/readme.test.ts tests/rest-route.test.ts: PASS (4/4 files, 94/94 tests)
  • node scripts/check-dropped-tests.mjs origin/main HEAD: PASS (0 dropped test cases)

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.

Staleness-aware median pricing with source fallback

1 participant