@waterx/sdk 3.1.1 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +54 -18
  2. package/dist/cjs/src/account/config.d.ts +0 -16
  3. package/dist/cjs/src/oracle/aggregate.d.ts +96 -17
  4. package/dist/cjs/src/oracle/aggregate.js +179 -21
  5. package/dist/cjs/src/oracle/config.d.ts +85 -2
  6. package/dist/cjs/src/oracle/config.js +30 -1
  7. package/dist/cjs/src/oracle/host.d.ts +14 -1
  8. package/dist/cjs/src/oracle/index.d.ts +19 -5
  9. package/dist/cjs/src/oracle/index.js +54 -6
  10. package/dist/cjs/src/oracle/price-update-rule.d.ts +180 -0
  11. package/dist/cjs/src/oracle/price-update-rule.js +56 -0
  12. package/dist/cjs/src/oracle/pyth.d.ts +142 -11
  13. package/dist/cjs/src/oracle/pyth.js +408 -25
  14. package/dist/cjs/src/oracle/rule-registry.d.ts +41 -0
  15. package/dist/cjs/src/oracle/rule-registry.js +65 -0
  16. package/dist/cjs/src/oracle/rules/pyth-core-rule.d.ts +15 -0
  17. package/dist/cjs/src/oracle/rules/pyth-core-rule.js +99 -0
  18. package/dist/cjs/src/oracle/rules/pyth-lazer-rule.d.ts +41 -0
  19. package/dist/cjs/src/oracle/rules/pyth-lazer-rule.js +197 -0
  20. package/dist/cjs/src/oracle/rules/pyth-rule.js +5 -0
  21. package/dist/cjs/src/oracle/rules/sponsor.d.ts +11 -7
  22. package/dist/cjs/src/oracle/rules/sponsor.js +11 -7
  23. package/dist/cjs/src/oracle/update-fetch.d.ts +115 -0
  24. package/dist/cjs/src/oracle/update-fetch.js +285 -0
  25. package/dist/cjs/src/perp/client.d.ts +40 -5
  26. package/dist/cjs/src/perp/client.js +18 -3
  27. package/dist/cjs/src/perp/config.d.ts +10 -7
  28. package/dist/cjs/src/perp/config.js +77 -17
  29. package/dist/cjs/src/perp/index.d.ts +3 -2
  30. package/dist/cjs/src/perp/index.js +6 -2
  31. package/dist/cjs/src/perp/tx-builders/common.d.ts +52 -15
  32. package/dist/cjs/src/perp/tx-builders/common.js +39 -6
  33. package/dist/cjs/src/perp/tx-builders/wlp.d.ts +11 -3
  34. package/dist/cjs/src/perp/tx-builders/wlp.js +29 -3
  35. package/dist/cjs/src/perp/tx-builders.d.ts +3 -3
  36. package/dist/cjs/src/perp/tx-builders.js +3 -3
  37. package/dist/cjs/src/unified-client.d.ts +25 -0
  38. package/dist/cjs/src/unified-client.js +3 -0
  39. package/dist/src/account/config.d.ts +0 -16
  40. package/dist/src/oracle/aggregate.d.ts +96 -17
  41. package/dist/src/oracle/aggregate.js +180 -22
  42. package/dist/src/oracle/config.d.ts +85 -2
  43. package/dist/src/oracle/config.js +29 -0
  44. package/dist/src/oracle/host.d.ts +14 -1
  45. package/dist/src/oracle/index.d.ts +19 -5
  46. package/dist/src/oracle/index.js +42 -6
  47. package/dist/src/oracle/price-update-rule.d.ts +180 -0
  48. package/dist/src/oracle/price-update-rule.js +53 -0
  49. package/dist/src/oracle/pyth.d.ts +142 -11
  50. package/dist/src/oracle/pyth.js +402 -24
  51. package/dist/src/oracle/rule-registry.d.ts +41 -0
  52. package/dist/src/oracle/rule-registry.js +60 -0
  53. package/dist/src/oracle/rules/pyth-core-rule.d.ts +15 -0
  54. package/dist/src/oracle/rules/pyth-core-rule.js +96 -0
  55. package/dist/src/oracle/rules/pyth-lazer-rule.d.ts +41 -0
  56. package/dist/src/oracle/rules/pyth-lazer-rule.js +192 -0
  57. package/dist/src/oracle/rules/pyth-rule.js +5 -0
  58. package/dist/src/oracle/rules/sponsor.d.ts +11 -7
  59. package/dist/src/oracle/rules/sponsor.js +11 -7
  60. package/dist/src/oracle/update-fetch.d.ts +115 -0
  61. package/dist/src/oracle/update-fetch.js +277 -0
  62. package/dist/src/perp/client.d.ts +40 -5
  63. package/dist/src/perp/client.js +18 -3
  64. package/dist/src/perp/config.d.ts +10 -7
  65. package/dist/src/perp/config.js +77 -17
  66. package/dist/src/perp/index.d.ts +3 -2
  67. package/dist/src/perp/index.js +1 -1
  68. package/dist/src/perp/tx-builders/common.d.ts +52 -15
  69. package/dist/src/perp/tx-builders/common.js +39 -6
  70. package/dist/src/perp/tx-builders/wlp.d.ts +11 -3
  71. package/dist/src/perp/tx-builders/wlp.js +29 -3
  72. package/dist/src/perp/tx-builders.d.ts +3 -3
  73. package/dist/src/perp/tx-builders.js +3 -3
  74. package/dist/src/unified-client.d.ts +25 -0
  75. package/dist/src/unified-client.js +3 -0
  76. package/package.json +1 -1
