@waterx/sdk 3.1.1 → 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 (76) hide show
  1. package/README.md +54 -18
  2. package/dist/cjs/src/account/config.d.ts +0 -16
  3. package/dist/cjs/src/oracle/aggregate.d.ts +96 -17
  4. package/dist/cjs/src/oracle/aggregate.js +179 -21
  5. package/dist/cjs/src/oracle/config.d.ts +85 -2
  6. package/dist/cjs/src/oracle/config.js +30 -1
  7. package/dist/cjs/src/oracle/host.d.ts +14 -1
  8. package/dist/cjs/src/oracle/index.d.ts +19 -5
  9. package/dist/cjs/src/oracle/index.js +54 -6
  10. package/dist/cjs/src/oracle/price-update-rule.d.ts +180 -0
  11. package/dist/cjs/src/oracle/price-update-rule.js +56 -0
  12. package/dist/cjs/src/oracle/pyth.d.ts +142 -11
  13. package/dist/cjs/src/oracle/pyth.js +408 -25
  14. package/dist/cjs/src/oracle/rule-registry.d.ts +41 -0
  15. package/dist/cjs/src/oracle/rule-registry.js +65 -0
  16. package/dist/cjs/src/oracle/rules/pyth-core-rule.d.ts +15 -0
  17. package/dist/cjs/src/oracle/rules/pyth-core-rule.js +99 -0
  18. package/dist/cjs/src/oracle/rules/pyth-lazer-rule.d.ts +41 -0
  19. package/dist/cjs/src/oracle/rules/pyth-lazer-rule.js +197 -0
  20. package/dist/cjs/src/oracle/rules/pyth-rule.js +5 -0
  21. package/dist/cjs/src/oracle/rules/sponsor.d.ts +11 -7
  22. package/dist/cjs/src/oracle/rules/sponsor.js +11 -7
  23. package/dist/cjs/src/oracle/update-fetch.d.ts +115 -0
  24. package/dist/cjs/src/oracle/update-fetch.js +285 -0
  25. package/dist/cjs/src/perp/client.d.ts +40 -5
  26. package/dist/cjs/src/perp/client.js +18 -3
  27. package/dist/cjs/src/perp/config.d.ts +10 -7
  28. package/dist/cjs/src/perp/config.js +77 -17
  29. package/dist/cjs/src/perp/index.d.ts +3 -2
  30. package/dist/cjs/src/perp/index.js +6 -2
  31. package/dist/cjs/src/perp/tx-builders/common.d.ts +52 -15
  32. package/dist/cjs/src/perp/tx-builders/common.js +39 -6
  33. package/dist/cjs/src/perp/tx-builders/wlp.d.ts +11 -3
  34. package/dist/cjs/src/perp/tx-builders/wlp.js +29 -3
  35. package/dist/cjs/src/perp/tx-builders.d.ts +3 -3
  36. package/dist/cjs/src/perp/tx-builders.js +3 -3
  37. package/dist/cjs/src/unified-client.d.ts +25 -0
  38. package/dist/cjs/src/unified-client.js +3 -0
  39. package/dist/src/account/config.d.ts +0 -16
  40. package/dist/src/oracle/aggregate.d.ts +96 -17
  41. package/dist/src/oracle/aggregate.js +180 -22
  42. package/dist/src/oracle/config.d.ts +85 -2
  43. package/dist/src/oracle/config.js +29 -0
  44. package/dist/src/oracle/host.d.ts +14 -1
  45. package/dist/src/oracle/index.d.ts +19 -5
  46. package/dist/src/oracle/index.js +42 -6
  47. package/dist/src/oracle/price-update-rule.d.ts +180 -0
  48. package/dist/src/oracle/price-update-rule.js +53 -0
  49. package/dist/src/oracle/pyth.d.ts +142 -11
  50. package/dist/src/oracle/pyth.js +402 -24
  51. package/dist/src/oracle/rule-registry.d.ts +41 -0
  52. package/dist/src/oracle/rule-registry.js +60 -0
  53. package/dist/src/oracle/rules/pyth-core-rule.d.ts +15 -0
  54. package/dist/src/oracle/rules/pyth-core-rule.js +96 -0
  55. package/dist/src/oracle/rules/pyth-lazer-rule.d.ts +41 -0
  56. package/dist/src/oracle/rules/pyth-lazer-rule.js +192 -0
  57. package/dist/src/oracle/rules/pyth-rule.js +5 -0
  58. package/dist/src/oracle/rules/sponsor.d.ts +11 -7
  59. package/dist/src/oracle/rules/sponsor.js +11 -7
  60. package/dist/src/oracle/update-fetch.d.ts +115 -0
  61. package/dist/src/oracle/update-fetch.js +277 -0
  62. package/dist/src/perp/client.d.ts +40 -5
  63. package/dist/src/perp/client.js +18 -3
  64. package/dist/src/perp/config.d.ts +10 -7
  65. package/dist/src/perp/config.js +77 -17
  66. package/dist/src/perp/index.d.ts +3 -2
  67. package/dist/src/perp/index.js +1 -1
  68. package/dist/src/perp/tx-builders/common.d.ts +52 -15
  69. package/dist/src/perp/tx-builders/common.js +39 -6
  70. package/dist/src/perp/tx-builders/wlp.d.ts +11 -3
  71. package/dist/src/perp/tx-builders/wlp.js +29 -3
  72. package/dist/src/perp/tx-builders.d.ts +3 -3
  73. package/dist/src/perp/tx-builders.js +3 -3
  74. package/dist/src/unified-client.d.ts +25 -0
  75. package/dist/src/unified-client.js +3 -0
  76. package/package.json +1 -1
