@waterx/sdk 4.0.0 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +34 -34
  2. package/dist/cjs/src/account/config.d.ts +0 -16
  3. package/dist/cjs/src/oracle/aggregate.d.ts +19 -21
  4. package/dist/cjs/src/oracle/aggregate.js +57 -69
  5. package/dist/cjs/src/oracle/config.d.ts +32 -52
  6. package/dist/cjs/src/oracle/config.js +1 -35
  7. package/dist/cjs/src/oracle/host.d.ts +1 -1
  8. package/dist/cjs/src/oracle/index.d.ts +2 -2
  9. package/dist/cjs/src/oracle/index.js +20 -6
  10. package/dist/cjs/src/oracle/pyth.d.ts +68 -6
  11. package/dist/cjs/src/oracle/pyth.js +338 -22
  12. package/dist/cjs/src/oracle/rule-registry.d.ts +10 -6
  13. package/dist/cjs/src/oracle/rule-registry.js +10 -6
  14. package/dist/cjs/src/oracle/rules/pyth-core-rule.js +17 -2
  15. package/dist/cjs/src/oracle/rules/pyth-lazer-rule.d.ts +6 -6
  16. package/dist/cjs/src/oracle/rules/pyth-lazer-rule.js +25 -22
  17. package/dist/cjs/src/oracle/rules/pyth-rule.js +5 -0
  18. package/dist/cjs/src/oracle/update-fetch.d.ts +32 -2
  19. package/dist/cjs/src/oracle/update-fetch.js +60 -3
  20. package/dist/cjs/src/perp/client.d.ts +33 -19
  21. package/dist/cjs/src/perp/client.js +16 -10
  22. package/dist/cjs/src/perp/config.d.ts +4 -6
  23. package/dist/cjs/src/perp/config.js +8 -12
  24. package/dist/cjs/src/perp/index.d.ts +2 -2
  25. package/dist/cjs/src/perp/index.js +3 -4
  26. package/dist/cjs/src/unified-client.d.ts +19 -11
  27. package/dist/cjs/src/unified-client.js +2 -1
  28. package/dist/src/account/config.d.ts +0 -16
  29. package/dist/src/oracle/aggregate.d.ts +19 -21
  30. package/dist/src/oracle/aggregate.js +57 -69
  31. package/dist/src/oracle/config.d.ts +32 -52
  32. package/dist/src/oracle/config.js +0 -34
  33. package/dist/src/oracle/host.d.ts +1 -1
  34. package/dist/src/oracle/index.d.ts +2 -2
  35. package/dist/src/oracle/index.js +15 -7
  36. package/dist/src/oracle/pyth.d.ts +68 -6
  37. package/dist/src/oracle/pyth.js +334 -22
  38. package/dist/src/oracle/rule-registry.d.ts +10 -6
  39. package/dist/src/oracle/rule-registry.js +10 -6
  40. package/dist/src/oracle/rules/pyth-core-rule.js +18 -3
  41. package/dist/src/oracle/rules/pyth-lazer-rule.d.ts +6 -6
  42. package/dist/src/oracle/rules/pyth-lazer-rule.js +26 -23
  43. package/dist/src/oracle/rules/pyth-rule.js +5 -0
  44. package/dist/src/oracle/update-fetch.d.ts +32 -2
  45. package/dist/src/oracle/update-fetch.js +57 -3
  46. package/dist/src/perp/client.d.ts +33 -19
  47. package/dist/src/perp/client.js +17 -11
  48. package/dist/src/perp/config.d.ts +4 -6
  49. package/dist/src/perp/config.js +9 -12
  50. package/dist/src/perp/index.d.ts +2 -2
  51. package/dist/src/perp/index.js +1 -1
  52. package/dist/src/unified-client.d.ts +19 -11
  53. package/dist/src/unified-client.js +2 -1
  54. package/package.json +1 -1
package/README.md CHANGED
@@ -14,11 +14,12 @@ import { WaterXClient } from "@waterx/sdk";
14
14
  // waterxConfigUrl is REQUIRED — the SDK has no built-in default and never reads env.
15
15
  const client = await WaterXClient.create({
16
16
  network: "TESTNET",
17
- waterxConfigUrl: "https://raw.githubusercontent.com/WaterXProtocol/waterx-config/main/testnet.json",
17
+ waterxConfigUrl:
18
+ "https://raw.githubusercontent.com/WaterXProtocol/waterx-config/main/testnet.json",
18
19
  });
19
- client.account.createAccount(tx, { alias }); // shared waterx_account + funding (credit/custody)
20
- client.perp.buildPlaceOrderTx(params); // perpetuals
21
- client.predict.placeOrder(tx, params); // prediction markets
20
+ client.account.createAccount(tx, { alias }); // shared waterx_account + funding (credit/custody)
21
+ client.perp.buildPlaceOrderTx(params); // perpetuals
22
+ client.predict.placeOrder(tx, params); // prediction markets
22
23
  // client.perp / client.predict ARE the line clients — sign/execute on them directly:
23
24
  // await client.perp.signAndExecuteTransaction({ transaction: tx, signer })
24
25
  // each line can target a different network + URL:
@@ -29,11 +30,11 @@ client.predict.placeOrder(tx, params); // prediction markets
29
30
 
30
31
  Import surfaces:
31
32
 
32
- | Import | What |
33
- |--------|------|
34
- | `@waterx/sdk` | `WaterXClient` (umbrella) + `perp` / `prediction` namespaces. Perp's API is also re-exported flat here (**deprecated** — prefer `client.perp` or the `perp` namespace; removed next major). |
35
- | `@waterx/sdk/perp` | Perp line: `PerpClient`, builders, fetch, Pyth/Wormhole utils. |
36
- | `@waterx/sdk/prediction` | Prediction line: `PredictClient`, builders, fetch, utils. |
33
+ | Import | What |
34
+ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
35
+ | `@waterx/sdk` | `WaterXClient` (umbrella) + `perp` / `prediction` namespaces. Perp's API is also re-exported flat here (**deprecated** — prefer `client.perp` or the `perp` namespace; removed next major). |
36
+ | `@waterx/sdk/perp` | Perp line: `PerpClient`, builders, fetch, Pyth/Wormhole utils. |
37
+ | `@waterx/sdk/prediction` | Prediction line: `PredictClient`, builders, fetch, utils. |
37
38
 