@@ -0,0 +1,277 @@
1
+ /**
2
+ * `fetchWithPolicy` — resilience wrapper around `fetch` for the oracle money
3
+ * path's off-chain update-data fetches. Every order/position/collateral
4
+ * tx-build depends on one of these REST calls landing (Hermes VAA for
5
+ * `pyth_rule`, Lazer signed updates for `pyth_lazer_rule`); a bare `fetch`
6
+ * with a single attempt and no retry means one Hermes 429/5xx or timeout
7
+ * fails every trade. `fetchPriceFeedsUpdateData` (`./pyth.ts`),
8
+ * `PythLazerRule.fetchUpdateData`'s Lazer POST (`./rules/pyth-lazer-rule.ts`),
9
+ * and `loadConfig` (`../perp/config.ts`) all delegate here instead of calling
10
+ * `fetch` directly — this is the ONE place a retry/timeout/auth policy is
11
+ * implemented for these fetches.
12
+ *
13
+ * Policy semantics:
14
+ * - Bearer auth is attached iff `policy.apiKey` is a non-empty string —
15
+ * absent/empty is byte-identical to today's keyless request (no
16
+ * `Authorization` header at all). This is the Phase-0 invariant of the
17
+ * Pyth Pro migration: existing keyless deployments see no behavior change.
18
+ * - Retries on network errors, HTTP 429, and HTTP 5xx, with exponential
19
+ * backoff (`retryDelayMs * 2^attempt`, capped at `MAX_BACKOFF_MS`). A 429
20
+ * carrying a numeric `Retry-After` header uses the SERVER'S delay instead,
21
+ * when it fits under the same cap — a longer ask degrades to normal
22
+ * backoff rather than stalling a money-path build for tens of seconds.
23
+ * Other
24
+ * 4xx statuses (401/400/403/404/…) are NOT retried — auth/bad-request
25
+ * failures are deterministic, so that `Response` (`ok: false`) is handed
26
+ * back on the first attempt for the caller to format its own
27
+ * domain-specific error, exactly as it did before this wrapper existed.
28
+ * - `init.body`, if set, MUST be replayable across attempts — a retry
29
+ * re-sends the SAME `init` object to `fetch` on every attempt. A string /
30
+ * `URLSearchParams` / BCS-serialized `Uint8Array` body (every caller today)
31
+ * is fine; a one-shot `ReadableStream` body would not survive a second
32
+ * attempt and must not be passed through this function.
33
+ * - Each attempt gets its own `AbortSignal.timeout(policy.timeoutMs)`
34
+ * combined with whichever of `init.signal` / the `externalSignal` param are
35
+ * set — ALL of them can end the whole policy (not just the in-flight
36
+ * attempt), including a queued backoff sleep, via `AbortSignal.any`
37
+ * (runtime floor: Node ≥20.3 / any modern browser — matches this repo's
38
+ * `target: ES2023` + `lib: ["dom", "esnext"]`).
39
+ * - Exhausting retries with no successful/non-retryable response (i.e. every
40
+ * attempt was a network error, or the final attempt was still a retryable
41
+ * HTTP failure) throws a {@link FetchPolicyError} naming the target's
42
+ * `host + pathname` (never the query string — feed ids are off-chain
43
+ * noise, not diagnostic value), the attempt count, and whichever of
44
+ * `status` (a retryable HTTP failure — plus a truncated response-body
45
+ * snippet, when the final attempt's response carried one) or `cause` (a
46
+ * network error) the final attempt produced. An INTERMEDIATE (non-final)
47
+ * retryable response's body is discarded via `response.body?.cancel()`
48
+ * instead of read, so a doomed-to-retry response doesn't pin its
49
+ * connection's socket open for no reason.
50
+ * - Retry worst case: with the defaults (15s timeout × 3 attempts + ~0.75s of
51
+ * backoff between them) a FULL outage takes up to ~46s to surface as a
52
+ * `FetchPolicyError`, vs ~15s pre-3.2.0's single bare-`fetch` attempt.
53
+ * Tunable per client via the `pythFetch` create option (`{timeoutMs,retries}`).
54
+ */
55
+ const DEFAULT_TIMEOUT_MS = 15_000;
56
+ const DEFAULT_RETRIES = 2;
57
+ const DEFAULT_RETRY_DELAY_MS = 250;
58
+ const MAX_BACKOFF_MS = 2_000;
59
+ /** Final-error diagnostic only — not a protocol limit. */
60
+ const MAX_BODY_SNIPPET_LENGTH = 200;
61
+ /** Thrown by {@link fetchWithPolicy} when every attempt failed. */
62
+ export class FetchPolicyError extends Error {
63
+ /** HTTP status of the final attempt, when it got a (retryable-but-failing) response. */
64
+ status;
65
+ /** Truncated (~200 char) body of the final attempt's response, when one was readable. */
66
+ bodySnippet;
67
+ /** Total attempts made (first try + retries actually used). */
68
+ attempts;
69
+ constructor(message, opts) {
70
+ super(message, opts.cause !== undefined ? { cause: opts.cause } : undefined);
71
+ this.name = "FetchPolicyError";
72
+ this.status = opts.status;
73
+ this.bodySnippet = opts.bodySnippet;
74
+ this.attempts = opts.attempts;
75
+ }
76
+ }
77
+ /**
78
+ * Rethrow a `catch`-ed {@link fetchWithPolicy} failure. When it is a
79
+ * status-carrying `FetchPolicyError` — a retryable status (429/5xx) that never
80
+ * recovered — throw a new Error `${describe(err)} (retries exhausted after N
81
+ * attempts)` with the original as `cause`; otherwise (a network-level
82
+ * exhaustion with no status, or any non-`FetchPolicyError`) rethrow it verbatim,
83
+ * since there is no domain reframing to add. `describe` builds the
84
+ * status-bearing prefix so each caller keeps its own message shape (the e2e
85
+ * transient detector keys off those prefixes) while the guard, the `retries
86
+ * exhausted` suffix, and the `cause` wrapping live in one place. `: never` so a
87
+ * caller's `catch` block is understood not to fall through.
88
+ */
89
+ export function rethrowExhaustedFetch(err, describe) {
90
+ if (err instanceof FetchPolicyError && err.status !== undefined) {
91
+ throw new Error(`${describe(err)} (retries exhausted after ${err.attempts} attempts)`, {
92
+ cause: err,
93
+ });
94
+ }
95
+ throw err;
96
+ }
97
+ /**
98
+ * Join an API `path` onto an `endpoint` PRESERVING the endpoint's own base
99
+ * path. `new URL(path, endpoint)` is the footgun this replaces: a
100
+ * leading-slash path is *absolute* and silently discards the endpoint's path
101
+ * — harmless for a bare-origin endpoint (`https://hermes.pyth.network`) but
102
+ * it dropped the `/hermes` prefix of the Pyth Pro compat endpoint and 404'd
103
+ * every feed (see `fetchPriceFeedsUpdateData`). Every oracle fetch that
104
+ * targets `<endpoint><fixed path>` must build its URL here.
105
+ */
106
+ /** One canonical trailing-slash trim — `joinEndpointPath` (URL building) and
107
+ * `pyth.ts`'s `memoKey` (endpoint identity) must never drift apart on it. */
108
+ export function trimTrailingSlashes(endpoint) {
109
+ return endpoint.replace(/\/+$/, "");
110
+ }
111
+ export function joinEndpointPath(endpoint, path) {
112
+ return new URL(`${trimTrailingSlashes(endpoint)}/${path.replace(/^\/+/, "")}`);
113
+ }
114
+ function isRetryableStatus(status) {
115
+ return status === 429 || status >= 500;
116
+ }
117
+ function backoffMs(retryDelayMs, attempt) {
118
+ return Math.min(retryDelayMs * 2 ** attempt, MAX_BACKOFF_MS);
119
+ }
120
+ /**
121
+ * The server's own `Retry-After` (numeric-seconds form only), when present
122
+ * and within `MAX_BACKOFF_MS` — `undefined` otherwise (absent, HTTP-date
123
+ * form, zero/garbage, or an ask too long to honor inside a build path).
124
+ */
125
+ function retryAfterMs(response) {
126
+ // Optional-chained: minimal test doubles (and some fetch shims) carry no
127
+ // `headers` — a missing header must read as "no hint", never throw.
128
+ const ms = Number(response.headers?.get?.("retry-after")) * 1_000;
129
+ return ms > 0 && ms <= MAX_BACKOFF_MS ? ms : undefined;
130
+ }
131
+ /** `host + pathname` only — never the query string (feed ids are noise, not diagnostic). */
132
+ function describeTarget(url) {
133
+ const parsed = new URL(url);
134
+ return `${parsed.host}${parsed.pathname}`;
135
+ }
136
+ function causeMessage(cause) {
137
+ return cause instanceof Error ? cause.message : String(cause);
138
+ }
139
+ /**
140
+ * Best-effort, truncated body text for the FINAL failed attempt's error
141
+ * message — restores the diagnostic a plain `if (!res.ok) throw new
142
+ * Error(...res.status, await res.text())` had before this wrapper existed.
143
+ * Swallows any read failure (missing/consumed body, a test double with no
144
+ * `.text()`, …) — a diagnostic snippet is never worth failing the request
145
+ * differently than the status/cause already dictate.
146
+ */
147
+ async function readBodySnippet(response) {
148
+ try {
149
+ const text = await response.text();
150
+ return text.length > MAX_BODY_SNIPPET_LENGTH
151
+ ? `${text.slice(0, MAX_BODY_SNIPPET_LENGTH)}…`
152
+ : text;
153
+ }
154
+ catch {
155
+ return "";
156
+ }
157
+ }
158
+ /** Resolves after `ms`, or rejects immediately (with `signal.reason`) if `signal` fires first. */
159
+ function sleep(ms, signal) {
160
+ if (!signal)
161
+ return new Promise((resolve) => setTimeout(resolve, ms));
162
+ const abortSignal = signal;
163
+ if (abortSignal.aborted)
164
+ return Promise.reject(abortSignal.reason);
165
+ return new Promise((resolve, reject) => {
166
+ const onAbort = () => {
167
+ clearTimeout(timer);
168
+ reject(abortSignal.reason);
169
+ };
170
+ const timer = setTimeout(() => {
171
+ abortSignal.removeEventListener("abort", onAbort);
172
+ resolve();
173
+ }, ms);
174
+ abortSignal.addEventListener("abort", onAbort, { once: true });
175
+ });
176
+ }
177
+ /** `undefined` if none are set; the lone signal if exactly one is; `AbortSignal.any(...)` otherwise. */
178
+ function combineSignals(signals) {
179
+ const present = signals.filter((s) => s != null);
180
+ if (present.length === 0)
181
+ return undefined;
182
+ if (present.length === 1)
183
+ return present[0];
184
+ return AbortSignal.any(present);
185
+ }
186
+ /**
187
+ * Merge `Authorization: Bearer <apiKey>` into `base` iff `apiKey` is
188
+ * non-empty; `base` is returned UNTOUCHED otherwise (byte-identical to
189
+ * today's keyless requests — no header, whatever shape the caller passed).
190
+ * Always builds a plain object (never a `Headers` instance) so callers that
191
+ * assert on the exact `init` they handed `fetch` keep working unchanged.
192
+ */
193
+ function withBearerAuth(base, apiKey) {
194
+ if (!apiKey)
195
+ return base;
196
+ const merged = {};
197
+ if (base instanceof Headers) {
198
+ base.forEach((value, key) => {
199
+ merged[key] = value;
200
+ });
201
+ }
202
+ else if (Array.isArray(base)) {
203
+ for (const [key, value] of base)
204
+ merged[key] = value;
205
+ }
206
+ else if (base) {
207
+ Object.assign(merged, base);
208
+ }
209
+ merged.Authorization = `Bearer ${apiKey}`;
210
+ return merged;
211
+ }
212
+ /**
213
+ * `fetch` with per-attempt timeout, bounded retry + backoff, and optional
214
+ * Bearer auth. See the module header for the full policy. Both `init.signal`
215
+ * (if the caller set one) AND the separate `externalSignal` param cancel the
216
+ * WHOLE policy — in-flight attempts AND queued backoff sleeps — not just a
217
+ * single attempt.
218
+ */
219
+ export async function fetchWithPolicy(url, init = {}, policy = {}, externalSignal) {
220
+ const timeoutMs = policy.timeoutMs ?? DEFAULT_TIMEOUT_MS;
221
+ const retries = policy.retries ?? DEFAULT_RETRIES;
222
+ const retryDelayMs = policy.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
223
+ const doFetch = policy.fetchImpl ?? fetch;
224
+ const headers = withBearerAuth(init.headers, policy.apiKey);
225
+ // init.signal is folded in here (not spread through per-attempt below) so
226
+ // it gates retries/backoff exactly like externalSignal, instead of being
227
+ // silently dropped by the `{ ...init, signal }` override per attempt.
228
+ const combinedExternalSignal = combineSignals([externalSignal, init.signal]);
229
+ for (let attempt = 0; attempt <= retries; attempt++) {
230
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
231
+ const signal = combinedExternalSignal
232
+ ? AbortSignal.any([timeoutSignal, combinedExternalSignal])
233
+ : timeoutSignal;
234
+ let status;
235
+ let bodySnippet;
236
+ let cause;
237
+ let serverRetryDelay;
238
+ try {
239
+ const response = await doFetch(url, { ...init, headers, signal });
240
+ if (response.ok || !isRetryableStatus(response.status))
241
+ return response;
242
+ status = response.status;
243
+ serverRetryDelay = retryAfterMs(response);
244
+ if (attempt === retries) {
245
+ bodySnippet = await readBodySnippet(response);
246
+ }
247
+ else {
248
+ // Doomed to be retried — discard rather than read, so this
249
+ // response's connection/socket isn't held open for a body nobody
250
+ // will consume. `.catch()` is mandatory here: an errored stream's
251
+ // `cancel()` returns a REJECTED promise, and a bare `void` on that
252
+ // is an unhandled rejection — process-fatal in Node — triggered by
253
+ // exactly the degraded-upstream condition this wrapper exists to
254
+ // survive.
255
+ void response.body?.cancel().catch(() => { });
256
+ }
257
+ }
258
+ catch (err) {
259
+ if (combinedExternalSignal?.aborted)
260
+ throw err;
261
+ cause = err;
262
+ }
263
+ if (attempt === retries) {
264
+ const statusDetail = status !== undefined
265
+ ? `last status ${status}${bodySnippet ? ` — ${bodySnippet}` : ""}`
266
+ : undefined;
267
+ const detail = statusDetail ?? causeMessage(cause);
268
+ throw new FetchPolicyError(`fetchWithPolicy: ${describeTarget(url)} failed after ${attempt + 1} attempt(s) — ${detail}`, { status, bodySnippet, cause, attempts: attempt + 1 });
269
+ }
270
+ await sleep(serverRetryDelay ?? backoffMs(retryDelayMs, attempt), combinedExternalSignal);
271
+ }
272
+ // Unreachable: the loop above always returns or throws on its final
273
+ // (attempt === retries) iteration — this satisfies the compiler only.
274
+ throw new FetchPolicyError(`fetchWithPolicy: ${describeTarget(url)} exhausted retries`, {
275
+ attempts: retries + 1,
276
+ });
277
+ }
@@ -11,24 +11,59 @@
11
11
  * {@link PerpConfigView}. This class is just the wiring + factory between them.
