@waterx/sdk 3.1.0 → 4.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 (86) hide show
  1. package/README.md +53 -7
  2. package/dist/cjs/src/oracle/aggregate.d.ts +98 -17
  3. package/dist/cjs/src/oracle/aggregate.js +191 -21
  4. package/dist/cjs/src/oracle/config.d.ts +103 -0
  5. package/dist/cjs/src/oracle/config.js +64 -1
  6. package/dist/cjs/src/oracle/host.d.ts +13 -0
  7. package/dist/cjs/src/oracle/index.d.ts +19 -5
  8. package/dist/cjs/src/oracle/index.js +40 -6
  9. package/dist/cjs/src/oracle/price-update-rule.d.ts +180 -0
  10. package/dist/cjs/src/oracle/price-update-rule.js +56 -0
  11. package/dist/cjs/src/oracle/pyth.d.ts +80 -11
  12. package/dist/cjs/src/oracle/pyth.js +84 -17
  13. package/dist/cjs/src/oracle/rule-registry.d.ts +37 -0
  14. package/dist/cjs/src/oracle/rule-registry.js +61 -0
  15. package/dist/cjs/src/oracle/rules/pyth-core-rule.d.ts +15 -0
  16. package/dist/cjs/src/oracle/rules/pyth-core-rule.js +84 -0
  17. package/dist/cjs/src/oracle/rules/pyth-lazer-rule.d.ts +41 -0
  18. package/dist/cjs/src/oracle/rules/pyth-lazer-rule.js +194 -0
  19. package/dist/cjs/src/oracle/rules/sponsor.d.ts +11 -7
  20. package/dist/cjs/src/oracle/rules/sponsor.js +11 -7
  21. package/dist/cjs/src/oracle/update-fetch.d.ts +85 -0
  22. package/dist/cjs/src/oracle/update-fetch.js +228 -0
  23. package/dist/cjs/src/perp/client.d.ts +22 -1
  24. package/dist/cjs/src/perp/client.js +11 -2
  25. package/dist/cjs/src/perp/config.d.ts +15 -20
  26. package/dist/cjs/src/perp/config.js +86 -30
  27. package/dist/cjs/src/perp/index.d.ts +4 -3
  28. package/dist/cjs/src/perp/index.js +8 -4
  29. package/dist/cjs/src/perp/tx-builders/common.d.ts +52 -15
  30. package/dist/cjs/src/perp/tx-builders/common.js +39 -6
  31. package/dist/cjs/src/perp/tx-builders/wlp.d.ts +11 -3
  32. package/dist/cjs/src/perp/tx-builders/wlp.js +29 -3
  33. package/dist/cjs/src/perp/tx-builders.d.ts +3 -3
  34. package/dist/cjs/src/perp/tx-builders.js +3 -3
  35. package/dist/cjs/src/prediction/config.d.ts +5 -15
  36. package/dist/cjs/src/prediction/config.js +4 -12
  37. package/dist/cjs/src/prediction/fetch.d.ts +6 -1
  38. package/dist/cjs/src/prediction/fetch.js +64 -0
  39. package/dist/cjs/src/prediction/index.d.ts +2 -2
  40. package/dist/cjs/src/prediction/index.js +7 -4
  41. package/dist/cjs/src/prediction/types.d.ts +19 -0
  42. package/dist/cjs/src/unified-client.d.ts +26 -4
  43. package/dist/cjs/src/unified-client.js +4 -2
  44. package/dist/src/oracle/aggregate.d.ts +98 -17
  45. package/dist/src/oracle/aggregate.js +192 -22
  46. package/dist/src/oracle/config.d.ts +103 -0
  47. package/dist/src/oracle/config.js +63 -0
  48. package/dist/src/oracle/host.d.ts +13 -0
  49. package/dist/src/oracle/index.d.ts +19 -5
  50. package/dist/src/oracle/index.js +34 -6
  51. package/dist/src/oracle/price-update-rule.d.ts +180 -0
  52. package/dist/src/oracle/price-update-rule.js +53 -0
  53. package/dist/src/oracle/pyth.d.ts +80 -11
  54. package/dist/src/oracle/pyth.js +82 -16
  55. package/dist/src/oracle/rule-registry.d.ts +37 -0
  56. package/dist/src/oracle/rule-registry.js +56 -0
  57. package/dist/src/oracle/rules/pyth-core-rule.d.ts +15 -0
  58. package/dist/src/oracle/rules/pyth-core-rule.js +81 -0
  59. package/dist/src/oracle/rules/pyth-lazer-rule.d.ts +41 -0
  60. package/dist/src/oracle/rules/pyth-lazer-rule.js +189 -0
  61. package/dist/src/oracle/rules/sponsor.d.ts +11 -7
  62. package/dist/src/oracle/rules/sponsor.js +11 -7
  63. package/dist/src/oracle/update-fetch.d.ts +85 -0
  64. package/dist/src/oracle/update-fetch.js +223 -0
  65. package/dist/src/perp/client.d.ts +22 -1
  66. package/dist/src/perp/client.js +12 -3
  67. package/dist/src/perp/config.d.ts +15 -20
  68. package/dist/src/perp/config.js +85 -29
  69. package/dist/src/perp/index.d.ts +4 -3
  70. package/dist/src/perp/index.js +2 -2
  71. package/dist/src/perp/tx-builders/common.d.ts +52 -15
  72. package/dist/src/perp/tx-builders/common.js +39 -6
  73. package/dist/src/perp/tx-builders/wlp.d.ts +11 -3
  74. package/dist/src/perp/tx-builders/wlp.js +29 -3
  75. package/dist/src/perp/tx-builders.d.ts +3 -3
  76. package/dist/src/perp/tx-builders.js +3 -3
  77. package/dist/src/prediction/config.d.ts +5 -15
  78. package/dist/src/prediction/config.js +4 -11
  79. package/dist/src/prediction/fetch.d.ts +6 -1
  80. package/dist/src/prediction/fetch.js +60 -0
  81. package/dist/src/prediction/index.d.ts +2 -2
  82. package/dist/src/prediction/index.js +2 -2
  83. package/dist/src/prediction/types.d.ts +19 -0
  84. package/dist/src/unified-client.d.ts +26 -4
  85. package/dist/src/unified-client.js +4 -2
  86. package/package.json +1 -1
