@waterx/sdk 4.0.1 → 4.3.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 (130) hide show
  1. package/README.md +37 -17
  2. package/dist/cjs/src/account/account.js +2 -1
  3. package/dist/cjs/src/account/config.d.ts +3 -2
  4. package/dist/cjs/src/account/funding/balance.d.ts +25 -2
  5. package/dist/cjs/src/account/funding/balance.js +36 -24
  6. package/dist/cjs/src/account/funding/credit.js +6 -10
  7. package/dist/cjs/src/constants.d.ts +15 -1
  8. package/dist/cjs/src/constants.js +18 -4
  9. package/dist/cjs/src/generated/waterx_rule/deps/bucket_v2_framework/float.d.ts +8 -0
  10. package/dist/cjs/src/generated/waterx_rule/deps/bucket_v2_framework/float.js +13 -0
  11. package/dist/cjs/src/generated/waterx_rule/deps/sui/vec_map.d.ts +36 -0
  12. package/dist/cjs/src/generated/waterx_rule/deps/sui/vec_map.js +31 -0
  13. package/dist/cjs/src/generated/waterx_rule/waterx_rule.d.ts +813 -0
  14. package/dist/cjs/src/generated/waterx_rule/waterx_rule.js +946 -0
  15. package/dist/cjs/src/oracle/aggregate.d.ts +23 -21
  16. package/dist/cjs/src/oracle/aggregate.js +133 -59
  17. package/dist/cjs/src/oracle/config.d.ts +82 -41
  18. package/dist/cjs/src/oracle/config.js +0 -42
  19. package/dist/cjs/src/oracle/host.d.ts +26 -11
  20. package/dist/cjs/src/oracle/index.d.ts +6 -2
  21. package/dist/cjs/src/oracle/index.js +36 -8
  22. package/dist/cjs/src/oracle/price-update-rule.d.ts +16 -10
  23. package/dist/cjs/src/oracle/price-update-rule.js +3 -3
  24. package/dist/cjs/src/oracle/pyth.d.ts +44 -0
  25. package/dist/cjs/src/oracle/pyth.js +48 -6
  26. package/dist/cjs/src/oracle/read-plane.d.ts +70 -0
  27. package/dist/cjs/src/oracle/read-plane.js +78 -0
  28. package/dist/cjs/src/oracle/rule-registry.d.ts +14 -11
  29. package/dist/cjs/src/oracle/rule-registry.js +16 -11
  30. package/dist/cjs/src/oracle/rules/pyth-core-rule.js +4 -4
  31. package/dist/cjs/src/oracle/rules/pyth-lazer-rule.d.ts +21 -0
  32. package/dist/cjs/src/oracle/rules/pyth-lazer-rule.js +29 -4
  33. package/dist/cjs/src/oracle/rules/pyth-rule.js +5 -4
  34. package/dist/cjs/src/oracle/rules/waterx-rule.d.ts +126 -0
  35. package/dist/cjs/src/oracle/rules/waterx-rule.js +312 -0
  36. package/dist/cjs/src/perp/client.d.ts +71 -20
  37. package/dist/cjs/src/perp/client.js +35 -13
  38. package/dist/cjs/src/perp/config.d.ts +6 -7
  39. package/dist/cjs/src/perp/config.js +12 -11
  40. package/dist/cjs/src/perp/constants.d.ts +0 -6
  41. package/dist/cjs/src/perp/constants.js +11 -9
  42. package/dist/cjs/src/perp/fetch/account.js +3 -0
  43. package/dist/cjs/src/perp/fetch/bridge.js +2 -1
  44. package/dist/cjs/src/perp/fetch/market.js +2 -1
  45. package/dist/cjs/src/perp/fetch/positions.d.ts +16 -10
  46. package/dist/cjs/src/perp/fetch/positions.js +23 -20
  47. package/dist/cjs/src/perp/index.d.ts +9 -5
  48. package/dist/cjs/src/perp/index.js +16 -7
  49. package/dist/cjs/src/perp/liq-view.d.ts +64 -0
  50. package/dist/cjs/src/perp/liq-view.js +74 -0
  51. package/dist/cjs/src/perp/user/order.d.ts +13 -0
  52. package/dist/cjs/src/perp/user/order.js +30 -16
  53. package/dist/cjs/src/perp/user/staking.js +3 -2
  54. package/dist/cjs/src/perp/user/trading.js +25 -24
  55. package/dist/cjs/src/perp/user/wlp.js +6 -5
  56. package/dist/cjs/src/prediction/utils.d.ts +11 -2
  57. package/dist/cjs/src/prediction/utils.js +22 -22
  58. package/dist/cjs/src/unified-client.d.ts +41 -15
  59. package/dist/cjs/src/unified-client.js +4 -2
  60. package/dist/cjs/src/utils/format.d.ts +14 -0
  61. package/dist/cjs/src/utils/format.js +24 -0
  62. package/dist/cjs/src/utils/math.d.ts +304 -12
  63. package/dist/cjs/src/utils/math.js +397 -17
  64. package/dist/cjs/src/utils/validate.d.ts +69 -0
  65. package/dist/cjs/src/utils/validate.js +183 -0
  66. package/dist/src/account/account.js +2 -1
  67. package/dist/src/account/config.d.ts +3 -2
  68. package/dist/src/account/funding/balance.d.ts +25 -2
  69. package/dist/src/account/funding/balance.js +36 -24
  70. package/dist/src/account/funding/credit.js +6 -10
  71. package/dist/src/constants.d.ts +15 -1
  72. package/dist/src/constants.js +17 -3
  73. package/dist/src/generated/waterx_rule/deps/bucket_v2_framework/float.d.ts +8 -0
  74. package/dist/src/generated/waterx_rule/deps/bucket_v2_framework/float.js +10 -0
  75. package/dist/src/generated/waterx_rule/deps/sui/vec_map.d.ts +36 -0
  76. package/dist/src/generated/waterx_rule/deps/sui/vec_map.js +27 -0
  77. package/dist/src/generated/waterx_rule/waterx_rule.d.ts +813 -0
  78. package/dist/src/generated/waterx_rule/waterx_rule.js +855 -0
  79. package/dist/src/oracle/aggregate.d.ts +23 -21
  80. package/dist/src/oracle/aggregate.js +133 -59
  81. package/dist/src/oracle/config.d.ts +82 -41
  82. package/dist/src/oracle/config.js +1 -41
  83. package/dist/src/oracle/host.d.ts +26 -11
  84. package/dist/src/oracle/index.d.ts +6 -2
  85. package/dist/src/oracle/index.js +27 -9
  86. package/dist/src/oracle/price-update-rule.d.ts +16 -10
  87. package/dist/src/oracle/price-update-rule.js +3 -3
  88. package/dist/src/oracle/pyth.d.ts +44 -0
  89. package/dist/src/oracle/pyth.js +45 -5
  90. package/dist/src/oracle/read-plane.d.ts +70 -0
  91. package/dist/src/oracle/read-plane.js +74 -0
  92. package/dist/src/oracle/rule-registry.d.ts +14 -11
  93. package/dist/src/oracle/rule-registry.js +16 -11
  94. package/dist/src/oracle/rules/pyth-core-rule.js +5 -5
  95. package/dist/src/oracle/rules/pyth-lazer-rule.d.ts +21 -0
  96. package/dist/src/oracle/rules/pyth-lazer-rule.js +28 -3
  97. package/dist/src/oracle/rules/pyth-rule.js +5 -4
  98. package/dist/src/oracle/rules/waterx-rule.d.ts +126 -0
  99. package/dist/src/oracle/rules/waterx-rule.js +305 -0
  100. package/dist/src/perp/client.d.ts +71 -20
  101. package/dist/src/perp/client.js +36 -14
  102. package/dist/src/perp/config.d.ts +6 -7
  103. package/dist/src/perp/config.js +11 -9
  104. package/dist/src/perp/constants.d.ts +0 -6
  105. package/dist/src/perp/constants.js +10 -8
  106. package/dist/src/perp/fetch/account.js +3 -0
  107. package/dist/src/perp/fetch/bridge.js +2 -1
  108. package/dist/src/perp/fetch/market.js +2 -1
  109. package/dist/src/perp/fetch/positions.d.ts +16 -10
  110. package/dist/src/perp/fetch/positions.js +28 -20
  111. package/dist/src/perp/index.d.ts +9 -5
  112. package/dist/src/perp/index.js +6 -4
  113. package/dist/src/perp/liq-view.d.ts +64 -0
  114. package/dist/src/perp/liq-view.js +71 -0
  115. package/dist/src/perp/user/order.d.ts +13 -0
  116. package/dist/src/perp/user/order.js +30 -16
  117. package/dist/src/perp/user/staking.js +3 -2
  118. package/dist/src/perp/user/trading.js +25 -24
  119. package/dist/src/perp/user/wlp.js +6 -5
  120. package/dist/src/prediction/utils.d.ts +11 -2
  121. package/dist/src/prediction/utils.js +22 -22
  122. package/dist/src/unified-client.d.ts +41 -15
  123. package/dist/src/unified-client.js +4 -2
  124. package/dist/src/utils/format.d.ts +14 -0
  125. package/dist/src/utils/format.js +21 -0
  126. package/dist/src/utils/math.d.ts +304 -12
  127. package/dist/src/utils/math.js +394 -17
  128. package/dist/src/utils/validate.d.ts +69 -0
  129. package/dist/src/utils/validate.js +167 -0
  130. package/package.json +4 -1
