@waterx/sdk 4.0.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/README.md +52 -37
  2. package/dist/cjs/src/account/account.js +2 -1
  3. package/dist/cjs/src/account/config.d.ts +0 -16
  4. package/dist/cjs/src/account/funding/balance.d.ts +25 -2
  5. package/dist/cjs/src/account/funding/balance.js +36 -24
  6. package/dist/cjs/src/account/funding/credit.js +6 -10
  7. package/dist/cjs/src/constants.d.ts +15 -1
  8. package/dist/cjs/src/constants.js +18 -4
  9. package/dist/cjs/src/generated/waterx_rule/deps/bucket_v2_framework/float.d.ts +8 -0
  10. package/dist/cjs/src/generated/waterx_rule/deps/bucket_v2_framework/float.js +13 -0
  11. package/dist/cjs/src/generated/waterx_rule/deps/sui/vec_map.d.ts +36 -0
  12. package/dist/cjs/src/generated/waterx_rule/deps/sui/vec_map.js +31 -0
  13. package/dist/cjs/src/generated/waterx_rule/waterx_rule.d.ts +940 -0
  14. package/dist/cjs/src/generated/waterx_rule/waterx_rule.js +1092 -0
  15. package/dist/cjs/src/oracle/aggregate.d.ts +21 -21
  16. package/dist/cjs/src/oracle/aggregate.js +84 -71
  17. package/dist/cjs/src/oracle/config.d.ts +107 -52
  18. package/dist/cjs/src/oracle/config.js +15 -35
  19. package/dist/cjs/src/oracle/host.d.ts +13 -2
  20. package/dist/cjs/src/oracle/index.d.ts +4 -2
  21. package/dist/cjs/src/oracle/index.js +25 -6
  22. package/dist/cjs/src/oracle/price-update-rule.d.ts +3 -4
  23. package/dist/cjs/src/oracle/pyth.d.ts +68 -6
  24. package/dist/cjs/src/oracle/pyth.js +338 -22
  25. package/dist/cjs/src/oracle/rule-registry.d.ts +11 -6
  26. package/dist/cjs/src/oracle/rule-registry.js +13 -6
  27. package/dist/cjs/src/oracle/rules/pyth-core-rule.js +17 -2
  28. package/dist/cjs/src/oracle/rules/pyth-lazer-rule.d.ts +6 -6
  29. package/dist/cjs/src/oracle/rules/pyth-lazer-rule.js +25 -22
  30. package/dist/cjs/src/oracle/rules/pyth-rule.js +5 -0
  31. package/dist/cjs/src/oracle/rules/waterx-rule.d.ts +89 -0
  32. package/dist/cjs/src/oracle/rules/waterx-rule.js +272 -0
  33. package/dist/cjs/src/oracle/update-fetch.d.ts +32 -2
  34. package/dist/cjs/src/oracle/update-fetch.js +60 -3
  35. package/dist/cjs/src/perp/client.d.ts +71 -19
  36. package/dist/cjs/src/perp/client.js +30 -10
  37. package/dist/cjs/src/perp/config.d.ts +4 -7
  38. package/dist/cjs/src/perp/config.js +9 -12
  39. package/dist/cjs/src/perp/constants.d.ts +0 -6
  40. package/dist/cjs/src/perp/constants.js +11 -9
  41. package/dist/cjs/src/perp/fetch/account.js +3 -0
  42. package/dist/cjs/src/perp/fetch/bridge.js +2 -1
  43. package/dist/cjs/src/perp/fetch/market.js +2 -1
  44. package/dist/cjs/src/perp/fetch/positions.d.ts +16 -10
  45. package/dist/cjs/src/perp/fetch/positions.js +23 -20
  46. package/dist/cjs/src/perp/index.d.ts +8 -4
  47. package/dist/cjs/src/perp/index.js +12 -7
  48. package/dist/cjs/src/perp/liq-view.d.ts +64 -0
  49. package/dist/cjs/src/perp/liq-view.js +74 -0
  50. package/dist/cjs/src/perp/user/order.d.ts +13 -0
  51. package/dist/cjs/src/perp/user/order.js +30 -16
  52. package/dist/cjs/src/perp/user/staking.js +3 -2
  53. package/dist/cjs/src/perp/user/trading.js +25 -24
  54. package/dist/cjs/src/perp/user/wlp.js +6 -5
  55. package/dist/cjs/src/prediction/utils.d.ts +11 -2
  56. package/dist/cjs/src/prediction/utils.js +22 -22
  57. package/dist/cjs/src/unified-client.d.ts +49 -20
  58. package/dist/cjs/src/unified-client.js +4 -1
  59. package/dist/cjs/src/utils/format.d.ts +14 -0
  60. package/dist/cjs/src/utils/format.js +24 -0
  61. package/dist/cjs/src/utils/math.d.ts +304 -12
  62. package/dist/cjs/src/utils/math.js +397 -17
  63. package/dist/cjs/src/utils/validate.d.ts +69 -0
  64. package/dist/cjs/src/utils/validate.js +183 -0
  65. package/dist/src/account/account.js +2 -1
  66. package/dist/src/account/config.d.ts +0 -16
  67. package/dist/src/account/funding/balance.d.ts +25 -2
  68. package/dist/src/account/funding/balance.js +36 -24
  69. package/dist/src/account/funding/credit.js +6 -10
  70. package/dist/src/constants.d.ts +15 -1
  71. package/dist/src/constants.js +17 -3
  72. package/dist/src/generated/waterx_rule/deps/bucket_v2_framework/float.d.ts +8 -0
  73. package/dist/src/generated/waterx_rule/deps/bucket_v2_framework/float.js +10 -0
  74. package/dist/src/generated/waterx_rule/deps/sui/vec_map.d.ts +36 -0
  75. package/dist/src/generated/waterx_rule/deps/sui/vec_map.js +27 -0
  76. package/dist/src/generated/waterx_rule/waterx_rule.d.ts +940 -0
  77. package/dist/src/generated/waterx_rule/waterx_rule.js +991 -0
  78. package/dist/src/oracle/aggregate.d.ts +21 -21
  79. package/dist/src/oracle/aggregate.js +84 -71
  80. package/dist/src/oracle/config.d.ts +107 -52
  81. package/dist/src/oracle/config.js +14 -34
  82. package/dist/src/oracle/host.d.ts +13 -2
  83. package/dist/src/oracle/index.d.ts +4 -2
  84. package/dist/src/oracle/index.js +18 -7
  85. package/dist/src/oracle/price-update-rule.d.ts +3 -4
  86. package/dist/src/oracle/pyth.d.ts +68 -6
  87. package/dist/src/oracle/pyth.js +334 -22
  88. package/dist/src/oracle/rule-registry.d.ts +11 -6
  89. package/dist/src/oracle/rule-registry.js +13 -6
  90. package/dist/src/oracle/rules/pyth-core-rule.js +18 -3
  91. package/dist/src/oracle/rules/pyth-lazer-rule.d.ts +6 -6
  92. package/dist/src/oracle/rules/pyth-lazer-rule.js +26 -23
  93. package/dist/src/oracle/rules/pyth-rule.js +5 -0
  94. package/dist/src/oracle/rules/waterx-rule.d.ts +89 -0
  95. package/dist/src/oracle/rules/waterx-rule.js +266 -0
  96. package/dist/src/oracle/update-fetch.d.ts +32 -2
  97. package/dist/src/oracle/update-fetch.js +57 -3
  98. package/dist/src/perp/client.d.ts +71 -19
  99. package/dist/src/perp/client.js +31 -11
  100. package/dist/src/perp/config.d.ts +4 -7
  101. package/dist/src/perp/config.js +9 -12
  102. package/dist/src/perp/constants.d.ts +0 -6
  103. package/dist/src/perp/constants.js +10 -8
  104. package/dist/src/perp/fetch/account.js +3 -0
  105. package/dist/src/perp/fetch/bridge.js +2 -1
  106. package/dist/src/perp/fetch/market.js +2 -1
  107. package/dist/src/perp/fetch/positions.d.ts +16 -10
  108. package/dist/src/perp/fetch/positions.js +28 -20
  109. package/dist/src/perp/index.d.ts +8 -4
  110. package/dist/src/perp/index.js +5 -3
  111. package/dist/src/perp/liq-view.d.ts +64 -0
  112. package/dist/src/perp/liq-view.js +71 -0
  113. package/dist/src/perp/user/order.d.ts +13 -0
  114. package/dist/src/perp/user/order.js +30 -16
  115. package/dist/src/perp/user/staking.js +3 -2
  116. package/dist/src/perp/user/trading.js +25 -24
  117. package/dist/src/perp/user/wlp.js +6 -5
  118. package/dist/src/prediction/utils.d.ts +11 -2
  119. package/dist/src/prediction/utils.js +22 -22
  120. package/dist/src/unified-client.d.ts +49 -20
  121. package/dist/src/unified-client.js +4 -1
  122. package/dist/src/utils/format.d.ts +14 -0
  123. package/dist/src/utils/format.js +21 -0
  124. package/dist/src/utils/math.d.ts +304 -12
  125. package/dist/src/utils/math.js +394 -17
  126. package/dist/src/utils/validate.d.ts +69 -0
  127. package/dist/src/utils/validate.js +167 -0
  128. package/package.json +4 -1