38
39
  ## Install
39
40
 
@@ -99,39 +100,38 @@ const predict = await PredictClient.create("TESTNET", { waterxConfigUrl }); // o
99
100
 
100
101
  Read-only queries use gRPC `simulateTransaction` (no signer) — the `getX` view helpers, e.g. `await perp.simulate(tx)` or `getMarketData(perp, …)`.
101
102
 
102
- ## Oracle sources & the Pyth Pro migration
103
+ ## Oracle sources
104
+
105
+ ONE client create option, `oracleSource`, selects the price-update source. Each source is **self-contained** — it owns its own infra + config and does **not** back-stop any other source. The name is source-neutral on purpose: a future source need not be Pyth. The SDK **never reads `process.env`** — each consumer wires it from its own env var, so every environment runs the **same SDK version** and differs only by env:
103
106
 
104
- Two independent client create options control oracle behavior. The SDK **never reads `process.env`** — each consumer wires them from its own env vars, so every environment runs the **same SDK version** and differs only by env:
107
+ | Option | Values | What it selects |
108
+ | -------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
109
+ | `oracleSource` | `'pyth_rule'` (default) \| `'pyth_lazer_rule'` | The price-update source. `'pyth_rule'` = Pyth Core updates (Hermes VAA + per-feed update fees, keyless `hermes.pyth.network`). `'pyth_lazer_rule'` = Pyth Lazer signed updates (ONE `leEcdsa` verify per PTB, no per-feed fees); needs `packages.pyth_lazer_rule` feeds + a `pythApiKey`. |
105
110
 
106
- | Option | Values | What it flips |
107
- |--------|--------|---------------|
108
- | `oracleSource` | `'pyth_rule'` (default) \| `'pyth_lazer_rule'` | Which `PriceUpdateRule` `refreshOraclePrices` uses for the on-chain price-update leg. |
109
- | `pythGeneration` | `'core'` (default) \| `'pro'` | Which Pyth infra constants feed `client.pyth` when the config JSON has no explicit `pyth` block: `PYTH_DEFAULTS` (original contracts, keyless `hermes.pyth.network`) or `PYTH_PRO_DEFAULTS` (post-2026-08-18 Pro-compatible contracts + the Hermes-compatible `https://pyth.dourolabs.app/hermes`, auth-first). |
111
+ **No cross-source fallback, no init guard.** Selecting a source whose feed for a requested ticker is absent is **not** an error at client creation — it fails at **tx-build** for exactly those tickers (constant-only tickers, which need no price update, are exempt). A present-but-wrong feed id is not validated by the SDK; it aborts on-chain at dry-run.
110
112
 
111
- They are orthogonal: `pythGeneration` moves the Pyth **Core** state ids + endpoint; `oracleSource` picks the **rule** (Core VAA vs Lazer signed updates). An explicit `pyth` block in the config JSON always overrides the generation constants wholesale.
113
+ The Pyth Core infra (`client.pyth`: state ids + Hermes endpoint) is **fixed per network** by `PYTH_DEFAULTS` and is **not** deployment-overridable the canonical `waterx-config` JSON carries no `pyth` block. The `pyth_lazer_rule` source reads only the credential/policy (`api_key`/`fetch`) from `client.pyth`; its on-chain infra comes from `LAZER_DEFAULTS` + config. The credential and fetch policy are passed at client init (`pythApiKey` / `pythFetch`), never through the JSON.
112
114
 
113
115
  ```ts
114
- // Per-environment wiring — the consumer owns the env vars, not the SDK:
116
+ // Per-environment wiring — the consumer owns the env var, not the SDK:
115
117
  const perp = await PerpClient.create(network, {
116
118
  waterxConfigUrl,
117
- oracleSource: process.env.ORACLE_SOURCE as OracleSource | undefined, // e.g. staging: pyth_lazer_rule
118
- pythGeneration: process.env.PYTH_GENERATION as PythGeneration | undefined, // e.g. staging: pro
119
+ oracleSource: process.env.ORACLE_SOURCE as OracleSource | undefined, // e.g. staging: 'pyth_lazer_rule'
120
+ pythApiKey: process.env.PYTH_API_KEY, // Lazer is auth-first; unused by 'pyth_rule'
119
121
  });
120
- // After the 2026-08-18 cutover, Pro-generation Hermes requires a key:
121
- perp.pyth = { ...perp.pyth, api_key: process.env.PYTH_API_KEY };
122
122
  ```
123
123
 