@@ -0,0 +1,126 @@
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 its own `WATERX_INFRA`), 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 ABSTAINS (the other weighted rules cover); a config/
17
+ * integrity mismatch, bad signature, future timestamp — or a REPLAYED signed
18
+ * timestamp — ABORTS (`EReplayedSignature`, audit F-014: a signed tuple is
19
+ * single-use per symbol, enforced by a per-symbol high-water mark BEFORE any
20
+ * weight arbitration). Consequence for concurrent builds: two PTBs carrying
21
+ * the same envelope for the same symbol cannot both land — the second aborts
22
+ * even if the rule is unweighted for that ticker. Never share one fetched
23
+ * envelope across builds that may execute concurrently for the same symbol.
24
+ */
25
+ import type { Transaction, TransactionArgument } from "@mysten/sui/transactions";
26
+ import type { Network } from "../../constants.ts";
27
+ import type { OracleHost } from "../host.ts";
28
+ import { type PriceUpdateRule, type RuleUpdateData } from "../price-update-rule.ts";
29
+ /** The single signing intent the quote-center emits — exported so read-plane
30
+ * consumers can mirror the rule's own envelope intent check (a mispointed
31
+ * endpoint must be rejected by reads exactly as tx-builds reject it). */
32
+ export declare const BATCH_PRICE_INTENT = 1;
33
+ /**
34
+ * WaterX quote-center external infra — owned by THIS source, by network.
35
+ * Mirrors `PYTH_CORE_INFRA` (oracle/pyth.ts) and `LAZER_INFRA`
36
+ * (rules/pyth-lazer-rule.ts): per-network constants for infrastructure the
37
+ * source's operator runs, co-located with the only rule that reads them — no
38
+ * other oracle source ever touches a quote-center endpoint. Public read (no
39
+ * auth), so there is no api_key. `endpoint` has no trailing slash — the rule
40
+ * appends the path.
41
+ *
42
+ * These are the DEFAULTS behind the caller's `client.waterx` access slice
43
+ * (`waterxEndpoint` / `waterxFetch` create options) — the browser-CORS proxy
44
+ * hook, since this is the one source fetched from the page.
45
+ */
46
+ export declare const WATERX_INFRA: Record<Network, {
47
+ endpoint: string;
48
+ }>;
49
+ /**
50
+ * The waterx source's quote-center base for `network` — the ONE accessor
51
+ * consumers (BE/FE read planes) use when, and only when, their own
52
+ * `ORACLE_SOURCE` resolves to `'waterx_rule'`. Mirrors
53
+ * `pythCoreHermesEndpoint`. Under any other source the read endpoint is that
54
+ * source's own configuration — never this one.
55
+ */
56
+ export declare function waterxQuoteCenterEndpoint(network: Network): string;
57
+ /**
58
+ * One item inside a signed batch payload, mirroring the quote-center
59
+ * `/v1/quotes/update` JSON 1:1 (snake_case). The u64 integer fields are the
60
+ * EXACT values the enclave signed over BCS — `collect_batch_latest` rebuilds
61
+ * the payload on-chain and re-verifies, so they must round-trip byte-for-byte.
62
+ * They are `bigint` (not `number`): {@link parseSignedEnvelope} decodes them
63
+ * from the raw JSON integer literals so a value above `Number.MAX_SAFE_INTEGER`
64
+ * (2^53) can never lose precision and silently abort the on-chain signature
65
+ * check. `num_sources` is a `u8` (≤ 255) and stays a `number`.
66
+ */
67
+ export interface WaterxBatchItem {
68
+ symbol: string;
69
+ ticker: string;
70
+ sources: bigint[];
71
+ method: string;
72
+ price_timestamp_ms: bigint;
73
+ price_n: bigint;
74
+ price_scale: bigint;
75
+ confidence_n: bigint;
76
+ confidence_scale: bigint;
77
+ max_source_deviation_bps: bigint;
78
+ num_sources: number;
79
+ }
80
+ /** The enclave-signed batch envelope from `GET /v1/quotes/update`. */
81
+ export interface WaterxSignedEnvelope {
82
+ intent: number;
83
+ /** Enclave signing timestamp (ms) — the on-chain `timestamp_ms` argument. */
84
+ timestamp_ms: bigint;
85
+ payload: {
86
+ items: WaterxBatchItem[];
87
+ };
88
+ /** ed25519 signature over `BCS(IntentMessage<BatchPricePayload>)`, hex (± `0x`). */
89
+ signature: string;
90
+ }
91
+ /** `waterx_rule`'s narrowed `RuleUpdateData.payload` shape. */
92
+ export interface WaterxUpdatePayload {
93
+ readonly envelope: WaterxSignedEnvelope;
94
+ }
95
+ /**
96
+ * Parse a quote-center `/v1/quotes/update` response body into a
97
+ * {@link WaterxSignedEnvelope} with the u64 fields decoded as `bigint`, exact.
98
+ *
99
+ * The signature is over `BCS(IntentMessage<BatchPricePayload>)`, so every u64
100
+ * the SDK rebuilds in-PTB must equal the enclave's byte-for-byte or
101
+ * `collect_batch_latest` aborts the whole trade PTB (bad signature — not an
102
+ * abstain). A plain `JSON.parse` yields IEEE-754 doubles that lose precision
103
+ * above 2^53, so instead we recover each integer's exact source literal via the
104
+ * ES2023 reviver `context.source` (Node 21+ / modern browsers) and `BigInt()`
105
+ * it. On an older runtime that passes no `context`, a value within 2^53 is
106
+ * still exact (`BigInt(number)`); a value ABOVE it throws loudly here rather
107
+ * than silently corrupting the payload into an on-chain abort. `num_sources`
108
+ * (u8) and `intent` are coerced back to `number` — both are tiny.
109
+ */
110
+ export declare function parseSignedEnvelope(text: string): WaterxSignedEnvelope;
111
+ /** Narrow a `RuleUpdateData` to its `WaterxSignedEnvelope`, or `null`. */
112
+ export declare function waterxEnvelopeOf(data: RuleUpdateData): WaterxSignedEnvelope | null;
113
+ /**
114
+ * `waterx_rule::collect_batch_latest(collector, config, clock, enclave_config,
115
+ * enclave, timestamp_ms, payload, sig)` — rebuild the enclave-signed batch
116
+ * payload in-PTB (`new_batch_payload` + one `new_batch_item`/`push_batch_item`
117
+ * per item, the exact shape the enclave signed) and contribute the price for
118
+ * `collector.symbol()` to the collector. One collect call re-verifies the batch
119
+ * signature and picks this collector's symbol out of the batch; on-chain it
120
+ * abstains (records `none`) when the symbol is stale or absent from the batch,
121
+ * but ABORTS `EReplayedSignature` when the symbol's signed timestamp was
122
+ * already accepted (per-symbol high-water mark, audit F-014) — see the module
123
+ * header for the concurrent-build consequence.
124
+ */
125
+ export declare function feedWaterxRule(tx: Transaction, host: OracleHost, collector: TransactionArgument, envelope: WaterxSignedEnvelope): void;
126
+ export declare const WaterxRule: PriceUpdateRule;
@@ -0,0 +1,305 @@
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 its own `WATERX_INFRA`), 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 ABSTAINS (the other weighted rules cover); a config/
17
+ * integrity mismatch, bad signature, future timestamp — or a REPLAYED signed
18
+ * timestamp — ABORTS (`EReplayedSignature`, audit F-014: a signed tuple is
19
+ * single-use per symbol, enforced by a per-symbol high-water mark BEFORE any
20
+ * weight arbitration). Consequence for concurrent builds: two PTBs carrying
21
+ * the same envelope for the same symbol cannot both land — the second aborts
22
+ * even if the rule is unweighted for that ticker. Never share one fetched
23
+ * envelope across builds that may execute concurrently for the same symbol.
24
+ */
25
+ import { fromHex } from "@mysten/bcs";
26
+ import { collectBatchLatest, newBatchItem, newBatchPayload, pushBatchItem, } from "../../generated/waterx_rule/waterx_rule.js";
27
+ import { assertRuleUpdateData, } from "../price-update-rule.js";
28
+ import { FetchPolicyError, fetchWithPolicy, joinEndpointPath, } from "../update-fetch.js";
29
+ /** The single signing intent the quote-center emits — exported so read-plane
30
+ * consumers can mirror the rule's own envelope intent check (a mispointed
31
+ * endpoint must be rejected by reads exactly as tx-builds reject it). */
32
+ export const BATCH_PRICE_INTENT = 1;
33
+ /**
34
+ * WaterX quote-center external infra — owned by THIS source, by network.
35
+ * Mirrors `PYTH_CORE_INFRA` (oracle/pyth.ts) and `LAZER_INFRA`
36
+ * (rules/pyth-lazer-rule.ts): per-network constants for infrastructure the
37
+ * source's operator runs, co-located with the only rule that reads them — no
38
+ * other oracle source ever touches a quote-center endpoint. Public read (no
39
+ * auth), so there is no api_key. `endpoint` has no trailing slash — the rule
40
+ * appends the path.
41
+ *
42
+ * These are the DEFAULTS behind the caller's `client.waterx` access slice
43
+ * (`waterxEndpoint` / `waterxFetch` create options) — the browser-CORS proxy
44
+ * hook, since this is the one source fetched from the page.
45
+ */
46
+ export const WATERX_INFRA = {
47
+ MAINNET: { endpoint: "https://quote-center.waterx.app" },
48
+ TESTNET: { endpoint: "https://quote-center-staging.waterx.app" },
49
+ };
50
+ /**
51
+ * The waterx source's quote-center base for `network` — the ONE accessor
52
+ * consumers (BE/FE read planes) use when, and only when, their own
53
+ * `ORACLE_SOURCE` resolves to `'waterx_rule'`. Mirrors
54
+ * `pythCoreHermesEndpoint`. Under any other source the read endpoint is that
55
+ * source's own configuration — never this one.
56
+ */
57
+ export function waterxQuoteCenterEndpoint(network) {
58
+ return WATERX_INFRA[network].endpoint;
59
+ }
60
+ /**
61
+ * Shape check ONLY — the `kind` discriminant is checked separately by the
62
+ * caller before this runs (mirrors the other rules' guard split), so a
63
+ * same-shaped payload from a different rule can never silently pass.
64
+ */
65
+ function isWaterxUpdatePayloadShape(payload) {
66
+ const env = payload?.envelope;
67
+ return (typeof env === "object" &&
68
+ env !== null &&
69
+ typeof env.signature === "string" &&
70
+ typeof env.timestamp_ms === "bigint" &&
71
+ Array.isArray(env.payload?.items));
72
+ }
73
+ /**
74
+ * Parse a quote-center `/v1/quotes/update` response body into a
75
+ * {@link WaterxSignedEnvelope} with the u64 fields decoded as `bigint`, exact.
76
+ *
77
+ * The signature is over `BCS(IntentMessage<BatchPricePayload>)`, so every u64
78
+ * the SDK rebuilds in-PTB must equal the enclave's byte-for-byte or
79
+ * `collect_batch_latest` aborts the whole trade PTB (bad signature — not an
80
+ * abstain). A plain `JSON.parse` yields IEEE-754 doubles that lose precision
81
+ * above 2^53, so instead we recover each integer's exact source literal via the
82
+ * ES2023 reviver `context.source` (Node 21+ / modern browsers) and `BigInt()`
83
+ * it. On an older runtime that passes no `context`, a value within 2^53 is
84
+ * still exact (`BigInt(number)`); a value ABOVE it throws loudly here rather
85
+ * than silently corrupting the payload into an on-chain abort. `num_sources`
86
+ * (u8) and `intent` are coerced back to `number` — both are tiny.
87
+ */
88
+ export function parseSignedEnvelope(text) {
89
+ const raw = JSON.parse(text, (_key, value, context) => {
90
+ if (typeof value !== "number" || !Number.isInteger(value))
91
+ return value;
92
+ if (context?.source !== undefined)
93
+ return BigInt(context.source);
94
+ if (!Number.isSafeInteger(value)) {
95
+ throw new Error("waterx envelope carries an integer above 2^53 and this runtime lacks JSON " +
96
+ "source access — cannot preserve u64 precision for the signed payload");
97
+ }
98
+ return BigInt(value);
99
+ });
100
+ if (typeof raw.signature !== "string" || !Array.isArray(raw.payload?.items)) {
101
+ throw new Error("WaterX quote-center returned a malformed signed envelope");
102
+ }
103
+ return {
104
+ intent: Number(raw.intent),
105
+ timestamp_ms: (raw.timestamp_ms ?? 0n),
106
+ signature: raw.signature,
107
+ payload: {
108
+ items: raw.payload.items.map((i) => ({ ...i, num_sources: Number(i.num_sources) })),
109
+ },
110
+ };
111
+ }
112
+ /** The `waterx_rule` deployment entry; throws when the config carries none. */
113
+ function requireWaterxPackage(host) {
114
+ const entry = host.config.packages.waterx_rule;
115
+ if (!entry) {
116
+ throw new Error("waterx_rule package is not deployed in this config");
117
+ }
118
+ return entry;
119
+ }
120
+ /**
121
+ * Resolve the quote-center infra for this host: each field independently from
122
+ * the caller's `client.waterx` access slice (`waterxEndpoint` / `waterxFetch`
123
+ * create options) when set, else this source's own `WATERX_INFRA` default /
124
+ * `fetchWithPolicy`'s built-ins. Deliberately NO fallback onto `pyth.fetch`
125
+ * or any other source's policy — sources stay fully independent.
126
+ *
127
+ * This is the seam a browser consumer needs: the envelope is fetched FROM THE
128
+ * PAGE, so a front end whose origin the quote-center does not allow (CORS)
129
+ * points `endpoint` at a same-origin proxy, or supplies its own `fetchImpl`.
130
+ */
131
+ function resolveWaterxInfra(host) {
132
+ return {
133
+ endpoint: host.waterx?.endpoint ?? WATERX_INFRA[host.network].endpoint,
134
+ fetch: host.waterx?.fetch,
135
+ };
136
+ }
137
+ /**
138
+ * Pull one enclave-signed batch envelope covering `symbols` from the
139
+ * quote-center. Goes through the shared `fetchWithPolicy` (`../update-fetch.ts`)
140
+ * — same retry/timeout policy as the Pyth/Lazer fetches. No auth: the
141
+ * quote-center read surface is public.
142
+ *
143
+ * The URL is built with `joinEndpointPath`, not `new URL(path, endpoint)`: a
144
+ * leading-slash path is ABSOLUTE and silently drops the endpoint's own base
145
+ * path, which is exactly what a `waterxEndpoint` proxy route is (a
146
+ * `https://app.example/api/quote-center` override would have been rewritten to
147
+ * `https://app.example/v1/quotes/update`, bypassing the proxy). Same footgun
148
+ * that 404'd every Pyth Pro feed by dropping its `/hermes` prefix.
149
+ */
150
+ async function fetchWaterxSignedUpdate(endpoint, symbols, fetchOpts) {
151
+ const url = joinEndpointPath(endpoint, "v1/quotes/update");
152
+ url.searchParams.set("symbols", symbols.join(","));
153
+ let res;
154
+ try {
155
+ res = await fetchWithPolicy(url.toString(), { method: "GET" }, { ...fetchOpts });
156
+ }
157
+ catch (err) {
158
+ if (err instanceof FetchPolicyError && err.status !== undefined) {
159
+ const body = err.bodySnippet ? ` ${err.bodySnippet}` : "";
160
+ throw new Error(`WaterX quote-center fetch failed: ${err.status}${body} (retries exhausted after ${err.attempts} attempts)`, { cause: err });
161
+ }
162
+ throw err;
163
+ }
164
+ if (!res.ok) {
165
+ throw new Error(`WaterX quote-center fetch failed: ${res.status} ${await res.text()}`);
166
+ }
167
+ // Parse from raw text (not res.json()) so the u64 fields are decoded exact as
168
+ // bigint — see parseSignedEnvelope. Malformed-shape check lives there.
169
+ const envelope = parseSignedEnvelope(await res.text());
170
+ if (envelope.intent !== BATCH_PRICE_INTENT) {
171
+ throw new Error(`WaterX quote-center returned intent ${envelope.intent}, expected BATCH_PRICE_INTENT ${BATCH_PRICE_INTENT}`);
172
+ }
173
+ return envelope;
174
+ }
175
+ /** Narrow a `RuleUpdateData` to its `WaterxSignedEnvelope`, or `null`. */
176
+ export function waterxEnvelopeOf(data) {
177
+ const payload = assertRuleUpdateData(data, "waterx_rule", isWaterxUpdatePayloadShape, "{ envelope: { intent, timestamp_ms, payload: { items }, signature } }");
178
+ return payload?.envelope ?? null;
179
+ }
180
+ /** Strip an optional `0x` prefix, then decode hex → bytes. */
181
+ function decodeSig(hex) {
182
+ return fromHex(hex.startsWith("0x") ? hex.slice(2) : hex);
183
+ }
184
+ /**
185
+ * `waterx_rule::collect_batch_latest(collector, config, clock, enclave_config,
186
+ * enclave, timestamp_ms, payload, sig)` — rebuild the enclave-signed batch
187
+ * payload in-PTB (`new_batch_payload` + one `new_batch_item`/`push_batch_item`
188
+ * per item, the exact shape the enclave signed) and contribute the price for
189
+ * `collector.symbol()` to the collector. One collect call re-verifies the batch
190
+ * signature and picks this collector's symbol out of the batch; on-chain it
191
+ * abstains (records `none`) when the symbol is stale or absent from the batch,
192
+ * but ABORTS `EReplayedSignature` when the symbol's signed timestamp was
193
+ * already accepted (per-symbol high-water mark, audit F-014) — see the module
194
+ * header for the concurrent-build consequence.
195
+ */
196
+ export function feedWaterxRule(tx, host, collector, envelope) {
197
+ const wr = requireWaterxPackage(host);
198
+ const pkg = wr.published_at;
199
+ const payload = newBatchPayload({ package: pkg })(tx);
200
+ for (const item of envelope.payload.items) {
201
+ // u64 fields are already exact bigints (see parseSignedEnvelope) — passed
202
+ // through verbatim so the rebuilt BCS matches the enclave's signed bytes.
203
+ const itemArg = newBatchItem({
204
+ package: pkg,
205
+ arguments: {
206
+ symbol: item.symbol,
207
+ ticker: item.ticker,
208
+ sources: item.sources,
209
+ method: item.method,
210
+ priceTimestampMs: item.price_timestamp_ms,
211
+ priceN: item.price_n,
212
+ priceScale: item.price_scale,
213
+ confidenceN: item.confidence_n,
214
+ confidenceScale: item.confidence_scale,
215
+ maxSourceDeviationBps: item.max_source_deviation_bps,
216
+ numSources: item.num_sources,
217
+ },
218
+ })(tx);
219
+ pushBatchItem({ package: pkg, arguments: { payload, item: itemArg } })(tx);
220
+ }
221
+ collectBatchLatest({
222
+ package: pkg,
223
+ arguments: {
224
+ collector,
225
+ config: tx.object(wr.config),
226
+ enclaveConfig: tx.object(wr.enclave_config),
227
+ enclave: tx.object(wr.enclave),
228
+ timestampMs: envelope.timestamp_ms,
229
+ payload,
230
+ sig: Array.from(decodeSig(envelope.signature)),
231
+ },
232
+ })(tx);
233
+ }
234
+ export const WaterxRule = {
235
+ kind: "waterx_rule",
236
+ // Verification is an in-Move ed25519 check with no Coin argument — no
237
+ // update fee — see `PriceUpdateRule.requiresFeeSource`.
238
+ requiresFeeSource: false,
239
+ /** Tickers with a `waterx_rule.feeds` entry (keyed by oracle ticker). */
240
+ supportedTickers(host) {
241
+ return Object.keys(host.config.packages.waterx_rule?.feeds ?? {});
242
+ },
243
+ /**
244
+ * Pulls one enclave-signed batch envelope covering `tickers` from the
245
+ * quote-center, and only returns it when it actually covers ALL of them.
246
+ *
247
+ * A 200 whose `items` omit a requested symbol is a valid, well-signed
248
+ * envelope — nothing downstream would reject it, and the build would emit a
249
+ * `collect_batch_latest` that abstains for the missing symbol, surfacing as
250
+ * an on-chain `EMissingPriceSource` (or a silently thinner weighted set) much
251
+ * later. Same coverage rule the cached path enforces in
252
+ * {@link WaterxRule.narrowUpdateData}; the difference is disposition — a
253
+ * cache miss falls back to this live fetch, whereas the live source itself
254
+ * coming up short has no fallback left, so it throws deterministically here.
255
+ */
256
+ async fetchUpdateData(host, tickers) {
257
+ if (tickers.length === 0)
258
+ return null;
259
+ // Package-level check first: a config without the deployment must say so,
260
+ // not fail per ticker as if only that feed were missing.
261
+ const { feeds } = requireWaterxPackage(host);
262
+ for (const ticker of tickers) {
263
+ if (feeds[ticker] === undefined) {
264
+ throw new Error(`No waterx_rule feed listed for ticker: ${ticker}`);
265
+ }
266
+ }
267
+ const { endpoint, fetch: fetchOpts } = resolveWaterxInfra(host);
268
+ const envelope = await fetchWaterxSignedUpdate(endpoint, tickers, fetchOpts);
269
+ const covered = new Set(envelope.payload.items.map((i) => i.symbol));
270
+ const missing = tickers.filter((t) => !covered.has(t));
271
+ if (missing.length > 0) {
272
+ throw new Error(`WaterX quote-center envelope does not cover ticker(s): ${missing.join(", ")} ` +
273
+ `(requested ${tickers.join(", ")}; served ${[...covered].join(", ") || "none"})`);
274
+ }
275
+ return { kind: "waterx_rule", payload: { envelope } };
276
+ },
277
+ /**
278
+ * One signed batch envelope carries a single ed25519 signature over its whole
279
+ * `payload` — it is indivisible: it can only be served whole (re-verified from
280
+ * the full item set). Returns the whole payload iff every requested ticker's
281
+ * item is present in THIS envelope; any coverage gap → `null` (miss), never a
282
+ * silent partial.
283
+ */
284
+ narrowUpdateData(_host, data, tickers) {
285
+ const envelope = waterxEnvelopeOf(data);
286
+ if (!envelope || tickers.length === 0)
287
+ return null;
288
+ const covered = new Set(envelope.payload.items.map((i) => i.symbol));
289
+ for (const ticker of tickers) {
290
+ if (!covered.has(ticker))
291
+ return null;
292
+ }
293
+ return { kind: "waterx_rule", payload: { envelope } };
294
+ },
295
+ /**
296
+ * No shared verify step: `waterx_rule::collect_batch_latest` bundles verify
297
+ * AND feed into one per-collector call, appended by {@link feedWaterxRule} in
298
+ * the per-ticker aggregate leg. So this emits nothing and returns `void` — the
299
+ * signed envelope reaches the feed leg via `aggregate.ts`'s per-ticker map
300
+ * (built from the group's fetched data), not a `RuleUpdateHandle`.
301
+ */
302
+ buildUpdateCalls(_tx, _host, _data, _opts) {
303
+ return;
304
+ },
305
+ };
@@ -12,27 +12,49 @@
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 PythAccessConfig, type PythFetchPolicy, type WaterxAccessConfig, type WaterXConfig, type WormholeInfraConfig } from "./config.ts";
16
17
  import type { Network } from "./constants.ts";