12
12
  */
13
13
  import { BaseLineClient } from "../base-client.ts";
14
- import { type LoadConfigOptions, type PythInfraConfig, type WaterXConfig, type WormholeInfraConfig } from "./config.ts";
14
+ import type { OracleSource } from "../oracle/price-update-rule.ts";
15
+ import { type LoadConfigOptions, type PythFetchPolicy, type PythInfraConfig, type WaterXConfig, type WormholeInfraConfig } from "./config.ts";
15
16
  import type { Network } from "./constants.ts";
16
17
  export interface CreateClientOptions extends LoadConfigOptions {
17
18
  grpcUrl?: string;
19
+ /**
20
+ * Which oracle price-update source drives `refreshOraclePrices`. Each source
21
+ * is self-contained (own infra + config) with NO cross-source fallback:
22
+ *
23
+ * - `'pyth_rule'` (default) — Pyth Core `pyth_rule` updates (Hermes VAA +
24
+ * per-feed update fees), Core state + keyless Core Hermes.
25
+ * - `'pyth_lazer_rule'` — Pyth Lazer signed updates (ONE `leEcdsa` verify
26
+ * per PTB, no per-feed fees); needs `packages.pyth_lazer_rule` with feeds
27
+ * and a `pythApiKey` (Lazer is auth-first).
28
+ *
29
+ * A source-neutral name on purpose — a future source need not be Pyth.
30
+ * Selecting a source whose feed for a requested ticker is absent is NOT an
31
+ * error at client creation: it fails at tx-build time for exactly those
32
+ * tickers (see `refreshOraclePrices`). The Pyth Core infra is fixed per
33
+ * network by `PYTH_DEFAULTS` and is not deployment-overridable.
34
+ */
35
+ oracleSource?: OracleSource;
36
+ /**
37
+ * Pyth Lazer access token (`Authorization: Bearer …`). Required under
38
+ * `oracleSource: 'pyth_lazer_rule'` (Lazer is auth-first) and unused by
39
+ * `'pyth_rule'` (keyless Core Hermes). This is a SECRET and never belongs in
40
+ * the canonical `waterx-config` JSON — pass it at client init from your own
41
+ * env var (e.g. `PYTH_API_KEY`); the SDK never reads `process.env`.
42
+ */
43
+ pythApiKey?: string;
44
+ /**
45
+ * Retry/timeout policy for the off-chain Hermes / Lazer update fetches (see
46
+ * `fetchWithPolicy`). Optional — defaults to 15s timeout, 2 retries.
47
+ */
48
+ pythFetch?: PythFetchPolicy;
18
49
  }
