@waterx/sdk 4.0.1 → 4.1.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 (110) hide show
  1. package/README.md +25 -10
  2. package/dist/cjs/src/account/account.js +2 -1
  3. package/dist/cjs/src/account/funding/balance.d.ts +25 -2
  4. package/dist/cjs/src/account/funding/balance.js +36 -24
  5. package/dist/cjs/src/account/funding/credit.js +6 -10
  6. package/dist/cjs/src/constants.d.ts +15 -1
  7. package/dist/cjs/src/constants.js +18 -4
  8. package/dist/cjs/src/generated/waterx_rule/deps/bucket_v2_framework/float.d.ts +8 -0
  9. package/dist/cjs/src/generated/waterx_rule/deps/bucket_v2_framework/float.js +13 -0
  10. package/dist/cjs/src/generated/waterx_rule/deps/sui/vec_map.d.ts +36 -0
  11. package/dist/cjs/src/generated/waterx_rule/deps/sui/vec_map.js +31 -0
  12. package/dist/cjs/src/generated/waterx_rule/waterx_rule.d.ts +940 -0
  13. package/dist/cjs/src/generated/waterx_rule/waterx_rule.js +1092 -0
  14. package/dist/cjs/src/oracle/aggregate.d.ts +2 -0
  15. package/dist/cjs/src/oracle/aggregate.js +27 -2
  16. package/dist/cjs/src/oracle/config.d.ts +75 -0
  17. package/dist/cjs/src/oracle/config.js +15 -1
  18. package/dist/cjs/src/oracle/host.d.ts +12 -1
  19. package/dist/cjs/src/oracle/index.d.ts +2 -0
  20. package/dist/cjs/src/oracle/index.js +6 -1
  21. package/dist/cjs/src/oracle/price-update-rule.d.ts +3 -4
  22. package/dist/cjs/src/oracle/rule-registry.d.ts +8 -7
  23. package/dist/cjs/src/oracle/rule-registry.js +10 -7
  24. package/dist/cjs/src/oracle/rules/waterx-rule.d.ts +89 -0
  25. package/dist/cjs/src/oracle/rules/waterx-rule.js +272 -0
  26. package/dist/cjs/src/perp/client.d.ts +44 -6
  27. package/dist/cjs/src/perp/client.js +14 -0
  28. package/dist/cjs/src/perp/config.d.ts +2 -3
  29. package/dist/cjs/src/perp/config.js +2 -1
  30. package/dist/cjs/src/perp/constants.d.ts +0 -6
  31. package/dist/cjs/src/perp/constants.js +11 -9
  32. package/dist/cjs/src/perp/fetch/account.js +3 -0
  33. package/dist/cjs/src/perp/fetch/bridge.js +2 -1
  34. package/dist/cjs/src/perp/fetch/market.js +2 -1
  35. package/dist/cjs/src/perp/fetch/positions.d.ts +16 -10
  36. package/dist/cjs/src/perp/fetch/positions.js +23 -20
  37. package/dist/cjs/src/perp/index.d.ts +6 -2
  38. package/dist/cjs/src/perp/index.js +12 -6
  39. package/dist/cjs/src/perp/liq-view.d.ts +64 -0
  40. package/dist/cjs/src/perp/liq-view.js +74 -0
  41. package/dist/cjs/src/perp/user/order.d.ts +13 -0
  42. package/dist/cjs/src/perp/user/order.js +30 -16
  43. package/dist/cjs/src/perp/user/staking.js +3 -2
  44. package/dist/cjs/src/perp/user/trading.js +25 -24
  45. package/dist/cjs/src/perp/user/wlp.js +6 -5
  46. package/dist/cjs/src/prediction/utils.d.ts +11 -2
  47. package/dist/cjs/src/prediction/utils.js +22 -22
  48. package/dist/cjs/src/unified-client.d.ts +31 -10
  49. package/dist/cjs/src/unified-client.js +2 -0
  50. package/dist/cjs/src/utils/format.d.ts +14 -0
  51. package/dist/cjs/src/utils/format.js +24 -0
  52. package/dist/cjs/src/utils/math.d.ts +304 -12
  53. package/dist/cjs/src/utils/math.js +397 -17
  54. package/dist/cjs/src/utils/validate.d.ts +69 -0
  55. package/dist/cjs/src/utils/validate.js +183 -0
  56. package/dist/src/account/account.js +2 -1
  57. package/dist/src/account/funding/balance.d.ts +25 -2
  58. package/dist/src/account/funding/balance.js +36 -24
  59. package/dist/src/account/funding/credit.js +6 -10
  60. package/dist/src/constants.d.ts +15 -1
  61. package/dist/src/constants.js +17 -3
  62. package/dist/src/generated/waterx_rule/deps/bucket_v2_framework/float.d.ts +8 -0
  63. package/dist/src/generated/waterx_rule/deps/bucket_v2_framework/float.js +10 -0
  64. package/dist/src/generated/waterx_rule/deps/sui/vec_map.d.ts +36 -0
  65. package/dist/src/generated/waterx_rule/deps/sui/vec_map.js +27 -0
  66. package/dist/src/generated/waterx_rule/waterx_rule.d.ts +940 -0
  67. package/dist/src/generated/waterx_rule/waterx_rule.js +991 -0
  68. package/dist/src/oracle/aggregate.d.ts +2 -0
  69. package/dist/src/oracle/aggregate.js +27 -2
  70. package/dist/src/oracle/config.d.ts +75 -0
  71. package/dist/src/oracle/config.js +14 -0
  72. package/dist/src/oracle/host.d.ts +12 -1
  73. package/dist/src/oracle/index.d.ts +2 -0
  74. package/dist/src/oracle/index.js +3 -0
  75. package/dist/src/oracle/price-update-rule.d.ts +3 -4
  76. package/dist/src/oracle/rule-registry.d.ts +8 -7
  77. package/dist/src/oracle/rule-registry.js +10 -7
  78. package/dist/src/oracle/rules/waterx-rule.d.ts +89 -0
  79. package/dist/src/oracle/rules/waterx-rule.js +266 -0
  80. package/dist/src/perp/client.d.ts +44 -6
  81. package/dist/src/perp/client.js +15 -1
  82. package/dist/src/perp/config.d.ts +2 -3
  83. package/dist/src/perp/config.js +1 -1
  84. package/dist/src/perp/constants.d.ts +0 -6
  85. package/dist/src/perp/constants.js +10 -8
  86. package/dist/src/perp/fetch/account.js +3 -0
  87. package/dist/src/perp/fetch/bridge.js +2 -1
  88. package/dist/src/perp/fetch/market.js +2 -1
  89. package/dist/src/perp/fetch/positions.d.ts +16 -10
  90. package/dist/src/perp/fetch/positions.js +28 -20
  91. package/dist/src/perp/index.d.ts +6 -2
  92. package/dist/src/perp/index.js +4 -2
  93. package/dist/src/perp/liq-view.d.ts +64 -0
  94. package/dist/src/perp/liq-view.js +71 -0
  95. package/dist/src/perp/user/order.d.ts +13 -0
  96. package/dist/src/perp/user/order.js +30 -16
  97. package/dist/src/perp/user/staking.js +3 -2
  98. package/dist/src/perp/user/trading.js +25 -24
  99. package/dist/src/perp/user/wlp.js +6 -5
  100. package/dist/src/prediction/utils.d.ts +11 -2
  101. package/dist/src/prediction/utils.js +22 -22
  102. package/dist/src/unified-client.d.ts +31 -10
  103. package/dist/src/unified-client.js +2 -0
  104. package/dist/src/utils/format.d.ts +14 -0
  105. package/dist/src/utils/format.js +21 -0
  106. package/dist/src/utils/math.d.ts +304 -12
  107. package/dist/src/utils/math.js +394 -17
  108. package/dist/src/utils/validate.d.ts +69 -0
  109. package/dist/src/utils/validate.js +167 -0
  110. package/package.json +4 -1