17
18
  export interface CreateClientOptions extends LoadConfigOptions {
18
19
  grpcUrl?: string;
19
20
  /**
20
- * Which oracle price-update source drives `refreshOraclePrices`. Each source
21
- * is self-contained (own infra + config) with NO cross-source fallback:
21
+ * Which oracle price-update source drives `refreshOraclePrices`. REQUIRED
22
+ * there is NO default source: every deployment names its source explicitly
23
+ * (wire it from your own env var, e.g. `ORACLE_SOURCE`). Each source is
24
+ * self-contained (own infra, own endpoints, own config) with NO cross-source
25
+ * fallback:
22
26
  *
23
- * - `'pyth_rule'` (default) — Pyth Core `pyth_rule` updates (Hermes VAA +
24
- * per-feed update fees), Core state + keyless Core Hermes.
27
+ * - `'pyth_rule'` — Pyth Core `pyth_rule` updates (Hermes VAA + per-feed
28
+ * update fees); Core state + Hermes endpoint live in the source's own
29
+ * `PYTH_CORE_INFRA` table.
25
30
  * - `'pyth_lazer_rule'` — Pyth Lazer signed updates (ONE `leEcdsa` verify
26
31
  * per PTB, no per-feed fees); needs `packages.pyth_lazer_rule` with feeds
27
- * and a `pythApiKey` (Lazer is auth-first).
32
+ * and a `pythApiKey` (Lazer is auth-first); Lazer infra lives in the
33
+ * source's own `LAZER_INFRA` table.
34
+ * - `'waterx_rule'` — the first-party WaterX quote-center (Nautilus-TEE,
35
+ * ed25519-signed batches): ONE envelope covering the build's tickers,
36
+ * verified AND fed by a single `collect_batch_latest` per collector. No
37
+ * credential and no per-update fee; needs `packages.waterx_rule` with
38
+ * feeds. Quote-center infra lives in the source's own `WATERX_INFRA`
39
+ * table; endpoint/transport overridable via
40
+ * {@link CreateClientOptions.waterxEndpoint} /
41
+ * {@link CreateClientOptions.waterxFetch} — the browser-CORS proxy hook,
42
+ * since this is the one source fetched from the page.
28
43
  *
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.
44
+ * The name is source-neutral on purpose — a source need not be Pyth (as
45
+ * `'waterx_rule'` shows). Selecting a source whose feed for a requested
46
+ * ticker is absent is NOT an error at client creation: it fails at tx-build
47
+ * time for exactly those tickers (see `refreshOraclePrices`).
48
+ *
49
+ * Accepts a SINGLE source or a LIST. A list means every listed source's
50
+ * data is fetched and fed in one build — required whenever the on-chain
51
+ * weight tables have more than one rule weighted (e.g. a Core→Pro or
52
+ * Pro+Waterx coexistence window): the chain drops unweighted contributions
53
+ * (harmless) but aborts on a starved weighted rule, so the list must stay a
54
+ * SUPERSET of every ticker's weighted set. Order is meaningful to consumers
55
+ * (read-plane priority), not to the on-chain build.
34
56
  */
35
- oracleSource?: OracleSource;
57
+ oracleSource: OracleSource | OracleSource[];
36
58
  /**
37
59
  * Pyth Lazer access token (`Authorization: Bearer …`). Required under
38
60
  * `oracleSource: 'pyth_lazer_rule'` (Lazer is auth-first) and unused by
@@ -46,17 +68,46 @@ export interface CreateClientOptions extends LoadConfigOptions {
46
68
  * `fetchWithPolicy`). Optional — defaults to 15s timeout, 2 retries.
47
69
  */
48
70
  pythFetch?: PythFetchPolicy;
71
+ /**
72
+ * Quote-center base URL for `oracleSource: 'waterx_rule'` — overrides the
73
+ * source's own per-network `WATERX_INFRA` default.
74
+ *
75
+ * This is the one source a BROWSER fetches itself (the signed envelope is
76
+ * pulled from the page), so it is bound by the quote-center deployment's CORS
77
+ * allowlist. A front end whose origin is not allowed — or one that must route
78
+ * egress through its own backend — points this at a same-origin proxy that
79
+ * forwards `GET /v1/quotes/update`. Unused by the Pyth sources.
80
+ *
81
+ * An absolute URL. Any base PATH is preserved (`joinEndpointPath`), so
82
+ * `https://app.example/api/quote-center` fetches
83
+ * `https://app.example/api/quote-center/v1/quotes/update` — a proxy route
84
+ * survives instead of being rewritten to the origin root.
85
+ */
86
+ waterxEndpoint?: string;
87
+ /**
88
+ * Retry/timeout policy — and `fetchImpl` — for the quote-center fetch (see
89
+ * `fetchWithPolicy`). Optional: falls back to the built-in defaults — never
90
+ * to `pythFetch` (sources stay independent). Supply `fetchImpl` to route the request through your own
91
+ * transport (a proxying `fetch` wrapper, a non-global `fetch`, a test double).
92
+ */
93
+ waterxFetch?: FetchPolicy;
49
94
  }