19
50
  export declare class PerpClient extends BaseLineClient<WaterXConfig> {
20
- /** Pyth infra (network defaults unless overridden in JSON). */
51
+ /** Pyth Core infra (fixed per network) plus the caller-supplied credential/policy. */
21
52
  pyth: PythInfraConfig;
22
53
  /** Wormhole infra for the credit bridge (network defaults unless overridden). */
23
54
  wormhole: WormholeInfraConfig;
55
+ /** Selected oracle price-update source (`oracleSource` create option; default `'pyth_rule'`). */
56
+ readonly oracleSource: OracleSource;
24
57
  /** Canonical-schema lookups (delegated to below); no transport. */
25
58
  private readonly view;
26
- constructor(network: Network, config: WaterXConfig, opts?: {
27
- grpcUrl?: string;
28
- });
59
+ constructor(network: Network, config: WaterXConfig, opts?: CreateClientOptions);
29
60
  /**
30
61
  * Async factory: fetches the deployment config for `network` and returns
31
62
  * a ready-to-use client. Pass `opts.cache=true` to memoize the JSON.
63
+ *
64
+ * No oracle-config guard here: selecting a source whose feeds are absent is
65
+ * not an error at init — it surfaces at tx-build time for the specific
66
+ * tickers that source can't serve (see `refreshOraclePrices`).
32
67
  */
33
68
  static create(network: Network, opts?: CreateClientOptions): Promise<PerpClient>;
34
69
  static mainnet(opts?: CreateClientOptions): Promise<PerpClient>;
@@ -14,25 +14,40 @@ import { BaseLineClient } from "../base-client.js";
14
14
  import { PerpConfigView } from "./config-view.js";
15
15
  import { loadConfig, PYTH_DEFAULTS, WORMHOLE_DEFAULTS, } from "./config.js";
16
16
  export class PerpClient extends BaseLineClient {
17
- /** Pyth infra (network defaults unless overridden in JSON). */
17
+ /** Pyth Core infra (fixed per network) plus the caller-supplied credential/policy. */
18
18
  pyth;
19
19
  /** Wormhole infra for the credit bridge (network defaults unless overridden). */
20
20
  wormhole;
21
+ /** Selected oracle price-update source (`oracleSource` create option; default `'pyth_rule'`). */
22
+ oracleSource;
21
23
  /** Canonical-schema lookups (delegated to below); no transport. */
22
24
  view;
23
25
  constructor(network, config, opts = {}) {
24
26
  super(network, config, opts);
25
- this.pyth = config.pyth ?? PYTH_DEFAULTS[network];
27
+ // Pyth Core infra is fixed per network — NOT deployment-overridable and
28
+ // NOT source-dependent (the pyth_lazer_rule source reads only api_key/fetch
29
+ // from here). The api_key + fetch policy are caller-supplied at init: a
30
+ // secret has no place in the canonical waterx-config JSON.
31
+ this.pyth = {
32
+ ...PYTH_DEFAULTS[network],
33
+ ...(opts.pythApiKey !== undefined ? { api_key: opts.pythApiKey } : {}),
34
+ ...(opts.pythFetch !== undefined ? { fetch: opts.pythFetch } : {}),
35
+ };
26
36
  this.wormhole = config.wormhole ?? WORMHOLE_DEFAULTS[network];
37
+ this.oracleSource = opts.oracleSource ?? "pyth_rule";
27
38
  this.view = new PerpConfigView(() => this.config, () => this.wormhole);
28
39
  }
29
40
  /**
30
41
  * Async factory: fetches the deployment config for `network` and returns
31
42
  * a ready-to-use client. Pass `opts.cache=true` to memoize the JSON.
43
+ *
44
+ * No oracle-config guard here: selecting a source whose feeds are absent is
45
+ * not an error at init — it surfaces at tx-build time for the specific
46
+ * tickers that source can't serve (see `refreshOraclePrices`).
32
47
  */
33
48
  static async create(network, opts = {}) {
34
49
  const config = await loadConfig(network, opts);
35
- return new PerpClient(network, config, { grpcUrl: opts.grpcUrl });
50
+ return new PerpClient(network, config, opts);
36
51
  }
37
52
  static mainnet(opts = {}) {
38
53
  return PerpClient.create("MAINNET", opts);
@@ -9,10 +9,10 @@
9
9
  * below, keyed by network.
10
10
  */
11
11
  import type { AccountPackages, BasePackageEntry, WormholeInfraConfig } from "../account/config.ts";
12
- import type { OraclePackages, PythInfraConfig } from "../oracle/config.ts";
12
+ import type { OraclePackages } from "../oracle/config.ts";
13
13
  import type { Network } from "./constants.ts";
14
- export type { AccountConfig, AccountPackages, BasePackageEntry, NativeCustodyAsset, NativeCustodyPackage, TrustedEmitterRow, WaterxCreditPackage, WaterxReferralPackage, WithdrawalQueuePackage, WormholeBridgePackage, WormholeInfraConfig, WxaAccountPackage, } from "../account/config.ts";
15
- export type { ConstantFeedEntry, OracleConfig, OraclePackages, PythInfraConfig, PythRulePackage, PythSponsorRulePackage, SupraFeedEntry, SupraRulePackage, WaterxConstantRulePackage, WaterxOraclePackage, } from "../oracle/config.ts";
14
+ export type { AccountConfig, AccountPackages, BasePackageEntry, NativeCustodyAsset, NativeCustodyPackage, WaterxCreditPackage, WaterxReferralPackage, WithdrawalQueuePackage, WormholeBridgePackage, WormholeInfraConfig, WxaAccountPackage, } from "../account/config.ts";
15
+ export type { ConstantFeedEntry, OracleConfig, OraclePackages, PythFetchPolicy, PythInfraConfig, PythLazerRulePackage, PythRulePackage, PythSponsorRulePackage, SupraFeedEntry, SupraRulePackage, WaterxConstantRulePackage, WaterxOraclePackage, } from "../oracle/config.ts";
16
16
  export { PYTH_DEFAULTS } from "../oracle/config.ts";
17
17
  export interface WaterxPerpMarketEntry {
18
18
  market: string;
@@ -82,8 +82,6 @@ export interface WaterXConfig {
82
82
  /** Sui gRPC base URL (default: public Mysten fullnode for the network). */
83
83
  grpcUrl?: string;
84
84
  packages: WaterXPackages;
85
- /** Pyth infra override (defaults from `PYTH_DEFAULTS[network]`). */
86
- pyth?: PythInfraConfig;
87
85
  /** Wormhole infra override (defaults from `WORMHOLE_DEFAULTS[network]`). */
88
86
  wormhole?: WormholeInfraConfig;
89
87
  /** Sui `CoinRegistry` shared object (credit deployments). */
@@ -104,12 +102,17 @@ export interface LoadConfigOptions {
104
102
  waterxConfigUrl?: string;
105
103
  /**
106
104
  * Reuse a previously-fetched config from the in-memory cache (keyed by
107
- * the effective URL). Default: false (always fetch fresh).
105
+ * network + the effective URL). Default: false (always fetch fresh).
108
106
  */
109
107
  cache?: boolean;
110
108
  /** Optional fetch implementation (for tests or environments without global `fetch`). */
111
109
  fetchImpl?: typeof fetch;
112
- /** Optional request timeout in ms. Default 10_000. */
110
+ /**
111
+ * Optional PER-ATTEMPT timeout in ms. Default 10_000. {@link loadConfig}
112
+ * retries a transient failure (network error / 429 / 5xx) via
113
+ * `fetchWithPolicy` (2 retries, exponential backoff) before falling back to
114
+ * the last successfully-validated config for this network+URL, if one exists.
115
+ */
113
116
  timeoutMs?: number;
114
117
  }
115
118
  export declare function clearConfigCache(): void;
@@ -8,6 +8,7 @@
8
8
  * **not** in the JSON — it lives in `PYTH_DEFAULTS` / `WORMHOLE_DEFAULTS`
9
9
  * below, keyed by network.
10
10
  */
11
+ import { fetchWithPolicy, rethrowExhaustedFetch } from "../oracle/update-fetch.js";
11
12
  export { PYTH_DEFAULTS } from "../oracle/config.js";
12
13
  // ============================================================================
13
14
  // Wormhole / Hermes — external chain infra, defaults by network
@@ -33,38 +34,94 @@ export const WORMHOLE_DEFAULTS = {
33
34
  wormholescan_api: "https://api.testnet.wormholescan.io/api/v1",
34
35
  },
35
36
  };
36
- const cache = new Map();
37
+ // Last successfully-validated config per `${network}:${url}` — the ONE module
38
+ // map, written UNCONDITIONALLY on every successful load regardless of
39
+ // `opts.cache`. It serves two roles at once: the resilience fallback for a
40
+ // refresh failure (see `loadConfig` below) AND the opt-in fast-path read
41
+ // `opts.cache: true` gates at the top of `loadConfig`. `opts.cache` therefore
42
+ // only gates whether a call *reads* this map early (skipping the fetch
43
+ // entirely) — it never gates whether a call *writes* it; every successful
44
+ // load writes here. The network prefix keeps one network's snapshot from ever
45
+ // satisfying another's request (see the cache-key note in `loadConfig`).
46
+ //
47
+ // Deliberate (benign) semantic refinement from the prior two-map design: a
48
+ // `cache: true` call can now hit an entry that was populated by an earlier
49
+ // `cache: false` call for the SAME network+url. That's fine — it's still that
50
+ // key's latest successfully-validated fetch, strictly FRESHER than any
51
+ // fallback read would have been, so a `cache: true` caller never observes
52
+ // staler data than before; it can only observe MORE-recent data sooner.
53
+ const configCache = new Map();
37
54
  export function clearConfigCache() {
38
- cache.clear();
55
+ configCache.clear();
39
56
  }
40
57
  export async function loadConfig(network, opts = {}) {
41
58
  const url = opts.waterxConfigUrl;
42
59
  if (!url) {
43
60
  throw new Error("loadConfig: no config URL — pass opts.waterxConfigUrl");
44
61
  }
45
- if (opts.cache && cache.has(url)) {
46
- return cache.get(url);
62
+ // Key by network AND url, never url alone: the same url can legitimately be
63
+ // requested for two networks (and `validateConfig` enforces network/url
64
+ // coherence on the success path), so a url-only key would let a testnet
65
+ // snapshot satisfy a mainnet request — both on this fast-path read and on
66
+ // the resilience fallback below — handing back wrong-CHAIN object ids to
67
+ // build transactions against. A wrong-network request simply misses here
68
+ // and fetches fresh.
69
+ const cacheKey = `${network}:${url}`;
70
+ if (opts.cache && configCache.has(cacheKey)) {
71
+ return configCache.get(cacheKey);
47
72
  }
48
73
  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
49
74
  if (!fetchImpl) {
50
75
  throw new Error("loadConfig: no global `fetch` available; pass opts.fetchImpl");
51
76
  }
52
- const controller = new AbortController();
53
- const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 10_000);
54
- let response;
77
+ // Same resilience policy as the oracle money-path fetches (see
78
+ // `fetchWithPolicy`): bounded retry with backoff instead of one bare
79
+ // attempt. A refresh failure (network exhaustion, a non-ok response, OR a
80
+ // 200 response that fails to parse/validate — see below) falls back to the
81
+ // last successfully-validated config for this network+URL when one exists — a
82
+ // config-endpoint blip must not crash a long-running process that already
83
+ // has a working deployment snapshot. First load (nothing cached yet) has
84
+ // no fallback and still throws. Intentionally no log line on the fallback
85
+ // path — the SDK never logs (see every other oracle error in this
86
+ // codebase); a caller that cares can tell it got a stale snapshot by
87
+ // re-deriving staleness itself if it needs to.
88
+ //
89
+ // Deliberate limitation (not fixed here — a follow-up): this treats EVERY
90
+ // failure mode identically, including a DETERMINISTIC one (404/403 — the
91
+ // URL moved, or access was revoked) once a `configCache` snapshot exists.
92
+ // Unlike a transient blip, a deterministic failure will never self-heal on
93
+ // the next retry, so a long-running process with a stale snapshot will
94
+ // keep serving it FOREVER and silently mask what is actually a permanent
95
+ // deployment problem. Disambiguating "blip" from "moved/revoked" (e.g. via
96
+ // a max-staleness budget, or treating non-retryable 4xx specially) is
97
+ // intentionally deferred rather than folded into this change.
98
+ //
99
+ // fetch → ok-check → parse → validate all run in ONE try, so any failure
100
+ // along that chain (network exhaustion, a non-ok response, malformed JSON,
101
+ // or a `validateConfig` rejection) lands in the same catch and takes the
102
+ // same single last-known-good lookup below.
103
+ let raw;
55
104
  try {
56
- response = await fetchImpl(url, { signal: controller.signal });
57
- }
58
- finally {
59
- clearTimeout(timer);
105
+ const response = await fetchWithPolicy(url, {}, { timeoutMs: opts.timeoutMs ?? 10_000, retries: 2, fetchImpl });
106
+ if (!response.ok) {
107
+ throw new Error(`loadConfig: HTTP ${response.status} fetching ${url}`);
108
+ }
109
+ raw = (await response.json());
110
+ validateConfig(raw, network, url);
60
111
  }
61
- if (!response.ok) {
62
- throw new Error(`loadConfig: HTTP ${response.status} fetching ${url}`);
112
+ catch (err) {
113
+ const stale = configCache.get(cacheKey);
114
+ if (stale)
115
+ return stale;
116
+ // Reframe a status-carrying FetchPolicyError into this function's own
117
+ // message shape, mirroring the non-retried `!response.ok` throw above and
118
+ // carrying the URL (the key datum for a config-fetch failure). A
119
+ // network-level exhaustion (no status), a `!response.ok` throw, or a JSON
120
+ // parse / `validateConfig` failure has no reframing to add — the helper
121
+ // propagates those verbatim.
122
+ rethrowExhaustedFetch(err, (e) => `loadConfig: HTTP ${e.status} fetching ${url}`);
63
123
  }
64
- const raw = (await response.json());
65
- validateConfig(raw, network, url);
66
- if (opts.cache)
67
- cache.set(url, raw);
124
+ configCache.set(cacheKey, raw);
68
125
  return raw;
69
126
  }
70
127
  function validateConfig(cfg, expected, url) {
@@ -82,6 +139,9 @@ function validateConfig(cfg, expected, url) {
82
139
  };
83
140
  // Validate by deployment kind. A perp config must carry the perp set; a
84
141
  // credit config the credit set. `waterx_account` is common to both.
142
+ // `pyth_lazer_rule` is intentionally NOT required (and never will be by
143
+ // presence alone) — it's an optional/experimental package selected only via
144
+ // a client's `oracleSource` option, never by its presence in the config.
85
145
  const isPerp = "waterx_perp" in cfg.packages;
86
146
  const isCredit = "waterx_credit" in cfg.packages || "wormhole_bridge" in cfg.packages;
87
147
  const required = isPerp
@@ -1,7 +1,7 @@
1
1
  export { PerpClient } from "./client.ts";
2
2
  export type { CreateClientOptions } from "./client.ts";
3
3
  export { PYTH_DEFAULTS, WORMHOLE_DEFAULTS, clearConfigCache, loadConfig } from "./config.ts";
4
- export type { BasePackageEntry, ConstantFeedEntry, WaterxReferralPackage, LoadConfigOptions, NativeCustodyAsset, NativeCustodyPackage, PythInfraConfig, PythRulePackage, PythSponsorRulePackage, SupraFeedEntry, SupraRulePackage, TestnetFaucetPackage, TrustedEmitterRow, WaterXConfig, WaterXPackages, WaterxCreditPackage, WaterxOraclePackage, WaterxPerpMarketEntry, WaterxPerpPackage, WaterxStakingPackage, WithdrawalQueuePackage, WlpPackage, WormholeBridgePackage, WormholeInfraConfig, WxaAccountPackage, } from "./config.ts";
4
+ export type { BasePackageEntry, ConstantFeedEntry, WaterxReferralPackage, LoadConfigOptions, NativeCustodyAsset, NativeCustodyPackage, PythFetchPolicy, PythInfraConfig, PythLazerRulePackage, PythRulePackage, PythSponsorRulePackage, SupraFeedEntry, SupraRulePackage, TestnetFaucetPackage, WaterXConfig, WaterXPackages, WaterxCreditPackage, WaterxOraclePackage, WaterxPerpMarketEntry, WaterxPerpPackage, WaterxStakingPackage, WithdrawalQueuePackage, WlpPackage, WormholeBridgePackage, WormholeInfraConfig, WxaAccountPackage, } from "./config.ts";
5
5
  export { ACTION_ADD_PRE_ORDER, ACTION_CANCEL_ORDER, ACTION_CANCEL_PRE_ORDER, ACTION_CLOSE_POSITION, ACTION_DECREASE_POSITION, ACTION_DEPOSIT_COLLATERAL, ACTION_INCREASE_POSITION, ACTION_LIQUIDATE, ACTION_OPEN_POSITION, ACTION_PLACE_ORDER, ACTION_UPDATE_ORDER, ACTION_WITHDRAW_COLLATERAL, BPS_SCALE, CRYPTO_FEE_RATE, DOUBLE_SCALE, DRY_RUN_SENDER, FLOAT_SCALE, MAINTENANCE_MARGIN_RATE, ORDER_LIMIT_BUY, ORDER_LIMIT_SELL, ORDER_STOP_BUY, ORDER_STOP_SELL, ORDER_TAG_WILDCARD, PERM_ALL, PERM_ALL_TRADING, PERM_CANCEL_ORDER, PERM_CLOSE_POSITION, PERM_DECREASE_POSITION, PERM_DEPOSIT_COLLATERAL, PERM_INCREASE_POSITION, PERM_MINT_WLP, PERM_OPEN_POSITION, PERM_PLACE_ORDER, PERM_REDEEM_WLP, PERM_WITHDRAW_COLLATERAL, STAKING_PERM_DEPOSIT_STAKE, STAKING_PERM_REDEEM_STAKE, STAKING_PERM_CLAIM_REWARD, STAKING_PERM_ALL, STOCK_FEE_RATE, MS_PER_YEAR, SUI_DECIMALS, WLP_DECIMALS, COLLATERAL_DECIMALS, TOKEN_DECIMALS, } from "./constants.ts";
6
6
  export type { Network } from "./constants.ts";
7
7
  export { getMarketTickers, getCollateralAssets } from "../utils/config.ts";
@@ -9,7 +9,8 @@ export { annualizedApyFromRatio, annualizeFundingRate, calcBorrowRate, calcBorro
9
9
  export * from "./user/index.ts";
10
10
  export * from "./tx-builders.ts";
11
11
  export * from "./fetch.ts";
12
- export { PythCache, aggregateTicker, aggregateTickerWithConstant, aggregateTickerWithPyth, buildPythPriceUpdateCalls, fetchPriceFeedsUpdateData, refreshOraclePrices, updatePythPrices, } from "../oracle/index.ts";
12
+ export { FetchPolicyError, LazerApiKeyMissingError, OracleFeeSourceUnavailableError, OracleSourceNotImplementedError, PythCache, aggregateTicker, aggregateTickerWithConstant, aggregateTickerWithPyth, buildPythPriceUpdateCalls, fetchPriceFeedsUpdateData, refreshOraclePrices, updatePythPrices, } from "../oracle/index.ts";
13
+ export type { FetchPolicy, OracleFeeSource, OracleSource, UpdateDataProvider, } from "../oracle/index.ts";
13
14
  export { fetchDepositVaa, fetchVaa, listBridgeWithdrawalVaas, listVaasByEmitter, padEvmEmitter, toWormholescanEmitter, vaaBase64ToBytes, vaaBase64ToHex, vaaBytesToBase64, waitForVaa, } from "../account/funding/wormhole.ts";
14
15
  export type { VaaListItem, VaaResponse, WormholescanOptions } from "../account/funding/wormhole.ts";
15
16
  export { AccountData as AccountDataBcs, GlobalConfigData as GlobalConfigDataBcs, MarketData as MarketDataBcs, OrderData as OrderDataBcs, PoolData as PoolDataBcs, PositionData as PositionDataBcs, RedeemRequestData as RedeemRequestDataBcs, TokenPoolData as TokenPoolDataBcs, } from "../generated/waterx_perp_view/view.ts";
@@ -13,7 +13,7 @@ export * from "./tx-builders.js";
13
13
  // ======== Read-only queries ========
14
14
  export * from "./fetch.js";
15
15
  // ======== Oracle utilities (Pyth source + rule aggregation) ========
16
- export { PythCache, aggregateTicker, aggregateTickerWithConstant, aggregateTickerWithPyth, buildPythPriceUpdateCalls, fetchPriceFeedsUpdateData, refreshOraclePrices, updatePythPrices, } from "../oracle/index.js";
16
+ export { FetchPolicyError, LazerApiKeyMissingError, OracleFeeSourceUnavailableError, OracleSourceNotImplementedError, PythCache, aggregateTicker, aggregateTickerWithConstant, aggregateTickerWithPyth, buildPythPriceUpdateCalls, fetchPriceFeedsUpdateData, refreshOraclePrices, updatePythPrices, } from "../oracle/index.js";
17
17
  // ======== Wormhole / Wormholescan utilities (credit bridge) ========
18
18
  export { fetchDepositVaa, fetchVaa, listBridgeWithdrawalVaas, listVaasByEmitter, padEvmEmitter, toWormholescanEmitter, vaaBase64ToBytes, vaaBase64ToHex, vaaBytesToBase64, waitForVaa, } from "../account/funding/wormhole.js";
19
19
  // ======== Generated BCS types (sui-ts-codegen) ========