124
- This is the staging-Pro / prod-Core rollout pattern: staging sets `ORACLE_SOURCE=pyth_lazer_rule` and/or `PYTH_GENERATION=pro` while production leaves both unset (Core defaults) — flipping an environment is an env-var change, never an SDK release. After August 18, 2026 (the Core-upgrade cutover — see https://docs.pyth.network/price-feeds/core/upgrade), consumers set `pythGeneration: 'pro'` + `pyth.api_key`.
124
+ This is the staging-Lazer / prod-Core rollout pattern: staging sets `ORACLE_SOURCE=pyth_lazer_rule` (+ `PYTH_API_KEY`) while production leaves it unset — flipping an environment is an env-var change, never an SDK release.
125
125
 
126
126
  ### Adding an oracle source (runbook)
127
127
 
128
- Every rule generation plugs in the same way — routing is driven **only** by the client's `oracleSource` option (never a config `enabled` flag, never `process.env`):
128
+ Every source plugs in the same way — routing is driven **only** by the client's `oracleSource` option (never a config `enabled` flag, never `process.env`):
129
129
 
130
130
  1. **Implement `PriceUpdateRule`** in `src/oracle/rules/<name>-rule.ts` — all port fields (`src/oracle/price-update-rule.ts`): `kind`, `requiresFeeSource` (`true` iff the on-chain verify draws a per-update fee — gates the fail-fast fee-source check), `supportedTickers`, `fetchUpdateData`, `narrowUpdateData` (subset a cached whole-universe payload to one build's tickers — a divisible payload returns a per-feed subset, an indivisible one returns itself whole iff fully covered; uncovered ticker → `null` miss), `buildUpdateCalls`.
131
131
  2. **Register it** in `src/oracle/rule-registry.ts` (`DEFAULT_RULES`) under a new `OracleSource` value (added to the union in `price-update-rule.ts`).
132
132
  3. **Publish the on-chain rule package** — its config entry (package ids, per-ticker `feeds`) arrives via the normal `waterx-config` deploy pipeline; type it in `OraclePackages` (`src/oracle/config.ts`).
133
- 4. **Add SDK infra constants** if the source needs external infra that is not part of the config JSON (API endpoints, verifier packages, state objects) — a per-network map in `src/oracle/config.ts`, mirroring `LAZER_DEFAULTS` / `PYTH_PRO_DEFAULTS`.
134
- 5. **Consumers flip `ORACLE_SOURCE`** per environment — no consumer code change, no SDK re-release.
133
+ 4. **Add SDK infra constants** if the source needs external infra that is not part of the config JSON (API endpoints, verifier packages, state objects) — a per-network map in `src/oracle/config.ts`, mirroring `LAZER_DEFAULTS`.
134
+ 5. **Consumers flip `oracleSource`** per environment — no consumer code change, no SDK re-release.
135
135
 
136
136
  The in-house `waterx_rule` (ed25519 enclave-signed CEX prices) follows exactly this path when it lands.
137
137
 
@@ -147,14 +147,14 @@ Perp `build*Tx` helpers are Pyth-backed (`async`; they refresh feeds before the
147
147
 
148
148
  ## Development
149
149
 
150
- | Command | Use |
151
- | --- | --- |
152
- | `pnpm typecheck` | Typecheck the whole tree |
153
- | `pnpm test` / `pnpm test:unit` | Unit tests (perp + prediction) |
154
- | `pnpm test:e2e` | Testnet simulate e2e (perp + prediction) |
155
- | `pnpm test:integration` | On-chain integration (needs `SUI_PRIVATE_KEY`; local-only) |
156
- | `pnpm lint` / `pnpm format` | ESLint + Prettier |
157
- | `pnpm codegen` | Regenerate `src/generated` from Move |
158
- | `pnpm seed:testnet` | Seed prediction testnet fixtures (needs `SUI_PRIVATE_KEY`) |
150
+ | Command | Use |
151
+ | ------------------------------ | ---------------------------------------------------------- |
152
+ | `pnpm typecheck` | Typecheck the whole tree |
153
+ | `pnpm test` / `pnpm test:unit` | Unit tests (perp + prediction) |
154
+ | `pnpm test:e2e` | Testnet simulate e2e (perp + prediction) |
155
+ | `pnpm test:integration` | On-chain integration (needs `SUI_PRIVATE_KEY`; local-only) |
156
+ | `pnpm lint` / `pnpm format` | ESLint + Prettier |
157
+ | `pnpm codegen` | Regenerate `src/generated` from Move |
158
+ | `pnpm seed:testnet` | Seed prediction testnet fixtures (needs `SUI_PRIVATE_KEY`) |
159
159
 
160
160
  Tests are split per line under `test/perp/` and `test/prediction/`, each with `unit` / `e2e` / `integration` tiers. See the per-line `README.md` in each.
@@ -48,28 +48,12 @@ export interface NativeCustodyPackage {
48
48
  /** Backing assets registered via `add_asset` (array, identified by `type`). */
49
49
  assets: NativeCustodyAsset[];
50
50
  }
51
- export interface TrustedEmitterRow {
52
- /** Source EVM chain's Wormhole chain id (e.g. 10002 = Sepolia). */
53
- chain_id: number;
54
- /** 32-byte left-padded EVM bridge address (0x form). */
55
- evm_bridge_address_32b: string;
56
- /** Whitelisted 20-byte EVM token addresses (0x form). */
57
- evm_tokens_20b: string[];
58
- }
59
51
  export interface WormholeBridgePackage {
60
52
  published_at: string;
61
53
  /** Shared Sui Wormhole `State` object id for this deployment. */
62
54
  wormhole_state: string;
63
- hourly_mint_limit?: string;
64
55
  max_mint_per_tx?: string;
65
- hourly_burn_limit?: string;
66
56
  max_burn_per_tx?: string;
67
- /**
68
- * @deprecated EVM emitter↔token config now lives solely under `evm.bridge.chains`
69
- * (deposit_vault = emitter, wormhole_chain_id = chain key). The runtime allowlist is
70
- * read from the on-chain `Bridge` object, not from config. Kept optional for back-compat.
71
- */
72
- trusted_emitters?: TrustedEmitterRow[];
73
57
  /** Shared `Bridge` (phase-5 output). */
74
58
  bridge?: string;
75
59
  /**
@@ -83,28 +83,26 @@ export declare function aggregateTickerWithConstant(tx: Transaction, host: Oracl
83
83
  * enabled, Constant when it's a constant ticker).
84
84
  *
85
85
  * Before that, the on-chain price *update* leg is routed by `host.oracleSource`
86
- * (see `rule-registry.ts`): the selected rule serves every ticker in its
87
- * `supportedTickers(host)`; tickers it doesn't cover fall back to `pyth_rule`
88
- * (`PythCoreRule`) when THEY support it so when `oracleSource` IS `'pyth_rule'`
89
- * there is exactly one group, identical to the pre-routing behavior. A ticker
90
- * supported by neither is simply skipped from this leg (no fetch/build call for
91
- * it) the same way today's non-pyth tickers (e.g. constant-only) always were;
92
- * it still gets aggregated below via whichever rule {@link aggregateTicker} finds.
86
+ * (see `rule-registry.ts`): the ONE selected source serves every ticker in its
87
+ * `supportedTickers(host)`. There is **no cross-source fallback** a requested
88
+ * ticker the selected source does not serve, and that is not a constant-only
89
+ * ticker (which needs no price-update leg), fails the build immediately with a
90
+ * clear error naming the ticker and source. That is the deliberate "fail the
91
+ * tx-build, don't silently reroute" contract: a wrong-but-present feed id is
92
+ * NOT validated here (it surfaces on-chain at dry-run); a MISSING feed for the
93
+ * selected source is caught here. When the selected source's feed exists but is
94
+ * wrong, this function does nothing special — the on-chain aggregate aborts at
95
+ * dry-run, which is correct.
93
96
  *
94
- * Each group's fetch + build runs against its own rule, which guarantees
95
- * per-rule PTB atomicity (no mixed-generation payload within one rule's calls).
96
- * When `oracleSource` isn't `'pyth_rule'`, one PTB may legitimately carry BOTH a
97
- * non-Pyth-Core block (selected group) and a Pyth Core block (fallback group) —
98
- * each verifies against its own contract objects, so that's fine. A fee-source
99
- * pre-check runs first, across every group's `requiresFeeSource` BEFORE any
100
- * off-chain fetch or PTB mutation — so a fee-charging group with no
101
- * `opts.feeSource` throws `OracleFeeSourceUnavailable` with zero wasted
102
- * network calls and zero stray moveCalls, even in a mixed shape (e.g. a
103
- * fee-free Lazer group ordered ahead of a Pyth Core fallback group). Only once
104
- * that check passes do all groups' off-chain fetches run concurrently
105
- * (`Promise.all`) and complete before any PTB mutation; on-chain reads inside
106
- * `buildUpdateCalls` can still fail mid-append for other reasons — callers
107
- * discard the tx on any throw.
97
+ * The selected source's fetch + build runs against its own infra, guaranteeing
98
+ * per-rule PTB atomicity. A fee-source pre-check runs first (the source's
99
+ * `requiresFeeSource`) BEFORE any off-chain fetch or PTB mutation so a
100
+ * fee-charging source with no `opts.feeSource` throws
101
+ * `OracleFeeSourceUnavailable` with zero wasted network calls and zero stray
102
+ * moveCalls. Only once that check passes does the off-chain fetch run and
103
+ * complete before any PTB mutation; on-chain reads inside `buildUpdateCalls`
104
+ * can still fail mid-append for other reasons — callers discard the tx on any
105
+ * throw.
108
106
  *
109
107
  * **Collector-feed leg is rule-aware:** a lazer-served group's
110
108
  * `buildUpdateCalls` returns the verified `Update` PTB value
@@ -165,28 +165,26 @@ function aggregateTickerWithConstant(tx, host, args) {
165
165
  * enabled, Constant when it's a constant ticker).
166
166
  *
167
167
  * Before that, the on-chain price *update* leg is routed by `host.oracleSource`
168
- * (see `rule-registry.ts`): the selected rule serves every ticker in its
169
- * `supportedTickers(host)`; tickers it doesn't cover fall back to `pyth_rule`
170
- * (`PythCoreRule`) when THEY support it so when `oracleSource` IS `'pyth_rule'`
171
- * there is exactly one group, identical to the pre-routing behavior. A ticker
172
- * supported by neither is simply skipped from this leg (no fetch/build call for
173
- * it) the same way today's non-pyth tickers (e.g. constant-only) always were;
174
- * it still gets aggregated below via whichever rule {@link aggregateTicker} finds.
168
+ * (see `rule-registry.ts`): the ONE selected source serves every ticker in its
169
+ * `supportedTickers(host)`. There is **no cross-source fallback** a requested
170
+ * ticker the selected source does not serve, and that is not a constant-only
171
+ * ticker (which needs no price-update leg), fails the build immediately with a
172
+ * clear error naming the ticker and source. That is the deliberate "fail the
173
+ * tx-build, don't silently reroute" contract: a wrong-but-present feed id is
174
+ * NOT validated here (it surfaces on-chain at dry-run); a MISSING feed for the
175
+ * selected source is caught here. When the selected source's feed exists but is
176
+ * wrong, this function does nothing special — the on-chain aggregate aborts at
177
+ * dry-run, which is correct.
175
178
  *
176
- * Each group's fetch + build runs against its own rule, which guarantees
177
- * per-rule PTB atomicity (no mixed-generation payload within one rule's calls).
178
- * When `oracleSource` isn't `'pyth_rule'`, one PTB may legitimately carry BOTH a
179
- * non-Pyth-Core block (selected group) and a Pyth Core block (fallback group) —
180
- * each verifies against its own contract objects, so that's fine. A fee-source
181
- * pre-check runs first, across every group's `requiresFeeSource` BEFORE any
182
- * off-chain fetch or PTB mutation — so a fee-charging group with no
183
- * `opts.feeSource` throws `OracleFeeSourceUnavailable` with zero wasted
184
- * network calls and zero stray moveCalls, even in a mixed shape (e.g. a
185
- * fee-free Lazer group ordered ahead of a Pyth Core fallback group). Only once
186
- * that check passes do all groups' off-chain fetches run concurrently
187
- * (`Promise.all`) and complete before any PTB mutation; on-chain reads inside
188
- * `buildUpdateCalls` can still fail mid-append for other reasons — callers
189
- * discard the tx on any throw.
179
+ * The selected source's fetch + build runs against its own infra, guaranteeing
180
+ * per-rule PTB atomicity. A fee-source pre-check runs first (the source's
181
+ * `requiresFeeSource`) BEFORE any off-chain fetch or PTB mutation so a
182
+ * fee-charging source with no `opts.feeSource` throws
183
+ * `OracleFeeSourceUnavailable` with zero wasted network calls and zero stray
184
+ * moveCalls. Only once that check passes does the off-chain fetch run and
185
+ * complete before any PTB mutation; on-chain reads inside `buildUpdateCalls`
186
+ * can still fail mid-append for other reasons — callers discard the tx on any
187
+ * throw.
190
188
  *
191
189
  * **Collector-feed leg is rule-aware:** a lazer-served group's
192
190
  * `buildUpdateCalls` returns the verified `Update` PTB value
@@ -213,59 +211,49 @@ async function refreshOraclePrices(tx, host, tickers, opts = {}) {
213
211
  const pythTickers = tickers.filter((t) => host.config.packages.pyth_rule?.feeds?.[t] !== undefined);
214
212
  const priceInfoByTicker = new Map();
215
213
  pythTickers.forEach((t) => priceInfoByTicker.set(t, host.getPythFeed(t).price_info_object));
216
- // Group tickers for the on-chain update leg: selected rule first, then the
217
- // pyth_rule fallback for whatever the selected rule doesn't cover. `source`
218
- // is tracked alongside each group (rather than read back off `rule.kind`,
219
- // which is typed as the broader PriceUpdateRuleKind) so the provider lookup
220
- // below has an OracleSource to key on without a cast.
214
+ // ONE source, no fallback. The selected source serves the tickers in its
215
+ // `supportedTickers(host)`; `source` is tracked alongside the group (rather
216
+ // than read back off `rule.kind`, typed as the broader PriceUpdateRuleKind)
217
+ // so the provider lookup below has an OracleSource to key on without a cast.
221
218
  const selectedRule = (0, rule_registry_ts_1.resolveOracleRule)(host.oracleSource, opts.ruleOverrides);
222
219
  const selectedSupported = new Set(selectedRule.supportedTickers(host));
223
- const selectedGroup = tickers.filter((t) => selectedSupported.has(t));
224
- const groups = [];
225
- if (selectedGroup.length > 0) {
226
- groups.push({ source: host.oracleSource, rule: selectedRule, tickers: selectedGroup });
227
- }
228
- if (host.oracleSource !== "pyth_rule") {
229
- const fallbackRule = (0, rule_registry_ts_1.resolveOracleRule)("pyth_rule", opts.ruleOverrides);
230
- const fallbackSupported = new Set(fallbackRule.supportedTickers(host));
231
- const fallbackGroup = tickers.filter((t) => !selectedSupported.has(t) && fallbackSupported.has(t));
232
- if (fallbackGroup.length > 0) {
233
- groups.push({ source: "pyth_rule", rule: fallbackRule, tickers: fallbackGroup });
234
- }
220
+ // Fail the tx-build (NOT client init, NOT a silent reroute) when the selected
221
+ // source has no feed for a requested ticker that actually needs a price
222
+ // update. Only a CONSTANT-ONLY ticker is exempt — priced entirely by
223
+ // `constant_rule`, it needs no update leg from any source. A DUAL-FEED ticker
224
+ // (constant AND pyth) still needs its Pyth leg refreshed, so `isConstantTicker`
225
+ // alone must NOT exempt it: under a source that can't serve it, with no
226
+ // fallback, feeding an unrefreshed Pyth leg would price it stale (or abort on a
227
+ // missing weighted source). `priceInfoByTicker.has(t)` ⇔ the ticker has a
228
+ // `pyth_rule.feeds` entry, so `constant && !hasPyth` is exactly constant-only.
229
+ // This catches a MISSING feed; a present-but-WRONG feed id is deliberately not
230
+ // validated here (it aborts on-chain at dry-run).
231
+ const isConstantOnly = (t) => host.isConstantTicker(t) && !priceInfoByTicker.has(t);
232
+ const unservable = tickers.filter((t) => !selectedSupported.has(t) && !isConstantOnly(t));
233
+ if (unservable.length > 0) {
234
+ throw new Error(`oracleSource '${host.oracleSource}' has no feed configured for ticker(s): ` +
235
+ `${unservable.join(", ")}. Sources are self-contained with no fallback — add ` +
236
+ `${host.oracleSource} feeds for them, or select a source that serves them.`);
235
237
  }
236
- // Fee-source pre-check, hoisted ABOVE both the off-chain fetch below AND
237
- // the per-group build loop further down. The condition only consults
238
- // `group.rule.requiresFeeSource` — known the moment `groups` is built,
239
- // before any fetch or PTB mutation so this throws with ZERO wasted
240
- // network calls and zero PTB commands. A per-call guard inside
241
- // `buildPythPriceUpdateCalls` alone would not be early enough: in a mixed
242
- // shape (e.g. a lazer-selected `oracleSource` with a `pyth_rule` fallback
243
- // group for tickers Lazer doesn't cover), the build loop runs each
244
- // group's `buildUpdateCalls` in sequence — a fee-free group ordered ahead
245
- // of a fee-charging one would already have appended its verify/feed
246
- // moveCalls to the shared `tx` by the time the fee-charging group's own
247
- // guard fired, breaking the "throw before any PTB mutation" guarantee.
248
- // Checking every group's `requiresFeeSource` up front — before ANY group
249
- // fetches or builds — closes that gap, and (unlike a referential check
250
- // against a specific rule instance) keeps protecting a future
251
- // fee-charging rule or a test double standing in for one.
252
- if (!opts.feeSource && groups.some((group) => group.rule.requiresFeeSource)) {
238
+ const selectedGroup = tickers.filter((t) => selectedSupported.has(t));
239
+ // Fee-source pre-check, hoisted ABOVE the off-chain fetch and PTB build below.
240
+ // It consults only `rule.requiresFeeSource` — known before any fetch or PTB
241
+ // mutation so a fee-charging source with no `feeSource` throws with ZERO
242
+ // wasted network calls and zero PTB commands, rather than waiting for
243
+ // `buildPythPriceUpdateCalls`'s own per-call guard to fire after the off-chain
244
+ // fetch already ran.
245
+ if (selectedGroup.length > 0 && !opts.feeSource && selectedRule.requiresFeeSource) {
253
246
  throw new pyth_ts_1.OracleFeeSourceUnavailableError();
254
247
  }
255
- // Fetch every group's off-chain payload concurrently (independent network
256
- // calls no reason to serialize) and let ALL of them settle before the
257
- // first PTB mutation below, so a later group's fetch failure can never
258
- // leave an earlier group's moveCalls stranded in a caller-owned tx.
259
- const groupsWithData = await Promise.all(groups.map(async (group) => ({
260
- rule: group.rule,
261
- tickers: group.tickers,
262
- data: await resolveGroupUpdateData(host, group, opts.updateDataProvider),
263
- })));
264
- // Verified-`Update` handle per lazer-served ticker (one shared PTB value per
265
- // group) — consumed by the collector-feed leg below.
248
+ // Resolve + build the selected source's update leg. The off-chain fetch
249
+ // settles before the first PTB mutation, so a fetch failure never strands
250
+ // moveCalls in a caller-owned tx. Map each lazer-served ticker to the one
251
+ // verified `Update` PTB value for the collector-feed leg below.
266
252
  const lazerUpdateByTicker = new Map();
267
- for (const group of groupsWithData) {
268
- const handle = (await group.rule.buildUpdateCalls(tx, host, group.data, {
253
+ if (selectedGroup.length > 0) {
254
+ const group = { source: host.oracleSource, rule: selectedRule, tickers: selectedGroup };
255
+ const data = await resolveGroupUpdateData(host, group, opts.updateDataProvider);
256
+ const handle = (await selectedRule.buildUpdateCalls(tx, host, data, {
269
257
  cache: opts.cache,
270
258
  feeSource: opts.feeSource,
271
259
  })) ?? undefined;
@@ -273,7 +261,7 @@ async function refreshOraclePrices(tx, host, tickers, opts = {}) {
273
261
  // protect: a future non-lazer handle (e.g. a WaterxRule value) must never
274
262
  // be silently fed into pyth_lazer_rule::feed.
275
263
  if (handle?.kind === "pyth_lazer_rule") {
276
- for (const ticker of group.tickers)
264
+ for (const ticker of selectedGroup)
277
265
  lazerUpdateByTicker.set(ticker, handle.update);
278
266
  }
279
267
  }
@@ -101,6 +101,29 @@ export interface OraclePackages {
101
101
  supra_rule?: SupraRulePackage;
102
102
  waterx_oracle: WaterxOraclePackage;
103
103
  }
104
+ /**
105
+ * Resolved Pyth Core infra as it lives on `client.pyth` — NOT a config-JSON
106
+ * shape. `state_id` / `wormhole_state_id` / `hermes_endpoint` come verbatim
107
+ * from the fixed per-network constant ({@link PYTH_DEFAULTS}); `api_key` /
108
+ * `fetch` are layered on from the caller's `pythApiKey` / `pythFetch` create
109
+ * options. None of it is sourced from the canonical `waterx-config` JSON — the
110
+ * SDK never reads a `pyth` block there (a Bearer secret has no place in a
111
+ * public CDN document). The infra is the same for every `oracleSource`; the
112
+ * `pyth_lazer_rule` source reads only the `api_key` / `fetch` from here and
113
+ * gets its on-chain infra from {@link LAZER_DEFAULTS} + config instead.
114
+ */
115
+ /**
116
+ * The caller-tunable subset of `fetchWithPolicy`'s policy exposed on the
117
+ * `pythFetch` create option and `client.pyth.fetch` — the retry/timeout budget
118
+ * for the off-chain Hermes (`fetchPriceFeedsUpdateData`) and Lazer
119
+ * (`PythLazerRule`) update fetches. Deliberately narrower than the internal
120
+ * `FetchPolicy` (no `retryDelayMs` / `apiKey` / `fetchImpl`). Both fetches fall
121
+ * back to `fetchWithPolicy`'s defaults (15s timeout, 2 retries) when unset.
122
+ */
123
+ export type PythFetchPolicy = {
124
+ timeoutMs?: number;
125
+ retries?: number;
126
+ };
104
127
  export interface PythInfraConfig {
105
128
  state_id: string;
106
129
  wormhole_state_id: string;
@@ -109,8 +132,8 @@ export interface PythInfraConfig {
109
132
  * Pyth Pro / Lazer access token (`Authorization: Bearer …`) for
110
133
  * `PythLazerRule`'s signed-update fetch — Lazer is auth-first, so there is
111
134
  * 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 →
135
+ * Supplied via the `pythApiKey` create option (the SDK never reads
136
+ * `process.env` or the config JSON). Absent when a lazer-routed fetch runs →
114
137
  * `LazerApiKeyMissing` is thrown at fetch time. As of the Pyth Pro
115
138
  * migration (post-2026-08-18, per
116
139
  * https://docs.pyth.network/price-feeds/core/upgrade) this is ALSO required
@@ -119,57 +142,16 @@ export interface PythInfraConfig {
119
142
  */
120
143
  api_key?: string;
121
144
  /**
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.
145
+ * Retry/timeout policy for the Hermes (`fetchPriceFeedsUpdateData`) and
146
+ * Lazer (`PythLazerRule`) off-chain update fetches — see `fetchWithPolicy`
147
+ * (`./update-fetch.ts`) for the full policy (backoff, which statuses retry,
148
+ * Bearer attachment). Supplied via the `pythFetch` create option. Optional:
149
+ * both fetches default to `fetchWithPolicy`'s built-in defaults (15s
150
+ * timeout, 2 retries) when unset.
128
151
  */
129
- fetch?: {
130
- timeoutMs?: number;
131
- retries?: number;
132
- };
152
+ fetch?: PythFetchPolicy;
133
153
  }
134
154
  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
155
  /**
174
156
  * Pyth Lazer (Pyth Pro) external infra the `PythLazerRule` needs, by network.
175
157
  * Mirrors {@link PYTH_DEFAULTS}: per-network constants for infrastructure Pyth
@@ -197,6 +179,4 @@ export declare const LAZER_DEFAULTS: Record<Network, {
197
179
  */
198
180
  export interface OracleConfig extends BaseLineConfig {
199
181
  packages: OraclePackages;
200
- /** Pyth infra override (defaults from {@link PYTH_DEFAULTS}). */
201
- pyth?: PythInfraConfig;
202
182
  }
@@ -11,7 +11,7 @@
11
11
  * mirrors the earlier account-config hoist.
12
12
  */
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.LAZER_DEFAULTS = exports.PYTH_PRO_DEFAULTS = exports.PYTH_DEFAULTS = void 0;
14
+ exports.LAZER_DEFAULTS = exports.PYTH_DEFAULTS = void 0;
15
15
  exports.PYTH_DEFAULTS = {
16
16
  MAINNET: {
17
17
  state_id: "0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",
@@ -24,40 +24,6 @@ exports.PYTH_DEFAULTS = {
24
24
  hermes_endpoint: "https://hermes-beta.pyth.network",
25
25
  },
26
26
  };
27
- /**
28
- * Pyth **Pro-generation** Core-compatible infra — the post-2026-08-18
29
- * contracts (cutover date per
30
- * https://docs.pyth.network/price-feeds/core/upgrade) from Pyth's Core-Upgrade
31
- * docs
32
- * (https://docs.pyth.network/price-feeds/core/upgrade/contracts, Sui section;
33
- * package revs `sui-pro-compatible-contract-mainnet` /
34
- * `sui-pro-compatible-contract-testnet`). Selected via the client's
35
- * `pythGeneration: 'pro'` create option; `config.pyth` still overrides
36
- * wholesale (see `PerpClient`). All four state ids were verified on-chain
37
- * (shared `state::State` objects under the docs' upgraded package ids).
38
- *
39
- * Kept as a second flat map beside {@link PYTH_DEFAULTS} rather than a nested
40
- * `PYTH_INFRA[network][generation]` — `PYTH_DEFAULTS` is a published export
41
- * with external consumers, so the smallest honest surface is an additive
42
- * sibling (same deferral note as {@link LAZER_DEFAULTS}).
43
- *
44
- * The Hermes-compatible endpoint (`pyth.dourolabs.app/hermes`) serves the
45
- * same REST surface as `hermes.pyth.network` but requires `pyth.api_key`
46
- * (`Authorization: Bearer …`) after the cutover — see
47
- * {@link PythInfraConfig.api_key}.
48
- */
49
- exports.PYTH_PRO_DEFAULTS = {
50
- MAINNET: {
51
- state_id: "0x03719fae774ddab3cfcaa53bbc046f0cbe21410019b6280811bf3f9f4b05839d",
52
- wormhole_state_id: "0xdbca52b9fb4f712e25f61f974586d93ac541bcf8389564f0323bb07215168b5c",
53
- hermes_endpoint: "https://pyth.dourolabs.app/hermes",
54
- },
55
- TESTNET: {
56
- state_id: "0x3c48fe392912de6c18087a2b3f5fdbfbfdb4598e180947feff1f12f8e9ea073e",
57
- wormhole_state_id: "0x750da8e6d16b6a363a39fe2eaa8295ac224a1e6fce4e47b58845e2e8746164f0",
58
- hermes_endpoint: "https://pyth.dourolabs.app/hermes",
59
- },
60
- };
61
27
  // ============================================================================
62
28
  // Pyth Lazer — external infra, defaults by network
63
29
  // ============================================================================
@@ -16,7 +16,7 @@ export interface OracleHost {
16
16
  readonly network: Network;
17
17
  /** Oracle slice of the canonical `waterx-config` JSON (rule packages + per-ticker feeds). */
18
18
  readonly config: OracleConfig;
19
- /** External Pyth/Wormhole/Hermes infra (network default, overridable via config). */
19
+ /** External Pyth/Wormhole/Hermes infra — fixed per `(network, generation)`; api_key/fetch layered from create options. */
20
20
  readonly pyth: PythInfraConfig;
21
21
  /** gRPC client for the on-chain reads the Pyth update path needs. */
22
22
  readonly grpcClient: SuiGrpcClient;
@@ -16,9 +16,9 @@
16
16
  * rules that consume it are separate concerns.
17
17
  */
18
18
  export type { OracleHost } from "./host.ts";
19
- export { FetchPolicyError } from "./update-fetch.ts";
19
+ export { FetchPolicyError, fetchWithPolicy, joinEndpointPath } from "./update-fetch.ts";
20
20
  export type { FetchPolicy } from "./update-fetch.ts";
21
- export { PythCache, fetchPriceFeedsUpdateData, buildPythPriceUpdateCalls, updatePythPrices, OracleFeeSourceUnavailableError, } from "./pyth.ts";
21
+ export { PythCache, fetchPriceFeedsUpdateData, endpointSupportedFeedIds, probeMissingFeeds, buildPythPriceUpdateCalls, updatePythPrices, HermesEndpointRejectedAllFeedsError, MISSING_FEED_MEMO_TTL_MS, OracleFeeSourceUnavailableError, } from "./pyth.ts";
22
22
  export type { OracleFeeSource } from "./pyth.ts";
23
23
  export type { PriceUpdateRule, PriceUpdateRuleKind, RuleUpdateData, RuleUpdateHandle, BuildUpdateOpts, OracleSource, UpdateDataProvider, } from "./price-update-rule.ts";
24
24
  export { PythCoreRule } from "./rules/pyth-core-rule.ts";
@@ -17,23 +17,37 @@
17
17
  * rules that consume it are separate concerns.
18
18
  */
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.reimbursePythSponsor = exports.openPythSponsorFund = exports.refreshOraclePrices = exports.aggregateTickerWithConstant = exports.aggregateTickerWithPyth = exports.aggregateTicker = exports.OracleSourceNotImplementedError = exports.LazerApiKeyMissingError = exports.PythLazerRule = exports.PythCoreRule = exports.OracleFeeSourceUnavailableError = exports.updatePythPrices = exports.buildPythPriceUpdateCalls = exports.fetchPriceFeedsUpdateData = exports.PythCache = exports.FetchPolicyError = void 0;
20
+ exports.reimbursePythSponsor = exports.openPythSponsorFund = exports.refreshOraclePrices = exports.aggregateTickerWithConstant = exports.aggregateTickerWithPyth = exports.aggregateTicker = exports.OracleSourceNotImplementedError = exports.LazerApiKeyMissingError = exports.PythLazerRule = exports.PythCoreRule = exports.OracleFeeSourceUnavailableError = exports.MISSING_FEED_MEMO_TTL_MS = exports.HermesEndpointRejectedAllFeedsError = exports.updatePythPrices = exports.buildPythPriceUpdateCalls = exports.probeMissingFeeds = exports.endpointSupportedFeedIds = exports.fetchPriceFeedsUpdateData = exports.PythCache = exports.joinEndpointPath = exports.fetchWithPolicy = exports.FetchPolicyError = void 0;
21
21
  // Shared fetch resilience wrapper — `FetchPolicyError` is re-exported (not
22
22
  // just the type) so a consumer (e.g. a BE prefetch cache) can `instanceof`
23
23
  // it off the failure `fetchPriceFeedsUpdateData` / `PythLazerRule` /
24
24
  // `loadConfig` surface, without a deep import of `./update-fetch.ts`.
25
- // `fetchWithPolicy` itself stays module-internal (no external caller yet).
25
+ // `fetchWithPolicy` + `joinEndpointPath` are exported for consumers that hit
26
+ // Hermes-compatible endpoints THEMSELVES (e.g. the BE's parsed latest-price
27
+ // bootstrap and Pyth schedule readers): one shared Bearer/timeout/retry
28
+ // policy and one base-path-safe URL join, instead of each caller re-rolling
29
+ // them (the hand-rolled copies were how the Pro `/hermes` base path got
30
+ // dropped and the Bearer went missing on sibling fetches).
26
31
  var update_fetch_ts_1 = require("./update-fetch.js");
27
32
  Object.defineProperty(exports, "FetchPolicyError", { enumerable: true, get: function () { return update_fetch_ts_1.FetchPolicyError; } });
28
- // Pyth source `OracleFeeSourceUnavailableError` is re-exported (not just
29
- // the type) for the same `instanceof` reason as `FetchPolicyError` above: a
30
- // consumer of `buildPythPriceUpdateCalls` / `updatePythPrices` /
31
- // `refreshOraclePrices` can branch on the fee-source failure directly.
33
+ Object.defineProperty(exports, "fetchWithPolicy", { enumerable: true, get: function () { return update_fetch_ts_1.fetchWithPolicy; } });
34
+ Object.defineProperty(exports, "joinEndpointPath", { enumerable: true, get: function () { return update_fetch_ts_1.joinEndpointPath; } });
35
+ // Pyth source `OracleFeeSourceUnavailableError` and
36
+ // `HermesEndpointRejectedAllFeedsError` are re-exported (not just the types)
37
+ // for the same `instanceof` reason as `FetchPolicyError` above: a consumer of
38
+ // `buildPythPriceUpdateCalls` / `updatePythPrices` / `refreshOraclePrices` can
39
+ // branch on the fee-source failure directly, and a consumer of
40
+ // `fetchPriceFeedsUpdateData` / `probeMissingFeeds` can tell a misconfigured
41
+ // or unentitled endpoint apart from feeds that endpoint genuinely lacks.
32
42
  var pyth_ts_1 = require("./pyth.js");
33
43
  Object.defineProperty(exports, "PythCache", { enumerable: true, get: function () { return pyth_ts_1.PythCache; } });
34
44
  Object.defineProperty(exports, "fetchPriceFeedsUpdateData", { enumerable: true, get: function () { return pyth_ts_1.fetchPriceFeedsUpdateData; } });
45
+ Object.defineProperty(exports, "endpointSupportedFeedIds", { enumerable: true, get: function () { return pyth_ts_1.endpointSupportedFeedIds; } });
46
+ Object.defineProperty(exports, "probeMissingFeeds", { enumerable: true, get: function () { return pyth_ts_1.probeMissingFeeds; } });
35
47
  Object.defineProperty(exports, "buildPythPriceUpdateCalls", { enumerable: true, get: function () { return pyth_ts_1.buildPythPriceUpdateCalls; } });
36
48
  Object.defineProperty(exports, "updatePythPrices", { enumerable: true, get: function () { return pyth_ts_1.updatePythPrices; } });
49
+ Object.defineProperty(exports, "HermesEndpointRejectedAllFeedsError", { enumerable: true, get: function () { return pyth_ts_1.HermesEndpointRejectedAllFeedsError; } });
50
+ Object.defineProperty(exports, "MISSING_FEED_MEMO_TTL_MS", { enumerable: true, get: function () { return pyth_ts_1.MISSING_FEED_MEMO_TTL_MS; } });
37
51
  Object.defineProperty(exports, "OracleFeeSourceUnavailableError", { enumerable: true, get: function () { return pyth_ts_1.OracleFeeSourceUnavailableError; } });
38
52
  // Pyth Core rule (PriceUpdateRule wrapper over the Pyth source above)
39
53
  var pyth_core_rule_ts_1 = require("./rules/pyth-core-rule.js");