@@ -19,19 +19,30 @@
19
19
  // just the type) so a consumer (e.g. a BE prefetch cache) can `instanceof`
20
20
  // it off the failure `fetchPriceFeedsUpdateData` / `PythLazerRule` /
21
21
  // `loadConfig` surface, without a deep import of `./update-fetch.ts`.
22
- // `fetchWithPolicy` itself stays module-internal (no external caller yet).
23
- export { FetchPolicyError } from "./update-fetch.js";
24
- // Pyth source `OracleFeeSourceUnavailableError` is re-exported (not just
25
- // the type) for the same `instanceof` reason as `FetchPolicyError` above: a
26
- // consumer of `buildPythPriceUpdateCalls` / `updatePythPrices` /
27
- // `refreshOraclePrices` can branch on the fee-source failure directly.
28
- export { PythCache, fetchPriceFeedsUpdateData, buildPythPriceUpdateCalls, updatePythPrices, OracleFeeSourceUnavailableError, } from "./pyth.js";
22
+ // `fetchWithPolicy` + `joinEndpointPath` are exported for consumers that hit
23
+ // Hermes-compatible endpoints THEMSELVES (e.g. the BE's parsed latest-price
24
+ // bootstrap and Pyth schedule readers): one shared Bearer/timeout/retry
25
+ // policy and one base-path-safe URL join, instead of each caller re-rolling
26
+ // them (the hand-rolled copies were how the Pro `/hermes` base path got
27
+ // dropped and the Bearer went missing on sibling fetches).
28
+ export { FetchPolicyError, fetchWithPolicy, joinEndpointPath } from "./update-fetch.js";
29
+ // Pyth source — `OracleFeeSourceUnavailableError` and
30
+ // `HermesEndpointRejectedAllFeedsError` are re-exported (not just the types)
31
+ // for the same `instanceof` reason as `FetchPolicyError` above: a consumer of
32
+ // `buildPythPriceUpdateCalls` / `updatePythPrices` / `refreshOraclePrices` can
33
+ // branch on the fee-source failure directly, and a consumer of
34
+ // `fetchPriceFeedsUpdateData` / `probeMissingFeeds` can tell a misconfigured
35
+ // or unentitled endpoint apart from feeds that endpoint genuinely lacks.
36
+ export { PythCache, fetchPriceFeedsUpdateData, endpointSupportedFeedIds, probeMissingFeeds, buildPythPriceUpdateCalls, updatePythPrices, HermesEndpointRejectedAllFeedsError, MISSING_FEED_MEMO_TTL_MS, OracleFeeSourceUnavailableError, } from "./pyth.js";
29
37
  // Pyth Core rule (PriceUpdateRule wrapper over the Pyth source above)
30
38
  export { PythCoreRule } from "./rules/pyth-core-rule.js";
31
39
  // Pyth Lazer rule (signed-update generation; `feedLazerRule` stays internal to `aggregate.ts`)
32
40
  // `LazerApiKeyMissingError` is re-exported (not just the type) for the same