@@ -2,38 +2,98 @@
2
2
  * Oracle aggregation — the orchestrator that composes rules into the shared
3
3
  * `Oracle`. This is the ONE file that knows about every rule: it builds a
4
4
  * `PriceCollector`, feeds whichever rules a ticker is configured for
5
- * (Pyth / Supra / Constant), then `aggregate`s.
5
+ * (Pyth / Lazer / Supra / Constant), then `aggregate`s.
6
6
  *
7
7
  * Per ticker:
8
8
  * collector = oracle::new_collector(ticker)
9
9
  * [pyth_rule::feed] when the ticker has a pyth_rule.feeds entry
10
+ * [pyth_lazer_rule::feed] when the update leg produced a verified lazer Update
10
11
  * [supra_rule::feed] when supra is enabled + wired
11
12
  * [constant_rule::feed] when the ticker is a constant ticker
12
13
  * oracle::aggregate(oracle, collector)
13
14
  *
14
- * The fed rule set must match the on-chain weighted set for the ticker —
15
+ * The fed rule set must cover the on-chain weighted set for the ticker —
15
16
  * `aggregator::remove_outliers` aborts `EMissingPriceSource` if a weighted rule
16
- * is missing from the collector.
17
+ * is missing from the collector (an abstaining feed call counts as present;
18
+ * a fed-but-unweighted rule is silently dropped).
19
+ *
20
+ * `refreshOraclePrices` additionally routes the on-chain price *update* leg
21
+ * (the fetch + verify/push step, before any of the above feeding) through the
22
+ * `PriceUpdateRule` selected by `host.oracleSource` — see `rule-registry.ts`.
17
23
  */
18
24
  import { aggregate as aggregateCall, newCollector } from "../generated/waterx_oracle/oracle.js";
19
- import { updatePythPrices } from "./pyth.js";
25
+ import { OracleFeeSourceUnavailableError } from "./pyth.js";
26
+ import { resolveOracleRule } from "./rule-registry.js";
20
27
  import { feedConstantRule } from "./rules/constant-rule.js";
28
+ import { feedLazerRule } from "./rules/pyth-lazer-rule.js";
21
29
  import { feedPythRule } from "./rules/pyth-rule.js";
22
30
  import { maybeFeedSupra } from "./rules/supra-rule.js";
31
+ /**
32
+ * Resolve one group's off-chain update payload for {@link refreshOraclePrices}:
33
+ * try `provider.get(source, tickers)` first (when a provider is configured),
34
+ * falling back to the group's own live `rule.fetchUpdateData` on a cache miss
35
+ * (`null`) or a throw from the provider — a broken/degraded cache must never
36
+ * break the money path.
37
+ *
38
+ * A cache HIT is treated as a payload for a POSSIBLY-WIDER ticker set (a
39
+ * provider commonly caches one whole-universe payload per source — see
40
+ * {@link UpdateDataProvider}), so it is narrowed to exactly `group.tickers`
41
+ * via `rule.narrowUpdateData` before use. This is load-bearing, not
42
+ * defensive: without it a Pyth Core hit would emit an
43
+ * `update_single_price_feed` — and charge its fee — for every cached feed
44
+ * instead of just this group's, and a payload that cannot cover the group
45
+ * (`narrowUpdateData` → `null`) would never reach the live-fetch fallback.
46
+ * Each rule owns its own subsetting (Core subsets per-feed entries; Lazer's
47
+ * indivisible payload passes whole iff fully covered), so the orchestrator
48
+ * never branches on `kind` here. A hit whose `kind` doesn't match the
49
+ * group's rule is a caller bug (the provider handed back a different rule's
50
+ * payload), so that throws — via `narrowUpdateData`'s own
51
+ * `assertRuleUpdateData` guard — instead of silently falling back.
52
+ */
53
+ async function resolveGroupUpdateData(host, group, provider) {
54
+ if (provider) {
55
+ let cached = null;
56
+ try {
57
+ cached = await provider.get(group.source, group.tickers);
58
+ }
59
+ catch {
60
+ // Provider errors must never break the money path — fall through to
61
+ // the live fetch below exactly as a cache miss (`null`) would.
62
+ }
63
+ if (cached !== null) {
64
+ // Wrong-kind hit throws inside narrowUpdateData (assertRuleUpdateData);
65
+ // a hit that can't cover the group narrows to null → live-fetch below.
66
+ const narrowed = group.rule.narrowUpdateData(host, cached, group.tickers);
67
+ if (narrowed !== null)
68
+ return narrowed;
69
+ }
70
+ }
71
+ return group.rule.fetchUpdateData(host, group.tickers);
72
+ }
23
73
  /**
24
74
  * Aggregate one ticker's price into the shared `Oracle`: build a collector, feed
25
75
  * every rule the ticker is configured for, then `aggregate`.
26
76
  *
27
77
  * - **Pyth** — fed when `priceInfoObjectId` is supplied (i.e. the ticker has a
28
- * `pyth_rule.feeds` entry). Caller must run the Pyth update first so the
29
- * `PriceInfoObject` is fresh.
30
- * - **Supra** fed alongside Pyth when supra is enabled + wired (abstains
31
- * on-chain for symbols it has no pair for).
78
+ * `pyth_rule.feeds` entry). When this PTB's update leg refreshed the
79
+ * `PriceInfoObject` it contributes a fresh price; when it did not (a
80
+ * lazer-routed ticker), the on-chain rule only READS the object and abstains
81
+ * if it is stale — it never aborts so the call stays mandatory while
82
+ * `pyth_rule` remains in the ticker's on-chain weighted set
83
+ * (`EMissingPriceSource` requires every weighted rule to appear).
84
+ * - **Lazer** — fed when `lazerUpdate` is supplied: the verified
85
+ * `pyth_lazer::update::Update` produced by this PTB's lazer update leg
86
+ * (see `PythLazerRule.buildUpdateCalls`). If the ticker's aggregator does
87
+ * not (yet) weight `PythLazerRule`, the contribution is silently dropped
88
+ * on-chain — feeding ahead of the weight migration is harmless.
89
+ * - **Supra** — fed alongside Pyth/Lazer when supra is enabled + wired
90
+ * (abstains on-chain for symbols it has no pair for).
32
91
  * - **Constant** — fed when the ticker is a constant ticker
33
92
  * ({@link OracleHost.isConstantTicker}).
34
93
  *
35
- * "Dual-feed" (Pyth + Constant) and "constant-only" are not special cases — they
36
- * fall out of which rules the ticker is in. Throws if no rule applies.
94
+ * "Dual-feed" (Pyth + Constant, or Pyth + Lazer) and "constant-only" are not
95
+ * special cases — they fall out of which rules the ticker is in. Throws if no
96
+ * rule applies.
37
97
  */