50
95
  export declare class PerpClient extends BaseLineClient<WaterXConfig> {
51
- /** Pyth Core infra (fixed per network) plus the caller-supplied credential/policy. */
52
- pyth: PythInfraConfig;
96
+ /** Caller-supplied Pyth credential + fetch policy — NO infra; each source owns its own tables. */
97
+ pyth: PythAccessConfig;
98
+ /**
99
+ * Caller-supplied quote-center overrides for `oracleSource: 'waterx_rule'`
100
+ * (`waterxEndpoint` / `waterxFetch` create options) — access-only, mirroring
101
+ * `pyth` above; unset fields resolve against the rule's own `WATERX_INFRA`.
102
+ */
103
+ waterx: WaterxAccessConfig;
53
104
  /** Wormhole infra for the credit bridge (network defaults unless overridden). */
54
105
  wormhole: WormholeInfraConfig;
55
- /** Selected oracle price-update source (`oracleSource` create option; default `'pyth_rule'`). */
56
- readonly oracleSource: OracleSource;
106
+ /** The fed set: `oracleSource` create option normalized to a non-empty, deduped list. */
107
+ readonly oracleSources: readonly OracleSource[];
57
108
  /** Canonical-schema lookups (delegated to below); no transport. */
58
109
  private readonly view;
59
- constructor(network: Network, config: WaterXConfig, opts?: CreateClientOptions);
110
+ constructor(network: Network, config: WaterXConfig, opts: CreateClientOptions);
60
111
  /**
61
112
  * Async factory: fetches the deployment config for `network` and returns
62
113
  * a ready-to-use client. Pass `opts.cache=true` to memoize the JSON.
@@ -65,9 +116,9 @@ export declare class PerpClient extends BaseLineClient<WaterXConfig> {
65
116
  * not an error at init — it surfaces at tx-build time for the specific
66
117
  * tickers that source can't serve (see `refreshOraclePrices`).
67
118
  */
68
- static create(network: Network, opts?: CreateClientOptions): Promise<PerpClient>;
69
- static mainnet(opts?: CreateClientOptions): Promise<PerpClient>;
70
- static testnet(opts?: CreateClientOptions): Promise<PerpClient>;
119
+ static create(network: Network, opts: CreateClientOptions): Promise<PerpClient>;
120
+ static mainnet(opts: CreateClientOptions): Promise<PerpClient>;
121
+ static testnet(opts: CreateClientOptions): Promise<PerpClient>;
71
122
  /** @see PerpConfigView.getMarket */
72
123
  getMarket(ticker: string): import("./config.ts").WaterxPerpMarketEntry;
73
124
  /** @see PerpConfigView.getAggregator */
@@ -12,29 +12,51 @@
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, WORMHOLE_DEFAULTS, } from "./config.js";
16
16
  export class PerpClient extends BaseLineClient {
17
- /** Pyth Core infra (fixed per network) plus the caller-supplied credential/policy. */
17
+ /** Caller-supplied Pyth credential + fetch policy — NO infra; each source owns its own tables. */
18
18
  pyth;
19
+ /**
20
+ * Caller-supplied quote-center overrides for `oracleSource: 'waterx_rule'`
21
+ * (`waterxEndpoint` / `waterxFetch` create options) — access-only, mirroring
22
+ * `pyth` above; unset fields resolve against the rule's own `WATERX_INFRA`.
23
+ */
24
+ waterx;
19
25
  /** Wormhole infra for the credit bridge (network defaults unless overridden). */
20
26
  wormhole;
21
- /** Selected oracle price-update source (`oracleSource` create option; default `'pyth_rule'`). */
22
- oracleSource;
27
+ /** The fed set: `oracleSource` create option normalized to a non-empty, deduped list. */
28
+ oracleSources;
23
29
  /** Canonical-schema lookups (delegated to below); no transport. */
24
30
  view;
25
- constructor(network, config, opts = {}) {
31
+ constructor(network, config, opts) {
26
32
  super(network, config, opts);
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.
33
+ // Access-only slice: the api_key + fetch policy are caller-supplied at
34
+ // init (a secret has no place in the canonical waterx-config JSON). All
35
+ // endpoint/object-id infra is per-source, owned by the rule modules
36
+ // nothing infra-shaped lives on the client.
31
37
  this.pyth = {
32
- ...PYTH_DEFAULTS[network],
33
38
  ...(opts.pythApiKey !== undefined ? { api_key: opts.pythApiKey } : {}),
34
39
  ...(opts.pythFetch !== undefined ? { fetch: opts.pythFetch } : {}),
35
40
  };
36
41
  this.wormhole = config.wormhole ?? WORMHOLE_DEFAULTS[network];
37
- this.oracleSource = opts.oracleSource ?? "pyth_rule";
42
+ // Quote-center access slice: overrides only — a browser blocked by the
43
+ // quote-center's CORS allowlist swaps `endpoint` for a same-origin proxy;
44
+ // unset fields resolve inside the rule against WATERX_INFRA[network].
45
+ this.waterx = {
46
+ ...(opts.waterxEndpoint !== undefined ? { endpoint: opts.waterxEndpoint } : {}),
47
+ ...(opts.waterxFetch !== undefined ? { fetch: opts.waterxFetch } : {}),
48
+ };
49
+ // Normalize single-or-list to a deduped, order-preserving list. An empty
50
+ // list — or a nullish/empty entry, the shape an untyped caller produces
51
+ // by omitting the REQUIRED option — is a caller bug, not "no oracle":
52
+ // fail construction loudly instead of booting green and surfacing as
53
+ // `OracleSourceNotImplemented: undefined` at the first tx-build.
54
+ const sources = Array.isArray(opts.oracleSource) ? opts.oracleSource : [opts.oracleSource];
55
+ this.oracleSources = [...new Set(sources)];
56
+ if (this.oracleSources.length === 0 ||
57
+ this.oracleSources.some((source) => typeof source !== "string" || source.length === 0)) {
58
+ throw new Error(`oracleSource is REQUIRED and must name at least one source (got ${JSON.stringify(sources)})`);
59
+ }
38
60
  this.view = new PerpConfigView(() => this.config, () => this.wormhole);
39
61
  }
40
62
  /**
@@ -45,14 +67,14 @@ export class PerpClient extends BaseLineClient {
45
67
  * not an error at init — it surfaces at tx-build time for the specific
46
68
  * tickers that source can't serve (see `refreshOraclePrices`).
47
69
  */
48
- static async create(network, opts = {}) {
70
+ static async create(network, opts) {
49
71
  const config = await loadConfig(network, opts);
50
72
  return new PerpClient(network, config, opts);
51
73
  }
52
- static mainnet(opts = {}) {
74
+ static mainnet(opts) {
53
75
  return PerpClient.create("MAINNET", opts);
54
76
  }
55
- static testnet(opts = {}) {
77
+ static testnet(opts) {
56
78
  return PerpClient.create("TESTNET", opts);
57
79
  }
58
80
  // ========================================================