33
41
  // `instanceof` reason as `OracleFeeSourceUnavailableError` above.
34
42
  export { PythLazerRule, LazerApiKeyMissingError } from "./rules/pyth-lazer-rule.js";
43
+ // WaterX quote-center rule (first-party ed25519 signed batches; `feedWaterxRule`
44
+ // stays internal to `aggregate.ts`).
45
+ export { WaterxRule, parseSignedEnvelope } from "./rules/waterx-rule.js";
35
46
  // `resolveOracleRule` (rule-registry.ts) is NOT re-exported here — it has one
36
47
  // production consumer (`refreshOraclePrices` below) and no external caller;
37
48
  // per repo convention ("no unused exports") it stays module-internal. Tests
@@ -24,11 +24,10 @@ export type PriceUpdateRuleKind = "pyth_rule" | "pyth_lazer_rule" | "supra_rule"
24
24
  * create option (see `OracleHost.oracleSource`) — i.e. rules that can serve as
25
25
  * the on-chain price *update* leg `refreshOraclePrices` runs before aggregating.
26
26
  * `supra_rule` and `constant_rule` are auxiliary rules fed alongside whichever
27
- * source is selected (see `aggregateTicker`), not sources themselves;
28
- * `waterx_rule` has no `PriceUpdateRule` implementation yet. The SDK never
29
- * reads `process.env` — consumers resolve their own env var to this type.
27
+ * source is selected (see `aggregateTicker`), not sources themselves. The SDK
28
+ * never reads `process.env` consumers resolve their own env var to this type.
30
29
  */
31
- export type OracleSource = "pyth_rule" | "pyth_lazer_rule";
30
+ export type OracleSource = "pyth_rule" | "pyth_lazer_rule" | "waterx_rule";
32
31
  /**
33
32
  * Off-chain payload fetched by a rule, tagged by `kind` so a caller holding
34
33
  * several rules' results can tell them apart. `payload` is `unknown` here —
@@ -14,6 +14,7 @@
14
14
  * 4. hot_potato_vector::destroy
15
15
  */
16
16
  import type { Transaction, TransactionArgument } from "@mysten/sui/transactions";
17
+ import type { PythFetchPolicy } from "./config.ts";
17
18
  import type { OracleHost } from "./host.ts";