38
98
  export function aggregateTicker(tx, host, args) {
39
99
  const oraclePkg = host.config.packages.waterx_oracle.published_at;
@@ -44,16 +104,22 @@ export function aggregateTicker(tx, host, args) {
44
104
  let fed = false;
45
105
  if (args.priceInfoObjectId) {
46
106
  feedPythRule(tx, host, collector, args.priceInfoObjectId);
107
+ fed = true;
108
+ }
109
+ if (args.lazerUpdate !== undefined) {
110
+ feedLazerRule(tx, host, collector, args.lazerUpdate);
111
+ fed = true;
112
+ }
113
+ if (fed) {
47
114
  // Supra rides on the same collector when enabled (abstains on-chain otherwise).
48
115
  maybeFeedSupra(tx, host, collector);
49
- fed = true;
50
116
  }
51
117
  if (host.isConstantTicker(args.ticker)) {
52
118
  feedConstantRule(tx, host, collector);
53
119
  fed = true;
54
120
  }
55
121
  if (!fed) {
56
- throw new Error(`no oracle rule configured for ticker '${args.ticker}' (no pyth feed, not a constant ticker)`);
122
+ throw new Error(`no oracle rule configured for ticker '${args.ticker}' (no pyth feed, no lazer update, not a constant ticker)`);
57
123
  }
58
124
  aggregateCall({
59
125
  package: oraclePkg,
@@ -89,24 +155,128 @@ export function aggregateTickerWithConstant(tx, host, args) {
89
155
  /**
90
156
  * Refresh multiple tickers in one PTB. For each ticker {@link aggregateTicker}
91
157
  * feeds whichever rules it is configured for (Pyth if it has a `pyth_rule.feeds`
92
- * entry, Supra when enabled, Constant when it's a constant ticker). Tickers with a
93
- * Pyth feed are updated on-chain via one shared Pyth accumulator first; the rest
94
- * (constant-only) skip Pyth entirely.
158
+ * entry, Lazer if the lazer update leg served it see below Supra when
159
+ * enabled, Constant when it's a constant ticker).
160
+ *
161
+ * Before that, the on-chain price *update* leg is routed by `host.oracleSource`
162
+ * (see `rule-registry.ts`): the selected rule serves every ticker in its
163
+ * `supportedTickers(host)`; tickers it doesn't cover fall back to `pyth_rule`
164
+ * (`PythCoreRule`) when THEY support it — so when `oracleSource` IS `'pyth_rule'`
165
+ * there is exactly one group, identical to the pre-routing behavior. A ticker
166
+ * supported by neither is simply skipped from this leg (no fetch/build call for
167
+ * it) — the same way today's non-pyth tickers (e.g. constant-only) always were;
168
+ * it still gets aggregated below via whichever rule {@link aggregateTicker} finds.
169
+ *
170
+ * Each group's fetch + build runs against its own rule, which guarantees
171
+ * per-rule PTB atomicity (no mixed-generation payload within one rule's calls).
172
+ * When `oracleSource` isn't `'pyth_rule'`, one PTB may legitimately carry BOTH a
173
+ * non-Pyth-Core block (selected group) and a Pyth Core block (fallback group) —
174
+ * each verifies against its own contract objects, so that's fine. A fee-source
175
+ * pre-check runs first, across every group's `requiresFeeSource` — BEFORE any
176
+ * off-chain fetch or PTB mutation — so a fee-charging group with no
177
+ * `opts.feeSource` throws `OracleFeeSourceUnavailable` with zero wasted
178
+ * network calls and zero stray moveCalls, even in a mixed shape (e.g. a
179
+ * fee-free Lazer group ordered ahead of a Pyth Core fallback group). Only once
180
+ * that check passes do all groups' off-chain fetches run concurrently
181
+ * (`Promise.all`) and complete before any PTB mutation; on-chain reads inside
182
+ * `buildUpdateCalls` can still fail mid-append for other reasons — callers
183
+ * discard the tx on any throw.
184
+ *
185
+ * **Collector-feed leg is rule-aware:** a lazer-served group's
186
+ * `buildUpdateCalls` returns the verified `Update` PTB value
187
+ * ({@link RuleUpdateHandle}), and every ticker in that group is aggregated
188
+ * with `lazerUpdate` set so {@link aggregateTicker} appends
189
+ * `pyth_lazer_rule::feed` against it. A lazer-routed ticker that still has a
190
+ * `pyth_rule.feeds` entry ALSO keeps its `pyth_rule::feed` leg — required
191
+ * on-chain while `pyth_rule` stays in the ticker's weighted set
192
+ * (`aggregator::remove_outliers` aborts `EMissingPriceSource` unless every
193
+ * weighted rule appears in the collector; an abstention counts as
194
+ * appearing), and safe: `pyth_rule::feed` only READS the `PriceInfoObject`
195
+ * this PTB never refreshed and abstains when it is stale rather than
196
+ * aborting. Conversely, a lazer feed call on an aggregator that does not
197
+ * (yet) weight `PythLazerRule` is silently dropped on-chain — so
198
+ * lazer-routing a ticker ahead of its on-chain weight migration prices it
199
+ * from the remaining weighted rules instead of failing.
95
200
  */
96
201
  export async function refreshOraclePrices(tx, host, tickers, opts = {}) {
97
202
  if (tickers.length === 0)
98
203
  return;
99
- // Every ticker with a pyth_rule.feeds entry needs the on-chain Pyth update
100
- // first (one shared accumulator). Constant-only tickers (no pyth feed) skip it.
204
+ // price_info_object lookup for every ticker with a pyth_rule.feeds entry
205
+ // needed by aggregateTicker's (unchanged) Pyth feed step below regardless of
206
+ // which rule performed the on-chain update for that ticker.
101
207
  const pythTickers = tickers.filter((t) => host.config.packages.pyth_rule?.feeds?.[t] !== undefined);
102
208
  const priceInfoByTicker = new Map();
103
- if (pythTickers.length > 0) {
104
- const entries = pythTickers.map((t) => host.getPythFeed(t));
105
- await updatePythPrices(tx, host, entries.map((e) => e.feed_id), opts.cache, opts.sponsorFund);
106
- pythTickers.forEach((t, i) => priceInfoByTicker.set(t, entries[i].price_info_object));
209
+ pythTickers.forEach((t) => priceInfoByTicker.set(t, host.getPythFeed(t).price_info_object));
210
+ // Group tickers for the on-chain update leg: selected rule first, then the
211
+ // pyth_rule fallback for whatever the selected rule doesn't cover. `source`
212
+ // is tracked alongside each group (rather than read back off `rule.kind`,
213
+ // which is typed as the broader PriceUpdateRuleKind) so the provider lookup
214
+ // below has an OracleSource to key on without a cast.
215
+ const selectedRule = resolveOracleRule(host.oracleSource, opts.ruleOverrides);
216
+ const selectedSupported = new Set(selectedRule.supportedTickers(host));
217
+ const selectedGroup = tickers.filter((t) => selectedSupported.has(t));
218
+ const groups = [];
219
+ if (selectedGroup.length > 0) {
220
+ groups.push({ source: host.oracleSource, rule: selectedRule, tickers: selectedGroup });
221
+ }
222
+ if (host.oracleSource !== "pyth_rule") {
223
+ const fallbackRule = resolveOracleRule("pyth_rule", opts.ruleOverrides);
224
+ const fallbackSupported = new Set(fallbackRule.supportedTickers(host));
225
+ const fallbackGroup = tickers.filter((t) => !selectedSupported.has(t) && fallbackSupported.has(t));
226
+ if (fallbackGroup.length > 0) {
227
+ groups.push({ source: "pyth_rule", rule: fallbackRule, tickers: fallbackGroup });
228
+ }
229
+ }
230
+ // Fee-source pre-check, hoisted ABOVE both the off-chain fetch below AND
231
+ // the per-group build loop further down. The condition only consults
232
+ // `group.rule.requiresFeeSource` — known the moment `groups` is built,
233
+ // before any fetch or PTB mutation — so this throws with ZERO wasted
234
+ // network calls and zero PTB commands. A per-call guard inside
235
+ // `buildPythPriceUpdateCalls` alone would not be early enough: in a mixed
236
+ // shape (e.g. a lazer-selected `oracleSource` with a `pyth_rule` fallback
237
+ // group for tickers Lazer doesn't cover), the build loop runs each
238
+ // group's `buildUpdateCalls` in sequence — a fee-free group ordered ahead
239
+ // of a fee-charging one would already have appended its verify/feed
240
+ // moveCalls to the shared `tx` by the time the fee-charging group's own
241
+ // guard fired, breaking the "throw before any PTB mutation" guarantee.
242
+ // Checking every group's `requiresFeeSource` up front — before ANY group
243
+ // fetches or builds — closes that gap, and (unlike a referential check
244
+ // against a specific rule instance) keeps protecting a future
245
+ // fee-charging rule or a test double standing in for one.
246
+ if (!opts.feeSource && groups.some((group) => group.rule.requiresFeeSource)) {
247
+ throw new OracleFeeSourceUnavailableError();
248
+ }
249
+ // Fetch every group's off-chain payload concurrently (independent network
250
+ // calls — no reason to serialize) and let ALL of them settle before the
251
+ // first PTB mutation below, so a later group's fetch failure can never
252
+ // leave an earlier group's moveCalls stranded in a caller-owned tx.
253
+ const groupsWithData = await Promise.all(groups.map(async (group) => ({
254
+ rule: group.rule,
255
+ tickers: group.tickers,
256
+ data: await resolveGroupUpdateData(host, group, opts.updateDataProvider),
257
+ })));
258
+ // Verified-`Update` handle per lazer-served ticker (one shared PTB value per
259
+ // group) — consumed by the collector-feed leg below.
260
+ const lazerUpdateByTicker = new Map();
261
+ for (const group of groupsWithData) {
262
+ const handle = (await group.rule.buildUpdateCalls(tx, host, group.data, {
263
+ cache: opts.cache,
264
+ feeSource: opts.feeSource,
265
+ })) ?? undefined;
266
+ // Route by the handle's kind discriminant — the one site the tag exists to
267
+ // protect: a future non-lazer handle (e.g. a WaterxRule value) must never
268
+ // be silently fed into pyth_lazer_rule::feed.
269
+ if (handle?.kind === "pyth_lazer_rule") {
270
+ for (const ticker of group.tickers)
271
+ lazerUpdateByTicker.set(ticker, handle.update);
272
+ }
107
273
  }
108
274
  // Aggregate each ticker, feeding whichever rules it is configured for.
109
275
  for (const ticker of tickers) {
110
- aggregateTicker(tx, host, { ticker, priceInfoObjectId: priceInfoByTicker.get(ticker) });
276
+ aggregateTicker(tx, host, {
277
+ ticker,
278
+ priceInfoObjectId: priceInfoByTicker.get(ticker),
279
+ lazerUpdate: lazerUpdateByTicker.get(ticker),
280
+ });
111
281
  }
112
282
  }
@@ -22,6 +22,24 @@ export interface PythRulePackage extends BasePackageEntry {
22
22
  export interface PythSponsorRulePackage extends BasePackageEntry {
23
23
  pyth_sponsor: string;
24
24
  }
25
+ /**
26
+ * `pyth_lazer_rule` deployment entry — present in the deployed testnet
27
+ * `waterx-config` JSON. Read by `PythLazerRule` (`rules/pyth-lazer-rule.ts`):
28
+ * `feeds` for ticker support + integer feed-id resolution, `state` for the
29
+ * verify call, `published_at`/`config` for the per-ticker feed call.
30
+ *
31
+ * `enabled` mirrors the JSON field verbatim but MUST NOT be read for routing —
32
+ * which rule prices a ticker is decided solely by the client's `oracleSource`
33
+ * create option (see `OracleHost.oracleSource`), never by this flag or any
34
+ * other config value.
35
+ */
36
+ export interface PythLazerRulePackage extends BasePackageEntry {
37
+ config: string;
38
+ state: string;
39
+ enabled?: boolean;
40
+ /** Oracle ticker → integer Pyth Lazer feed id (distinct id scheme from `pyth_rule`'s hex `feed_id`). */
41
+ feeds: Record<string, number>;
42
+ }
25
43
  /** Per-ticker `constant_rule` feed entry (mirrors the `pyth_rule.feeds` shape). */
26
44
  export interface ConstantFeedEntry {
27
45
  /**
@@ -77,6 +95,8 @@ export interface WaterxOraclePackage extends BasePackageEntry {
77
95
  export interface OraclePackages {
78
96
  pyth_rule: PythRulePackage;
79
97
  pyth_sponsor_rule?: PythSponsorRulePackage;
98
+ /** See {@link PythLazerRulePackage} — typed only, not read for routing. */
99
+ pyth_lazer_rule?: PythLazerRulePackage;
80
100
  constant_rule?: WaterxConstantRulePackage;
81
101
  supra_rule?: SupraRulePackage;
82
102
  waterx_oracle: WaterxOraclePackage;
@@ -85,8 +105,91 @@ export interface PythInfraConfig {
85
105
  state_id: string;
86
106
  wormhole_state_id: string;
87
107
  hermes_endpoint: string;
108
+ /**
109
+ * Pyth Pro / Lazer access token (`Authorization: Bearer …`) for
110
+ * `PythLazerRule`'s signed-update fetch — Lazer is auth-first, so there is
111
+ * no keyless default. Optional: Pyth-Core-only deployments never need it.
112
+ * Consumers pass it through client config (`config.pyth`); the SDK never
113
+ * reads `process.env`. Absent when a lazer-routed fetch runs →
114
+ * `LazerApiKeyMissing` is thrown at fetch time. As of the Pyth Pro
115
+ * migration (post-2026-08-18, per
116
+ * https://docs.pyth.network/price-feeds/core/upgrade) this is ALSO required
117
+ * for `pyth_rule`'s Hermes fetch (`fetchPriceFeedsUpdateData`) — see
118
+ * `fetch` below.
119
+ */
120
+ api_key?: string;
121
+ /**
122
+ * Retry/timeout policy override for the Hermes (`fetchPriceFeedsUpdateData`)
123
+ * and Lazer (`PythLazerRule`) off-chain update fetches — see
124
+ * `fetchWithPolicy` (`./update-fetch.ts`) for the full policy (backoff,
125
+ * which statuses retry, Bearer attachment). Optional: both fetches default
126
+ * to `fetchWithPolicy`'s built-in defaults (15s timeout, 2 retries) when
127
+ * unset.
128
+ */
129
+ fetch?: {
130
+ timeoutMs?: number;
131
+ retries?: number;
132
+ };
88
133
  }
89
134
  export declare const PYTH_DEFAULTS: Record<Network, PythInfraConfig>;
135
+ /**
136
+ * Which Pyth Core contract generation feeds `host.pyth` when the config JSON
137
+ * carries no explicit `pyth` override:
138
+ *
139
+ * - `'core'` (default) — the original contracts + keyless Hermes
140
+ * ({@link PYTH_DEFAULTS}).
141
+ * - `'pro'` — the Pro-compatible upgraded contracts + the Hermes-compatible
142
+ * endpoint ({@link PYTH_PRO_DEFAULTS}); pair with `pyth.api_key` after the
143
+ * 2026-08-18 cutover.
144
+ *
145
+ * Resolved once at client creation from the `pythGeneration` create option.
146
+ * Orthogonal to `oracleSource` — this flips the Pyth-Core *infra* (state ids
147
+ * + endpoint), not which `PriceUpdateRule` routes tickers.
148
+ */
149
+ export type PythGeneration = "core" | "pro";
150
+ /**
151
+ * Pyth **Pro-generation** Core-compatible infra — the post-2026-08-18
152
+ * contracts (cutover date per
153
+ * https://docs.pyth.network/price-feeds/core/upgrade) from Pyth's Core-Upgrade
154
+ * docs
155
+ * (https://docs.pyth.network/price-feeds/core/upgrade/contracts, Sui section;
156
+ * package revs `sui-pro-compatible-contract-mainnet` /
157
+ * `sui-pro-compatible-contract-testnet`). Selected via the client's
158
+ * `pythGeneration: 'pro'` create option; `config.pyth` still overrides
159
+ * wholesale (see `PerpClient`). All four state ids were verified on-chain
160
+ * (shared `state::State` objects under the docs' upgraded package ids).
161
+ *
162
+ * Kept as a second flat map beside {@link PYTH_DEFAULTS} rather than a nested
163
+ * `PYTH_INFRA[network][generation]` — `PYTH_DEFAULTS` is a published export
164
+ * with external consumers, so the smallest honest surface is an additive
165
+ * sibling (same deferral note as {@link LAZER_DEFAULTS}).
166
+ *
167
+ * The Hermes-compatible endpoint (`pyth.dourolabs.app/hermes`) serves the
168
+ * same REST surface as `hermes.pyth.network` but requires `pyth.api_key`
169
+ * (`Authorization: Bearer …`) after the cutover — see
170
+ * {@link PythInfraConfig.api_key}.
171
+ */
172
+ export declare const PYTH_PRO_DEFAULTS: Record<Network, PythInfraConfig>;
173
+ /**
174
+ * Pyth Lazer (Pyth Pro) external infra the `PythLazerRule` needs, by network.
175
+ * Mirrors {@link PYTH_DEFAULTS}: per-network constants for infrastructure Pyth
176
+ * operates (not part of the `waterx-config` JSON). A fuller `PYTH_INFRA`
177
+ * restructure is deferred — this stays a minimal map until then.
178
+ *
179
+ * - `endpoint` — Lazer HTTP API base; signed updates come from
180
+ * `POST /v1/latest_price` (Bearer-authenticated). The service is
181
+ * network-agnostic (one signed payload verifies on any chain that trusts the
182
+ * Lazer signers), so both networks share the production host.
183
+ * - `verifier_package` — the Sui package carrying
184
+ * `pyth_lazer::parse_and_verify_le_ecdsa_update`. Per-network: testnet is
185
+ * still the original v1 publish; mainnet is the v2-upgraded package (which
186
+ * still exposes the v1 entry `pyth_lazer_rule` binds). Values mirror the
187
+ * contract repo's `pyth_lazer_rule/Move.toml` published-at pins.
188
+ */
189
+ export declare const LAZER_DEFAULTS: Record<Network, {
190
+ endpoint: string;
191
+ verifier_package: string;
192
+ }>;
90
193
  /**
91
194
  * The narrow config shape the oracle/refresh code needs. `WaterXConfig`
92
195
  * (the perp line's full config) is assignable to this, so `PerpClient` satisfies
@@ -21,3 +21,66 @@ export const PYTH_DEFAULTS = {
21
21
  hermes_endpoint: "https://hermes-beta.pyth.network",
22
22
  },
23
23
  };
24
+ /**
25
+ * Pyth **Pro-generation** Core-compatible infra — the post-2026-08-18
26
+ * contracts (cutover date per
27
+ * https://docs.pyth.network/price-feeds/core/upgrade) from Pyth's Core-Upgrade
28
+ * docs
29
+ * (https://docs.pyth.network/price-feeds/core/upgrade/contracts, Sui section;
30
+ * package revs `sui-pro-compatible-contract-mainnet` /
31
+ * `sui-pro-compatible-contract-testnet`). Selected via the client's
32
+ * `pythGeneration: 'pro'` create option; `config.pyth` still overrides
33
+ * wholesale (see `PerpClient`). All four state ids were verified on-chain
34
+ * (shared `state::State` objects under the docs' upgraded package ids).
35
+ *
36
+ * Kept as a second flat map beside {@link PYTH_DEFAULTS} rather than a nested
37
+ * `PYTH_INFRA[network][generation]` — `PYTH_DEFAULTS` is a published export
38
+ * with external consumers, so the smallest honest surface is an additive
39
+ * sibling (same deferral note as {@link LAZER_DEFAULTS}).
40
+ *
41
+ * The Hermes-compatible endpoint (`pyth.dourolabs.app/hermes`) serves the
42
+ * same REST surface as `hermes.pyth.network` but requires `pyth.api_key`
43
+ * (`Authorization: Bearer …`) after the cutover — see
44
+ * {@link PythInfraConfig.api_key}.
45
+ */
46
+ export const PYTH_PRO_DEFAULTS = {
47
+ MAINNET: {
48
+ state_id: "0x03719fae774ddab3cfcaa53bbc046f0cbe21410019b6280811bf3f9f4b05839d",
49
+ wormhole_state_id: "0xdbca52b9fb4f712e25f61f974586d93ac541bcf8389564f0323bb07215168b5c",
50
+ hermes_endpoint: "https://pyth.dourolabs.app/hermes",
51
+ },
52
+ TESTNET: {
53
+ state_id: "0x3c48fe392912de6c18087a2b3f5fdbfbfdb4598e180947feff1f12f8e9ea073e",
54
+ wormhole_state_id: "0x750da8e6d16b6a363a39fe2eaa8295ac224a1e6fce4e47b58845e2e8746164f0",
55
+ hermes_endpoint: "https://pyth.dourolabs.app/hermes",
56
+ },
57
+ };
58
+ // ============================================================================
59
+ // Pyth Lazer — external infra, defaults by network
60
+ // ============================================================================
61
+ /**
62
+ * Pyth Lazer (Pyth Pro) external infra the `PythLazerRule` needs, by network.
63
+ * Mirrors {@link PYTH_DEFAULTS}: per-network constants for infrastructure Pyth
64
+ * operates (not part of the `waterx-config` JSON). A fuller `PYTH_INFRA`
65
+ * restructure is deferred — this stays a minimal map until then.
66
+ *
67
+ * - `endpoint` — Lazer HTTP API base; signed updates come from
68
+ * `POST /v1/latest_price` (Bearer-authenticated). The service is
69
+ * network-agnostic (one signed payload verifies on any chain that trusts the
70
+ * Lazer signers), so both networks share the production host.
71
+ * - `verifier_package` — the Sui package carrying
72
+ * `pyth_lazer::parse_and_verify_le_ecdsa_update`. Per-network: testnet is
73
+ * still the original v1 publish; mainnet is the v2-upgraded package (which
74
+ * still exposes the v1 entry `pyth_lazer_rule` binds). Values mirror the
75
+ * contract repo's `pyth_lazer_rule/Move.toml` published-at pins.
76
+ */
77
+ export const LAZER_DEFAULTS = {
78
+ MAINNET: {
79
+ endpoint: "https://pyth-lazer.dourolabs.app",
80
+ verifier_package: "0xefbfd064480777699fd9c557a5804d72ace7bc82661fdc8d1f1a44ea6d92ee10",
81
+ },
82
+ TESTNET: {
83
+ endpoint: "https://pyth-lazer.dourolabs.app",
84
+ verifier_package: "0xf5bd2141967507050a91b58de3d95e77c432cd90d1799ee46effc27430a68c21",
85
+ },
86
+ };
@@ -8,14 +8,27 @@
8
8
  * clause, and a future `PredictClient` (or a test double) can too.
9
9
  */
10
10
  import type { SuiGrpcClient } from "@mysten/sui/grpc";
11
+ import type { Network } from "../constants.ts";
11
12
  import type { OracleConfig, PythInfraConfig } from "./config.ts";
13
+ import type { OracleSource } from "./price-update-rule.ts";
12
14
  export interface OracleHost {
15
+ /** Sui network this client targets — selects per-network external-infra defaults (e.g. `LAZER_DEFAULTS`). */
16
+ readonly network: Network;
13
17
  /** Oracle slice of the canonical `waterx-config` JSON (rule packages + per-ticker feeds). */
14
18
  readonly config: OracleConfig;
15
19
  /** External Pyth/Wormhole/Hermes infra (network default, overridable via config). */
16
20
  readonly pyth: PythInfraConfig;
17
21
  /** gRPC client for the on-chain reads the Pyth update path needs. */
18
22
  readonly grpcClient: SuiGrpcClient;
23
+ /**
24
+ * Client-selected oracle rule source for `refreshOraclePrices`'s on-chain
25
+ * update leg — resolved at client creation from the `oracleSource` create
26
+ * option (default `'pyth_rule'`). Routing is driven by this value ALONE:
27
+ * never by a config JSON `enabled` flag (e.g. a future `pyth_lazer_rule.enabled`)
28
+ * and never by `process.env` — the SDK never reads it; consumers (BE/FE) wire
29
+ * this option from their own env var.
30
+ */
31
+ readonly oracleSource: OracleSource;
19
32
  /** True when `ticker` is priced by `constant_rule`. */
20
33
  isConstantTicker(ticker: string): boolean;
21
34
  /** The `supra_rule` config when deployed, enabled, and fully wired; else `undefined`. */
@@ -2,15 +2,29 @@
2
2
  * Oracle module — the single source of truth for price freshness.
3
3
  *
4
4
  * Layering (no cross-imports between siblings except via `aggregate.ts`):
5
- * - `host.ts` — `OracleHost`, the narrow client slice this module reads.
6
- * - `pyth.ts` — Pyth as a price source: Hermes REST + on-chain update PTB.
7
- * - `rules/*` — one file per oracle rule (pyth / supra / constant / sponsor).
8
- * - `aggregate.ts`— the orchestrator that feeds rules into a collector + aggregates.
5
+ * - `host.ts` — `OracleHost`, the narrow client slice this module reads.
6
+ * - `update-fetch.ts` — `fetchWithPolicy`, the shared retry/timeout/Bearer resilience
7
+ * wrapper every off-chain oracle (and config) fetch goes through.
8
+ * - `pyth.ts` — Pyth as a price source: Hermes REST + on-chain update PTB.
9
+ * - `price-update-rule.ts`— `PriceUpdateRule`, the fetch/build strategy port a rule
10
+ * implements; `rule-registry.ts` + `aggregate.ts` wire
11
+ * routing across rules.
12
+ * - `rules/*` — one file per oracle rule (pyth / supra / constant / sponsor).
13
+ * - `aggregate.ts` — the orchestrator that feeds rules into a collector + aggregates.
9
14
  *
10
15
  * `pyth.ts` deliberately imports NO rule package — Pyth-the-source and the
11
16
  * rules that consume it are separate concerns.
12
17
  */
13
18
  export type { OracleHost } from "./host.ts";
14
- export { PythCache, fetchPriceFeedsUpdateData, buildPythPriceUpdateCalls, updatePythPrices, } from "./pyth.ts";
19
+ export { FetchPolicyError } from "./update-fetch.ts";
20
+ export type { FetchPolicy } from "./update-fetch.ts";
21
+ export { PythCache, fetchPriceFeedsUpdateData, buildPythPriceUpdateCalls, updatePythPrices, OracleFeeSourceUnavailableError, } from "./pyth.ts";
22
+ export type { OracleFeeSource } from "./pyth.ts";
23
+ export type { PriceUpdateRule, PriceUpdateRuleKind, RuleUpdateData, RuleUpdateHandle, BuildUpdateOpts, OracleSource, UpdateDataProvider, } from "./price-update-rule.ts";
24
+ export { PythCoreRule } from "./rules/pyth-core-rule.ts";
25
+ export type { PythCoreUpdatePayload } from "./rules/pyth-core-rule.ts";
26
+ export { PythLazerRule, LazerApiKeyMissingError } from "./rules/pyth-lazer-rule.ts";
27
+ export type { PythLazerUpdatePayload } from "./rules/pyth-lazer-rule.ts";
28
+ export { OracleSourceNotImplementedError } from "./rule-registry.ts";
15
29
  export { aggregateTicker, aggregateTickerWithPyth, aggregateTickerWithConstant, refreshOraclePrices, } from "./aggregate.ts";
16
30
  export { openPythSponsorFund, reimbursePythSponsor } from "./rules/sponsor.ts";
@@ -2,16 +2,44 @@
2
2
  * Oracle module — the single source of truth for price freshness.
3
3
  *
4
4
  * Layering (no cross-imports between siblings except via `aggregate.ts`):
5
- * - `host.ts` — `OracleHost`, the narrow client slice this module reads.
6
- * - `pyth.ts` — Pyth as a price source: Hermes REST + on-chain update PTB.
7
- * - `rules/*` — one file per oracle rule (pyth / supra / constant / sponsor).
8
- * - `aggregate.ts`— the orchestrator that feeds rules into a collector + aggregates.
5
+ * - `host.ts` — `OracleHost`, the narrow client slice this module reads.
6
+ * - `update-fetch.ts` — `fetchWithPolicy`, the shared retry/timeout/Bearer resilience
7
+ * wrapper every off-chain oracle (and config) fetch goes through.
8
+ * - `pyth.ts` — Pyth as a price source: Hermes REST + on-chain update PTB.
9
+ * - `price-update-rule.ts`— `PriceUpdateRule`, the fetch/build strategy port a rule
10
+ * implements; `rule-registry.ts` + `aggregate.ts` wire
11
+ * routing across rules.
12
+ * - `rules/*` — one file per oracle rule (pyth / supra / constant / sponsor).
13
+ * - `aggregate.ts` — the orchestrator that feeds rules into a collector + aggregates.
9
14
  *
10
15
  * `pyth.ts` deliberately imports NO rule package — Pyth-the-source and the
11
16
  * rules that consume it are separate concerns.
12
17
  */
13
- // Pyth source
14
- export { PythCache, fetchPriceFeedsUpdateData, buildPythPriceUpdateCalls, updatePythPrices, } from "./pyth.js";
18
+ // Shared fetch resilience wrapper — `FetchPolicyError` is re-exported (not
19
+ // just the type) so a consumer (e.g. a BE prefetch cache) can `instanceof`
20
+ // it off the failure `fetchPriceFeedsUpdateData` / `PythLazerRule` /
21
+ // `loadConfig` surface, without a deep import of `./update-fetch.ts`.
22
+ // `fetchWithPolicy` itself stays module-internal (no external caller yet).
23
+ export { FetchPolicyError } from "./update-fetch.js";
24
+ // Pyth source — `OracleFeeSourceUnavailableError` is re-exported (not just
25
+ // the type) for the same `instanceof` reason as `FetchPolicyError` above: a
26
+ // consumer of `buildPythPriceUpdateCalls` / `updatePythPrices` /
27
+ // `refreshOraclePrices` can branch on the fee-source failure directly.
28
+ export { PythCache, fetchPriceFeedsUpdateData, buildPythPriceUpdateCalls, updatePythPrices, OracleFeeSourceUnavailableError, } from "./pyth.js";
29
+ // Pyth Core rule (PriceUpdateRule wrapper over the Pyth source above)
30
+ export { PythCoreRule } from "./rules/pyth-core-rule.js";
31
+ // Pyth Lazer rule (signed-update generation; `feedLazerRule` stays internal to `aggregate.ts`)
32
+ // `LazerApiKeyMissingError` is re-exported (not just the type) for the same
33
+ // `instanceof` reason as `OracleFeeSourceUnavailableError` above.
34
+ export { PythLazerRule, LazerApiKeyMissingError } from "./rules/pyth-lazer-rule.js";
35
+ // `resolveOracleRule` (rule-registry.ts) is NOT re-exported here — it has one
36
+ // production consumer (`refreshOraclePrices` below) and no external caller;
37
+ // per repo convention ("no unused exports") it stays module-internal. Tests
38
+ // import it directly from `./rule-registry.ts`. `OracleSourceNotImplementedError`
39
+ // IS re-exported (the same `instanceof` reason as `OracleFeeSourceUnavailableError`
40
+ // above) — a consumer of `refreshOraclePrices` can catch it without importing
41
+ // `resolveOracleRule` itself.
42
+ export { OracleSourceNotImplementedError } from "./rule-registry.js";
15
43
  // Aggregation orchestrator
16
44
  export { aggregateTicker, aggregateTickerWithPyth, aggregateTickerWithConstant, refreshOraclePrices, } from "./aggregate.js";
17
45
  // Sponsor rule (fund open / reimburse + witness attach)