@waterx/sdk 4.3.3 → 5.0.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 (145) hide show
  1. package/.claude/skills/waterx-sdk-integration/SKILL.md +41 -35
  2. package/README.md +81 -77
  3. package/dist/cjs/src/account/config.d.ts +3 -5
  4. package/dist/cjs/src/account/funding/wormhole.d.ts +1 -2
  5. package/dist/cjs/src/account/funding/wormhole.js +1 -2
  6. package/dist/cjs/src/oracle/aggregate.d.ts +45 -61
  7. package/dist/cjs/src/oracle/aggregate.js +138 -138
  8. package/dist/cjs/src/oracle/config.d.ts +35 -49
  9. package/dist/cjs/src/oracle/config.js +1 -1
  10. package/dist/cjs/src/oracle/host.d.ts +14 -19
  11. package/dist/cjs/src/oracle/host.js +3 -3
  12. package/dist/cjs/src/oracle/index.d.ts +25 -16
  13. package/dist/cjs/src/oracle/index.js +79 -66
  14. package/dist/cjs/src/oracle/price-update-rule.d.ts +104 -66
  15. package/dist/cjs/src/oracle/price-update-rule.js +24 -16
  16. package/dist/cjs/src/oracle/pyth-pro-history.d.ts +36 -0
  17. package/dist/cjs/src/oracle/pyth-pro-history.js +41 -0
  18. package/dist/cjs/src/oracle/read-plane.d.ts +35 -53
  19. package/dist/cjs/src/oracle/read-plane.js +26 -48
  20. package/dist/cjs/src/oracle/read-prices.d.ts +105 -0
  21. package/dist/cjs/src/oracle/read-prices.js +162 -0
  22. package/dist/cjs/src/oracle/rule-registry.d.ts +12 -12
  23. package/dist/cjs/src/oracle/rule-registry.js +12 -14
  24. package/dist/cjs/src/oracle/rules/pyth-lazer-rule.d.ts +24 -3
  25. package/dist/cjs/src/oracle/rules/pyth-lazer-rule.js +40 -20
  26. package/dist/cjs/src/oracle/rules/waterx-rule.d.ts +137 -12
  27. package/dist/cjs/src/oracle/rules/waterx-rule.js +318 -55
  28. package/dist/cjs/src/oracle/schedule.d.ts +109 -0
  29. package/dist/cjs/src/oracle/schedule.js +991 -0
  30. package/dist/cjs/src/oracle/source-list.d.ts +31 -27
  31. package/dist/cjs/src/oracle/source-list.js +43 -45
  32. package/dist/cjs/src/oracle/symbol-catalog.d.ts +54 -0
  33. package/dist/cjs/src/oracle/symbol-catalog.js +69 -0
  34. package/dist/cjs/src/oracle/update-fetch.d.ts +11 -15
  35. package/dist/cjs/src/oracle/update-fetch.js +12 -19
  36. package/dist/cjs/src/oracle/validate.d.ts +105 -0
  37. package/dist/cjs/src/oracle/validate.js +185 -0
  38. package/dist/cjs/src/oracle/weight-coverage.d.ts +79 -0
  39. package/dist/cjs/src/oracle/weight-coverage.js +173 -0
  40. package/dist/cjs/src/perp/client.d.ts +35 -52
  41. package/dist/cjs/src/perp/client.js +44 -17
  42. package/dist/cjs/src/perp/config-view.d.ts +5 -14
  43. package/dist/cjs/src/perp/config-view.js +5 -16
  44. package/dist/cjs/src/perp/config.d.ts +3 -3
  45. package/dist/cjs/src/perp/config.js +11 -13
  46. package/dist/cjs/src/perp/index.d.ts +4 -6
  47. package/dist/cjs/src/perp/index.js +35 -18
  48. package/dist/cjs/src/perp/tx-builders/common.d.ts +86 -48
  49. package/dist/cjs/src/perp/tx-builders/common.js +115 -47
  50. package/dist/cjs/src/perp/tx-builders/wlp.d.ts +3 -14
  51. package/dist/cjs/src/perp/tx-builders/wlp.js +6 -35
  52. package/dist/cjs/src/perp/tx-builders.d.ts +6 -5
  53. package/dist/cjs/src/perp/tx-builders.js +16 -10
  54. package/dist/cjs/src/unified-client.d.ts +8 -34
  55. package/dist/cjs/src/unified-client.js +3 -4
  56. package/dist/cjs/src/utils/config.d.ts +0 -8
  57. package/dist/cjs/src/utils/config.js +5 -13
  58. package/dist/src/account/config.d.ts +3 -5
  59. package/dist/src/account/funding/wormhole.d.ts +1 -2
  60. package/dist/src/account/funding/wormhole.js +1 -2
  61. package/dist/src/oracle/aggregate.d.ts +45 -61
  62. package/dist/src/oracle/aggregate.js +138 -137
  63. package/dist/src/oracle/config.d.ts +35 -49
  64. package/dist/src/oracle/config.js +1 -1
  65. package/dist/src/oracle/host.d.ts +14 -19
  66. package/dist/src/oracle/host.js +3 -3
  67. package/dist/src/oracle/index.d.ts +25 -16
  68. package/dist/src/oracle/index.js +55 -50
  69. package/dist/src/oracle/price-update-rule.d.ts +104 -66
  70. package/dist/src/oracle/price-update-rule.js +23 -16
  71. package/dist/src/oracle/pyth-pro-history.d.ts +36 -0
  72. package/dist/src/oracle/pyth-pro-history.js +38 -0
  73. package/dist/src/oracle/read-plane.d.ts +35 -53
  74. package/dist/src/oracle/read-plane.js +25 -47
  75. package/dist/src/oracle/read-prices.d.ts +105 -0
  76. package/dist/src/oracle/read-prices.js +156 -0
  77. package/dist/src/oracle/rule-registry.d.ts +12 -12
  78. package/dist/src/oracle/rule-registry.js +12 -14
  79. package/dist/src/oracle/rules/pyth-lazer-rule.d.ts +24 -3
  80. package/dist/src/oracle/rules/pyth-lazer-rule.js +39 -20
  81. package/dist/src/oracle/rules/waterx-rule.d.ts +137 -12
  82. package/dist/src/oracle/rules/waterx-rule.js +314 -56
  83. package/dist/src/oracle/schedule.d.ts +109 -0
  84. package/dist/src/oracle/schedule.js +985 -0
  85. package/dist/src/oracle/source-list.d.ts +31 -27
  86. package/dist/src/oracle/source-list.js +42 -43
  87. package/dist/src/oracle/symbol-catalog.d.ts +54 -0
  88. package/dist/src/oracle/symbol-catalog.js +65 -0
  89. package/dist/src/oracle/update-fetch.d.ts +11 -15
  90. package/dist/src/oracle/update-fetch.js +12 -18
  91. package/dist/src/oracle/validate.d.ts +105 -0
  92. package/dist/src/oracle/validate.js +177 -0
  93. package/dist/src/oracle/weight-coverage.d.ts +79 -0
  94. package/dist/src/oracle/weight-coverage.js +166 -0
  95. package/dist/src/perp/client.d.ts +35 -52
  96. package/dist/src/perp/client.js +45 -18
  97. package/dist/src/perp/config-view.d.ts +5 -14
  98. package/dist/src/perp/config-view.js +5 -16
  99. package/dist/src/perp/config.d.ts +3 -3
  100. package/dist/src/perp/config.js +11 -13
  101. package/dist/src/perp/index.d.ts +4 -6
  102. package/dist/src/perp/index.js +11 -5
  103. package/dist/src/perp/tx-builders/common.d.ts +86 -48
  104. package/dist/src/perp/tx-builders/common.js +114 -48
  105. package/dist/src/perp/tx-builders/wlp.d.ts +3 -14
  106. package/dist/src/perp/tx-builders/wlp.js +6 -35
  107. package/dist/src/perp/tx-builders.d.ts +6 -5
  108. package/dist/src/perp/tx-builders.js +15 -6
  109. package/dist/src/unified-client.d.ts +8 -34
  110. package/dist/src/unified-client.js +3 -4
  111. package/dist/src/utils/config.d.ts +0 -8
  112. package/dist/src/utils/config.js +5 -12
  113. package/package.json +1 -1
  114. package/dist/cjs/src/generated/pyth_sponsor_rule/deps/sui/balance.d.ts +0 -12
  115. package/dist/cjs/src/generated/pyth_sponsor_rule/deps/sui/balance.js +0 -17
  116. package/dist/cjs/src/generated/pyth_sponsor_rule/pyth_sponsor_rule.d.ts +0 -68
  117. package/dist/cjs/src/generated/pyth_sponsor_rule/pyth_sponsor_rule.js +0 -113
  118. package/dist/cjs/src/generated/waterx_pyth_rule/deps/sui/vec_map.d.ts +0 -36
  119. package/dist/cjs/src/generated/waterx_pyth_rule/deps/sui/vec_map.js +0 -31
  120. package/dist/cjs/src/generated/waterx_pyth_rule/pyth_rule.d.ts +0 -192
  121. package/dist/cjs/src/generated/waterx_pyth_rule/pyth_rule.js +0 -214
  122. package/dist/cjs/src/oracle/pyth.d.ts +0 -227
  123. package/dist/cjs/src/oracle/pyth.js +0 -652
  124. package/dist/cjs/src/oracle/rules/pyth-core-rule.d.ts +0 -15
  125. package/dist/cjs/src/oracle/rules/pyth-core-rule.js +0 -100
  126. package/dist/cjs/src/oracle/rules/pyth-rule.d.ts +0 -11
  127. package/dist/cjs/src/oracle/rules/pyth-rule.js +0 -29
  128. package/dist/cjs/src/oracle/rules/sponsor.d.ts +0 -32
  129. package/dist/cjs/src/oracle/rules/sponsor.js +0 -56
  130. package/dist/src/generated/pyth_sponsor_rule/deps/sui/balance.d.ts +0 -12
  131. package/dist/src/generated/pyth_sponsor_rule/deps/sui/balance.js +0 -14
  132. package/dist/src/generated/pyth_sponsor_rule/pyth_sponsor_rule.d.ts +0 -68
  133. package/dist/src/generated/pyth_sponsor_rule/pyth_sponsor_rule.js +0 -73
  134. package/dist/src/generated/waterx_pyth_rule/deps/sui/vec_map.d.ts +0 -36
  135. package/dist/src/generated/waterx_pyth_rule/deps/sui/vec_map.js +0 -27
  136. package/dist/src/generated/waterx_pyth_rule/pyth_rule.d.ts +0 -192
  137. package/dist/src/generated/waterx_pyth_rule/pyth_rule.js +0 -170
  138. package/dist/src/oracle/pyth.d.ts +0 -227
  139. package/dist/src/oracle/pyth.js +0 -638
  140. package/dist/src/oracle/rules/pyth-core-rule.d.ts +0 -15
  141. package/dist/src/oracle/rules/pyth-core-rule.js +0 -97
  142. package/dist/src/oracle/rules/pyth-rule.d.ts +0 -11
  143. package/dist/src/oracle/rules/pyth-rule.js +0 -26
  144. package/dist/src/oracle/rules/sponsor.d.ts +0 -32
  145. package/dist/src/oracle/rules/sponsor.js +0 -52