18
19
  type PriceTableInfo = {
19
20
  id: string;
@@ -29,13 +30,74 @@ export declare class PythCache {
29
30
  priceTableInfo?: PriceTableInfo;
30
31
  priceFeedObjectIdCache: Map<string, string | undefined>;
31
32
  }
32
- export declare function fetchPriceFeedsUpdateData(endpoint: string, priceIds: string[], opts?: {
33
+ type FetchOpts = {
33
34
  apiKey?: string;
34
- fetch?: {
35
- timeoutMs?: number;
36
- retries?: number;
37
- };
38
- }): Promise<Uint8Array[]>;
35
+ fetch?: PythFetchPolicy;
36
+ };
37
+ /**
38
+ * How long a "this endpoint lacks feed X" verdict stays memoized. The verdict
39
+ * is a claim about *someone else's* deployment — a feed can be added to the
40
+ * catalog, an entitlement can be granted, a Pro plan can be upgraded — so it
41
+ * must expire rather than bind the whole process lifetime. Long enough that a
42
+ * genuinely-absent feed costs one discovery per window instead of one per
43
+ * build; short enough that a recovered endpoint self-heals without a restart.
44
+ */
45
+ export declare const MISSING_FEED_MEMO_TTL_MS: number;
46
+ /**
47
+ * Thrown when discovery concludes that an endpoint rejects EVERY requested
48
+ * feed id without a catalog vouching for that verdict. `instanceof`-able
49
+ * (mirrors `FetchPolicyError` / {@link OracleFeeSourceUnavailableError}).
50
+ *
51
+ * "All of them are missing" is the signature of an endpoint/credential fault —
52
+ * a wrong base path (the Pyth Pro `/hermes` prefix dropped), a changed route,
53
+ * a revoked or downgraded entitlement — not of N individually-absent feeds.
54
+ * Memoizing it would convert a loud, fixable misconfiguration into a silent
55
+ * permanent one: every id marked missing ⇒ `fetchPriceFeedsUpdateData` returns
56
+ * `[]` ⇒ `buildPythPriceUpdateCalls` throws "Hermes returned empty results",
57
+ * blaming Hermes for having no data, for the rest of the process's life. So
58
+ * this case writes NOTHING to the memo and throws instead; the next call
59
+ * re-probes and recovers on its own once the endpoint does.
60
+ *
61
+ * The message keeps the `Hermes price fetch failed: <status>` prefix on its
62
+ * first line — the documented contract downstream consumers string-match (see
63
+ * {@link fetchPriceFeedsUpdateData} and the e2e transient detector).
64
+ */
65
+ export declare class HermesEndpointRejectedAllFeedsError extends Error {
66
+ readonly endpoint: string;
67
+ readonly requestedCount: number;
68
+ constructor(endpoint: string, requestedCount: number, catalogState: "unreadable" | "empty");
69
+ }
70
+ /**
71
+ * The subset of `feedIds` this `endpoint` is known to serve — i.e. minus any
72
+ * discovered to be absent within the last {@link MISSING_FEED_MEMO_TTL_MS}
73
+ * (see {@link fetchPriceFeedsUpdateData}). Callers building a
74
+ * `{ updates, feedIds }` payload use this to keep `feedIds` aligned with the
75
+ * feeds the fetch actually returned data for, so `buildPythPriceUpdateCalls`
76
+ * (one moveCall per feed id) never references a feed the accumulator blob
77
+ * doesn't cover.
78
+ *
79
+ * Expired entries are pruned here rather than on a timer: the memo is only
80
+ * ever consulted through this function, so a lazy sweep is both sufficient and
81
+ * free of a dangling interval in a library.
82
+ */
83
+ export declare function endpointSupportedFeedIds(endpoint: string, feedIds: string[], apiKey?: string): string[];
84
+ /** Test-only: forget everything learned about which feeds an endpoint lacks. */
85
+ export declare function __resetMissingFeedCacheForTest(): void;
86
+ /**
87
+ * Discovery-only entry for consumers that fetch Hermes THEMSELVES (e.g. a
88
+ * parsed latest-price reader) and just observed a whole-batch 404: resolves
89
+ * which ids the endpoint lacks, memoizes them (see {@link
90
+ * endpointSupportedFeedIds}), fetches NO survivor data. Without this, such a
91
+ * consumer's only way to populate the memo was calling {@link
92
+ * fetchPriceFeedsUpdateData} and discarding its accumulator blob — two full
93
+ * redundant transfers per cold discovery.
94
+ *
95
+ * @throws HermesEndpointRejectedAllFeedsError when the rejection looks
96
+ * endpoint-wide rather than per-feed — the caller's own 404 is then a
97
+ * misconfiguration to surface, not a set of feeds to quietly drop.
98
+ */
99
+ export declare function probeMissingFeeds(endpoint: string, ids: string[], opts?: FetchOpts): Promise<void>;
100
+ export declare function fetchPriceFeedsUpdateData(endpoint: string, priceIds: string[], opts?: FetchOpts): Promise<Uint8Array[]>;
39
101
  /**
40
102
  * Resolved source for the Pyth Core on-chain update fee. Deliberately a
41
103
  * closed two-variant union, not a `{ sponsorFund?, allowGasFee? }` pair — a
@@ -15,40 +15,343 @@
15
15
  */
16
16
  import { fromHex, toHex } from "@mysten/bcs";
17
17
  import { bcs } from "@mysten/sui/bcs";
18
- import { FetchPolicyError, fetchWithPolicy } from "./update-fetch.js";
18
+ import { fetchWithPolicy, joinEndpointPath, rethrowExhaustedFetch, trimTrailingSlashes, } from "./update-fetch.js";
19
19
  export class PythCache {
20
20
  pythStateInfo;
21
21
  wormholePackageId;
22
22
  priceTableInfo;
23
23
  priceFeedObjectIdCache = new Map();
24
24
  }
25
- // ============================================================================
26
- // Hermes REST
27
- // ============================================================================
25
+ /**
26
+ * How long a "this endpoint lacks feed X" verdict stays memoized. The verdict
27
+ * is a claim about *someone else's* deployment — a feed can be added to the
28
+ * catalog, an entitlement can be granted, a Pro plan can be upgraded — so it
29
+ * must expire rather than bind the whole process lifetime. Long enough that a
30
+ * genuinely-absent feed costs one discovery per window instead of one per
31
+ * build; short enough that a recovered endpoint self-heals without a restart.
32
+ */
33
+ export const MISSING_FEED_MEMO_TTL_MS = 15 * 60_000;
34
+ /**
35
+ * Per-endpoint memo of feed ids this endpoint has rejected as unknown (a 404
36
+ * on `/v2/updates/price/latest`). The Pyth Pro compat endpoint carries a
37
+ * SUBSET of Core's feeds — mainnet `WTIUSD`/`BRENTUSD` (Commodities
38
+ * USOILSPOT/UKOILSPOT) are absent, for example. Pyth 404s the WHOLE batch if
39
+ * ANY id is unknown, and the body naming the bad ids is NOT reliably delivered
40
+ * to `fetch` (Cloudflare returns it to curl but `content-length: 0` to node's
41
+ * undici), so the ids are isolated by catalog read (or bisection) and
42
+ * remembered here — later batches skip them instead of 404ing every time.
43
+ *
44
+ * Entries carry an expiry ({@link MISSING_FEED_MEMO_TTL_MS}); an
45
+ * endpoint-level fault never lands here at all (see {@link
46
+ * HermesEndpointRejectedAllFeedsError}).
47
+ */
48
+ const missingFeedIdsByEndpoint = new Map();
49
+ /**
50
+ * Thrown when discovery concludes that an endpoint rejects EVERY requested
51
+ * feed id without a catalog vouching for that verdict. `instanceof`-able
52
+ * (mirrors `FetchPolicyError` / {@link OracleFeeSourceUnavailableError}).
53
+ *
54
+ * "All of them are missing" is the signature of an endpoint/credential fault —
55
+ * a wrong base path (the Pyth Pro `/hermes` prefix dropped), a changed route,
56
+ * a revoked or downgraded entitlement — not of N individually-absent feeds.
57
+ * Memoizing it would convert a loud, fixable misconfiguration into a silent
58
+ * permanent one: every id marked missing ⇒ `fetchPriceFeedsUpdateData` returns
59
+ * `[]` ⇒ `buildPythPriceUpdateCalls` throws "Hermes returned empty results",
60
+ * blaming Hermes for having no data, for the rest of the process's life. So
61
+ * this case writes NOTHING to the memo and throws instead; the next call
62
+ * re-probes and recovers on its own once the endpoint does.
63
+ *
64
+ * The message keeps the `Hermes price fetch failed: <status>` prefix on its
65
+ * first line — the documented contract downstream consumers string-match (see
66
+ * {@link fetchPriceFeedsUpdateData} and the e2e transient detector).
67
+ */
68
+ export class HermesEndpointRejectedAllFeedsError extends Error {
69
+ endpoint;
70
+ requestedCount;
71
+ constructor(endpoint, requestedCount, catalogState) {
72
+ super(`Hermes price fetch failed: 404 — endpoint rejected ALL ${requestedCount} requested feed id(s) ` +
73
+ `and its feed catalog was ${catalogState}, so nothing vouches for those feeds being ` +
74
+ `individually absent. Treating this as an endpoint/credential fault (wrong base path — ` +
75
+ `e.g. a dropped Pyth Pro '/hermes' prefix — changed route, or revoked entitlement) rather ` +
76
+ `than caching every feed as missing. Endpoint: ${endpoint}`);
77
+ this.endpoint = endpoint;
78
+ this.requestedCount = requestedCount;
79
+ this.name = "HermesEndpointRejectedAllFeedsError";
80
+ }
81
+ }
82
+ /**
83
+ * Memo key for `(endpoint, credential)` — the same trailing-slash trim
84
+ * {@link joinEndpointPath} applies to the request URL (shared helper, so the
85
+ * two can't drift), plus the apiKey: "feed X is missing" is a property of the
86
+ * endpoint AND the credential (Pyth Pro entitlements are per-key), so two
87
+ * clients in one process with different keys must not cross-poison each
88
+ * other's memo. Without the trim, two consumers spelling the same endpoint
89
+ * differently (`…/hermes` vs `…/hermes/`) would fragment the memo and re-run
90
+ * the whole 404 discovery despite one of them having already paid for it.
91
+ */
92
+ function memoKey(endpoint, apiKey) {
93
+ return `${trimTrailingSlashes(endpoint)}\u0000${apiKey ?? ""}`;
94
+ }
95
+ function recordMissingFeeds(endpoint, feedIds, apiKey) {
96
+ const key = memoKey(endpoint, apiKey);
97
+ let entries = missingFeedIdsByEndpoint.get(key);
98
+ if (!entries) {
99
+ entries = new Map();
100
+ missingFeedIdsByEndpoint.set(key, entries);
101
+ }
102
+ const expiresAt = Date.now() + MISSING_FEED_MEMO_TTL_MS;
103
+ // Key on the bare (0x-stripped, lowercased) form — the SAME normalization the
104
+ // catalog comparison and the in-flight latch use — so a feed can't fragment
105
+ // the memo across `0xAB`/`ab` spellings and slip back through as unfiltered.
106
+ for (const feedId of feedIds)
107
+ entries.set(bareFeedId(feedId), expiresAt);
108
+ }
109
+ /**
110
+ * The subset of `feedIds` this `endpoint` is known to serve — i.e. minus any
111
+ * discovered to be absent within the last {@link MISSING_FEED_MEMO_TTL_MS}
112
+ * (see {@link fetchPriceFeedsUpdateData}). Callers building a
113
+ * `{ updates, feedIds }` payload use this to keep `feedIds` aligned with the
114
+ * feeds the fetch actually returned data for, so `buildPythPriceUpdateCalls`
115
+ * (one moveCall per feed id) never references a feed the accumulator blob
116
+ * doesn't cover.
117
+ *
118
+ * Expired entries are pruned here rather than on a timer: the memo is only
119
+ * ever consulted through this function, so a lazy sweep is both sufficient and
120
+ * free of a dangling interval in a library.
121
+ */
122
+ export function endpointSupportedFeedIds(endpoint, feedIds, apiKey) {
123
+ const key = memoKey(endpoint, apiKey);
124
+ const entries = missingFeedIdsByEndpoint.get(key);
125
+ if (!entries)
126
+ return feedIds;
127
+ const now = Date.now();
128
+ for (const [id, expiresAt] of entries) {
129
+ if (expiresAt <= now)
130
+ entries.delete(id);
131
+ }
132
+ if (entries.size === 0) {
133
+ missingFeedIdsByEndpoint.delete(key);
134
+ return feedIds;
135
+ }
136
+ return feedIds.filter((id) => !entries.has(bareFeedId(id)));
137
+ }
138
+ /**
139
+ * Discovery runs currently in flight, keyed by `(endpoint, credential,
140
+ * requested id set)`. A cold memo plus two concurrent tx-builds asking the
141
+ * same question ran two full independent discoveries — duplicate catalog reads
142
+ * (or duplicate bisection probe trees) on the money path, for one answer. The
143
+ * second caller now joins the first run's promise: each still gets its own
144
+ * survivor data, but they share the one discovery behind it.
145
+ */
146
+ const inFlightDiscoveries = new Map();
147
+ /** Test-only: forget everything learned about which feeds an endpoint lacks. */
148
+ export function __resetMissingFeedCacheForTest() {
149
+ missingFeedIdsByEndpoint.clear();
150
+ inFlightDiscoveries.clear();
151
+ }
152
+ /**
153
+ * One `GET /v2/price_feeds` — the set of feed ids this endpoint serves for
154
+ * THIS credential (verified against the Pro compat endpoint: WTI absent from
155
+ * the catalog AND 404 on latest-price; BTC present AND 200 —
156
+ * entitlement-filtered per key), normalized to bare lowercase hex.
157
+ *
158
+ * Returns `null` when the catalog is unreadable (non-2xx, unparseable, network
159
+ * error) — the catalog is an optimization, {@link bisectMissingFeeds} remains
160
+ * the ground truth derived from the money-path fetch itself. Note that "read
161
+ * fine, served nothing" (`size === 0`) is NOT the same as unreadable: an empty
162
+ * catalog is an entitlement/route fault in its own right, and the caller
163
+ * treats it as one.
164
+ */
165
+ async function readEndpointCatalog(endpoint, opts) {
166
+ try {
167
+ const res = await fetchWithPolicy(joinEndpointPath(endpoint, "v2/price_feeds").toString(), {}, { apiKey: opts?.apiKey, ...opts?.fetch });
168
+ if (!res.ok) {
169
+ void res.body?.cancel().catch(() => { });
170
+ return null;
171
+ }
172
+ const catalog = (await res.json());
173
+ if (!Array.isArray(catalog))
174
+ return null;
175
+ // Catalog ids come WITHOUT the 0x prefix; callers pass either form.
176
+ return new Set(catalog.map((f) => bareFeedId(f.id)));
177
+ }
178
+ catch {
179
+ return null;
180
+ }
181
+ }
182
+ /** Feed ids are compared prefix- and case-insensitively (`0xAB` ≡ `ab`). */
183
+ function bareFeedId(feedId) {
184
+ return feedId.toLowerCase().replace(/^0x/, "");
185
+ }
186
+ async function rawFetch(endpoint, ids, opts) {
187
+ // joinEndpointPath preserves the endpoint's own base path — `new URL`
188
+ // with a leading-slash path would discard it (the Pyth Pro `/hermes`
189
+ // prefix → 404 on EVERY feed); see its doc in update-fetch.ts.
190
+ const url = joinEndpointPath(endpoint, "v2/updates/price/latest");
191
+ ids.forEach((id) => url.searchParams.append("ids[]", id));
192
+ return fetchWithPolicy(url.toString(), {}, { apiKey: opts?.apiKey, ...opts?.fetch });
193
+ }
194
+ /**
195
+ * Bisect `ids` down to the individual ones this endpoint 404s on — the
196
+ * response body isn't readable, so a single id that still 404s IS the unknown
197
+ * one. Data is discarded; this only *reports* (the caller decides whether the
198
+ * verdict is trustworthy enough to memoize). A non-404 (the subset is fine) or
199
+ * a network error stops that branch and contributes nothing.
200
+ *
201
+ * `known404: true` skips the root probe — the caller has already watched this
202
+ * exact batch 404, so re-fetching it would only re-learn a fact in hand (a
203
+ * wasted round trip on the money path during cold discovery). Recursive
204
+ * half-calls always probe: their status is genuinely unknown.
205
+ */
206
+ async function bisectMissingFeeds(endpoint, ids, opts, known404 = false) {
207
+ if (ids.length === 0)
208
+ return new Set();
209
+ if (!known404) {
210
+ let res;
211
+ try {
212
+ res = await rawFetch(endpoint, ids, opts);
213
+ }
214
+ catch {
215
+ return new Set(); // transient/network failure — can't classify
216
+ }
217
+ void res.body?.cancel().catch(() => { });
218
+ if (res.status !== 404)
219
+ return new Set(); // this subset is serveable
220
+ }
221
+ if (ids.length === 1)
222
+ return new Set([ids[0]]);
223
+ const mid = Math.floor(ids.length / 2);
224
+ const [lo, hi] = await Promise.all([
225
+ bisectMissingFeeds(endpoint, ids.slice(0, mid), opts),
226
+ bisectMissingFeeds(endpoint, ids.slice(mid), opts),
227
+ ]);
228
+ return new Set([...lo, ...hi]);
229
+ }
230
+ /**
231
+ * Work out which of `ids` this endpoint lacks and memoize exactly those.
232
+ *
233
+ * Catalog first: one `GET /v2/price_feeds` answers for the whole batch, so a
234
+ * confirmed 404 costs one extra request instead of O(log n) bisection probes.
235
+ * The catalog is also the only *authoritative* source here — it says what the
236
+ * endpoint DOES serve, which is what separates "these two feeds are absent"
237
+ * from "this endpoint is serving nothing to me". Bisection can only observe
238
+ * 404s, and a wrong base path 404s identically to an unknown feed.
239
+ *
240
+ * Hence the guard: a verdict of "every requested id is missing" is only
241
+ * committed when a non-empty catalog vouches for it. Otherwise nothing is
242
+ * written and {@link HermesEndpointRejectedAllFeedsError} is thrown — see its
243
+ * docblock for why silently memoizing that case is worse than failing.
244
+ *
245
+ * Concurrent callers asking the identical question share ONE run (see {@link
246
+ * inFlightDiscoveries}); the latch is released on failure too, so a blip never
247
+ * pins later callers to a stale outcome.
248
+ *
249
+ * @throws HermesEndpointRejectedAllFeedsError on an endpoint-level rejection.
250
+ */
251
+ function discoverMissingFeeds(endpoint, ids, opts, known404 = false) {
252
+ // Same endpoint + credential + requested set ⇒ same answer; anything else
253
+ // is a different question and runs on its own.
254
+ const key = `${memoKey(endpoint, opts?.apiKey)}${ids.map(bareFeedId).sort().join(",")}`;
255
+ const inFlight = inFlightDiscoveries.get(key);
256
+ if (inFlight)
257
+ return inFlight;
258
+ const run = runDiscovery(endpoint, ids, opts, known404).finally(() => {
259
+ inFlightDiscoveries.delete(key);
260
+ });
261
+ inFlightDiscoveries.set(key, run);
262
+ return run;
263
+ }
264
+ async function runDiscovery(endpoint, ids, opts, known404 = false) {
265
+ if (ids.length === 0)
266
+ return;
267
+ if (!known404) {
268
+ let res;
269
+ try {
270
+ res = await rawFetch(endpoint, ids, opts);
271
+ }
272
+ catch {
273
+ return; // transient/network failure — can't classify; leave the memo untouched
274
+ }
275
+ void res.body?.cancel().catch(() => { });
276
+ if (res.status !== 404)
277
+ return; // this batch is serveable — nothing to record
278
+ }
279
+ const catalog = await readEndpointCatalog(endpoint, opts);
280
+ if (catalog !== null && catalog.size === 0) {
281
+ // Read fine, serves nothing: an entitlement/route fault, not N absent feeds.
282
+ throw new HermesEndpointRejectedAllFeedsError(endpoint, ids.length, "empty");
283
+ }
284
+ const missing = catalog !== null
285
+ ? new Set(ids.filter((id) => !catalog.has(bareFeedId(id))))
286
+ : await bisectMissingFeeds(endpoint, ids, opts, true);
287
+ if (missing.size === 0)
288
+ return;
289
+ if (catalog === null && missing.size === ids.length) {
290
+ throw new HermesEndpointRejectedAllFeedsError(endpoint, ids.length, "unreadable");
291
+ }
292
+ recordMissingFeeds(endpoint, missing, opts?.apiKey);
293
+ }
294
+ /**
295
+ * Discovery-only entry for consumers that fetch Hermes THEMSELVES (e.g. a
296
+ * parsed latest-price reader) and just observed a whole-batch 404: resolves
297
+ * which ids the endpoint lacks, memoizes them (see {@link
298
+ * endpointSupportedFeedIds}), fetches NO survivor data. Without this, such a
299
+ * consumer's only way to populate the memo was calling {@link
300
+ * fetchPriceFeedsUpdateData} and discarding its accumulator blob — two full
301
+ * redundant transfers per cold discovery.
302
+ *
303
+ * @throws HermesEndpointRejectedAllFeedsError when the rejection looks
304
+ * endpoint-wide rather than per-feed — the caller's own 404 is then a
305
+ * misconfiguration to surface, not a set of feeds to quietly drop.
306
+ */
307
+ export function probeMissingFeeds(endpoint, ids, opts) {
308
+ return discoverMissingFeeds(endpoint, ids, opts, true);
309
+ }
28
310
  export async function fetchPriceFeedsUpdateData(endpoint, priceIds, opts) {
29
- if (priceIds.length === 0)
311
+ // Skip feeds this endpoint has already told us it doesn't have.
312
+ const ids = endpointSupportedFeedIds(endpoint, priceIds, opts?.apiKey);
313
+ if (ids.length === 0)
30
314
  return [];
31
- const url = new URL("/v2/updates/price/latest", endpoint);
32
- priceIds.forEach((id) => url.searchParams.append("ids[]", id));
33
315
  let res;
34
316
  try {
35
- res = await fetchWithPolicy(url.toString(), {}, { apiKey: opts?.apiKey, ...opts?.fetch });
317
+ res = await rawFetch(endpoint, ids, opts);
36
318
  }
37
319
  catch (err) {
38
- // A retryable status (429/5xx) that never recovered surfaces as a
39
- // FetchPolicyError with `status` set — reformat it into this function's
40
- // own message shape so callers (and the e2e transient-failure detector,
41
- // which keys off "Hermes price fetch failed") see the same text whether
42
- // the failure was retried or not. A network-level exhaustion (no status)
43
- // has no domain-specific reframing to add propagate it as-is.
44
- if (err instanceof FetchPolicyError && err.status !== undefined) {
45
- const body = err.bodySnippet ? ` ${err.bodySnippet}` : "";
46
- throw new Error(`Hermes price fetch failed: ${err.status}${body} (retries exhausted after ${err.attempts} attempts)`, { cause: err });
320
+ rethrowExhaustedFetch(err, (e) => `Hermes price fetch failed: ${e.status}${e.bodySnippet ? ` ${e.bodySnippet}` : ""}`);
321
+ }
322
+ if (!res.ok) {
323
+ // Drain the body ONCE, here. A `Response` body can only be read once, and
324
+ // the 404 branch below finishes with it before the throw is reached — so
325
+ // reading it inside the throw surfaced `TypeError: Body is unusable`
326
+ // instead of this function's documented message whenever a 404 fell
327
+ // through. Reading up front also releases the connection on every path.
328
+ const body = await res.text().catch(() => "");
329
+ // Pyth 404s the ENTIRE batch if ANY id is unknown to the endpoint (a Core
330
+ // feed absent from the Pyth Pro compat endpoint). This is on the money
331
+ // path of every order/position/WLP tx-build, so instead of failing the
332
+ // whole refresh: discover the unknown ids (catalog, else bisection — the
333
+ // body isn't reliably delivered), memoize them, and re-fetch the survivors
334
+ // as ONE clean batch (a single combined accumulator blob, which
335
+ // buildPythPriceUpdateCalls requires). A genuinely-absent ticker just
336
+ // isn't in the payload — its on-chain aggregate abstains/aborts, which is
337
+ // correct. Steady state: once discovered, survivors are filtered up front
338
+ // and this never runs. A rejection that looks endpoint-wide instead of
339
+ // per-feed throws out of here (HermesEndpointRejectedAllFeedsError).
340
+ if (res.status === 404) {
341
+ // known404: this exact batch just 404'd above — skip the root re-probe.
342
+ await discoverMissingFeeds(endpoint, ids, opts, true);
343
+ const survivors = endpointSupportedFeedIds(endpoint, ids, opts?.apiKey);
344
+ if (survivors.length === 0)
345
+ return [];
346
+ // survivors < ids ⇒ we removed the offender(s); re-fetch cleanly. Equal
347
+ // ⇒ nothing was recorded (a 404 that wasn't a missing-feed rejection) —
348
+ // surface it rather than loop.
349
+ if (survivors.length < ids.length) {
350
+ return fetchPriceFeedsUpdateData(endpoint, survivors, opts);
351
+ }
47
352
  }
48
- throw err;
353
+ throw new Error(`Hermes price fetch failed: ${res.status}${body ? ` ${body}` : ""}`);
49
354
  }
50
- if (!res.ok)
51
- throw new Error(`Hermes price fetch failed: ${res.status} ${await res.text()}`);
52
355
  const json = (await res.json());
53
356
  const data = json.binary?.data;
54
357
  if (!Array.isArray(data) || data.length === 0) {
@@ -278,9 +581,18 @@ export async function buildPythPriceUpdateCalls(tx, host, updates, feedIds, opts
278
581
  }
279
582
  /** All-in-one: fetch from Hermes, append update calls. Returns PriceInfoObject IDs. */
280
583
  export async function updatePythPrices(tx, host, feedIds, opts) {
281
- const updates = await fetchPriceFeedsUpdateData(host.pyth.hermes_endpoint, feedIds, {
584
+ // `host.pyth` is the Pyth Core infra (fixed per network) plus the caller's
585
+ // api_key/fetch — endpoint, credential and policy all come from it.
586
+ const endpoint = host.pyth.hermes_endpoint;
587
+ const updates = await fetchPriceFeedsUpdateData(endpoint, feedIds, {
282
588
  apiKey: host.pyth.api_key,
283
589
  fetch: host.pyth.fetch,
284
590
  });
285
- return buildPythPriceUpdateCalls(tx, host, updates, feedIds, opts);
591
+ // Align feedIds with the feeds the endpoint actually served — the fetch drops
592
+ // (and memoizes) any it lacks, and `buildPythPriceUpdateCalls` emits one
593
+ // update call per feedId, so a dropped feed would reference a PriceInfoObject
594
+ // the accumulator blob doesn't cover (invalid PTB / on-chain abort). Mirrors
595
+ // `PythCoreRule.fetchUpdateData`.
596
+ const servedFeedIds = endpointSupportedFeedIds(endpoint, feedIds, host.pyth.api_key);
597
+ return buildPythPriceUpdateCalls(tx, host, updates, servedFeedIds, opts);
286
598
  }
@@ -3,13 +3,18 @@
3
3
  * `PriceUpdateRule` implementation. `refreshOraclePrices` (`aggregate.ts`) is
4
4
  * the only production caller; this is the one place `OracleSource` values are
5
5
  * wired to a rule instance. Selection is driven purely by the value passed in
6
- * (ultimately `OracleHost.oracleSource`, a client create option) — never by a
7
- * config JSON `enabled` flag and never by `process.env`.
6
+ * (ultimately `OracleHost.oracleSource`, the `oracleSource` client create
7
+ * option) — never by a config JSON `enabled` flag and never by `process.env`.
8
8
  *
9
- * Both sources are registered: `pyth_rule` (`PythCoreRule`, Hermes VAA) and
10
- * `pyth_lazer_rule` (`PythLazerRule`, Lazer signed updates). Resolving a
11
- * source with no registered rule throws a clear `OracleSourceNotImplemented`
12
- * error instead of silently falling back to Pyth Core.
9
+ * Each source is self-contained: it owns its own infra + config and does NOT
10
+ * back-stop any other source. Three are registered: `pyth_rule`
11
+ * (`PythCoreRule`, Hermes VAA), `pyth_lazer_rule` (`PythLazerRule`, Lazer
12
+ * signed updates), and `waterx_rule` (`WaterxRule`, first-party quote-center
13
+ * ed25519 signed batches). Resolving a source with no registered rule throws a
14
+ * clear `OracleSourceNotImplemented` error. There is deliberately no
15
+ * cross-source fallback and no client-creation config guard: selecting a source
16
+ * whose feeds are absent is not an error at init — it surfaces at tx-build time
17
+ * for the specific tickers that source can't serve (see `refreshOraclePrices`).
13
18
  */
14
19
  import type { OracleSource, PriceUpdateRule } from "./price-update-rule.ts";
15
20
  /**
@@ -3,16 +3,22 @@
3
3
  * `PriceUpdateRule` implementation. `refreshOraclePrices` (`aggregate.ts`) is
4
4
  * the only production caller; this is the one place `OracleSource` values are
5
5
  * wired to a rule instance. Selection is driven purely by the value passed in
6
- * (ultimately `OracleHost.oracleSource`, a client create option) — never by a
7
- * config JSON `enabled` flag and never by `process.env`.
6
+ * (ultimately `OracleHost.oracleSource`, the `oracleSource` client create
7
+ * option) — never by a config JSON `enabled` flag and never by `process.env`.
8
8
  *
9
- * Both sources are registered: `pyth_rule` (`PythCoreRule`, Hermes VAA) and
10
- * `pyth_lazer_rule` (`PythLazerRule`, Lazer signed updates). Resolving a
11
- * source with no registered rule throws a clear `OracleSourceNotImplemented`
12
- * error instead of silently falling back to Pyth Core.
9
+ * Each source is self-contained: it owns its own infra + config and does NOT
10
+ * back-stop any other source. Three are registered: `pyth_rule`
11
+ * (`PythCoreRule`, Hermes VAA), `pyth_lazer_rule` (`PythLazerRule`, Lazer
12
+ * signed updates), and `waterx_rule` (`WaterxRule`, first-party quote-center
13
+ * ed25519 signed batches). Resolving a source with no registered rule throws a
14
+ * clear `OracleSourceNotImplemented` error. There is deliberately no
15
+ * cross-source fallback and no client-creation config guard: selecting a source
16
+ * whose feeds are absent is not an error at init — it surfaces at tx-build time
17
+ * for the specific tickers that source can't serve (see `refreshOraclePrices`).
13
18
  */
14
19
  import { PythCoreRule } from "./rules/pyth-core-rule.js";
15
20
  import { PythLazerRule } from "./rules/pyth-lazer-rule.js";
21
+ import { WaterxRule } from "./rules/waterx-rule.js";
16
22
  /**
17
23
  * Production registry. Frozen — tests inject a fake rule via
18
24
  * `resolveOracleRule`'s `overrides` param instead of mutating this.
@@ -20,6 +26,7 @@ import { PythLazerRule } from "./rules/pyth-lazer-rule.js";
20
26
  const DEFAULT_RULES = Object.freeze({
21
27
  pyth_rule: PythCoreRule,
22
28
  pyth_lazer_rule: PythLazerRule,
29
+ waterx_rule: WaterxRule,
23
30
  });
24
31
  /**
25
32
  * Thrown by {@link resolveOracleRule} when `source` has no `PriceUpdateRule`
@@ -7,7 +7,7 @@
7
7
  * changes vs `../pyth.ts` / `./pyth-rule.ts`.
8
8
  */
9
9
  import { assertRuleUpdateData, } from "../price-update-rule.js";
10
- import { buildPythPriceUpdateCalls, fetchPriceFeedsUpdateData } from "../pyth.js";
10
+ import { buildPythPriceUpdateCalls, endpointSupportedFeedIds, fetchPriceFeedsUpdateData, } from "../pyth.js";
11
11
  /**
12
12
  * Shape check ONLY — the `kind` discriminant is checked separately by the
13
13
  * caller before this runs, since a same-shaped payload from a different rule
@@ -33,12 +33,27 @@ export const PythCoreRule = {
33
33
  async fetchUpdateData(host, tickers) {
34
34
  if (tickers.length === 0)
35
35
  return null;
36
+ // `host.pyth` is this source's own infra — the fixed per-network Core
37
+ // Pyth block plus the caller's api_key/fetch. Endpoint, credential and
38
+ // retry/timeout policy all come from it.
39
+ const endpoint = host.pyth.hermes_endpoint;
36
40
  const feedIds = tickers.map((ticker) => host.getPythFeed(ticker).feed_id);
37
- const updates = await fetchPriceFeedsUpdateData(host.pyth.hermes_endpoint, feedIds, {
41
+ const updates = await fetchPriceFeedsUpdateData(endpoint, feedIds, {
38
42
  apiKey: host.pyth.api_key,
39
43
  fetch: host.pyth.fetch,
40
44
  });
41
- return { kind: "pyth_rule", payload: { updates, feedIds } };
45
+ // `updates` covers only the feeds this endpoint actually served — the fetch
46
+ // drops (and memoizes) any it lacks, e.g. Core feeds absent from Pyth Pro
47
+ // (WTIUSD/BRENTUSD). Align `feedIds` with them: buildPythPriceUpdateCalls
48
+ // emits one moveCall per feedId and must not reference a feed the
49
+ // accumulator blob doesn't cover.
50
+ return {
51
+ kind: "pyth_rule",
52
+ payload: {
53
+ updates,
54
+ feedIds: endpointSupportedFeedIds(endpoint, feedIds, host.pyth.api_key),
55
+ },
56
+ };
42
57
  },
43
58
  /**
44
59
  * Subsets a (typically whole-universe) payload from {@link fetchUpdateData}