@@ -0,0 +1,266 @@
1
+ /**
2
+ * `WaterxRule` — `PriceUpdateRule` for the first-party WaterX quote-center
3
+ * (Nautilus-TEE, ed25519), plus `feedWaterxRule`, the collector-feed leg
4
+ * `aggregateTicker` appends per waterx-routed ticker. Pulls one enclave-signed
5
+ * batch envelope covering every requested ticker from the quote-center
6
+ * (`GET /v1/quotes/update?symbols=…`, endpoint from `host.waterx` — the
7
+ * `waterxEndpoint`/`waterxFetch` create options — else `WATERX_DEFAULTS`), then —
8
+ * unlike Pyth Lazer, whose verify is a single shared PTB step — verifies AND
9
+ * feeds in ONE `waterx_rule::collect_batch_latest` call per collector (the Move
10
+ * API bundles the two). So `buildUpdateCalls` emits nothing and the signed
11
+ * envelope is handed straight to the per-ticker feed leg.
12
+ *
13
+ * `collect_batch_latest` is the dual-rule path: it feeds the item matching
14
+ * `collector.symbol()` WITHOUT aggregating, so a waterx-routed ticker composes
15
+ * onto the same collector as Pyth/Supra (compose-then-aggregate). On-chain a
16
+ * freshness miss / replayed timestamp ABSTAINS (the other weighted rules
17
+ * cover); a config/integrity mismatch or bad signature aborts.
18
+ */
19
+ import { fromHex } from "@mysten/bcs";
20
+ import { collectBatchLatest, newBatchItem, newBatchPayload, pushBatchItem, } from "../../generated/waterx_rule/waterx_rule.js";
21
+ import { WATERX_DEFAULTS } from "../config.js";
22
+ import { assertRuleUpdateData, } from "../price-update-rule.js";
23
+ import { FetchPolicyError, fetchWithPolicy, joinEndpointPath, } from "../update-fetch.js";
24
+ /** The single signing intent (`BATCH_PRICE_INTENT`) the quote-center emits. */
25
+ const BATCH_PRICE_INTENT = 1;
26
+ /**
27
+ * Shape check ONLY — the `kind` discriminant is checked separately by the
28
+ * caller before this runs (mirrors the other rules' guard split), so a
29
+ * same-shaped payload from a different rule can never silently pass.
30
+ */
31
+ function isWaterxUpdatePayloadShape(payload) {
32
+ const env = payload?.envelope;
33
+ return (typeof env === "object" &&
34
+ env !== null &&
35
+ typeof env.signature === "string" &&
36
+ typeof env.timestamp_ms === "bigint" &&
37
+ Array.isArray(env.payload?.items));
38
+ }
39
+ /**
40
+ * Parse a quote-center `/v1/quotes/update` response body into a
41
+ * {@link WaterxSignedEnvelope} with the u64 fields decoded as `bigint`, exact.
42
+ *
43
+ * The signature is over `BCS(IntentMessage<BatchPricePayload>)`, so every u64
44
+ * the SDK rebuilds in-PTB must equal the enclave's byte-for-byte or
45
+ * `collect_batch_latest` aborts the whole trade PTB (bad signature — not an
46
+ * abstain). A plain `JSON.parse` yields IEEE-754 doubles that lose precision
47
+ * above 2^53, so instead we recover each integer's exact source literal via the
48
+ * ES2023 reviver `context.source` (Node 21+ / modern browsers) and `BigInt()`
49
+ * it. On an older runtime that passes no `context`, a value within 2^53 is
50
+ * still exact (`BigInt(number)`); a value ABOVE it throws loudly here rather
51
+ * than silently corrupting the payload into an on-chain abort. `num_sources`
52
+ * (u8) and `intent` are coerced back to `number` — both are tiny.
53
+ */
54
+ export function parseSignedEnvelope(text) {
55
+ const raw = JSON.parse(text, (_key, value, context) => {
56
+ if (typeof value !== "number" || !Number.isInteger(value))
57
+ return value;
58
+ if (context?.source !== undefined)
59
+ return BigInt(context.source);
60
+ if (!Number.isSafeInteger(value)) {
61
+ throw new Error("waterx envelope carries an integer above 2^53 and this runtime lacks JSON " +
62
+ "source access — cannot preserve u64 precision for the signed payload");
63
+ }
64
+ return BigInt(value);
65
+ });
66
+ if (typeof raw.signature !== "string" || !Array.isArray(raw.payload?.items)) {
67
+ throw new Error("WaterX quote-center returned a malformed signed envelope");
68
+ }
69
+ return {
70
+ intent: Number(raw.intent),
71
+ timestamp_ms: (raw.timestamp_ms ?? 0n),
72
+ signature: raw.signature,
73
+ payload: {
74
+ items: raw.payload.items.map((i) => ({ ...i, num_sources: Number(i.num_sources) })),
75
+ },
76
+ };
77
+ }
78
+ /** The `waterx_rule` deployment entry; throws when the config carries none. */
79
+ function requireWaterxPackage(host) {
80
+ const entry = host.config.packages.waterx_rule;
81
+ if (!entry) {
82
+ throw new Error("waterx_rule package is not deployed in this config");
83
+ }
84
+ return entry;
85
+ }
86
+ /**
87
+ * Resolve the quote-center infra for this host: the `waterxEndpoint` /
88
+ * `waterxFetch` create options when the client carries them, else the network
89
+ * default. The fetch policy falls back to the shared `pyth.fetch` policy so a
90
+ * consumer that already tuned timeouts/retries once keeps them here.
91
+ *
92
+ * This is the seam a browser consumer needs: the envelope is fetched FROM THE
93
+ * PAGE, so a front end whose origin the quote-center does not allow (CORS)
94
+ * points `endpoint` at a same-origin proxy, or supplies its own `fetchImpl`.
95
+ */
96
+ function resolveWaterxInfra(host) {
97
+ const infra = host.waterx ?? WATERX_DEFAULTS[host.network];
98
+ return { endpoint: infra.endpoint, fetch: infra.fetch ?? host.pyth.fetch };
99
+ }
100
+ /**
101
+ * Pull one enclave-signed batch envelope covering `symbols` from the
102
+ * quote-center. Goes through the shared `fetchWithPolicy` (`../update-fetch.ts`)
103
+ * — same retry/timeout policy as the Pyth/Lazer fetches. No auth: the
104
+ * quote-center read surface is public.
105
+ *
106
+ * The URL is built with `joinEndpointPath`, not `new URL(path, endpoint)`: a
107
+ * leading-slash path is ABSOLUTE and silently drops the endpoint's own base
108
+ * path, which is exactly what a `waterxEndpoint` proxy route is (a
109
+ * `https://app.example/api/quote-center` override would have been rewritten to
110
+ * `https://app.example/v1/quotes/update`, bypassing the proxy). Same footgun
111
+ * that 404'd every Pyth Pro feed by dropping its `/hermes` prefix.
112
+ */
113
+ async function fetchWaterxSignedUpdate(endpoint, symbols, fetchOpts) {
114
+ const url = joinEndpointPath(endpoint, "v1/quotes/update");
115
+ url.searchParams.set("symbols", symbols.join(","));
116
+ let res;
117
+ try {
118
+ res = await fetchWithPolicy(url.toString(), { method: "GET" }, { ...fetchOpts });
119
+ }
120
+ catch (err) {
121
+ if (err instanceof FetchPolicyError && err.status !== undefined) {
122
+ const body = err.bodySnippet ? ` ${err.bodySnippet}` : "";
123
+ throw new Error(`WaterX quote-center fetch failed: ${err.status}${body} (retries exhausted after ${err.attempts} attempts)`, { cause: err });
124
+ }
125
+ throw err;
126
+ }
127
+ if (!res.ok) {
128
+ throw new Error(`WaterX quote-center fetch failed: ${res.status} ${await res.text()}`);
129
+ }
130
+ // Parse from raw text (not res.json()) so the u64 fields are decoded exact as
131
+ // bigint — see parseSignedEnvelope. Malformed-shape check lives there.
132
+ const envelope = parseSignedEnvelope(await res.text());
133
+ if (envelope.intent !== BATCH_PRICE_INTENT) {
134
+ throw new Error(`WaterX quote-center returned intent ${envelope.intent}, expected BATCH_PRICE_INTENT ${BATCH_PRICE_INTENT}`);
135
+ }
136
+ return envelope;
137
+ }
138
+ /** Narrow a `RuleUpdateData` to its `WaterxSignedEnvelope`, or `null`. */
139
+ export function waterxEnvelopeOf(data) {
140
+ const payload = assertRuleUpdateData(data, "waterx_rule", isWaterxUpdatePayloadShape, "{ envelope: { intent, timestamp_ms, payload: { items }, signature } }");
141
+ return payload?.envelope ?? null;
142
+ }
143
+ /** Strip an optional `0x` prefix, then decode hex → bytes. */
144
+ function decodeSig(hex) {
145
+ return fromHex(hex.startsWith("0x") ? hex.slice(2) : hex);
146
+ }
147
+ /**
148
+ * `waterx_rule::collect_batch_latest(collector, config, clock, enclave_config,
149
+ * enclave, timestamp_ms, payload, sig)` — rebuild the enclave-signed batch
150
+ * payload in-PTB (`new_batch_payload` + one `new_batch_item`/`push_batch_item`
151
+ * per item, the exact shape the enclave signed) and contribute the price for
152
+ * `collector.symbol()` to the collector. One collect call re-verifies the batch
153
+ * signature and picks this collector's symbol out of the batch; on-chain it
154
+ * abstains (records `none`) instead of aborting when the symbol is stale,
155
+ * absent from the batch, or its timestamp was already accepted (replay).
156
+ */
157
+ export function feedWaterxRule(tx, host, collector, envelope) {
158
+ const wr = requireWaterxPackage(host);
159
+ const pkg = wr.published_at;
160
+ const payload = newBatchPayload({ package: pkg })(tx);
161
+ for (const item of envelope.payload.items) {
162
+ // u64 fields are already exact bigints (see parseSignedEnvelope) — passed
163
+ // through verbatim so the rebuilt BCS matches the enclave's signed bytes.
164
+ const itemArg = newBatchItem({
165
+ package: pkg,
166
+ arguments: {
167
+ symbol: item.symbol,
168
+ ticker: item.ticker,
169
+ sources: item.sources,
170
+ method: item.method,
171
+ priceTimestampMs: item.price_timestamp_ms,
172
+ priceN: item.price_n,
173
+ priceScale: item.price_scale,
174
+ confidenceN: item.confidence_n,
175
+ confidenceScale: item.confidence_scale,
176
+ maxSourceDeviationBps: item.max_source_deviation_bps,
177
+ numSources: item.num_sources,
178
+ },
179
+ })(tx);
180
+ pushBatchItem({ package: pkg, arguments: { payload, item: itemArg } })(tx);
181
+ }
182
+ collectBatchLatest({
183
+ package: pkg,
184
+ arguments: {
185
+ collector,
186
+ config: tx.object(wr.config),
187
+ enclaveConfig: tx.object(wr.enclave_config),
188
+ enclave: tx.object(wr.enclave),
189
+ timestampMs: envelope.timestamp_ms,
190
+ payload,
191
+ sig: Array.from(decodeSig(envelope.signature)),
192
+ },
193
+ })(tx);
194
+ }
195
+ export const WaterxRule = {
196
+ kind: "waterx_rule",
197
+ // Verification is an in-Move ed25519 check with no Coin argument — no
198
+ // update fee — see `PriceUpdateRule.requiresFeeSource`.
199
+ requiresFeeSource: false,
200
+ /** Tickers with a `waterx_rule.feeds` entry (keyed by oracle ticker). */
201
+ supportedTickers(host) {
202
+ return Object.keys(host.config.packages.waterx_rule?.feeds ?? {});
203
+ },
204
+ /**
205
+ * Pulls one enclave-signed batch envelope covering `tickers` from the
206
+ * quote-center, and only returns it when it actually covers ALL of them.
207
+ *
208
+ * A 200 whose `items` omit a requested symbol is a valid, well-signed
209
+ * envelope — nothing downstream would reject it, and the build would emit a
210
+ * `collect_batch_latest` that abstains for the missing symbol, surfacing as
211
+ * an on-chain `EMissingPriceSource` (or a silently thinner weighted set) much
212
+ * later. Same coverage rule the cached path enforces in
213
+ * {@link WaterxRule.narrowUpdateData}; the difference is disposition — a
214
+ * cache miss falls back to this live fetch, whereas the live source itself
215
+ * coming up short has no fallback left, so it throws deterministically here.
216
+ */
217
+ async fetchUpdateData(host, tickers) {
218
+ if (tickers.length === 0)
219
+ return null;
220
+ // Package-level check first: a config without the deployment must say so,
221
+ // not fail per ticker as if only that feed were missing.
222
+ const { feeds } = requireWaterxPackage(host);
223
+ for (const ticker of tickers) {
224
+ if (feeds[ticker] === undefined) {
225
+ throw new Error(`No waterx_rule feed listed for ticker: ${ticker}`);
226
+ }
227
+ }
228
+ const { endpoint, fetch: fetchOpts } = resolveWaterxInfra(host);
229
+ const envelope = await fetchWaterxSignedUpdate(endpoint, tickers, fetchOpts);
230
+ const covered = new Set(envelope.payload.items.map((i) => i.symbol));
231
+ const missing = tickers.filter((t) => !covered.has(t));
232
+ if (missing.length > 0) {
233
+ throw new Error(`WaterX quote-center envelope does not cover ticker(s): ${missing.join(", ")} ` +
234
+ `(requested ${tickers.join(", ")}; served ${[...covered].join(", ") || "none"})`);
235
+ }
236
+ return { kind: "waterx_rule", payload: { envelope } };
237
+ },
238
+ /**
239
+ * One signed batch envelope carries a single ed25519 signature over its whole
240
+ * `payload` — it is indivisible: it can only be served whole (re-verified from
241
+ * the full item set). Returns the whole payload iff every requested ticker's
242
+ * item is present in THIS envelope; any coverage gap → `null` (miss), never a
243
+ * silent partial.
244
+ */
245
+ narrowUpdateData(_host, data, tickers) {
246
+ const envelope = waterxEnvelopeOf(data);
247
+ if (!envelope || tickers.length === 0)
248
+ return null;
249
+ const covered = new Set(envelope.payload.items.map((i) => i.symbol));
250
+ for (const ticker of tickers) {
251
+ if (!covered.has(ticker))
252
+ return null;
253
+ }
254
+ return { kind: "waterx_rule", payload: { envelope } };
255
+ },
256
+ /**
257
+ * No shared verify step: `waterx_rule::collect_batch_latest` bundles verify
258
+ * AND feed into one per-collector call, appended by {@link feedWaterxRule} in
259
+ * the per-ticker aggregate leg. So this emits nothing and returns `void` — the
260
+ * signed envelope reaches the feed leg via `aggregate.ts`'s per-ticker map
261
+ * (built from the group's fetched data), not a `RuleUpdateHandle`.
262
+ */
263
+ buildUpdateCalls(_tx, _host, _data, _opts) {
264
+ return;
265
+ },
266
+ };
@@ -12,7 +12,8 @@
12
12
  */