@@ -15,23 +15,343 @@
15
15
  */
16
16
  import { fromHex, toHex } from "@mysten/bcs";
17
17
  import { bcs } from "@mysten/sui/bcs";
18
+ import { fetchWithPolicy, joinEndpointPath, rethrowExhaustedFetch, trimTrailingSlashes, } from "./update-fetch.js";
18
19
  export class PythCache {
19
20
  pythStateInfo;
20
21
  wormholePackageId;
21
22
  priceTableInfo;
22
23
  priceFeedObjectIdCache = new Map();
23
24
  }
24
- // ============================================================================
25
- // Hermes REST
26
- // ============================================================================
27
- export async function fetchPriceFeedsUpdateData(endpoint, priceIds) {
28
- if (priceIds.length === 0)
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
+ }
310
+ export async function fetchPriceFeedsUpdateData(endpoint, priceIds, opts) {
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)
29
314
  return [];
30
- const url = new URL("/v2/updates/price/latest", endpoint);
31
- priceIds.forEach((id) => url.searchParams.append("ids[]", id));
32
- const res = await fetch(url.toString(), { signal: AbortSignal.timeout(15_000) });
33
- if (!res.ok)
34
- throw new Error(`Hermes price fetch failed: ${res.status} ${await res.text()}`);
315
+ let res;
316
+ try {
317
+ res = await rawFetch(endpoint, ids, opts);
318
+ }
319
+ catch (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
+ }
352
+ }
353
+ throw new Error(`Hermes price fetch failed: ${res.status}${body ? ` ${body}` : ""}`);
354
+ }
35
355
  const json = (await res.json());
36
356
  const data = json.binary?.data;