@@ -1,638 +0,0 @@
1
- /**
2
- * Pyth as a price *source*: Hermes REST + the on-chain Pyth update PTB.
3
- *
4
- * This file knows nothing about oracle *rules* (pyth_rule / supra_rule /
5
- * constant_rule / sponsor) — it only fetches price update VAAs from Hermes and
6
- * appends the Pyth on-chain update block, returning the refreshed
7
- * `PriceInfoObject` IDs. Feeding rules into a collector and aggregating lives in
8
- * `aggregate.ts`; the rule wrappers live in `rules/`.
9
- *
10
- * On-chain a single PTB:
11
- * 1. wormhole::vaa::parse_and_verify
12
- * 2. pyth::create_authenticated_price_infos_using_accumulator
13
- * 3. pyth::update_single_price_feed (one per feed)
14
- * 4. hot_potato_vector::destroy
15
- */
16
- import { fromHex, toHex } from "@mysten/bcs";
17
- import { bcs } from "@mysten/sui/bcs";
18
- import { fetchWithPolicy, joinEndpointPath, rethrowExhaustedFetch, trimTrailingSlashes, } from "./update-fetch.js";
19
- export const PYTH_CORE_INFRA = {
20
- MAINNET: {
21
- state_id: "0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",
22
- wormhole_state_id: "0xaeab97f96cf9877fee2883315d459552b2b921edc16d7ceac6eab944dd88919c",
23
- hermes_endpoint: "https://hermes.pyth.network",
24
- },
25
- TESTNET: {
26
- state_id: "0x243759059f4c3111179da5878c12f68d612c21a8d54d85edc86164bb18be1c7c",
27
- wormhole_state_id: "0x31358d198147da50db32eda2562951d53973a0c0ad5ed738e9b17d88b213d790",
28
- hermes_endpoint: "https://hermes-beta.pyth.network",
29
- },
30
- };
31
- /**
32
- * The Core source's Hermes REST base for `network` — for consumers (BE/FE
33
- * read planes) whose `ORACLE_SOURCE` fed set includes `'pyth_rule'`. A fed
34
- * set WITHOUT `pyth_rule` reads the keyed Pyth Pro base instead — resolve
35
- * through `resolveHermesReadEndpoint` (`oracle/read-plane.ts`) rather than
36
- * branching by hand.
37
- */
38
- export function pythCoreHermesEndpoint(network) {
39
- return PYTH_CORE_INFRA[network].hermes_endpoint;
40
- }
41
- /**
42
- * The Pyth Pro Hermes-compatible REST base — the documented drop-in
43
- * replacement for the Core endpoint (`https://pyth.dourolabs.app/hermes/…`),
44
- * IDENTICAL for every subscriber: only the `Authorization: Bearer` key
45
- * (`client.pyth.api_key` / the `pythApiKey` create option) is
46
- * account-specific, so the URL is SDK infra, not deployment config. One base
47
- * for both networks — Pro has no testnet variant (Pyth feed ids are
48
- * chain-agnostic; `hermes-beta` is a Core-testnet concern). Consumers with a
49
- * proxy/self-hosted mirror override it per deployment via
50
- * `resolveHermesReadEndpoint`'s `override` param.
51
- */
52
- export const PYTH_PRO_HERMES_ENDPOINT = "https://pyth.dourolabs.app/hermes";
53
- /** Accessor mirror of {@link pythCoreHermesEndpoint} for the Pro base. */
54
- export function pythProHermesEndpoint() {
55
- return PYTH_PRO_HERMES_ENDPOINT;
56
- }
57
- export class PythCache {
58
- pythStateInfo;
59
- wormholePackageId;
60
- priceTableInfo;
61
- priceFeedObjectIdCache = new Map();
62
- }
63
- /**
64
- * How long a "this endpoint lacks feed X" verdict stays memoized. The verdict
65
- * is a claim about *someone else's* deployment — a feed can be added to the
66
- * catalog, an entitlement can be granted, a Pro plan can be upgraded — so it
67
- * must expire rather than bind the whole process lifetime. Long enough that a
68
- * genuinely-absent feed costs one discovery per window instead of one per
69
- * build; short enough that a recovered endpoint self-heals without a restart.
70
- */
71
- export const MISSING_FEED_MEMO_TTL_MS = 15 * 60_000;
72
- /**
73
- * Per-endpoint memo of feed ids this endpoint has rejected as unknown (a 404
74
- * on `/v2/updates/price/latest`). The Pyth Pro compat endpoint carries a
75
- * SUBSET of Core's feeds — mainnet `WTIUSD`/`BRENTUSD` (Commodities
76
- * USOILSPOT/UKOILSPOT) are absent, for example. Pyth 404s the WHOLE batch if
77
- * ANY id is unknown, and the body naming the bad ids is NOT reliably delivered
78
- * to `fetch` (Cloudflare returns it to curl but `content-length: 0` to node's
79
- * undici), so the ids are isolated by catalog read (or bisection) and
80
- * remembered here — later batches skip them instead of 404ing every time.
81
- *
82
- * Entries carry an expiry ({@link MISSING_FEED_MEMO_TTL_MS}); an
83
- * endpoint-level fault never lands here at all (see {@link
84
- * HermesEndpointRejectedAllFeedsError}).
85
- */
86
- const missingFeedIdsByEndpoint = new Map();
87
- /**
88
- * Thrown when discovery concludes that an endpoint rejects EVERY requested
89
- * feed id without a catalog vouching for that verdict. `instanceof`-able
90
- * (mirrors `FetchPolicyError` / {@link OracleFeeSourceUnavailableError}).
91
- *
92
- * "All of them are missing" is the signature of an endpoint/credential fault —
93
- * a wrong base path (the Pyth Pro `/hermes` prefix dropped), a changed route,
94
- * a revoked or downgraded entitlement — not of N individually-absent feeds.
95
- * Memoizing it would convert a loud, fixable misconfiguration into a silent
96
- * permanent one: every id marked missing ⇒ `fetchPriceFeedsUpdateData` returns
97
- * `[]` ⇒ `buildPythPriceUpdateCalls` throws "Hermes returned empty results",
98
- * blaming Hermes for having no data, for the rest of the process's life. So
99
- * this case writes NOTHING to the memo and throws instead; the next call
100
- * re-probes and recovers on its own once the endpoint does.
101
- *
102
- * The message keeps the `Hermes price fetch failed: <status>` prefix on its
103
- * first line — the documented contract downstream consumers string-match (see
104
- * {@link fetchPriceFeedsUpdateData} and the e2e transient detector).
105
- */
106
- export class HermesEndpointRejectedAllFeedsError extends Error {
107
- endpoint;
108
- requestedCount;
109
- constructor(endpoint, requestedCount, catalogState) {
110
- super(`Hermes price fetch failed: 404 — endpoint rejected ALL ${requestedCount} requested feed id(s) ` +
111
- `and its feed catalog was ${catalogState}, so nothing vouches for those feeds being ` +
112
- `individually absent. Treating this as an endpoint/credential fault (wrong base path — ` +
113
- `e.g. a dropped Pyth Pro '/hermes' prefix — changed route, or revoked entitlement) rather ` +
114
- `than caching every feed as missing. Endpoint: ${endpoint}`);
115
- this.endpoint = endpoint;
116
- this.requestedCount = requestedCount;
117
- this.name = "HermesEndpointRejectedAllFeedsError";
118
- }
119
- }
120
- /**
121
- * Memo key for `(endpoint, credential)` — the same trailing-slash trim
122
- * {@link joinEndpointPath} applies to the request URL (shared helper, so the
123
- * two can't drift), plus the apiKey: "feed X is missing" is a property of the
124
- * endpoint AND the credential (Pyth Pro entitlements are per-key), so two
125
- * clients in one process with different keys must not cross-poison each
126
- * other's memo. Without the trim, two consumers spelling the same endpoint
127
- * differently (`…/hermes` vs `…/hermes/`) would fragment the memo and re-run
128
- * the whole 404 discovery despite one of them having already paid for it.
129
- */
130
- function memoKey(endpoint, apiKey) {
131
- return `${trimTrailingSlashes(endpoint)}\u0000${apiKey ?? ""}`;
132
- }
133
- function recordMissingFeeds(endpoint, feedIds, apiKey) {
134
- const key = memoKey(endpoint, apiKey);
135
- let entries = missingFeedIdsByEndpoint.get(key);
136
- if (!entries) {
137
- entries = new Map();
138
- missingFeedIdsByEndpoint.set(key, entries);
139
- }
140
- const expiresAt = Date.now() + MISSING_FEED_MEMO_TTL_MS;
141
- // Key on the bare (0x-stripped, lowercased) form — the SAME normalization the
142
- // catalog comparison and the in-flight latch use — so a feed can't fragment
143
- // the memo across `0xAB`/`ab` spellings and slip back through as unfiltered.
144
- for (const feedId of feedIds)
145
- entries.set(bareFeedId(feedId), expiresAt);
146
- }
147
- /**
148
- * The subset of `feedIds` this `endpoint` is known to serve — i.e. minus any
149
- * discovered to be absent within the last {@link MISSING_FEED_MEMO_TTL_MS}
150
- * (see {@link fetchPriceFeedsUpdateData}). Callers building a
151
- * `{ updates, feedIds }` payload use this to keep `feedIds` aligned with the
152
- * feeds the fetch actually returned data for, so `buildPythPriceUpdateCalls`
153
- * (one moveCall per feed id) never references a feed the accumulator blob
154
- * doesn't cover.
155
- *
156
- * Expired entries are pruned here rather than on a timer: the memo is only
157
- * ever consulted through this function, so a lazy sweep is both sufficient and
158
- * free of a dangling interval in a library.
159
- */
160
- export function endpointSupportedFeedIds(endpoint, feedIds, apiKey) {
161
- const key = memoKey(endpoint, apiKey);
162
- const entries = missingFeedIdsByEndpoint.get(key);
163
- if (!entries)
164
- return feedIds;
165
- const now = Date.now();
166
- for (const [id, expiresAt] of entries) {
167
- if (expiresAt <= now)
168
- entries.delete(id);
169
- }
170
- if (entries.size === 0) {
171
- missingFeedIdsByEndpoint.delete(key);
172
- return feedIds;
173
- }
174
- return feedIds.filter((id) => !entries.has(bareFeedId(id)));
175
- }
176
- /**
177
- * Discovery runs currently in flight, keyed by `(endpoint, credential,
178
- * requested id set)`. A cold memo plus two concurrent tx-builds asking the
179
- * same question ran two full independent discoveries — duplicate catalog reads
180
- * (or duplicate bisection probe trees) on the money path, for one answer. The
181
- * second caller now joins the first run's promise: each still gets its own
182
- * survivor data, but they share the one discovery behind it.
183
- */
184
- const inFlightDiscoveries = new Map();
185
- /** Test-only: forget everything learned about which feeds an endpoint lacks. */
186
- export function __resetMissingFeedCacheForTest() {
187
- missingFeedIdsByEndpoint.clear();
188
- inFlightDiscoveries.clear();
189
- }
190
- /**
191
- * One `GET /v2/price_feeds` — the set of feed ids this endpoint serves for
192
- * THIS credential (verified against the Pro compat endpoint: WTI absent from
193
- * the catalog AND 404 on latest-price; BTC present AND 200 —
194
- * entitlement-filtered per key), normalized to bare lowercase hex.
195
- *
196
- * Returns `null` when the catalog is unreadable (non-2xx, unparseable, network
197
- * error) — the catalog is an optimization, {@link bisectMissingFeeds} remains
198
- * the ground truth derived from the money-path fetch itself. Note that "read
199
- * fine, served nothing" (`size === 0`) is NOT the same as unreadable: an empty
200
- * catalog is an entitlement/route fault in its own right, and the caller
201
- * treats it as one.
202
- */
203
- async function readEndpointCatalog(endpoint, opts) {
204
- try {
205
- const res = await fetchWithPolicy(joinEndpointPath(endpoint, "v2/price_feeds").toString(), {}, { apiKey: opts?.apiKey, ...opts?.fetch });
206
- if (!res.ok) {
207
- void res.body?.cancel().catch(() => { });
208
- return null;
209
- }
210
- const catalog = (await res.json());
211
- if (!Array.isArray(catalog))
212
- return null;
213
- // Catalog ids come WITHOUT the 0x prefix; callers pass either form.
214
- return new Set(catalog.map((f) => bareFeedId(f.id)));
215
- }
216
- catch {
217
- return null;
218
- }
219
- }
220
- /** Feed ids are compared prefix- and case-insensitively (`0xAB` ≡ `ab`). */
221
- function bareFeedId(feedId) {
222
- return feedId.toLowerCase().replace(/^0x/, "");
223
- }
224
- async function rawFetch(endpoint, ids, opts) {
225
- // joinEndpointPath preserves the endpoint's own base path — `new URL`
226
- // with a leading-slash path would discard it (the Pyth Pro `/hermes`
227
- // prefix → 404 on EVERY feed); see its doc in update-fetch.ts.
228
- const url = joinEndpointPath(endpoint, "v2/updates/price/latest");
229
- ids.forEach((id) => url.searchParams.append("ids[]", id));
230
- return fetchWithPolicy(url.toString(), {}, { apiKey: opts?.apiKey, ...opts?.fetch });
231
- }
232
- /**
233
- * Bisect `ids` down to the individual ones this endpoint 404s on — the
234
- * response body isn't readable, so a single id that still 404s IS the unknown
235
- * one. Data is discarded; this only *reports* (the caller decides whether the
236
- * verdict is trustworthy enough to memoize). A non-404 (the subset is fine) or
237
- * a network error stops that branch and contributes nothing.
238
- *
239
- * `known404: true` skips the root probe — the caller has already watched this
240
- * exact batch 404, so re-fetching it would only re-learn a fact in hand (a
241
- * wasted round trip on the money path during cold discovery). Recursive
242
- * half-calls always probe: their status is genuinely unknown.
243
- */
244
- async function bisectMissingFeeds(endpoint, ids, opts, known404 = false) {
245
- if (ids.length === 0)
246
- return new Set();
247
- if (!known404) {
248
- let res;
249
- try {
250
- res = await rawFetch(endpoint, ids, opts);
251
- }
252
- catch {
253
- return new Set(); // transient/network failure — can't classify
254
- }
255
- void res.body?.cancel().catch(() => { });
256
- if (res.status !== 404)
257
- return new Set(); // this subset is serveable
258
- }
259
- if (ids.length === 1)
260
- return new Set([ids[0]]);
261
- const mid = Math.floor(ids.length / 2);
262
- const [lo, hi] = await Promise.all([
263
- bisectMissingFeeds(endpoint, ids.slice(0, mid), opts),
264
- bisectMissingFeeds(endpoint, ids.slice(mid), opts),
265
- ]);
266
- return new Set([...lo, ...hi]);
267
- }
268
- /**
269
- * Work out which of `ids` this endpoint lacks and memoize exactly those.
270
- *
271
- * Catalog first: one `GET /v2/price_feeds` answers for the whole batch, so a
272
- * confirmed 404 costs one extra request instead of O(log n) bisection probes.
273
- * The catalog is also the only *authoritative* source here — it says what the
274
- * endpoint DOES serve, which is what separates "these two feeds are absent"
275
- * from "this endpoint is serving nothing to me". Bisection can only observe
276
- * 404s, and a wrong base path 404s identically to an unknown feed.
277
- *
278
- * Hence the guard: a verdict of "every requested id is missing" is only
279
- * committed when a non-empty catalog vouches for it. Otherwise nothing is
280
- * written and {@link HermesEndpointRejectedAllFeedsError} is thrown — see its
281
- * docblock for why silently memoizing that case is worse than failing.
282
- *
283
- * Concurrent callers asking the identical question share ONE run (see {@link
284
- * inFlightDiscoveries}); the latch is released on failure too, so a blip never
285
- * pins later callers to a stale outcome.
286
- *
287
- * @throws HermesEndpointRejectedAllFeedsError on an endpoint-level rejection.
288
- */
289
- function discoverMissingFeeds(endpoint, ids, opts, known404 = false) {
290
- // Same endpoint + credential + requested set ⇒ same answer; anything else
291
- // is a different question and runs on its own.
292
- const key = `${memoKey(endpoint, opts?.apiKey)}${ids.map(bareFeedId).sort().join(",")}`;
293
- const inFlight = inFlightDiscoveries.get(key);
294
- if (inFlight)
295
- return inFlight;
296
- const run = runDiscovery(endpoint, ids, opts, known404).finally(() => {
297
- inFlightDiscoveries.delete(key);
298
- });
299
- inFlightDiscoveries.set(key, run);
300
- return run;
301
- }
302
- async function runDiscovery(endpoint, ids, opts, known404 = false) {
303
- if (ids.length === 0)
304
- return;
305
- if (!known404) {
306
- let res;
307
- try {
308
- res = await rawFetch(endpoint, ids, opts);
309
- }
310
- catch {
311
- return; // transient/network failure — can't classify; leave the memo untouched
312
- }
313
- void res.body?.cancel().catch(() => { });
314
- if (res.status !== 404)
315
- return; // this batch is serveable — nothing to record
316
- }
317
- const catalog = await readEndpointCatalog(endpoint, opts);
318
- if (catalog !== null && catalog.size === 0) {
319
- // Read fine, serves nothing: an entitlement/route fault, not N absent feeds.
320
- throw new HermesEndpointRejectedAllFeedsError(endpoint, ids.length, "empty");
321
- }
322
- const missing = catalog !== null
323
- ? new Set(ids.filter((id) => !catalog.has(bareFeedId(id))))
324
- : await bisectMissingFeeds(endpoint, ids, opts, true);
325
- if (missing.size === 0)
326
- return;
327
- if (catalog === null && missing.size === ids.length) {
328
- throw new HermesEndpointRejectedAllFeedsError(endpoint, ids.length, "unreadable");
329
- }
330
- recordMissingFeeds(endpoint, missing, opts?.apiKey);
331
- }
332
- /**
333
- * Discovery-only entry for consumers that fetch Hermes THEMSELVES (e.g. a
334
- * parsed latest-price reader) and just observed a whole-batch 404: resolves
335
- * which ids the endpoint lacks, memoizes them (see {@link
336
- * endpointSupportedFeedIds}), fetches NO survivor data. Without this, such a
337
- * consumer's only way to populate the memo was calling {@link
338
- * fetchPriceFeedsUpdateData} and discarding its accumulator blob — two full
339
- * redundant transfers per cold discovery.
340
- *
341
- * @throws HermesEndpointRejectedAllFeedsError when the rejection looks
342
- * endpoint-wide rather than per-feed — the caller's own 404 is then a
343
- * misconfiguration to surface, not a set of feeds to quietly drop.
344
- */
345
- export function probeMissingFeeds(endpoint, ids, opts) {
346
- return discoverMissingFeeds(endpoint, ids, opts, true);
347
- }
348
- export async function fetchPriceFeedsUpdateData(endpoint, priceIds, opts) {
349
- // Skip feeds this endpoint has already told us it doesn't have.
350
- const ids = endpointSupportedFeedIds(endpoint, priceIds, opts?.apiKey);
351
- if (ids.length === 0)
352
- return [];
353
- let res;
354
- try {
355
- res = await rawFetch(endpoint, ids, opts);
356
- }
357
- catch (err) {
358
- rethrowExhaustedFetch(err, (e) => `Hermes price fetch failed: ${e.status}${e.bodySnippet ? ` ${e.bodySnippet}` : ""}`);
359
- }
360
- if (!res.ok) {
361
- // Drain the body ONCE, here. A `Response` body can only be read once, and
362
- // the 404 branch below finishes with it before the throw is reached — so
363
- // reading it inside the throw surfaced `TypeError: Body is unusable`
364
- // instead of this function's documented message whenever a 404 fell
365
- // through. Reading up front also releases the connection on every path.
366
- const body = await res.text().catch(() => "");
367
- // Pyth 404s the ENTIRE batch if ANY id is unknown to the endpoint (a Core
368
- // feed absent from the Pyth Pro compat endpoint). This is on the money
369
- // path of every order/position/WLP tx-build, so instead of failing the
370
- // whole refresh: discover the unknown ids (catalog, else bisection — the
371
- // body isn't reliably delivered), memoize them, and re-fetch the survivors
372
- // as ONE clean batch (a single combined accumulator blob, which
373
- // buildPythPriceUpdateCalls requires). A genuinely-absent ticker just
374
- // isn't in the payload — its on-chain aggregate abstains/aborts, which is
375
- // correct. Steady state: once discovered, survivors are filtered up front
376
- // and this never runs. A rejection that looks endpoint-wide instead of
377
- // per-feed throws out of here (HermesEndpointRejectedAllFeedsError).
378
- if (res.status === 404) {
379
- // known404: this exact batch just 404'd above — skip the root re-probe.
380
- await discoverMissingFeeds(endpoint, ids, opts, true);
381
- const survivors = endpointSupportedFeedIds(endpoint, ids, opts?.apiKey);
382
- if (survivors.length === 0)
383
- return [];
384
- // survivors < ids ⇒ we removed the offender(s); re-fetch cleanly. Equal
385
- // ⇒ nothing was recorded (a 404 that wasn't a missing-feed rejection) —
386
- // surface it rather than loop.
387
- if (survivors.length < ids.length) {
388
- return fetchPriceFeedsUpdateData(endpoint, survivors, opts);
389
- }
390
- }
391
- throw new Error(`Hermes price fetch failed: ${res.status}${body ? ` ${body}` : ""}`);
392
- }
393
- const json = (await res.json());
394
- const data = json.binary?.data;
395
- if (!Array.isArray(data) || data.length === 0) {
396
- throw new Error("Hermes returned no binary price data");
397
- }
398
- return data.map((hex) => fromHex(hex));
399
- }
400
- // ============================================================================
401
- // On-chain helpers (cached)
402
- // ============================================================================
403
- function pkgFromUpgradeCap(json, objectId) {
404
- const upgradeCap = json.upgrade_cap ??
405
- json.fields?.upgrade_cap;
406
- const nested = upgradeCap?.fields?.package;
407
- const pkg = typeof upgradeCap?.package === "string"
408
- ? upgradeCap.package
409
- : typeof nested === "string"
410
- ? nested
411
- : undefined;
412
- if (!pkg)
413
- throw new Error(`Cannot resolve package id for object ${objectId}`);
414
- return pkg;
415
- }
416
- async function getPythStateInfo(client, pythStateId, cache) {
417
- if (cache?.pythStateInfo)
418
- return cache.pythStateInfo;
419
- const result = await client.getObject({ objectId: pythStateId, include: { json: true } });
420
- const json = result.object?.json;
421
- if (!json)
422
- throw new Error("Unable to fetch pyth state");
423
- const packageId = pkgFromUpgradeCap(json, pythStateId);
424
- const fields = json.fields;
425
- const fee = (fields?.base_update_fee ?? json.base_update_fee);
426
- if (fee === undefined)
427
- throw new Error("Unable to fetch pyth state base_update_fee");
428
- const info = { packageId, baseUpdateFee: BigInt(fee) };
429
- if (cache)
430
- cache.pythStateInfo = info;
431
- return info;
432
- }
433
- async function getWormholePackageId(client, wormholeStateId, cache) {
434
- if (cache?.wormholePackageId)
435
- return cache.wormholePackageId;
436
- const result = await client.getObject({ objectId: wormholeStateId, include: { json: true } });
437
- const json = result.object?.json;
438
- if (!json)
439
- throw new Error(`Cannot resolve wormhole package id from ${wormholeStateId}`);
440
- const pkg = pkgFromUpgradeCap(json, wormholeStateId);
441
- if (cache)
442
- cache.wormholePackageId = pkg;
443
- return pkg;
444
- }
445
- async function getPriceTableInfo(client, pythStateId, cache) {
446
- if (cache?.priceTableInfo)
447
- return cache.priceTableInfo;
448
- const list = await client.listDynamicFields({ parentId: pythStateId });
449
- const entry = list.dynamicFields.find((e) => {
450
- const vt = e.valueType || e.objectType || "";
451
- return vt.includes("PriceIdentifier") || vt.includes("price_info");
452
- });
453
- if (!entry)
454
- throw new Error("Price table not found in Pyth state dynamic fields");
455
- const childId = entry.childId ?? entry.objectId;
456
- const typeStr = entry.valueType || entry.objectType || "";
457
- if (!childId)
458
- throw new Error("Price table missing childId");
459
- const pkgMatch = typeStr.match(/(0x[a-fA-F0-9]+)::price_identifier::PriceIdentifier/);
460
- if (!pkgMatch)
461
- throw new Error(`Cannot extract package from price table type: ${typeStr}`);
462
- const info = { id: childId, fieldType: pkgMatch[1] };
463
- if (cache)
464
- cache.priceTableInfo = info;
465
- return info;
466
- }
467
- async function getPriceFeedObjectId(client, table, feedId, cache, pythStateId) {
468
- const normalized = feedId.replace(/^0x/, "");
469
- const cacheKey = `${pythStateId}:${normalized}`;
470
- if (cache?.priceFeedObjectIdCache.has(cacheKey)) {
471
- return cache.priceFeedObjectIdCache.get(cacheKey);
472
- }
473
- const keyBytes = bcs
474
- .struct("PriceIdentifier", { bytes: bcs.vector(bcs.u8()) })
475
- .serialize({ bytes: fromHex(normalized) })
476
- .toBytes();
477
- const result = await client.getDynamicField({
478
- parentId: table.id,
479
- name: { type: `${table.fieldType}::price_identifier::PriceIdentifier`, bcs: keyBytes },
480
- });
481
- const value = result.dynamicField?.value;
482
- const objectId = !value?.bcs || value.bcs.length < 32 ? undefined : "0x" + toHex(value.bcs);
483
- if (cache)
484
- cache.priceFeedObjectIdCache.set(cacheKey, objectId);
485
- return objectId;
486
- }
487
- // ============================================================================
488
- // Accumulator parsing
489
- // ============================================================================
490
- function extractVaaBytes(accumulatorMessage) {
491
- const view = new DataView(accumulatorMessage.buffer, accumulatorMessage.byteOffset, accumulatorMessage.byteLength);
492
- const trailingPayloadSize = view.getUint8(6);
493
- const vaaSizeOffset = 7 + trailingPayloadSize + 1; // +1 for proof_type
494
- const vaaSize = view.getUint16(vaaSizeOffset, false);
495
- const vaaOffset = vaaSizeOffset + 2;
496
- return accumulatorMessage.subarray(vaaOffset, vaaOffset + vaaSize);
497
- }
498
- /**
499
- * Thrown when no {@link OracleFeeSource} is available for the Pyth update fee
500
- * — from `buildPythPriceUpdateCalls`'s own per-call guard, or `aggregate.ts`'s
501
- * hoisted `refreshOraclePrices` pre-check (see its docblock). `instanceof`-able
502
- * (mirrors `FetchPolicyError` in `update-fetch.ts`) so a consumer — e.g. a BE
503
- * integration wiring its own `allowGasFee` decision — can branch on the error
504
- * type directly instead of string-matching `error.message`.
505
- */
506
- export class OracleFeeSourceUnavailableError extends Error {
507
- constructor() {
508
- super("OracleFeeSourceUnavailable: no fee source available for the Pyth update fee — " +
509
- "deploy pyth_sponsor_rule to config so a sponsor fund can be opened (see " +
510
- "openPythSponsorFund / wrapRequestAndExecute), or pass allowGasFee: true to draw " +
511
- "the fee from tx.gas in a non-sponsored context");
512
- this.name = "OracleFeeSourceUnavailableError";
513
- }
514
- }
515
- /**
516
- * Append the on-chain Pyth update PTB block. Returns `PriceInfoObject` IDs
517
- * (one per `feedIds`, same order). After this you can feed `pyth_rule` per
518
- * ticker against the matching `PriceInfoObject` (see `rules/pyth-rule.ts`).
519
- *
520
- * `opts.feeSource` is resolved BEFORE any PTB mutation and is never silently
521
- * defaulted — this function trusts whatever single {@link OracleFeeSource}
522
- * it's handed, it does not choose between competing candidates:
523
- * - `{ kind: 'sponsor' }` → the per-feed update fee is drawn from the
524
- * sponsor pool (`pyth_sponsor_rule::split`) instead of `tx.gas`. Opening
525
- * and reimbursing that fund is the caller's job (`rules/sponsor.ts` /
526
- * `wrapRequestAndExecute`, which opens it whenever the client's config
527
- * has `pyth_sponsor_rule` deployed) — this function only draws a fee
528
- * coin from the already-open `fund` hot potato.
529
- * - `{ kind: 'gas' }` → the fee is drawn from `tx.gas` via `tx.splitCoins`.
530
- * Only safe in a non-sponsored context — Enoki-sponsored transactions
531
- * reject any `tx.gas` draw.
532
- * - `undefined` → throws `OracleFeeSourceUnavailable` instead of silently
533
- * drawing from `tx.gas` (the old default), which broke under Enoki and,
534
- * worse, could fail ON-CHAIN when the market's `request_checklist`
535
- * requires the `PythSponsorRule` witness that only a real sponsor fund
536
- * attaches.
537
- *
538
- * This function's own check runs AFTER `updates`/`feedIds` are already in
539
- * hand, so for `updatePythPrices` (which fetches from Hermes, then calls
540
- * straight into this function) the off-chain fetch has already completed by
541
- * the time this throws — a wasted network call, never a stray PTB command.
542
- * `refreshOraclePrices` avoids that waste entirely: it hoists an EQUIVALENT
543
- * check ABOVE its off-chain fetch AND its per-group build loop (see its
544
- * docblock in `aggregate.ts`), keyed on `PriceUpdateRule.requiresFeeSource`
545
- * rather than waiting for a specific rule's fetch to complete — so for that
546
- * route neither the network call NOR any PTB command happens before the
547
- * throw. This function's own (later, per-call) guard alone could not
548
- * provide that "before any group builds" guarantee in a mixed shape (e.g. a
549
- * fee-free Lazer group ordered ahead of a Pyth Core fallback group in the
550
- * same PTB) — `refreshOraclePrices`'s pre-check is what closes it.
551
- */
552
- export async function buildPythPriceUpdateCalls(tx, host, updates, feedIds, opts) {
553
- if (updates.length === 0) {
554
- throw new Error("No price update data provided; Hermes returned empty results");
555
- }
556
- if (updates.length > 1) {
557
- throw new Error("Only a single accumulator message is supported per transaction");
558
- }
559
- const feeSource = opts?.feeSource;
560
- if (!feeSource) {
561
- throw new OracleFeeSourceUnavailableError();
562
- }
563
- const cache = opts?.cache;
564
- // Core on-chain infra is the `pyth_rule` source's own table, keyed by the
565
- // host's network — `client.pyth` carries only the caller's credential/policy.
566
- const pyth = PYTH_CORE_INFRA[host.network];
567
- const [stateInfo, wormholePackageId, table] = await Promise.all([
568
- getPythStateInfo(host.grpcClient, pyth.state_id, cache),
569
- getWormholePackageId(host.grpcClient, pyth.wormhole_state_id, cache),
570
- getPriceTableInfo(host.grpcClient, pyth.state_id, cache),
571
- ]);
572
- const priceInfoObjectIds = await Promise.all(feedIds.map((feedId) => getPriceFeedObjectId(host.grpcClient, table, feedId, cache, pyth.state_id)));
573
- const { packageId: pythPackageId, baseUpdateFee } = stateInfo;
574
- // 1. Verify VAA
575
- const vaa = extractVaaBytes(updates[0]);
576
- const [verifiedVaa] = tx.moveCall({
577
- target: `${wormholePackageId}::vaa::parse_and_verify`,
578
- arguments: [tx.object(pyth.wormhole_state_id), tx.pure.vector("u8", vaa), tx.object.clock()],
579
- });
580
- // 2. Authenticate price infos
581
- const [hotPotato0] = tx.moveCall({
582
- target: `${pythPackageId}::pyth::create_authenticated_price_infos_using_accumulator`,
583
- arguments: [
584
- tx.object(pyth.state_id),
585
- tx.pure.vector("u8", updates[0]),
586
- verifiedVaa,
587
- tx.object.clock(),
588
- ],
589
- });
590
- // 3. Per-feed update
591
- let hotPotato = hotPotato0;
592
- for (let i = 0; i < feedIds.length; i++) {
593
- const priceInfoObjectId = priceInfoObjectIds[i];
594
- if (!priceInfoObjectId) {
595
- throw new Error(`Pyth feed ${feedIds[i]} not registered on-chain in Pyth state`);
596
- }
597
- const feeCoin = feeSource.kind === "sponsor"
598
- ? tx.moveCall({
599
- target: `${feeSource.packageId}::pyth_sponsor_rule::split`,
600
- arguments: [feeSource.fund],
601
- })[0]
602
- : tx.splitCoins(tx.gas, [tx.pure.u64(baseUpdateFee)])[0];
603
- [hotPotato] = tx.moveCall({
604
- target: `${pythPackageId}::pyth::update_single_price_feed`,
605
- arguments: [
606
- tx.object(pyth.state_id),
607
- hotPotato,
608
- tx.object(priceInfoObjectId),
609
- feeCoin,
610
- tx.object.clock(),
611
- ],
612
- });
613
- }
614
- // 4. Destroy hot potato
615
- tx.moveCall({
616
- target: `${pythPackageId}::hot_potato_vector::destroy`,
617
- arguments: [hotPotato],
618
- typeArguments: [`${pythPackageId}::price_info::PriceInfo`],
619
- });
620
- return priceInfoObjectIds;
621
- }
622
- /** All-in-one: fetch from Hermes, append update calls. Returns PriceInfoObject IDs. */
623
- export async function updatePythPrices(tx, host, feedIds, opts) {
624
- // The Core source's own Hermes endpoint (per-network, rule-owned table);
625
- // credential + fetch policy are the caller-supplied `client.pyth` slice.
626
- const endpoint = PYTH_CORE_INFRA[host.network].hermes_endpoint;
627
- const updates = await fetchPriceFeedsUpdateData(endpoint, feedIds, {
628
- apiKey: host.pyth.api_key,
629
- fetch: host.pyth.fetch,
630
- });
631
- // Align feedIds with the feeds the endpoint actually served — the fetch drops
632
- // (and memoizes) any it lacks, and `buildPythPriceUpdateCalls` emits one
633
- // update call per feedId, so a dropped feed would reference a PriceInfoObject
634
- // the accumulator blob doesn't cover (invalid PTB / on-chain abort). Mirrors
635
- // `PythCoreRule.fetchUpdateData`.
636
- const servedFeedIds = endpointSupportedFeedIds(endpoint, feedIds, host.pyth.api_key);
637
- return buildPythPriceUpdateCalls(tx, host, updates, servedFeedIds, opts);
638
- }
@@ -1,15 +0,0 @@
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;