13
13
  import { BaseLineClient } from "../base-client.ts";
14
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
+ import type { FetchPolicy } from "../oracle/update-fetch.ts";
16
+ import { type LoadConfigOptions, type PythFetchPolicy, type PythInfraConfig, type WaterXConfig, type WaterxInfraConfig, type WormholeInfraConfig } from "./config.ts";
16
17
  import type { Network } from "./constants.ts";
17
18
  export interface CreateClientOptions extends LoadConfigOptions {
18
19
  grpcUrl?: string;
@@ -25,12 +26,20 @@ export interface CreateClientOptions extends LoadConfigOptions {
25
26
  * - `'pyth_lazer_rule'` — Pyth Lazer signed updates (ONE `leEcdsa` verify
26
27
  * per PTB, no per-feed fees); needs `packages.pyth_lazer_rule` with feeds
27
28
  * and a `pythApiKey` (Lazer is auth-first).
29
+ * - `'waterx_rule'` — the first-party WaterX quote-center (Nautilus-TEE,
30
+ * ed25519-signed batches): ONE envelope covering the build's tickers,
31
+ * verified AND fed by a single `collect_batch_latest` per collector. No
32
+ * credential and no per-update fee; needs `packages.waterx_rule` with
33
+ * feeds. Endpoint/transport via {@link CreateClientOptions.waterxEndpoint}
34
+ * / {@link CreateClientOptions.waterxFetch} — the browser-CORS proxy hook,
35
+ * since this is the one source fetched from the page.
28
36
  *
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.
37
+ * The name is source-neutral on purpose — a source need not be Pyth (as
38
+ * `'waterx_rule'` shows). Selecting a source whose feed for a requested
39
+ * ticker is absent is NOT an error at client creation: it fails at tx-build
40
+ * time for exactly those tickers (see `refreshOraclePrices`). The Pyth Core
41
+ * infra is fixed per network by `PYTH_DEFAULTS` and is not
42
+ * deployment-overridable.
34
43
  */
35
44
  oracleSource?: OracleSource;
36
45
  /**
@@ -46,10 +55,39 @@ export interface CreateClientOptions extends LoadConfigOptions {
46
55
  * `fetchWithPolicy`). Optional — defaults to 15s timeout, 2 retries.
47
56
  */
48
57
  pythFetch?: PythFetchPolicy;
58
+ /**
59
+ * Quote-center base URL for `oracleSource: 'waterx_rule'` — overrides the
60
+ * per-network {@link WATERX_DEFAULTS} host.
61
+ *
62
+ * This is the one source a BROWSER fetches itself (the signed envelope is
63
+ * pulled from the page), so it is bound by the quote-center deployment's CORS
64
+ * allowlist. A front end whose origin is not allowed — or one that must route
65
+ * egress through its own backend — points this at a same-origin proxy that
66
+ * forwards `GET /v1/quotes/update`. Unused by the Pyth sources.
67
+ *
68
+ * An absolute URL. Any base PATH is preserved (`joinEndpointPath`), so
69
+ * `https://app.example/api/quote-center` fetches
70
+ * `https://app.example/api/quote-center/v1/quotes/update` — a proxy route
71
+ * survives instead of being rewritten to the origin root.
72
+ */
73
+ waterxEndpoint?: string;
74
+ /**
75
+ * Retry/timeout policy — and `fetchImpl` — for the quote-center fetch (see
76
+ * `fetchWithPolicy`). Optional: falls back to `pythFetch`, then to the
77
+ * built-in defaults. Supply `fetchImpl` to route the request through your own
78
+ * transport (a proxying `fetch` wrapper, a non-global `fetch`, a test double).
79
+ */
80
+ waterxFetch?: FetchPolicy;
49
81
  }
50
82
  export declare class PerpClient extends BaseLineClient<WaterXConfig> {
51
83
  /** Pyth Core infra (fixed per network) plus the caller-supplied credential/policy. */
52
84
  pyth: PythInfraConfig;
85
+ /**
86
+ * WaterX quote-center infra for `oracleSource: 'waterx_rule'` — the network
87
+ * default, overridden by the `waterxEndpoint` / `waterxFetch` create options
88
+ * (a same-origin proxy or a custom `fetchImpl` for browser consumers).
89
+ */
90
+ waterx: WaterxInfraConfig;
53
91
  /** Wormhole infra for the credit bridge (network defaults unless overridden). */
54
92
  wormhole: WormholeInfraConfig;
55
93
  /** Selected oracle price-update source (`oracleSource` create option; default `'pyth_rule'`). */
@@ -12,10 +12,16 @@
12
12
  */
13
13
  import { BaseLineClient } from "../base-client.js";
14
14
  import { PerpConfigView } from "./config-view.js";
15
- import { loadConfig, PYTH_DEFAULTS, WORMHOLE_DEFAULTS, } from "./config.js";
15
+ import { loadConfig, PYTH_DEFAULTS, WATERX_DEFAULTS, WORMHOLE_DEFAULTS, } from "./config.js";
16
16
  export class PerpClient extends BaseLineClient {
17
17
  /** Pyth Core infra (fixed per network) plus the caller-supplied credential/policy. */
18
18
  pyth;
19
+ /**
20
+ * WaterX quote-center infra for `oracleSource: 'waterx_rule'` — the network
21
+ * default, overridden by the `waterxEndpoint` / `waterxFetch` create options
22
+ * (a same-origin proxy or a custom `fetchImpl` for browser consumers).
23
+ */
24
+ waterx;
19
25
  /** Wormhole infra for the credit bridge (network defaults unless overridden). */
20
26
  wormhole;
21
27
  /** Selected oracle price-update source (`oracleSource` create option; default `'pyth_rule'`). */
@@ -34,6 +40,14 @@ export class PerpClient extends BaseLineClient {
34
40
  ...(opts.pythFetch !== undefined ? { fetch: opts.pythFetch } : {}),
35
41
  };
36
42
  this.wormhole = config.wormhole ?? WORMHOLE_DEFAULTS[network];
43
+ // Quote-center infra: network default, each field independently overridable
44
+ // — a browser blocked by the quote-center's CORS allowlist swaps `endpoint`
45
+ // for a same-origin proxy without touching anything else.
46
+ this.waterx = {
47
+ ...WATERX_DEFAULTS[network],
48
+ ...(opts.waterxEndpoint !== undefined ? { endpoint: opts.waterxEndpoint } : {}),
49
+ ...(opts.waterxFetch !== undefined ? { fetch: opts.waterxFetch } : {}),
50
+ };
37
51
  this.oracleSource = opts.oracleSource ?? "pyth_rule";
38
52
  this.view = new PerpConfigView(() => this.config, () => this.wormhole);
39
53
  }
@@ -12,8 +12,8 @@ import type { AccountPackages, BasePackageEntry, WormholeInfraConfig } from "../
12
12
  import type { OraclePackages } from "../oracle/config.ts";
13
13
  import type { Network } from "./constants.ts";
14
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
- export { PYTH_DEFAULTS } from "../oracle/config.ts";
15
+ export type { ConstantFeedEntry, OracleConfig, OraclePackages, PythFetchPolicy, PythInfraConfig, PythLazerRulePackage, PythRulePackage, PythSponsorRulePackage, SupraFeedEntry, SupraRulePackage, WaterxConstantRulePackage, WaterxInfraConfig, WaterxOraclePackage, WaterxRulePackage, } from "../oracle/config.ts";
16
+ export { PYTH_DEFAULTS, WATERX_DEFAULTS } from "../oracle/config.ts";
17
17
  export interface WaterxPerpMarketEntry {
18
18
  market: string;
19
19
  config: string;
@@ -71,7 +71,6 @@ export interface WaterXPackages extends AccountPackages, OraclePackages {
71
71
  mock_usdc?: MockCoinPackage;
72
72
  mock_usdsui?: MockCoinPackage;
73
73
  mock_sui?: MockCoinPackage;
74
- waterx_rule?: BasePackageEntry;
75
74
  waterx_rule_nautilus_enclave?: BasePackageEntry;
76
75
  }
77
76
  export declare const WORMHOLE_DEFAULTS: Record<Network, WormholeInfraConfig>;
@@ -9,7 +9,7 @@
9
9
  * below, keyed by network.
10
10
  */
11
11
  import { fetchWithPolicy, rethrowExhaustedFetch } from "../oracle/update-fetch.js";
12
- export { PYTH_DEFAULTS } from "../oracle/config.js";
12
+ export { PYTH_DEFAULTS, WATERX_DEFAULTS } from "../oracle/config.js";
13
13
  // ============================================================================
14
14
  // Wormhole / Hermes — external chain infra, defaults by network
15
15
  // ============================================================================
@@ -1,10 +1,4 @@
1
1
  export * from "../constants.ts";
2
- /** Default crypto market trading fee rate (3 bps). Per-market value lives in MarketConfig. */
3
- export declare const CRYPTO_FEE_RATE = 0.0003;
4
- /** Default stock / commodity market trading fee rate (5 bps). Per-market value lives in MarketConfig. */
5
- export declare const STOCK_FEE_RATE = 0.0005;
6
- /** Default maintenance margin rate (150 bps = 1.5%). Per-market value lives in MarketConfig. */
7
- export declare const MAINTENANCE_MARGIN_RATE = 0.015;
8
2
  export declare const PERM_OPEN_POSITION = 1;
9
3
  export declare const PERM_CLOSE_POSITION = 2;
10
4
  export declare const PERM_INCREASE_POSITION = 4;
@@ -1,15 +1,17 @@
1
1
  // Perp-line domain constants (trading permissions / order tags / action codes /
2
- // fee rates / well-known addresses). Re-exports the shared primitives from
2
+ // well-known addresses). Re-exports the shared primitives from
3
3
  // `../constants.ts` so perp code and the `./perp` barrel get the full set from
4
4
  // a single import.
5
+ //
6
+ // NOTE: there are deliberately NO fee-rate / maintenance-margin constants here.
7
+ // `CRYPTO_FEE_RATE` / `STOCK_FEE_RATE` / `MAINTENANCE_MARGIN_RATE` were removed
8
+ // — they were defaults masquerading as truth; per-market `MarketConfig` on
9
+ // chain is the only source for fee and margin parameters (real MMRs span
10
+ // 0.5%–5%; the flat 1.5% understated AAPLX-class risk >3x — mainnet incident
11
+ // 2026-07-28: shorts displayed liq ~$364 but were liquidated at ~$343). When
12
+ // the market rate is unavailable, treat the value as NOT estimable and fail
13
+ // safe — never substitute a flat default.
5
14
  export * from "../constants.js";
6
- // ======== Fee rates & risk parameters ========
7
- /** Default crypto market trading fee rate (3 bps). Per-market value lives in MarketConfig. */
8
- export const CRYPTO_FEE_RATE = 0.0003;
9
- /** Default stock / commodity market trading fee rate (5 bps). Per-market value lives in MarketConfig. */
10
- export const STOCK_FEE_RATE = 0.0005;
11
- /** Default maintenance margin rate (150 bps = 1.5%). Per-market value lives in MarketConfig. */
12
- export const MAINTENANCE_MARGIN_RATE = 0.015;
13
15
  // ======== Permission Bitmasks (matches account_data.move) ========
14
16
  export const PERM_OPEN_POSITION = 1;
15
17
  export const PERM_CLOSE_POSITION = 2;
@@ -51,6 +51,9 @@ export async function getSpendableCreditBalance(client, accountId) {
51
51
  probeParkedBackingAssets(client, accountId),
52
52
  probeAddressCreditBalance(client, accountId),
53
53
  ]);
54
+ // COLLATERAL_DECIMALS here is the CREDIT/wxUSD *target* scale (collateral-typed;
55
+ // 6 on all current deployments — config carries no credit decimal). The
56
+ // per-asset backing decimals come from config via each row's `decimals`.
54
57
  const pendingBackingRaw = sumParkedBackingAsCreditRaw(parkedBacking, COLLATERAL_DECIMALS);
55
58
  const pendingCreditAtAddressRaw = addressCredit.fundsRaw + addressCredit.coinsRaw;
56
59
  const totalRaw = internalRaw + pendingBackingRaw + pendingCreditAtAddressRaw;
@@ -6,6 +6,7 @@ import { bcs } from "@mysten/sui/bcs";
6
6
  import { Transaction } from "@mysten/sui/transactions";
7
7
  import { bridgeFeeAmount as bridgeFeeAmountCall, bridgeFeeRate as bridgeFeeRateCall, bridgeMinFee as bridgeMinFeeCall, wouldExecuteWormhole as wouldExecuteWormholeCall, } from "../../generated/withdrawal_queue/withdrawal_queue.js";
8
8
  import { dailyBurned as dailyBurnedCall, dailyBurnLimit as dailyBurnLimitCall, dailyMinted as dailyMintedCall, dailyMintLimit as dailyMintLimitCall, maxBurnPerTx as maxBurnPerTxCall, maxMintPerTx as maxMintPerTxCall, mintedFor as mintedForCall, paused as pausedCall, personalBurnCapAmount as personalBurnCapAmountCall, personalBurned as personalBurnedCall, } from "../../generated/wormhole_bridge/wormhole_bridge.js";
9
+ import { toU64 } from "../../utils/validate.js";
9
10
  import { extractAt, simulateRaw } from "./simulate.js";
10
11
  /**
11
12
  * Batched read of the bridge's rate-limit / cap state in a single simulate.
@@ -96,7 +97,7 @@ function requireWithdrawalQueue(client) {
96
97
  */
97
98
  export async function getBridgeFee(client, args) {
98
99
  const { pkg, queue } = requireWithdrawalQueue(client);
99
- const amount = BigInt(args.amount);
100
+ const amount = toU64(args.amount, "amount");
100
101
  const common = {
101
102
  package: pkg,
102
103
  typeArguments: [args.creditType ?? client.creditType()],
@@ -5,6 +5,7 @@
5
5
  import { bcs } from "@mysten/sui/bcs";
6
6
  import { Transaction } from "@mysten/sui/transactions";
7
7
  import { AccountData, accountData as accountDataCall, GlobalConfigData, globalConfigData as globalConfigDataCall, MarketData, marketData as marketDataCall, PoolData, poolData as poolDataCall, TokenPoolData, tokenPoolData as tokenPoolDataCall, } from "../../generated/waterx_perp_view/view.js";
8
+ import { toU64 } from "../../utils/validate.js";
8
9
  import { simulateAndExtract, withLp } from "./simulate.js";
9
10
  /**
10
11
  * Look up the registered AccountData for a given wxa account ID.
@@ -52,7 +53,7 @@ export async function getTokenPoolData(client, args) {
52
53
  package: client.config.packages.waterx_perp_view.published_at,
53
54
  arguments: {
54
55
  pool: tx.object(client.config.packages.wlp.wlp_pool),
55
- tokenIndex: args.tokenIndex,
56
+ tokenIndex: toU64(args.tokenIndex, "tokenIndex"),
56
57
  },
57
58
  typeArguments: [withLp(client, args.lpType)],
58
59
  })(tx);
@@ -3,7 +3,9 @@
3
3
  * list (`waterx_perp_view`).
4
4
  */
5
5
  import { OrderData, PositionData, RedeemRequestData } from "../../generated/waterx_perp_view/view.ts";
6
+ import { parseWholeDollarU64, type WholeDollarUsdPrice } from "../../utils/validate.ts";
6
7
  import type { PerpClient } from "../client.ts";
8
+ export { parseWholeDollarU64, type WholeDollarUsdPrice };
7
9
  export type PositionDataView = ReturnType<typeof PositionData.parse>;
8
10
  export declare function positionExists(client: PerpClient, args: {
9
11
  ticker: string;
@@ -13,9 +15,8 @@ export declare function positionExists(client: PerpClient, args: {
13
15
  export declare function getPosition(client: PerpClient, args: {
14
16
  ticker: string;
15
17
  positionId: bigint | number;
16
- /** Human-readable USD prices for Pnl / liq price calc; pass 0n if unsure. */
17
- basePriceUsd: bigint | number;
18
- collateralPriceUsd: bigint | number;
18
+ basePriceUsd: WholeDollarUsdPrice;
19
+ collateralPriceUsd: WholeDollarUsdPrice;
19
20
  lpType?: string;
20
21
  }): Promise<PositionDataView>;
21
22
  export type OrderDataView = ReturnType<typeof OrderData.parse>;
@@ -23,8 +24,9 @@ export declare function getOrder(client: PerpClient, args: {
23
24
  ticker: string;
24
25
  orderId: bigint | number;
25
26
  orderTypeTag: number;
27
+ /** Raw 1e9-scaled u128 order-book key — same scale as tx-build `rawPrice()`. */
26
28
  triggerPrice: bigint | number;
27
- basePriceUsd: bigint | number;
29
+ basePriceUsd: WholeDollarUsdPrice;
28
30
  lpType?: string;
29
31
  }): Promise<OrderDataView>;
30
32
  export interface PageOpts {
@@ -33,7 +35,8 @@ export interface PageOpts {
33
35
  }
34
36
  export declare function getMarketOrders(client: PerpClient, args: {
35
37
  ticker: string;
36
- basePriceUsd?: bigint | number;
38
+ /** Defaults to `0n`. */
39
+ basePriceUsd?: WholeDollarUsdPrice;
37
40
  lpType?: string;
38
41
  } & PageOpts): Promise<{
39
42
  orders: OrderDataView[];
@@ -41,8 +44,9 @@ export declare function getMarketOrders(client: PerpClient, args: {
41
44
  }>;
42
45
  export declare function getMarketPositions(client: PerpClient, args: {
43
46
  ticker: string;
44
- basePriceUsd: bigint | number;
45
- collateralPriceUsd?: bigint | number;
47
+ basePriceUsd: WholeDollarUsdPrice;
48
+ /** Defaults to `0n`. */
49
+ collateralPriceUsd?: WholeDollarUsdPrice;
46
50
  lpType?: string;
47
51
  } & PageOpts): Promise<{
48
52
  positions: PositionDataView[];
@@ -51,14 +55,16 @@ export declare function getMarketPositions(client: PerpClient, args: {
51
55
  export declare function getAccountPositions(client: PerpClient, args: {
52
56
  ticker: string;
53
57
  accountObjectAddress: string;
54
- basePriceUsd: bigint | number;
55
- collateralPriceUsd?: bigint | number;
58
+ basePriceUsd: WholeDollarUsdPrice;
59
+ /** Defaults to `0n`. */
60
+ collateralPriceUsd?: WholeDollarUsdPrice;
56
61
  lpType?: string;
57
62
  }): Promise<PositionDataView[]>;
58
63
  export declare function getAccountOrders(client: PerpClient, args: {
59
64
  ticker: string;
60
65
  accountObjectAddress: string;
61
- basePriceUsd?: bigint | number;
66
+ /** Defaults to `0n`. */
67
+ basePriceUsd?: WholeDollarUsdPrice;
62
68
  lpType?: string;
63
69
  }): Promise<OrderDataView[]>;
64
70
  export type RedeemRequestDataView = ReturnType<typeof RedeemRequestData.parse>;