37
357
  if (!Array.isArray(data) || data.length === 0) {
@@ -137,26 +457,72 @@ function extractVaaBytes(accumulatorMessage) {
137
457
  const vaaOffset = vaaSizeOffset + 2;
138
458
  return accumulatorMessage.subarray(vaaOffset, vaaOffset + vaaSize);
139
459
  }
140
- // ============================================================================
141
- // Pyth update calls
142
- // ============================================================================
460
+ /**
461
+ * Thrown when no {@link OracleFeeSource} is available for the Pyth update fee
462
+ * — from `buildPythPriceUpdateCalls`'s own per-call guard, or `aggregate.ts`'s
463
+ * hoisted `refreshOraclePrices` pre-check (see its docblock). `instanceof`-able
464
+ * (mirrors `FetchPolicyError` in `update-fetch.ts`) so a consumer — e.g. a BE
465
+ * integration wiring its own `allowGasFee` decision — can branch on the error
466
+ * type directly instead of string-matching `error.message`.
467
+ */
468
+ export class OracleFeeSourceUnavailableError extends Error {
469
+ constructor() {
470
+ super("OracleFeeSourceUnavailable: no fee source available for the Pyth update fee — " +
471
+ "deploy pyth_sponsor_rule to config so a sponsor fund can be opened (see " +
472
+ "openPythSponsorFund / wrapRequestAndExecute), or pass allowGasFee: true to draw " +
473
+ "the fee from tx.gas in a non-sponsored context");
474
+ this.name = "OracleFeeSourceUnavailableError";
475
+ }
476
+ }
143
477
  /**
144
478
  * Append the on-chain Pyth update PTB block. Returns `PriceInfoObject` IDs
145
479
  * (one per `feedIds`, same order). After this you can feed `pyth_rule` per
146
480
  * ticker against the matching `PriceInfoObject` (see `rules/pyth-rule.ts`).
147
481
  *
148
- * If `sponsorFund` is provided, the per-feed update fee comes from the
149
- * sponsor pool (`pyth_sponsor_rule::split`) instead of `tx.gas`. Opening and
150
- * reimbursing that fund is the sponsor rule's job (`rules/sponsor.ts`); here we
151
- * only draw a fee coin from the already-open `fund` hot potato.
482
+ * `opts.feeSource` is resolved BEFORE any PTB mutation and is never silently
483
+ * defaulted this function trusts whatever single {@link OracleFeeSource}
484
+ * it's handed, it does not choose between competing candidates:
485
+ * - `{ kind: 'sponsor' }` the per-feed update fee is drawn from the
486
+ * sponsor pool (`pyth_sponsor_rule::split`) instead of `tx.gas`. Opening
487
+ * and reimbursing that fund is the caller's job (`rules/sponsor.ts` /
488
+ * `wrapRequestAndExecute`, which opens it whenever the client's config
489
+ * has `pyth_sponsor_rule` deployed) — this function only draws a fee
490
+ * coin from the already-open `fund` hot potato.
491
+ * - `{ kind: 'gas' }` → the fee is drawn from `tx.gas` via `tx.splitCoins`.
492
+ * Only safe in a non-sponsored context — Enoki-sponsored transactions
493
+ * reject any `tx.gas` draw.
494
+ * - `undefined` → throws `OracleFeeSourceUnavailable` instead of silently
495
+ * drawing from `tx.gas` (the old default), which broke under Enoki and,
496
+ * worse, could fail ON-CHAIN when the market's `request_checklist`
497
+ * requires the `PythSponsorRule` witness that only a real sponsor fund
498
+ * attaches.
499
+ *
500
+ * This function's own check runs AFTER `updates`/`feedIds` are already in
501
+ * hand, so for `updatePythPrices` (which fetches from Hermes, then calls
502
+ * straight into this function) the off-chain fetch has already completed by
503
+ * the time this throws — a wasted network call, never a stray PTB command.
504
+ * `refreshOraclePrices` avoids that waste entirely: it hoists an EQUIVALENT
505
+ * check ABOVE its off-chain fetch AND its per-group build loop (see its
506
+ * docblock in `aggregate.ts`), keyed on `PriceUpdateRule.requiresFeeSource`
507
+ * rather than waiting for a specific rule's fetch to complete — so for that
508
+ * route neither the network call NOR any PTB command happens before the
509
+ * throw. This function's own (later, per-call) guard alone could not
510
+ * provide that "before any group builds" guarantee in a mixed shape (e.g. a
511
+ * fee-free Lazer group ordered ahead of a Pyth Core fallback group in the
512
+ * same PTB) — `refreshOraclePrices`'s pre-check is what closes it.
152
513
  */
153
- export async function buildPythPriceUpdateCalls(tx, host, updates, feedIds, cache, sponsorFund) {
514
+ export async function buildPythPriceUpdateCalls(tx, host, updates, feedIds, opts) {
154
515
  if (updates.length === 0) {
155
516
  throw new Error("No price update data provided; Hermes returned empty results");
156
517
  }
157
518
  if (updates.length > 1) {
158
519
  throw new Error("Only a single accumulator message is supported per transaction");
159
520
  }
521
+ const feeSource = opts?.feeSource;
522
+ if (!feeSource) {
523
+ throw new OracleFeeSourceUnavailableError();
524
+ }
525
+ const cache = opts?.cache;
160
526
  const pyth = host.pyth;
161
527
  const [stateInfo, wormholePackageId, table] = await Promise.all([
162
528
  getPythStateInfo(host.grpcClient, pyth.state_id, cache),
@@ -188,10 +554,10 @@ export async function buildPythPriceUpdateCalls(tx, host, updates, feedIds, cach
188
554
  if (!priceInfoObjectId) {
189
555
  throw new Error(`Pyth feed ${feedIds[i]} not registered on-chain in Pyth state`);
190
556
  }
191
- const feeCoin = sponsorFund
557
+ const feeCoin = feeSource.kind === "sponsor"
192
558
  ? tx.moveCall({
193
- target: `${sponsorFund.packageId}::pyth_sponsor_rule::split`,
194
- arguments: [sponsorFund.fund],
559
+ target: `${feeSource.packageId}::pyth_sponsor_rule::split`,
560
+ arguments: [feeSource.fund],
195
561
  })[0]
196
562
  : tx.splitCoins(tx.gas, [tx.pure.u64(baseUpdateFee)])[0];
197
563
  [hotPotato] = tx.moveCall({
@@ -214,7 +580,19 @@ export async function buildPythPriceUpdateCalls(tx, host, updates, feedIds, cach
214
580
  return priceInfoObjectIds;
215
581
  }
216
582
  /** All-in-one: fetch from Hermes, append update calls. Returns PriceInfoObject IDs. */
217
- export async function updatePythPrices(tx, host, feedIds, cache, sponsorFund) {
218
- const updates = await fetchPriceFeedsUpdateData(host.pyth.hermes_endpoint, feedIds);
219
- return buildPythPriceUpdateCalls(tx, host, updates, feedIds, cache, sponsorFund);
583
+ export async function updatePythPrices(tx, host, feedIds, opts) {
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, {
588
+ apiKey: host.pyth.api_key,
589
+ fetch: host.pyth.fetch,
590
+ });
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);
220
598
  }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * `rule-registry.ts` — maps a client-selected `OracleSource` to its concrete
3
+ * `PriceUpdateRule` implementation. `refreshOraclePrices` (`aggregate.ts`) is
4
+ * the only production caller; this is the one place `OracleSource` values are
5
+ * wired to a rule instance. Selection is driven purely by the value passed in
6
+ * (ultimately `OracleHost.oracleSource`, the `oracleSource` client create
7
+ * option) — never by a config JSON `enabled` flag and never by `process.env`.
8
+ *
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`).
17
+ */
18
+ import type { OracleSource, PriceUpdateRule } from "./price-update-rule.ts";
19
+ /**
20
+ * Thrown by {@link resolveOracleRule} when `source` has no `PriceUpdateRule`
21
+ * registered in either the production registry or a test's `overrides` map.
22
+ * `instanceof`-able (mirrors `OracleFeeSourceUnavailableError` in `pyth.ts`)
23
+ * so a consumer can branch on the failure type directly instead of
24
+ * string-matching `error.message`.
25
+ */
26
+ export declare class OracleSourceNotImplementedError extends Error {
27
+ /** The unregistered `OracleSource` that was requested. */
28
+ readonly source: OracleSource;
29
+ constructor(source: OracleSource);
30
+ }
31
+ /**
32
+ * Resolve the `PriceUpdateRule` registered for `source`.
33
+ *
34
+ * `overrides` — test-only — layers on top of the production registry so a
35
+ * spec can inject a fake rule (e.g. a stub `pyth_lazer_rule`) without
36
+ * touching {@link DEFAULT_RULES}; production callers never pass it.
37
+ *
38
+ * Throws {@link OracleSourceNotImplementedError} (`OracleSourceNotImplemented:
39
+ * <source>`) when nothing is registered for `source` in either map.
40
+ */
41
+ export declare function resolveOracleRule(source: OracleSource, overrides?: Partial<Record<OracleSource, PriceUpdateRule>>): PriceUpdateRule;
@@ -0,0 +1,60 @@
1
+ /**
2
+ * `rule-registry.ts` — maps a client-selected `OracleSource` to its concrete
3
+ * `PriceUpdateRule` implementation. `refreshOraclePrices` (`aggregate.ts`) is
4
+ * the only production caller; this is the one place `OracleSource` values are
5
+ * wired to a rule instance. Selection is driven purely by the value passed in
6
+ * (ultimately `OracleHost.oracleSource`, the `oracleSource` client create
7
+ * option) — never by a config JSON `enabled` flag and never by `process.env`.
8
+ *
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`).
17
+ */
18
+ import { PythCoreRule } from "./rules/pyth-core-rule.js";
19
+ import { PythLazerRule } from "./rules/pyth-lazer-rule.js";
20
+ /**
21
+ * Production registry. Frozen — tests inject a fake rule via
22
+ * `resolveOracleRule`'s `overrides` param instead of mutating this.
23
+ */
24
+ const DEFAULT_RULES = Object.freeze({
25
+ pyth_rule: PythCoreRule,
26
+ pyth_lazer_rule: PythLazerRule,
27
+ });
28
+ /**
29
+ * Thrown by {@link resolveOracleRule} when `source` has no `PriceUpdateRule`
30
+ * registered in either the production registry or a test's `overrides` map.
31
+ * `instanceof`-able (mirrors `OracleFeeSourceUnavailableError` in `pyth.ts`)
32
+ * so a consumer can branch on the failure type directly instead of
33
+ * string-matching `error.message`.
34
+ */
35
+ export class OracleSourceNotImplementedError extends Error {
36
+ /** The unregistered `OracleSource` that was requested. */
37
+ source;
38
+ constructor(source) {
39
+ super(`OracleSourceNotImplemented: ${source}`);
40
+ this.name = "OracleSourceNotImplementedError";
41
+ this.source = source;
42
+ }
43
+ }
44
+ /**
45
+ * Resolve the `PriceUpdateRule` registered for `source`.
46
+ *
47
+ * `overrides` — test-only — layers on top of the production registry so a
48
+ * spec can inject a fake rule (e.g. a stub `pyth_lazer_rule`) without
49
+ * touching {@link DEFAULT_RULES}; production callers never pass it.
50
+ *
51
+ * Throws {@link OracleSourceNotImplementedError} (`OracleSourceNotImplemented:
52
+ * <source>`) when nothing is registered for `source` in either map.
53
+ */
54
+ export function resolveOracleRule(source, overrides) {
55
+ const rule = overrides?.[source] ?? DEFAULT_RULES[source];
56
+ if (!rule) {
57
+ throw new OracleSourceNotImplementedError(source);
58
+ }
59
+ return rule;
60
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `PythCoreRule` — `PriceUpdateRule` wrapper around the existing Pyth Core
3
+ * (Hermes VAA) source in `../pyth.ts`. Delegates to `fetchPriceFeedsUpdateData`
4
+ * / `buildPythPriceUpdateCalls` verbatim; this file only adapts them to the
5
+ * `PriceUpdateRule` port shape (fetch → build) so a future router can select
6
+ * across rules by `kind`. Mechanical wrap only — no on-chain/off-chain logic
7
+ * changes vs `../pyth.ts` / `./pyth-rule.ts`.
8
+ */
9
+ import { type PriceUpdateRule } from "../price-update-rule.ts";
10
+ /** `pyth_rule`'s narrowed `RuleUpdateData.payload` shape. */
11
+ export interface PythCoreUpdatePayload {
12
+ readonly updates: Uint8Array[];
13
+ readonly feedIds: string[];
14
+ }
15
+ export declare const PythCoreRule: PriceUpdateRule;