Intelligence, Advanced Charting & Trading Platform
Phase 1: establish market domain and provider contracts
* docs: update architecture for provider-neutral PostgreSQL * docs: make managed PostgreSQL hosting replaceable * test: specify theoretical gold and premium behavior * feat: implement deterministic gold pricing domain * test: run market domain tests in CI * test: use tolerance for floating-point premium * test: define provider normalization and health contracts * feat: implement provider normalization and health contracts * test: define deterministic market data quality states * feat: implement deterministic market data quality evaluation * docs: advance Phase 1 execution ledger * docs: add verified Phase 1 provider source matrix
davoodmehraban89 committed
Oct 5, 2026 at 16:20 UTC
fbda7ec2daf81b16f973a7ecbed3c27ae61bb554
10 files changed
+472
-20
PROJECT_STATE.md
+30
-20
@@ -3,7 +3,7 @@
3
Last updated: 2026-10-05
4
5
## Current phase
6
-Phase 0 — Foundation & Governance; PostgreSQL core implementation in progress.
6
+Phase 1 — Market Domain & Data Proof started. Phase 0 PostgreSQL foundation is merged.
7
8
## Product scope locked for MVP
9
- Iran free-market USD/IRT
@@ -14,41 +14,51 @@ Phase 0 — Foundation & Governance; PostgreSQL core implementation in progress.
14
- Professional charting, drawing tools, technical indicators, overlays, and persistent user workspaces
15
16
## Architecture baseline
17
-- Modular monolith for the MVP.
17
+- Modular monolith for MVP, with independently schedulable ingestion workers.
18
- TypeScript/React/Next.js web application.
19
-- PostgreSQL is the canonical datastore; hosting is provider-portable through `DATABASE_URL`.
20
-- Neon is the preferred initial managed PostgreSQL provider, but is not a domain dependency.
21
-- Cloudflare is edge/runtime/cache/protection; Hyperdrive may front PostgreSQL after credentials exist.
19
+- PostgreSQL is the only canonical database contract. Hosting provider is replaceable through `DATABASE_URL`.
20
+- Initial hosting target is Aiven Free PostgreSQL if it can be provisioned without payment credentials; Aiven is infrastructure only, never a domain dependency.
21
+- Supabase, Neon, Render and Railway are not architectural dependencies. They remain replaceable hosting alternatives.
22
+- Cloudflare is edge/runtime/cache/protection. Hyperdrive can front any compatible reachable PostgreSQL once credentials exist.
23
- Provider adapters feed immutable raw observations, normalization, quality gates, candle construction, and derived-series calculation.
24
- UTC canonical storage; Asia/Tehran presentation.
25
+- No UI timeframe may imply precision not supported by source data.
26
27
## Completed
28
- Independent private GitHub repository established.
27
-- Phase 0 foundation PR passed CI and was merged to `main`.
29
+- Phase 0 foundation merged to `main` with green CI.
30
+- Provider-neutral PostgreSQL market core merged to `main` with green CI.
31
- Engineering rules, Definition of Done, architecture baseline and canonical market contracts established.
29
-- PostgreSQL portability decision recorded in ADR-0002.
30
-- Initial PostgreSQL migrations created for instruments, providers, raw observations, normalized ticks, candles, derived values, data-quality events, users, workspaces and drawings.
32
+- PostgreSQL migrations exist for instruments, providers, raw observations, normalized ticks, candles, derived values, data-quality events, users, workspaces and drawings.
33
- Six canonical MVP instruments are seeded.
32
-- Database invariant test added for canonical instruments and invalid OHLC rejection.
33
-- Cloudflare account connection verified; Hyperdrive API is available and currently has no configurations.
34
-- Neon plugin is installed in the ChatGPT environment, but its operational actions are not exposed in this conversation yet.
34
+- Database invariant test exists for canonical instruments and invalid OHLC rejection.
35
+- Cloudflare account connection verified.
36
+- Render Free PostgreSQL was tested and rejected for the current zero-cost constraint because provisioning required payment credentials.
37
+- Deterministic theoretical 18K gold and premium calculations implemented.
38
+- Source timestamp alignment and staleness semantics implemented.
39
+- Provider normalization contract implemented, including IRR-to-IRT conversion and refusal to guess unsupported units.
40
+- Provider health contract implemented.
41
+- Deterministic market-data quality classification implemented for GOOD / DEGRADED / STALE / INVALID.
42
+- CI floating-point assertion defect was identified from workflow logs and corrected with tolerance-based numeric assertions.
43
44
## In progress
37
-- Provisioning a managed PostgreSQL database for VELYQOR.
38
-- Applying and executing database migrations/invariant tests against a real PostgreSQL instance.
39
-- Cloudflare Hyperdrive configuration after PostgreSQL credentials exist.
40
-- Phase 1 provider research/data proof.
45
+- Phase 1 provider research/data proof for USD/IRT, GOLD18/IRT and XAU/USD.
46
+- Managed PostgreSQL provisioning on a no-card free provider.
47
+- Provider-specific adapters only after legal/technical source suitability is documented.
48
+- Integration of quality state with ingestion/candle pipeline.
49
50
## External blocker
43
-A live PostgreSQL instance has not yet been provisioned/connected in this conversation. Until a database connection is available, migrations cannot truthfully be reported as executed. Neon is the selected initial provider; the schema itself remains portable PostgreSQL.
51
+A live VELYQOR PostgreSQL endpoint is not yet connected. This blocks executing migrations against production-like infrastructure, but it does not block domain implementation, deterministic tests, provider research, or application scaffolding.
52
53
## Risks
54
- Iranian market-data provider licensing, timestamp quality, anti-bot restrictions, history and reliability.
55
- UI timeframes must reflect actual observation frequency; synthetic precision is prohibited.
56
- XAU/USD and USD/IRT source timestamps require explicit alignment/staleness thresholds.
57
+- Free database hosting is temporary infrastructure and must not become a product dependency.
58
59
## Next checkpoint
51
-1. Provision/connect VELYQOR PostgreSQL.
52
-2. Execute migrations and invariant tests.
53
-3. Create Cloudflare Hyperdrive against the database.
54
-4. Start Phase 1 provider adapters and data-quality proof.
60
+1. Get Phase 1 domain/provider contract CI green and merge.
61
+2. Complete provider source matrix and select primary/secondary candidates for each canonical symbol.
62
+3. Connect Aiven or another no-card PostgreSQL endpoint and execute migrations/invariants.
63
+4. Configure Cloudflare Hyperdrive only after a real PostgreSQL endpoint exists.
64
+5. Start chart application shell after Data Proof gates are satisfied.
docs/architecture/ADR-0003-managed-postgres-hosting.md
new
+21
@@ -0,0 +1,21 @@
1
+# ADR-0003: Managed PostgreSQL Hosting Is Replaceable Infrastructure
2
+
3
+Status: Accepted
4
+Date: 2026-10-05
5
+
6
+## Context
7
+VELYQOR requires PostgreSQL, but the initial project must avoid foreign-payment dependencies. Supabase project capacity is constrained, Neon actions are not exposed in the current execution environment, and Render Free provisioning was observed to require payment credentials.
8
+
9
+## Decision
10
+- The product depends on PostgreSQL, not on a PostgreSQL hosting vendor.
11
+- Runtime configuration exposes the database only as `DATABASE_URL` plus non-secret connection policy settings.
12
+- Aiven Free PostgreSQL is the current initial hosting target if it can be provisioned without payment credentials.
13
+- Hosting-provider SDKs, proprietary auth, proprietary realtime, and provider-specific SQL are prohibited from the core market domain.
14
+- Cloudflare Hyperdrive may be introduced as a connection/edge optimization layer after a reachable PostgreSQL endpoint exists.
15
+- Migrations remain plain PostgreSQL and versioned in the repository.
16
+
17
+## Portability gate
18
+Changing the managed PostgreSQL provider must not require changes to market symbols, pricing formulas, candle semantics, data-quality rules, or chart contracts.
19
+
20
+## Consequences
21
+Aiven, Neon, Supabase, Render, Railway, a VPS, or a future dedicated PostgreSQL cluster can be substituted without rewriting the product domain. Provider-specific operational configuration stays outside the domain layer.
docs/data/provider-source-matrix.md
new
+116
@@ -0,0 +1,116 @@
1
+# Provider Source Matrix — Phase 1 Data Proof
2
+
3
+Research date: 2026-10-05
4
+
5
+This matrix is an engineering gate, not a provider endorsement. A provider is not promoted to production solely because an API is reachable. Licensing/commercial rights, timestamp quality, update frequency, history, reliability, and reproducibility must all be acceptable.
6
+
7
+## Canonical symbols
8
+
9
+| Canonical symbol | Needed for MVP | Data requirement |
10
+|---|---:|---|
11
+| USD_IRT_FREE | Yes | Iranian free-market USD/IRT, timestamped observations |
12
+| GOLD18_IRT | Yes | Iranian 18K gold/IRT, timestamped observations |
13
+| XAU_USD | Yes | Global gold spot USD/troy ounce |
14
+| GOLD18_THEORETICAL_IRT | Derived | Calculated internally |
15
+| GOLD18_PREMIUM_IRT | Derived | Calculated internally |
16
+| GOLD18_PREMIUM_PCT | Derived | Calculated internally |
17
+
18
+## Current candidates
19
+
20
+### Navasan
21
+Official source: https://www.navasan.tech/en/api
22
+
23
+Observed capabilities:
24
+- Iranian currency prices in IRR.
25
+- Latest rates and historical updates.
26
+- Historical OHLC is documented.
27
+- Free tier currently advertises 120 calls/month and update rate every two hours.
28
+- Paid Standard tier advertises instantaneous updates with higher call limits.
29
+
30
+Engineering ruling:
31
+- Suitable for schema/integration proof and possibly low-frequency reference/backfill.
32
+- Free tier is NOT sufficient for a genuine 1-minute/live chart.
33
+- Never expose a 1m timeframe from this source alone.
34
+- Commercial use/plan terms must be confirmed before production dependency.
35
+
36
+Candidate role:
37
+REFERENCE / DEVELOPMENT PROOF
38
+
39
+### Bon-bast
40
+Official docs: https://www.bon-bast.com/docs
41
+
42
+Observed capabilities:
43
+- Near-real-time Iran open-market FX plus gold/silver/coin.
44
+- Historical data is advertised.
45
+- Bon-bast states its displayed rates are in toman.
46
+- Official commercial API is paid; current Basic plan is advertised at USD 469/year with 10,000 API calls/month.
47
+- The service explicitly directs businesses to its API for commercial use.
48
+
49
+Engineering ruling:
50
+- Strong production candidate from a licensing/official-API perspective if/when budget is approved.
51
+- Does not satisfy the current zero-foreign-spend MVP constraint.
52
+- Do not scrape the public site as a substitute for commercial API rights.
53
+
54
+Candidate role:
55
+FUTURE PRODUCTION / COMMERCIAL REFERENCE
56
+
57
+### Alpha Vantage — XAU/USD
58
+Official docs: https://www.alphavantage.co/documentation/
59
+
60
+Observed capabilities:
61
+- Dedicated Gold & Silver Spot endpoint.
62
+- Historical gold/silver daily/weekly/monthly endpoint.
63
+- Free API keys are offered.
64
+- Suitable as an immediately testable global-XAU source, subject to actual free quota and freshness observed during Data Proof.
65
+
66
+Engineering ruling:
67
+- Good initial XAU/USD candidate for development and validation.
68
+- Production/live suitability must be measured, not assumed.
69
+- If free quota/frequency is insufficient for desired chart resolution, replace behind the provider adapter without domain changes.
70
+
71
+Candidate role:
72
+PRIMARY DEVELOPMENT CANDIDATE FOR XAU_USD
73
+
74
+## Rejected assumptions
75
+
76
+- Binance market streams are useful for crypto/futures streams, but they are not adopted here as the canonical XAU/USD source without explicit evidence for the required spot-gold instrument.
77
+- Unofficial scrapers/wrappers are not production truth sources.
78
+- A source that updates every two hours cannot truthfully support a 1m candle.
79
+- Missing observations are not synthesized into fake ticks.
80
+
81
+## Selection gates
82
+
83
+A provider can become PRIMARY only after all applicable gates pass:
84
+
85
+1. Legal/commercial usage path is documented.
86
+2. Unit convention is explicit (IRR vs IRT, gram vs ounce, purity).
87
+3. Provider timestamp is present or a documented receive-time fallback is used.
88
+4. Update frequency is measured over a continuous test window.
89
+5. Duplicate/out-of-order behavior is measured.
90
+6. Outage/recovery behavior is known.
91
+7. Historical depth and OHLC semantics are verified if used for backfill.
92
+8. Cross-provider divergence can be observed where a reference source exists.
93
+9. Credentials are server-side only.
94
+10. The UI exposes only timeframes justified by observed source frequency.
95
+
96
+## Current Phase 1 source plan
97
+
98
+USD_IRT_FREE:
99
+- Navasan as immediate integration/reference candidate.
100
+- Bon-bast retained as future commercial-quality candidate.
101
+- Continue searching for a second zero-cost legally usable reference before calling the source stack resilient.
102
+
103
+GOLD18_IRT:
104
+- Evaluate Navasan's gold instruments/units in the same proof harness.
105
+- Bon-bast retained as future commercial candidate.
106
+- Reject any source whose gold definition (18K / mesghal / ounce / rial/toman) is ambiguous.
107
+
108
+XAU_USD:
109
+- Implement Alpha Vantage adapter first for proof.
110
+- Measure actual freshness/quota.
111
+- Keep adapter replaceable.
112
+
113
+## Exit condition for provider selection
114
+
115
+No provider is marked production-ready in this document yet.
116
+Phase 1 Data Proof exits only when USD_IRT_FREE, GOLD18_IRT, and XAU_USD each have a tested ingestion path with observed timestamps, units, freshness, failure behavior, and documented usage constraints.
package.json
+1
@@ -7,6 +7,7 @@
7
"node": ">=20.9.0"
8
},
9
"scripts": {
10
+ "test": "node --test packages/market-domain/test/*.test.mjs",
11
"verify": "pnpm --if-present lint && pnpm --if-present typecheck && pnpm --if-present test && pnpm --if-present build"
12
}
13
}
packages/market-domain/src/data-quality.mjs
new
+40
@@ -0,0 +1,40 @@
1
+function finiteNonNegative(value, name) {
2
+ if (!Number.isFinite(value) || value < 0) {
3
+ throw new RangeError(`${name} must be non-negative and finite`);
4
+ }
5
+}
6
+
7
+export function evaluateObservationQuality({
8
+ price,
9
+ ageMs,
10
+ maxAgeMs,
11
+ referencePrice = null,
12
+ maxDivergencePct = null,
13
+}) {
14
+ finiteNonNegative(ageMs, 'ageMs');
15
+ finiteNonNegative(maxAgeMs, 'maxAgeMs');
16
+
17
+ const flags = [];
18
+
19
+ if (!Number.isFinite(price) || price <= 0) {
20
+ return { state: 'INVALID', flags: ['NON_POSITIVE_PRICE'], divergencePct: null };
21
+ }
22
+
23
+ if (ageMs > maxAgeMs) {
24
+ flags.push('STALE_SOURCE');
25
+ }
26
+
27
+ let divergencePct = null;
28
+ if (referencePrice !== null) {
29
+ if (!Number.isFinite(referencePrice) || referencePrice <= 0) {
30
+ throw new RangeError('referencePrice must be positive and finite when provided');
31
+ }
32
+ finiteNonNegative(maxDivergencePct, 'maxDivergencePct');
33
+ divergencePct = Math.abs(price / referencePrice - 1) * 100;
34
+ if (divergencePct > maxDivergencePct) flags.push('PROVIDER_DIVERGENCE');
35
+ }
36
+
37
+ if (flags.includes('STALE_SOURCE')) return { state: 'STALE', flags, divergencePct };
38
+ if (flags.length > 0) return { state: 'DEGRADED', flags, divergencePct };
39
+ return { state: 'GOOD', flags, divergencePct };
40
+}
packages/market-domain/src/gold-pricing.mjs
new
+45
@@ -0,0 +1,45 @@
1
+export const TROY_OUNCE_GRAMS = 31.1034768;
2
+export const GOLD_18K_PURITY = 0.75;
3
+
4
+function positiveFinite(value, name) {
5
+ if (!Number.isFinite(value) || value <= 0) throw new RangeError(`${name} must be positive and finite`);
6
+}
7
+
8
+export function theoreticalGold18Irt({ xauUsdPerTroyOunce, usdIrt }) {
9
+ positiveFinite(xauUsdPerTroyOunce, 'xauUsdPerTroyOunce');
10
+ positiveFinite(usdIrt, 'usdIrt');
11
+ return (xauUsdPerTroyOunce / TROY_OUNCE_GRAMS) * GOLD_18K_PURITY * usdIrt;
12
+}
13
+
14
+export function goldPremium({ marketIrtPerGram, theoreticalIrtPerGram }) {
15
+ positiveFinite(marketIrtPerGram, 'marketIrtPerGram');
16
+ positiveFinite(theoreticalIrtPerGram, 'theoreticalIrtPerGram');
17
+ return {
18
+ absoluteIrt: marketIrtPerGram - theoreticalIrtPerGram,
19
+ percent: (marketIrtPerGram / theoreticalIrtPerGram - 1) * 100,
20
+ };
21
+}
22
+
23
+export function alignSources({ target, xau, usdIrt, maxAgeMs }) {
24
+ if (!(target instanceof Date) || Number.isNaN(target.valueOf())) throw new TypeError('target must be a valid Date');
25
+ if (!Number.isFinite(maxAgeMs) || maxAgeMs < 0) throw new RangeError('maxAgeMs must be non-negative and finite');
26
+ positiveFinite(xau.value, 'xau.value');
27
+ positiveFinite(usdIrt.value, 'usdIrt.value');
28
+
29
+ const targetMs = target.valueOf();
30
+ const xauMs = xau.timestamp?.valueOf();
31
+ const usdMs = usdIrt.timestamp?.valueOf();
32
+ if (!Number.isFinite(xauMs) || !Number.isFinite(usdMs)) throw new TypeError('source timestamps must be valid Dates');
33
+ if (xauMs > targetMs || usdMs > targetMs) throw new RangeError('source timestamp cannot be after target');
34
+
35
+ const xauAgeMs = targetMs - xauMs;
36
+ const usdIrtAgeMs = targetMs - usdMs;
37
+ return {
38
+ targetTimestamp: target.toISOString(),
39
+ xau: { value: xau.value, timestamp: xau.timestamp.toISOString() },
40
+ usdIrt: { value: usdIrt.value, timestamp: usdIrt.timestamp.toISOString() },
41
+ xauAgeMs,
42
+ usdIrtAgeMs,
43
+ quality: xauAgeMs <= maxAgeMs && usdIrtAgeMs <= maxAgeMs ? 'GOOD' : 'STALE',
44
+ };
45
+}
packages/market-domain/src/provider-contract.mjs
new
+77
@@ -0,0 +1,77 @@
1
+function positiveFinite(value, name) {
2
+ if (!Number.isFinite(value) || value <= 0) {
3
+ throw new RangeError(`${name} must be positive and finite`);
4
+ }
5
+}
6
+
7
+function validDate(value, name) {
8
+ if (!(value instanceof Date) || Number.isNaN(value.valueOf())) {
9
+ throw new TypeError(`${name} must be a valid Date`);
10
+ }
11
+}
12
+
13
+export function normalizeIranianQuote({ value, unit }) {
14
+ positiveFinite(value, 'value');
15
+ if (unit === 'IRT_PER_USD' || unit === 'IRT_PER_GRAM') return value;
16
+ if (unit === 'IRR_PER_USD' || unit === 'IRR_PER_GRAM') return value / 10;
17
+ throw new RangeError(`unsupported unit: ${unit}`);
18
+}
19
+
20
+export function canonicalObservation({
21
+ providerCode,
22
+ canonicalSymbol,
23
+ providerTimestamp,
24
+ receivedAt,
25
+ price,
26
+ rawUnit,
27
+}) {
28
+ if (!providerCode || !canonicalSymbol) throw new TypeError('providerCode and canonicalSymbol are required');
29
+ validDate(providerTimestamp, 'providerTimestamp');
30
+ validDate(receivedAt, 'receivedAt');
31
+ if (receivedAt.valueOf() < providerTimestamp.valueOf()) {
32
+ throw new RangeError('receivedAt cannot be before providerTimestamp');
33
+ }
34
+
35
+ const canonicalUnits = {
36
+ USD_IRT_FREE: 'IRT_PER_USD',
37
+ GOLD18_IRT: 'IRT_PER_GRAM',
38
+ XAU_USD: 'USD_PER_TROY_OUNCE',
39
+ };
40
+ const canonicalUnit = canonicalUnits[canonicalSymbol];
41
+ if (!canonicalUnit) throw new RangeError(`unsupported canonical symbol: ${canonicalSymbol}`);
42
+
43
+ let normalizedPrice = price;
44
+ if (canonicalSymbol === 'USD_IRT_FREE' || canonicalSymbol === 'GOLD18_IRT') {
45
+ normalizedPrice = normalizeIranianQuote({ value: price, unit: rawUnit });
46
+ } else {
47
+ positiveFinite(price, 'price');
48
+ if (rawUnit !== canonicalUnit) throw new RangeError(`unsupported unit: ${rawUnit}`);
49
+ }
50
+
51
+ return {
52
+ providerCode,
53
+ canonicalSymbol,
54
+ providerTimestamp: providerTimestamp.toISOString(),
55
+ receivedAt: receivedAt.toISOString(),
56
+ price: normalizedPrice,
57
+ canonicalUnit,
58
+ rawUnit,
59
+ };
60
+}
61
+
62
+export function providerHealth({ now, lastSuccessAt, staleAfterMs }) {
63
+ validDate(now, 'now');
64
+ validDate(lastSuccessAt, 'lastSuccessAt');
65
+ if (!Number.isFinite(staleAfterMs) || staleAfterMs < 0) {
66
+ throw new RangeError('staleAfterMs must be non-negative and finite');
67
+ }
68
+ if (lastSuccessAt.valueOf() > now.valueOf()) {
69
+ throw new RangeError('lastSuccessAt cannot be in the future');
70
+ }
71
+
72
+ const ageMs = now.valueOf() - lastSuccessAt.valueOf();
73
+ return {
74
+ status: ageMs <= staleAfterMs ? 'GOOD' : 'STALE',
75
+ ageMs,
76
+ };
77
+}
packages/market-domain/test/data-quality.test.mjs
new
+51
@@ -0,0 +1,51 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import { evaluateObservationQuality } from '../src/data-quality.mjs';
4
+
5
+test('classifies a fresh agreeing observation as GOOD', () => {
6
+ const result = evaluateObservationQuality({
7
+ price: 100_000,
8
+ ageMs: 5_000,
9
+ maxAgeMs: 60_000,
10
+ referencePrice: 100_200,
11
+ maxDivergencePct: 1,
12
+ });
13
+ assert.equal(result.state, 'GOOD');
14
+ assert.deepEqual(result.flags, []);
15
+});
16
+
17
+test('classifies stale data before considering market divergence', () => {
18
+ const result = evaluateObservationQuality({
19
+ price: 100_000,
20
+ ageMs: 120_000,
21
+ maxAgeMs: 60_000,
22
+ referencePrice: 100_000,
23
+ maxDivergencePct: 1,
24
+ });
25
+ assert.equal(result.state, 'STALE');
26
+ assert.ok(result.flags.includes('STALE_SOURCE'));
27
+});
28
+
29
+test('classifies excessive provider disagreement as DEGRADED', () => {
30
+ const result = evaluateObservationQuality({
31
+ price: 103_000,
32
+ ageMs: 10_000,
33
+ maxAgeMs: 60_000,
34
+ referencePrice: 100_000,
35
+ maxDivergencePct: 1,
36
+ });
37
+ assert.equal(result.state, 'DEGRADED');
38
+ assert.ok(result.flags.includes('PROVIDER_DIVERGENCE'));
39
+});
40
+
41
+test('rejects zero/negative prices as INVALID', () => {
42
+ const result = evaluateObservationQuality({
43
+ price: 0,
44
+ ageMs: 0,
45
+ maxAgeMs: 60_000,
46
+ referencePrice: 100_000,
47
+ maxDivergencePct: 1,
48
+ });
49
+ assert.equal(result.state, 'INVALID');
50
+ assert.ok(result.flags.includes('NON_POSITIVE_PRICE'));
51
+});
packages/market-domain/test/gold-pricing.test.mjs
new
+42
@@ -0,0 +1,42 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import { theoreticalGold18Irt, goldPremium, alignSources } from '../src/gold-pricing.mjs';
4
+
5
+test('calculates theoretical 18K gold in IRT per gram', () => {
6
+ const result = theoreticalGold18Irt({ xauUsdPerTroyOunce: 4000, usdIrt: 100000 });
7
+ const expected = (4000 / 31.1034768) * 0.75 * 100000;
8
+ assert.ok(Math.abs(result - expected) < 1e-8);
9
+});
10
+
11
+test('calculates absolute and percentage premium', () => {
12
+ const result = goldPremium({ marketIrtPerGram: 10_500_000, theoreticalIrtPerGram: 10_000_000 });
13
+ assert.equal(result.absoluteIrt, 500_000);
14
+ assert.ok(Math.abs(result.percent - 5) < 1e-12);
15
+});
16
+
17
+test('rejects zero or negative market inputs', () => {
18
+ assert.throws(() => theoreticalGold18Irt({ xauUsdPerTroyOunce: 0, usdIrt: 100000 }), /positive/);
19
+ assert.throws(() => goldPremium({ marketIrtPerGram: -1, theoreticalIrtPerGram: 10 }), /positive/);
20
+});
21
+
22
+test('marks aligned sources stale when either source exceeds threshold', () => {
23
+ const target = new Date('2026-10-05T12:00:00Z');
24
+ const aligned = alignSources({
25
+ target,
26
+ xau: { value: 4000, timestamp: new Date('2026-10-05T11:59:40Z') },
27
+ usdIrt: { value: 100000, timestamp: new Date('2026-10-05T11:57:00Z') },
28
+ maxAgeMs: 60_000,
29
+ });
30
+ assert.equal(aligned.quality, 'STALE');
31
+ assert.equal(aligned.xauAgeMs, 20_000);
32
+ assert.equal(aligned.usdIrtAgeMs, 180_000);
33
+});
34
+
35
+test('rejects future source observations for a target timestamp', () => {
36
+ assert.throws(() => alignSources({
37
+ target: new Date('2026-10-05T12:00:00Z'),
38
+ xau: { value: 4000, timestamp: new Date('2026-10-05T12:00:01Z') },
39
+ usdIrt: { value: 100000, timestamp: new Date('2026-10-05T11:59:59Z') },
40
+ maxAgeMs: 60_000,
41
+ }), /after target/);
42
+});
packages/market-domain/test/provider-contract.test.mjs
new
+49
@@ -0,0 +1,49 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import {
4
+ normalizeIranianQuote,
5
+ canonicalObservation,
6
+ providerHealth,
7
+} from '../src/provider-contract.mjs';
8
+
9
+test('normalizes provider rial values to canonical toman', () => {
10
+ assert.equal(normalizeIranianQuote({ value: 1_000_000, unit: 'IRR_PER_USD' }), 100_000);
11
+});
12
+
13
+test('keeps canonical toman values unchanged', () => {
14
+ assert.equal(normalizeIranianQuote({ value: 100_000, unit: 'IRT_PER_USD' }), 100_000);
15
+});
16
+
17
+test('rejects unsupported units instead of guessing', () => {
18
+ assert.throws(() => normalizeIranianQuote({ value: 100, unit: 'UNKNOWN' }), /unsupported unit/i);
19
+});
20
+
21
+test('creates an auditable canonical observation with distinct source and receive timestamps', () => {
22
+ const observation = canonicalObservation({
23
+ providerCode: 'example',
24
+ canonicalSymbol: 'USD_IRT_FREE',
25
+ providerTimestamp: new Date('2026-10-05T12:00:00Z'),
26
+ receivedAt: new Date('2026-10-05T12:00:02Z'),
27
+ price: 100_000,
28
+ rawUnit: 'IRT_PER_USD',
29
+ });
30
+ assert.deepEqual(observation, {
31
+ providerCode: 'example',
32
+ canonicalSymbol: 'USD_IRT_FREE',
33
+ providerTimestamp: '2026-10-05T12:00:00.000Z',
34
+ receivedAt: '2026-10-05T12:00:02.000Z',
35
+ price: 100_000,
36
+ canonicalUnit: 'IRT_PER_USD',
37
+ rawUnit: 'IRT_PER_USD',
38
+ });
39
+});
40
+
41
+test('marks provider stale when last successful observation exceeds threshold', () => {
42
+ const result = providerHealth({
43
+ now: new Date('2026-10-05T12:05:00Z'),
44
+ lastSuccessAt: new Date('2026-10-05T12:00:00Z'),
45
+ staleAfterMs: 60_000,
46
+ });
47
+ assert.equal(result.status, 'STALE');
48
+ assert.equal(result.ageMs, 300_000);
49
+});