@waterx/sdk 4.0.0 → 4.0.1

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