@waterx/sdk 3.1.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +53 -7
  2. package/dist/cjs/src/oracle/aggregate.d.ts +98 -17
  3. package/dist/cjs/src/oracle/aggregate.js +191 -21
  4. package/dist/cjs/src/oracle/config.d.ts +103 -0
  5. package/dist/cjs/src/oracle/config.js +64 -1
  6. package/dist/cjs/src/oracle/host.d.ts +13 -0
  7. package/dist/cjs/src/oracle/index.d.ts +19 -5
  8. package/dist/cjs/src/oracle/index.js +40 -6
  9. package/dist/cjs/src/oracle/price-update-rule.d.ts +180 -0
  10. package/dist/cjs/src/oracle/price-update-rule.js +56 -0
  11. package/dist/cjs/src/oracle/pyth.d.ts +80 -11
  12. package/dist/cjs/src/oracle/pyth.js +84 -17
  13. package/dist/cjs/src/oracle/rule-registry.d.ts +37 -0
  14. package/dist/cjs/src/oracle/rule-registry.js +61 -0
  15. package/dist/cjs/src/oracle/rules/pyth-core-rule.d.ts +15 -0
  16. package/dist/cjs/src/oracle/rules/pyth-core-rule.js +84 -0
  17. package/dist/cjs/src/oracle/rules/pyth-lazer-rule.d.ts +41 -0
  18. package/dist/cjs/src/oracle/rules/pyth-lazer-rule.js +194 -0
  19. package/dist/cjs/src/oracle/rules/sponsor.d.ts +11 -7
  20. package/dist/cjs/src/oracle/rules/sponsor.js +11 -7
  21. package/dist/cjs/src/oracle/update-fetch.d.ts +85 -0
  22. package/dist/cjs/src/oracle/update-fetch.js +228 -0
  23. package/dist/cjs/src/perp/client.d.ts +22 -1
  24. package/dist/cjs/src/perp/client.js +11 -2
  25. package/dist/cjs/src/perp/config.d.ts +15 -20
  26. package/dist/cjs/src/perp/config.js +86 -30
  27. package/dist/cjs/src/perp/index.d.ts +4 -3
  28. package/dist/cjs/src/perp/index.js +8 -4
  29. package/dist/cjs/src/perp/tx-builders/common.d.ts +52 -15
  30. package/dist/cjs/src/perp/tx-builders/common.js +39 -6
  31. package/dist/cjs/src/perp/tx-builders/wlp.d.ts +11 -3
  32. package/dist/cjs/src/perp/tx-builders/wlp.js +29 -3
  33. package/dist/cjs/src/perp/tx-builders.d.ts +3 -3
  34. package/dist/cjs/src/perp/tx-builders.js +3 -3
  35. package/dist/cjs/src/prediction/config.d.ts +5 -15
  36. package/dist/cjs/src/prediction/config.js +4 -12
  37. package/dist/cjs/src/prediction/fetch.d.ts +6 -1
  38. package/dist/cjs/src/prediction/fetch.js +64 -0
  39. package/dist/cjs/src/prediction/index.d.ts +2 -2
  40. package/dist/cjs/src/prediction/index.js +7 -4
  41. package/dist/cjs/src/prediction/types.d.ts +19 -0
  42. package/dist/cjs/src/unified-client.d.ts +26 -4
  43. package/dist/cjs/src/unified-client.js +4 -2
  44. package/dist/src/oracle/aggregate.d.ts +98 -17
  45. package/dist/src/oracle/aggregate.js +192 -22
  46. package/dist/src/oracle/config.d.ts +103 -0
  47. package/dist/src/oracle/config.js +63 -0
  48. package/dist/src/oracle/host.d.ts +13 -0
  49. package/dist/src/oracle/index.d.ts +19 -5
  50. package/dist/src/oracle/index.js +34 -6
  51. package/dist/src/oracle/price-update-rule.d.ts +180 -0
  52. package/dist/src/oracle/price-update-rule.js +53 -0
  53. package/dist/src/oracle/pyth.d.ts +80 -11
  54. package/dist/src/oracle/pyth.js +82 -16
  55. package/dist/src/oracle/rule-registry.d.ts +37 -0
  56. package/dist/src/oracle/rule-registry.js +56 -0
  57. package/dist/src/oracle/rules/pyth-core-rule.d.ts +15 -0
  58. package/dist/src/oracle/rules/pyth-core-rule.js +81 -0
  59. package/dist/src/oracle/rules/pyth-lazer-rule.d.ts +41 -0
  60. package/dist/src/oracle/rules/pyth-lazer-rule.js +189 -0
  61. package/dist/src/oracle/rules/sponsor.d.ts +11 -7
  62. package/dist/src/oracle/rules/sponsor.js +11 -7
  63. package/dist/src/oracle/update-fetch.d.ts +85 -0
  64. package/dist/src/oracle/update-fetch.js +223 -0
  65. package/dist/src/perp/client.d.ts +22 -1
  66. package/dist/src/perp/client.js +12 -3
  67. package/dist/src/perp/config.d.ts +15 -20
  68. package/dist/src/perp/config.js +85 -29
  69. package/dist/src/perp/index.d.ts +4 -3
  70. package/dist/src/perp/index.js +2 -2
  71. package/dist/src/perp/tx-builders/common.d.ts +52 -15
  72. package/dist/src/perp/tx-builders/common.js +39 -6
  73. package/dist/src/perp/tx-builders/wlp.d.ts +11 -3
  74. package/dist/src/perp/tx-builders/wlp.js +29 -3
  75. package/dist/src/perp/tx-builders.d.ts +3 -3
  76. package/dist/src/perp/tx-builders.js +3 -3
  77. package/dist/src/prediction/config.d.ts +5 -15
  78. package/dist/src/prediction/config.js +4 -11
  79. package/dist/src/prediction/fetch.d.ts +6 -1
  80. package/dist/src/prediction/fetch.js +60 -0
  81. package/dist/src/prediction/index.d.ts +2 -2
  82. package/dist/src/prediction/index.js +2 -2
  83. package/dist/src/prediction/types.d.ts +19 -0
  84. package/dist/src/unified-client.d.ts +26 -4
  85. package/dist/src/unified-client.js +4 -2
  86. package/package.json +1 -1
@@ -4,7 +4,7 @@
4
4
  * and the request+execute envelope (optional Pyth-sponsor flow + pre-sweep).
5
5
  */
6
6
  import { Transaction, type TransactionArgument } from "@mysten/sui/transactions";
7
- import { PythCache } from "../../oracle/index.ts";
7
+ import { PythCache, type OracleFeeSource, type UpdateDataProvider } from "../../oracle/index.ts";
8
8
  import type { PerpClient } from "../client.ts";
9
9
  export interface CommonBuildOpts {
10
10
  /** Append to an existing PTB instead of creating a new one. */
@@ -14,16 +14,31 @@ export interface CommonBuildOpts {
14
14
  /** Share a `PythCache` across builders to avoid redundant pyth_state reads. */
15
15
  pythCache?: PythCache;
16
16
  /**
17
- * Wire the `pyth_sponsor_rule` flow:
18
- * - open a Fund via `pyth_sponsor_rule::request(sponsor)`
19
- * - pay Pyth update fees from the Fund (instead of `tx.gas`)
20
- * - reimburse leftover into the sponsor pool + attach
21
- * `PythSponsorRule` witness to the TradingRequest so markets
22
- * whose `request_checklist` contains `PythSponsorRule` accept it
23
- * Default: true (matches the testnet/mainnet checklist config).
24
- * Pass `false` only when the market checklist is empty.
17
+ * @deprecated No longer a fee-source decision. `wrapRequestAndExecute` now
18
+ * opens (and reimburses) the `pyth_sponsor_rule` Fund purely from config
19
+ * presence whenever `client.config.packages.pyth_sponsor_rule` is
20
+ * deployed, the fund is ALWAYS opened, regardless of this flag (see
21
+ * `OracleFeeSourceUnavailable` in `oracle/pyth.ts`). This closes the gap
22
+ * where a market whose checklist required `PythSponsorRule`, or a caller
23
+ * that mis-set this flag, silently drew from `tx.gas` and failed
24
+ * ON-CHAIN instead of at build time. Use `allowGasFee` for the
25
+ * non-sponsored case instead. Kept accepted (as a no-op) only so existing
26
+ * callers keep compiling; will be removed in a future major version.
25
27
  */
26
28
  useSponsor?: boolean;
29
+ /**
30
+ * Explicit opt-in to draw the Pyth update fee from `tx.gas` when this
31
+ * client's config has no `pyth_sponsor_rule` deployed. Ignored whenever a
32
+ * sponsor fund IS available — the sponsor pool always wins over `tx.gas`
33
+ * when one can be opened (see `useSponsor`'s deprecation note above).
34
+ * Required for flows with no `TradingRequest` to reimburse a sponsor fund
35
+ * against (e.g. `buildMintWlpTx` — see its doc comment). Building an
36
+ * oracle refresh with neither a sponsor fund nor this flag throws
37
+ * `OracleFeeSourceUnavailable` instead of silently drawing from `tx.gas`
38
+ * (Enoki-sponsored transactions reject any `tx.gas` draw). Default:
39
+ * `false`.
40
+ */
41
+ allowGasFee?: boolean;
27
42
  /**
28
43
  * Pre-sweep parked backing assets (USDC, USDsui, …) at the wxa account's
29
44
  * address into USD credit, plus any CREDIT coins/funds at the address into
@@ -42,6 +57,15 @@ export interface CommonBuildOpts {
42
57
  * {@link buildConsolidateToUsdTx} separately.
43
58
  */
44
59
  consolidateToUsd?: boolean;
60
+ /**
61
+ * BE prefetch-cache seam for the oracle update-data fetch — forwarded
62
+ * verbatim into `refreshOraclePrices`'s `updateDataProvider` opt (see
63
+ * `UpdateDataProvider` in `oracle/price-update-rule.ts`). Default: none
64
+ * (always a live fetch). A caller-supplied provider that misses or throws
65
+ * still falls back to a live fetch — this option can only make a refresh
66
+ * faster, never break it.
67
+ */
68
+ updateDataProvider?: UpdateDataProvider;
45
69
  }
46
70
  interface RequestParams {
47
71
  ticker: string;
@@ -57,20 +81,33 @@ export declare function newTx(opts?: CommonBuildOpts): Transaction;
57
81
  */
58
82
  export declare function refreshWlpPoolOracles(tx: Transaction, client: PerpClient, extraTickers: string[], opts: {
59
83
  cache?: PythCache;
60
- sponsorFund?: {
61
- fund: TransactionArgument;
62
- packageId: string;
63
- };
84
+ /** Forwarded to `refreshOraclePrices` — already resolved by the caller (see `OracleFeeSource`). */
85
+ feeSource?: OracleFeeSource;
64
86
  lpType?: string;
87
+ updateDataProvider?: UpdateDataProvider;
65
88
  }): Promise<void>;
66
89
  /**
67
- * Build the *Request + execute envelope with optional Pyth sponsor flow:
90
+ * Build the *Request + execute envelope with the config-driven Pyth sponsor flow:
68
91
  *
92
+ * [maybeConsolidate(tx)]
69
93
  * [fund = sponsor.request()]
70
- * refreshOraclePrices(..., sponsorFund?)
94
+ * refreshOraclePrices(..., feeSource?)
71
95
  * req = buildRequest()
72
96
  * [sponsor.reimburse(fund, req)]
73
97
  * trading::execute(req)
98
+ *
99
+ * Accepted ordering caveat: `maybeConsolidate` runs FIRST and can itself
100
+ * append PTB commands (the consolidation sweep) before the fee-source check
101
+ * inside `refreshOraclePrices` ever runs — so an `OracleFeeSourceUnavailable`
102
+ * throw here is NOT the "zero commands appended" guarantee
103
+ * `refreshOraclePrices` gives its own callers (see its docblock in
104
+ * `aggregate.ts`); `tx` can already carry the sweep. This is the same
105
+ * discard-tx-on-throw contract every `build*Tx` composer already has for
106
+ * mid-build on-chain-read failures — not a new hole. It matters only for a
107
+ * caller that passed in their OWN `opts.tx` (reusing one `Transaction`
108
+ * across builder calls, e.g. to compose several actions in one PTB); such a
109
+ * caller must discard the whole `tx` on any throw from this function, not
110
+ * just retry the failed step.
74
111
  */
75
112
  export declare function wrapRequestAndExecute(client: PerpClient, tx: Transaction, req: RequestParams & {
76
113
  accountId: string;
@@ -23,32 +23,65 @@ export async function refreshWlpPoolOracles(tx, client, extraTickers, opts) {
23
23
  const oracleTickers = Array.from(new Set([...extraTickers, ...poolTickers]));
24
24
  await refreshOraclePrices(tx, client, oracleTickers, {
25
25
  cache: opts.cache,
26
- sponsorFund: opts.sponsorFund,
26
+ feeSource: opts.feeSource,
27
+ updateDataProvider: opts.updateDataProvider,
27
28
  });
28
29
  for (const tokenType of Object.values(client.config.packages.wlp.pool_tokens)) {
29
30
  updateTokenValue(client, tx, { tokenType, lpType: opts.lpType });
30
31
  }
31
32
  }
32
33
  /**
33
- * Build the *Request + execute envelope with optional Pyth sponsor flow:
34
+ * Build the *Request + execute envelope with the config-driven Pyth sponsor flow:
34
35
  *
36
+ * [maybeConsolidate(tx)]
35
37
  * [fund = sponsor.request()]
36
- * refreshOraclePrices(..., sponsorFund?)
38
+ * refreshOraclePrices(..., feeSource?)
37
39
  * req = buildRequest()
38
40
  * [sponsor.reimburse(fund, req)]
39
41
  * trading::execute(req)
42
+ *
43
+ * Accepted ordering caveat: `maybeConsolidate` runs FIRST and can itself
44
+ * append PTB commands (the consolidation sweep) before the fee-source check
45
+ * inside `refreshOraclePrices` ever runs — so an `OracleFeeSourceUnavailable`
46
+ * throw here is NOT the "zero commands appended" guarantee
47
+ * `refreshOraclePrices` gives its own callers (see its docblock in
48
+ * `aggregate.ts`); `tx` can already carry the sweep. This is the same
49
+ * discard-tx-on-throw contract every `build*Tx` composer already has for
50
+ * mid-build on-chain-read failures — not a new hole. It matters only for a
51
+ * caller that passed in their OWN `opts.tx` (reusing one `Transaction`
52
+ * across builder calls, e.g. to compose several actions in one PTB); such a
53
+ * caller must discard the whole `tx` on any throw from this function, not
54
+ * just retry the failed step.
40
55
  */
41
56
  export async function wrapRequestAndExecute(client, tx, req, collateralTicker, opts, buildRequest) {
42
57
  await maybeConsolidate(client, tx, req.accountId, opts);
43
- const useSponsor = opts?.useSponsor ?? true;
58
+ // Fee source + witness attachment is config-driven, not a caller flag: the
59
+ // sponsor fund is opened (and later reimbursed) whenever this client's
60
+ // config has `pyth_sponsor_rule` deployed — regardless of the deprecated
61
+ // `useSponsor` flag (see its JSDoc). `allowGasFee` is the only caller lever
62
+ // left, and it only matters when config has NO sponsor rule to open (see
63
+ // `OracleFeeSourceUnavailable` in `oracle/pyth.ts`).
64
+ //
65
+ // `feeSource` is resolved HERE, once, from that same decision — sponsor
66
+ // beats gas structurally because this is the only branch that ever sees
67
+ // both candidates; everything downstream (`refreshWlpPoolOracles` →
68
+ // `refreshOraclePrices` → `BuildUpdateOpts` → `PythCoreRule` →
69
+ // `buildPythPriceUpdateCalls`) just carries the single resolved value.
44
70
  let sponsorFund;
45
- if (useSponsor)
71
+ if (client.config.packages.pyth_sponsor_rule) {
46
72
  sponsorFund = openPythSponsorFund(tx, client);
73
+ }
74
+ const feeSource = sponsorFund
75
+ ? { kind: "sponsor", ...sponsorFund }
76
+ : opts?.allowGasFee
77
+ ? { kind: "gas" }
78
+ : undefined;
47
79
  if (!opts?.skipOraclePriceRefresh) {
48
80
  await refreshWlpPoolOracles(tx, client, [req.ticker, collateralTicker], {
49
81
  cache: opts?.pythCache,
50
- sponsorFund,
82
+ feeSource,
51
83
  lpType: req.lpType,
84
+ updateDataProvider: opts?.updateDataProvider,
52
85
  });
53
86
  }
54
87
  const tradingReq = buildRequest(sponsorFund);
@@ -17,9 +17,15 @@ export interface BuildMintWlpParams extends MintWlpParams, CommonBuildOpts {
17
17
  * `last_price_refresh_timestamp` so `assert_prices_fresh` inside
18
18
  * `mint_wlp` passes.
19
19
  *
20
- * Does NOT use the pyth_sponsor flow — `mint_wlp` produces no
20
+ * Never uses the pyth_sponsor flow — `mint_wlp` produces no
21
21
  * `TradingRequest`, so there's nothing for the sponsor to attach its
22
- * witness to. Pyth update fees come from `tx.gas`.
22
+ * witness to, and `pyth_sponsor_rule::reimburse` cannot consume a Fund
23
+ * without one. So when `skipOraclePriceRefresh` is `false` (the refresh
24
+ * actually runs), the caller MUST pass `allowGasFee: true` — the Pyth
25
+ * update fee is drawn from `tx.gas`, which Enoki-sponsored transactions
26
+ * reject; a sponsored caller should keep `skipOraclePriceRefresh: true`
27
+ * instead and rely on freshness from other trade traffic (see
28
+ * `OracleFeeSourceUnavailable` in `oracle/pyth.ts`).
23
29
  */
24
30
  export declare function buildMintWlpTx(client: PerpClient, params: BuildMintWlpParams): Promise<Transaction>;
25
31
  export interface BuildMintAndStakeWlpParams extends BuildMintWlpParams {
@@ -62,7 +68,9 @@ export interface BuildUnstakeAndRequestRedeemWlpParams extends Omit<RequestRedee
62
68
  * Refreshes every WLP pool-token oracle by default — `request_redeem` runs
63
69
  * `assert_prices_fresh` internally, so a stale oracle would abort the PTB.
64
70
  * Pass `skipOraclePriceRefresh: true` only when the caller is composing this
65
- * into a larger PTB that already pre-pumps prices.
71
+ * into a larger PTB that already pre-pumps prices. Like `buildMintWlpTx`,
72
+ * `request_redeem` produces no `TradingRequest`, so a non-skipped refresh
73
+ * requires `allowGasFee: true` (see `buildMintWlpTx`'s doc comment).
66
74
  */
67
75
  export declare function buildUnstakeAndRequestRedeemWlpTx(client: PerpClient, params: BuildUnstakeAndRequestRedeemWlpParams): Promise<Transaction>;
68
76
  export interface BuildCancelRedeemAndStakeWlpParams extends CancelRedeemWlpParams, CommonBuildOpts {
@@ -12,17 +12,29 @@ import { maybeConsolidate, newTx, refreshWlpPoolOracles } from "./common.js";
12
12
  * `last_price_refresh_timestamp` so `assert_prices_fresh` inside
13
13
  * `mint_wlp` passes.
14
14
  *
15
- * Does NOT use the pyth_sponsor flow — `mint_wlp` produces no
15
+ * Never uses the pyth_sponsor flow — `mint_wlp` produces no
16
16
  * `TradingRequest`, so there's nothing for the sponsor to attach its
17
- * witness to. Pyth update fees come from `tx.gas`.
17
+ * witness to, and `pyth_sponsor_rule::reimburse` cannot consume a Fund
18
+ * without one. So when `skipOraclePriceRefresh` is `false` (the refresh
19
+ * actually runs), the caller MUST pass `allowGasFee: true` — the Pyth
20
+ * update fee is drawn from `tx.gas`, which Enoki-sponsored transactions
21
+ * reject; a sponsored caller should keep `skipOraclePriceRefresh: true`
22
+ * instead and rely on freshness from other trade traffic (see
23
+ * `OracleFeeSourceUnavailable` in `oracle/pyth.ts`).
18
24
  */
19
25
  export async function buildMintWlpTx(client, params) {
20
26
  const tx = newTx(params);
21
27
  await maybeConsolidate(client, tx, params.accountId, params);
28
+ // `mint_wlp` has no sponsor flow to resolve against (see the doc comment
29
+ // above) — the only candidate source at this edge is the caller's
30
+ // ergonomic `allowGasFee` opt-in.
31
+ const feeSource = params.allowGasFee ? { kind: "gas" } : undefined;
22
32
  if (!params.skipOraclePriceRefresh) {
23
33
  await refreshWlpPoolOracles(tx, client, [params.depositTicker], {
24
34
  cache: params.pythCache,
25
35
  lpType: params.lpType,
36
+ feeSource,
37
+ updateDataProvider: params.updateDataProvider,
26
38
  });
27
39
  }
28
40
  mintWlp(client, tx, params);
@@ -40,10 +52,16 @@ export async function buildMintWlpTx(client, params) {
40
52
  export async function buildMintAndStakeWlpTx(client, params) {
41
53
  const tx = newTx(params);
42
54
  await maybeConsolidate(client, tx, params.accountId, params);
55
+ // `mint_wlp` has no sponsor flow to resolve against (see `buildMintWlpTx`'s
56
+ // doc comment) — the only candidate source at this edge is the caller's
57
+ // ergonomic `allowGasFee` opt-in.
58
+ const feeSource = params.allowGasFee ? { kind: "gas" } : undefined;
43
59
  if (!params.skipOraclePriceRefresh) {
44
60
  await refreshWlpPoolOracles(tx, client, [params.depositTicker], {
45
61
  cache: params.pythCache,
46
62
  lpType: params.lpType,
63
+ feeSource,
64
+ updateDataProvider: params.updateDataProvider,
47
65
  });
48
66
  }
49
67
  const stakeAlias = params.stakeAlias ?? "WLP";
@@ -65,16 +83,24 @@ export async function buildMintAndStakeWlpTx(client, params) {
65
83
  * Refreshes every WLP pool-token oracle by default — `request_redeem` runs
66
84
  * `assert_prices_fresh` internally, so a stale oracle would abort the PTB.
67
85
  * Pass `skipOraclePriceRefresh: true` only when the caller is composing this
68
- * into a larger PTB that already pre-pumps prices.
86
+ * into a larger PTB that already pre-pumps prices. Like `buildMintWlpTx`,
87
+ * `request_redeem` produces no `TradingRequest`, so a non-skipped refresh
88
+ * requires `allowGasFee: true` (see `buildMintWlpTx`'s doc comment).
69
89
  */
70
90
  export async function buildUnstakeAndRequestRedeemWlpTx(client, params) {
71
91
  const tx = newTx(params);
72
92
  const stakeAlias = params.stakeAlias ?? "WLP";
73
93
  await maybeConsolidate(client, tx, params.accountId, params);
94
+ // `request_redeem` has no sponsor flow to resolve against (see
95
+ // `buildMintWlpTx`'s doc comment) — the only candidate source at this edge
96
+ // is the caller's ergonomic `allowGasFee` opt-in.
97
+ const feeSource = params.allowGasFee ? { kind: "gas" } : undefined;
74
98
  if (!params.skipOraclePriceRefresh) {
75
99
  await refreshWlpPoolOracles(tx, client, [], {
76
100
  cache: params.pythCache,
77
101
  lpType: params.lpType,
102
+ feeSource,
103
+ updateDataProvider: params.updateDataProvider,
78
104
  });
79
105
  }
80
106
  unstake(client, tx, {
@@ -3,9 +3,9 @@
3
3
  *
4
4
  * Each `build*Tx` composer creates (or appends to) a `Transaction`, refreshes
5
5
  * the on-chain `Oracle` via Pyth, optionally pre-sweeps parked balances
6
- * (`consolidateToUsd`), wires the `pyth_sponsor_rule` flow when enabled, and
7
- * calls the matching `*_request` + `execute`. Implementations are split by
8
- * domain under `tx-builders/`:
6
+ * (`consolidateToUsd`), wires the `pyth_sponsor_rule` flow when deployed in
7
+ * config, and calls the matching `*_request` + `execute`. Implementations are
8
+ * split by domain under `tx-builders/`:
9
9
  *
10
10
  * common.ts CommonBuildOpts + request/execute envelope + oracle refresh
11
11
  * consolidate.ts parked-balance → wxUSD pre-sweep (appendConsolidate*)
@@ -3,9 +3,9 @@
3
3
  *
4
4
  * Each `build*Tx` composer creates (or appends to) a `Transaction`, refreshes
5
5
  * the on-chain `Oracle` via Pyth, optionally pre-sweeps parked balances
6
- * (`consolidateToUsd`), wires the `pyth_sponsor_rule` flow when enabled, and
7
- * calls the matching `*_request` + `execute`. Implementations are split by
8
- * domain under `tx-builders/`:
6
+ * (`consolidateToUsd`), wires the `pyth_sponsor_rule` flow when deployed in
7
+ * config, and calls the matching `*_request` + `execute`. Implementations are
8
+ * split by domain under `tx-builders/`:
9
9
  *
10
10
  * common.ts CommonBuildOpts + request/execute envelope + oracle refresh
11
11
  * consolidate.ts parked-balance → wxUSD pre-sweep (appendConsolidate*)
@@ -47,17 +47,12 @@ export interface WaterxPredictionConfig {
47
47
  }
48
48
  export interface LoadConfigOptions {
49
49
  /**
50
- * Override the default waterx-config raw JSON URL. Use this to point at a
51
- * local mirror during development. Takes precedence over {@link configRef}.
50
+ * Canonical `waterx-config` JSON URL to fetch, **as-is** (no `<network>.json`
51
+ * / git ref appended). Required {@link loadConfig} reads the URL only from
52
+ * this option (there is no env-var fallback and no built-in default) and
53
+ * throws when it is unset.
52
54
  */
53
- configUrl?: string;
54
- /**
55
- * Pin the canonical config to a specific git ref — a commit SHA, branch, or
56
- * tag — instead of the default `main` branch. Resolves to
57
- * `https://raw.githubusercontent.com/WaterXProtocol/waterx-config/<ref>/<network>.json`.
58
- * Ignored when {@link configUrl} is set.
59
- */
60
- configRef?: string;
55
+ waterxConfigUrl?: string;
61
56
  /** Reuse a previously fetched config in memory. Default: false. */
62
57
  cache?: boolean;
63
58
  /** Optional fetch implementation for tests or runtimes without global fetch. */
@@ -65,10 +60,5 @@ export interface LoadConfigOptions {
65
60
  /** Request timeout in ms. Default: 10_000. */
66
61
  timeoutMs?: number;
67
62
  }
68
- /**
69
- * Build the canonical config URL for `network`, optionally pinned to a
70
- * specific git `ref` (commit SHA, branch, or tag). Defaults to `main`.
71
- */
72
- export declare function defaultConfigUrl(network: Network, ref?: string): string;
73
63
  export declare function clearConfigCache(): void;
74
64
  export declare function loadConfig(network: Network, opts?: LoadConfigOptions): Promise<WaterxPredictionConfig>;
@@ -4,22 +4,15 @@
4
4
  * Mirrors the canonical `waterx-config` JSON for the packages used by this SDK
5
5
  * and fetches it from GitHub raw by default.
6
6
  */
7
- const CONFIG_REPO_RAW_BASE = "https://raw.githubusercontent.com/WaterXProtocol/waterx-config";
8
- /** Default git ref for the canonical config when none is pinned. */
9
- const DEFAULT_CONFIG_REF = "main";
10
- /**
11
- * Build the canonical config URL for `network`, optionally pinned to a
12
- * specific git `ref` (commit SHA, branch, or tag). Defaults to `main`.
13
- */
14
- export function defaultConfigUrl(network, ref = DEFAULT_CONFIG_REF) {
15
- return `${CONFIG_REPO_RAW_BASE}/${ref}/${network.toLowerCase()}.json`;
16
- }
17
7
  const configCache = new Map();
18
8
  export function clearConfigCache() {
19
9
  configCache.clear();
20
10
  }
21
11
  export async function loadConfig(network, opts = {}) {
22
- const url = opts.configUrl ?? defaultConfigUrl(network, opts.configRef);
12
+ const url = opts.waterxConfigUrl;
13
+ if (!url) {
14
+ throw new Error("loadConfig: no config URL — pass opts.waterxConfigUrl");
15
+ }
23
16
  if (opts.cache && configCache.has(url)) {
24
17
  return configCache.get(url);
25
18
  }
@@ -1,5 +1,5 @@
1
1
  import type { PredictClient } from "./client.ts";
2
- import type { AccountDataView, CursorView, MarketExposure, MarketIdInput, MarketView, OrderView, PositionView, RegistryView } from "./types.ts";
2
+ import type { AccountDataView, CursorView, MarketExposure, MarketIdInput, MarketPage, MarketView, OrderView, PageParams, PositionPage, PositionView, RegistryView } from "./types.ts";
3
3
  export declare function extractReturnBytes(result: any, commandIndex?: number, returnIndex?: number): Uint8Array;
4
4
  export interface ViewBaseParams {
5
5
  packageId?: string;
@@ -30,6 +30,11 @@ export declare function getOrderCursor(client: PredictClient, params?: ViewBaseP
30
30
  export declare function getPositionCursor(client: PredictClient, params?: ViewBaseParams): Promise<CursorView>;
31
31
  export declare function getUnresolvedMarketCursor(client: PredictClient, params?: ViewBaseParams): Promise<CursorView>;
32
32
  export declare function getResolvedMarketCursor(client: PredictClient, params?: ViewBaseParams): Promise<CursorView>;
33
+ /** Every unresolved (active) market in one call. Prefer `getUnresolvedMarketsPage` when the table is large. */
34
+ export declare function getUnresolvedMarkets(client: PredictClient, params?: ViewBaseParams): Promise<MarketView[]>;
35
+ export declare function getUnresolvedMarketsPage(client: PredictClient, params?: PageParams): Promise<MarketPage>;
36
+ export declare function getResolvedMarketsPage(client: PredictClient, params?: PageParams): Promise<MarketPage>;
37
+ export declare function getPositionsPage(client: PredictClient, params?: PageParams): Promise<PositionPage>;
33
38
  export interface GetAccountIdsParams {
34
39
  /** Wallet address that owns sub-accounts in the registry. */
35
40
  owner: string;
@@ -125,6 +125,66 @@ export function getUnresolvedMarketCursor(client, params = {}) {
125
125
  export function getResolvedMarketCursor(client, params = {}) {
126
126
  return readCursor(client, "resolved_market_cursor", params);
127
127
  }
128
+ const DEFAULT_PAGE_LIMIT = 100n;
129
+ /** Encode an optional cursor key as a Move `Option<u64>` pure arg (`undefined` → none / from front). */
130
+ function startArg(tx, start) {
131
+ return tx.pure(bcs.option(bcs.u64()).serialize(start === undefined ? null : toBigInt(start)));
132
+ }
133
+ /** Every unresolved (active) market in one call. Prefer `getUnresolvedMarketsPage` when the table is large. */
134
+ export async function getUnresolvedMarkets(client, params = {}) {
135
+ const tx = new Transaction();
136
+ tx.moveCall({
137
+ target: `${resolvePackageId(client, params.packageId)}::view::unresolved_markets`,
138
+ typeArguments: [resolveSettlementCoinType(client, params.settlementCoinType)],
139
+ arguments: [tx.object(resolveMarketRegistry(client, params.marketRegistry))],
140
+ });
141
+ const result = await client.simulate(tx);
142
+ return bcs.vector(MarketViewBcs).parse(extractReturnBytes(result)).map(mapMarketView);
143
+ }
144
+ async function readMarketsPage(client, functionName, params = {}) {
145
+ const tx = new Transaction();
146
+ tx.moveCall({
147
+ target: `${resolvePackageId(client, params.packageId)}::view::${functionName}`,
148
+ typeArguments: [resolveSettlementCoinType(client, params.settlementCoinType)],
149
+ arguments: [
150
+ tx.object(resolveMarketRegistry(client, params.marketRegistry)),
151
+ startArg(tx, params.start),
152
+ tx.pure.u64(params.limit === undefined ? DEFAULT_PAGE_LIMIT : toBigInt(params.limit)),
153
+ ],
154
+ });
155
+ const result = await client.simulate(tx);
156
+ const markets = bcs
157
+ .vector(MarketViewBcs)
158
+ .parse(extractReturnBytes(result, 0, 0))
159
+ .map(mapMarketView);
160
+ const next = bcs.option(bcs.u64()).parse(extractReturnBytes(result, 0, 1));
161
+ return { markets, nextCursor: next == null ? null : BigInt(next) };
162
+ }
163
+ export function getUnresolvedMarketsPage(client, params = {}) {
164
+ return readMarketsPage(client, "unresolved_markets_page", params);
165
+ }
166
+ export function getResolvedMarketsPage(client, params = {}) {
167
+ return readMarketsPage(client, "resolved_markets_page", params);
168
+ }
169
+ export async function getPositionsPage(client, params = {}) {
170
+ const tx = new Transaction();
171
+ tx.moveCall({
172
+ target: `${resolvePackageId(client, params.packageId)}::view::positions_page`,
173
+ typeArguments: [resolveSettlementCoinType(client, params.settlementCoinType)],
174
+ arguments: [
175
+ tx.object(resolveMarketRegistry(client, params.marketRegistry)),
176
+ startArg(tx, params.start),
177
+ tx.pure.u64(params.limit === undefined ? DEFAULT_PAGE_LIMIT : toBigInt(params.limit)),
178
+ ],
179
+ });
180
+ const result = await client.simulate(tx);
181
+ const positions = bcs
182
+ .vector(PositionViewBcs)
183
+ .parse(extractReturnBytes(result, 0, 0))
184
+ .map(mapPositionView);
185
+ const next = bcs.option(bcs.u64()).parse(extractReturnBytes(result, 0, 1));
186
+ return { positions, nextCursor: next == null ? null : BigInt(next) };
187
+ }
128
188
  /**
129
189
  * Registry account ids (`0x2::object::ID`) for an owner via `waterx_account::account::account_ids`.
130
190
  * Use these ids with `getAccountData`, `deposit`, and `placeOrder` — not Suiscan "Account" object addresses.
@@ -1,6 +1,6 @@
1
1
  export { PredictClient } from "./client.ts";
2
2
  export type { CreateClientOptions } from "./client.ts";
3
- export { clearConfigCache, defaultConfigUrl, loadConfig } from "./config.ts";
3
+ export { clearConfigCache, loadConfig } from "./config.ts";
4
4
  export type { LoadConfigOptions, WaterxAccountPackage, WaterxConfigPackageBase, WaterxPredictionConfig, WaterxPredictionConfigPackages, WaterxPredictionGiftPackage, WaterxPredictionPackage, WaterxReferralPackage, } from "./config.ts";
5
5
  export * from "./constants.ts";
6
6
  export * from "./types.ts";
@@ -14,7 +14,7 @@ export { adminPlaceOrderFor, batchClaim, batchForceClaim, buildBatchForceClaimTr
14
14
  export type { AdminPlaceOrderForParams, BatchClaimParams, BatchForceClaimParams, BuildBatchForceClaimTransactionsParams, CancelCloseParams, CancelOrderParams, ClaimParams, ConfirmCloseParams, FillOrderParams, ForceClaimParams, PlaceOrderParams, RequestCloseParams, RequestPartialCloseParams, ResolveMarketParams, SelfCancelCloseParams, SelfCancelOrderParams, SplitPositionParams, TransferPositionParams, } from "./prediction.ts";
15
15
  export { buildBatchClaimTx, buildPlaceOrderTx } from "./tx-builders.ts";
16
16
  export type { BuildBatchClaimTxParams, BuildPlaceOrderTxParams, PredictCommonBuildOpts, } from "./tx-builders.ts";
17
- export { getAccountData, getAccountIds, getAccountOrderIds, getAccountOrderIdsByMarketId, getAccountPositionIds, getAccountPositionIdsByMarketId, getKeeperAddresses, getAllowedVersions, getMarketExposure, getMarketExposureByKey, getMarketById, getMarketByKey, getOrder, getOrderCursor, getPosition, getPositionCursor, getRegistry, getResolvedMarketCursor, getUnresolvedMarketCursor, isKeeper, isPredictionProtocolAssetAllowed, } from "./fetch.ts";
17
+ export { getAccountData, getAccountIds, getAccountOrderIds, getAccountOrderIdsByMarketId, getAccountPositionIds, getAccountPositionIdsByMarketId, getKeeperAddresses, getAllowedVersions, getMarketExposure, getMarketExposureByKey, getMarketById, getMarketByKey, getOrder, getOrderCursor, getPosition, getPositionCursor, getPositionsPage, getRegistry, getResolvedMarketCursor, getResolvedMarketsPage, getUnresolvedMarketCursor, getUnresolvedMarkets, getUnresolvedMarketsPage, isKeeper, isPredictionProtocolAssetAllowed, } from "./fetch.ts";
18
18
  export type { GetAccountIdsParams, ViewBaseParams } from "./fetch.ts";
19
19
  export { base64UrlNoPadDecode, base64UrlNoPadEncode, buildClaimShareFlow, buildCreateGiftFlow, buildGiftClaimMessage, claimShare, createGift, deleteGift, deriveGiftAddress, deriveGiftKeypair, encodeGiftUrl, generateGiftSeed, getCreatorGiftCount, getCreatorGiftIds, getGift, getGiftConfigPaused, getGiftControllerAddress, getGiftHasClaimed, parseGiftUrl, signGiftClaim, } from "./gift.ts";
20
20
  export type { BuildClaimShareFlowParams, BuildClaimShareFlowResult, BuildCreateGiftFlowResult, ClaimShareParams, CreateGiftParams, DeleteGiftParams, GiftBaseParams, GiftReferralParams, GiftUrlParts, GiftView, } from "./gift.ts";
@@ -1,5 +1,5 @@
1
1
  export { PredictClient } from "./client.js";
2
- export { clearConfigCache, defaultConfigUrl, loadConfig } from "./config.js";
2
+ export { clearConfigCache, loadConfig } from "./config.js";
3
3
  export * from "./constants.js";
4
4
  export * from "./types.js";
5
5
  export * as user from "./user/index.js";
@@ -8,7 +8,7 @@ export { addDelegate, allowPredictionProtocolAsset, consumeDepositDirect, consum
8
8
  export { addKeeper, adminWithdraw, createMarketRegistry, depositSettlement, pauseMarket, removeKeeper, setMinReserve, setOrderCancelCooldownMs, unpauseMarket, } from "./admin.js";
9
9
  export { adminPlaceOrderFor, batchClaim, batchForceClaim, buildBatchForceClaimTransactions, cancelClose, cancelOrder, claim, confirmClose, fillOrder, forceClaim, outcomeArg, placeOrder, requestClose, requestPartialClose, resolveMarket, selectionArg, selfCancelClose, selfCancelOrder, splitPosition, transferPosition, } from "./prediction.js";
10
10
  export { buildBatchClaimTx, buildPlaceOrderTx } from "./tx-builders.js";
11
- export { getAccountData, getAccountIds, getAccountOrderIds, getAccountOrderIdsByMarketId, getAccountPositionIds, getAccountPositionIdsByMarketId, getKeeperAddresses, getAllowedVersions, getMarketExposure, getMarketExposureByKey, getMarketById, getMarketByKey, getOrder, getOrderCursor, getPosition, getPositionCursor, getRegistry, getResolvedMarketCursor, getUnresolvedMarketCursor, isKeeper, isPredictionProtocolAssetAllowed, } from "./fetch.js";
11
+ export { getAccountData, getAccountIds, getAccountOrderIds, getAccountOrderIdsByMarketId, getAccountPositionIds, getAccountPositionIdsByMarketId, getKeeperAddresses, getAllowedVersions, getMarketExposure, getMarketExposureByKey, getMarketById, getMarketByKey, getOrder, getOrderCursor, getPosition, getPositionCursor, getPositionsPage, getRegistry, getResolvedMarketCursor, getResolvedMarketsPage, getUnresolvedMarketCursor, getUnresolvedMarkets, getUnresolvedMarketsPage, isKeeper, isPredictionProtocolAssetAllowed, } from "./fetch.js";
12
12
  export { base64UrlNoPadDecode, base64UrlNoPadEncode, buildClaimShareFlow, buildCreateGiftFlow, buildGiftClaimMessage, claimShare, createGift, deleteGift, deriveGiftAddress, deriveGiftKeypair, encodeGiftUrl, generateGiftSeed, getCreatorGiftCount, getCreatorGiftIds, getGift, getGiftConfigPaused, getGiftControllerAddress, getGiftHasClaimed, parseGiftUrl, signGiftClaim, } from "./gift.js";
13
13
  export * as bucketFrameworkAccountCalls from "../generated/bucket_v2_framework/account.js";
14
14
  export * as waterxAccountCalls from "../generated/waterx_account/account.js";
@@ -88,6 +88,25 @@ export interface CursorView {
88
88
  front: bigint | null;
89
89
  back: bigint | null;
90
90
  }
91
+ export interface PageParams {
92
+ packageId?: string;
93
+ marketRegistry?: string;
94
+ settlementCoinType?: string;
95
+ /** Cursor key to resume from; omit to start at the front of the table. */
96
+ start?: bigint | number | string;
97
+ /** Max entries in this page (default 100). */
98
+ limit?: bigint | number | string;
99
+ }
100
+ export interface MarketPage {
101
+ markets: MarketView[];
102
+ /** Pass as `start` for the next page; `null` when the table is exhausted. */
103
+ nextCursor: bigint | null;
104
+ }
105
+ export interface PositionPage {
106
+ positions: PositionView[];
107
+ /** Pass as `start` for the next page; `null` when the table is exhausted. */
108
+ nextCursor: bigint | null;
109
+ }
91
110
  export interface CoinRef {
92
111
  objectId: string;
93
112
  version: string | bigint | number;
@@ -32,6 +32,8 @@ import { Transaction } from "@mysten/sui/transactions";
32
32
  import * as accountOps from "./account/index.ts";
33
33
  import * as perpReferral from "./account/referral.ts";
34
34
  import type { Network } from "./constants.ts";
35
+ import type { PythGeneration } from "./oracle/config.ts";
36
+ import type { OracleSource } from "./oracle/price-update-rule.ts";
35
37
  import { PerpClient, type CreateClientOptions as PerpCreateOptions } from "./perp/client.ts";
36
38
  import * as perpFetch from "./perp/fetch.ts";
37
39
  import * as perpTx from "./perp/tx-builders.ts";
@@ -263,6 +265,10 @@ declare const predictOps: {
263
265
  getPositionCursor(client: PredictClient, params?: predFetch.ViewBaseParams): Promise<import("./prediction/types.ts").CursorView>;
264
266
  getUnresolvedMarketCursor(client: PredictClient, params?: predFetch.ViewBaseParams): Promise<import("./prediction/types.ts").CursorView>;
265
267
  getResolvedMarketCursor(client: PredictClient, params?: predFetch.ViewBaseParams): Promise<import("./prediction/types.ts").CursorView>;
268
+ getUnresolvedMarkets(client: PredictClient, params?: predFetch.ViewBaseParams): Promise<import("./prediction/types.ts").MarketView[]>;
269
+ getUnresolvedMarketsPage(client: PredictClient, params?: import("./prediction/types.ts").PageParams): Promise<import("./prediction/types.ts").MarketPage>;
270
+ getResolvedMarketsPage(client: PredictClient, params?: import("./prediction/types.ts").PageParams): Promise<import("./prediction/types.ts").MarketPage>;
271
+ getPositionsPage(client: PredictClient, params?: import("./prediction/types.ts").PageParams): Promise<import("./prediction/types.ts").PositionPage>;
266
272
  getAccountIds(client: PredictClient, params: predFetch.GetAccountIdsParams): Promise<string[]>;
267
273
  getAccountData(client: PredictClient, params: predFetch.ViewBaseParams & {
268
274
  accountId: string;
@@ -354,13 +360,29 @@ export interface ClientCreateOptions {
354
360
  network?: Network;
355
361
  /** Default gRPC URL for both lines. */
356
362
  grpcUrl?: string;
357
- /** Default `waterx-config` JSON URL for both lines. */
358
- configUrl?: string;
363
+ /** Default `waterx-config` JSON URL for both lines (fetched as-is). Required
364
+ * unless supplied per-line via `perp` / `predict`. */
365
+ waterxConfigUrl?: string;
359
366
  /** Memoize the fetched config JSON. */
360
367
  cache?: boolean;
361
- /** Perp-line overrides (network, grpcUrl, configUrl, cache, …). */
368
+ /**
369
+ * Selects which `PriceUpdateRule` the perp line's `refreshOraclePrices` uses
370
+ * for the on-chain price-update leg (see `OracleHost.oracleSource`).
371
+ * Default: `'pyth_rule'`. Perp-line only. The SDK never reads `process.env`
372
+ * — pass this from your own env var (e.g. `ORACLE_SOURCE`).
373
+ */
374
+ oracleSource?: OracleSource;
375
+ /**
376
+ * Selects which Pyth Core contract generation feeds the perp line's
377
+ * `client.perp.pyth` when the config JSON has no explicit `pyth` override:
378
+ * `'core'` (default) or `'pro'` (post-2026-08-18 Pro-compatible contracts +
379
+ * Hermes-compatible endpoint; pair with `pyth.api_key`). Perp-line only.
380
+ * See `PythGeneration` / `PYTH_PRO_DEFAULTS`.
381
+ */
382
+ pythGeneration?: PythGeneration;
383
+ /** Perp-line overrides (network, grpcUrl, waterxConfigUrl, cache, …). */
362
384
  perp?: PerpLineOptions;
363
- /** Prediction-line overrides (network, grpcUrl, configUrl, cache, settlement, …). */
385
+ /** Prediction-line overrides (network, grpcUrl, waterxConfigUrl, cache, settlement, …). */
364
386
  predict?: PredictLineOptions;
365
387
  }
366
388
  export declare class WaterXClient {
@@ -166,13 +166,15 @@ export class WaterXClient {
166
166
  }
167
167
  const perpClient = await PerpClient.create(resolvedPerpNetwork, {
168
168
  grpcUrl: opts.grpcUrl,
169
- configUrl: opts.configUrl,
169
+ waterxConfigUrl: opts.waterxConfigUrl,
170
170
  cache: opts.cache,
171
+ oracleSource: opts.oracleSource,
172
+ pythGeneration: opts.pythGeneration,
171
173
  ...perpRest,
172
174
  });
173
175
  const predictClient = await PredictClient.create(resolvedPredictNetwork, {
174
176
  grpcUrl: opts.grpcUrl,
175
- configUrl: opts.configUrl,
177
+ waterxConfigUrl: opts.waterxConfigUrl,
176
178
  cache: opts.cache,
177
179
  ...predictRest,
178
180
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@waterx/sdk",
3
- "version": "3.1.0",
3
+ "version": "4.0.0",
4
4
  "description": "WaterX SDK — perpetuals and prediction markets on Sui",
5
5
  "license": "MIT",
6
6
  "author": "WaterX",