aftermath-ts-sdk 1.3.26-perps.13 → 1.3.27

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 (120) hide show
  1. package/dist/general/apiHelpers/transactionsApiHelpers.d.ts +0 -3
  2. package/dist/general/apiHelpers/transactionsApiHelpers.d.ts.map +1 -1
  3. package/dist/general/apiHelpers/transactionsApiHelpers.js +0 -12
  4. package/dist/general/providers/aftermath.d.ts +5 -0
  5. package/dist/general/providers/aftermath.d.ts.map +1 -1
  6. package/dist/general/providers/aftermath.js +6 -1
  7. package/dist/general/providers/aftermathApi.d.ts +5 -0
  8. package/dist/general/providers/aftermathApi.d.ts.map +1 -1
  9. package/dist/general/providers/aftermathApi.js +5 -0
  10. package/dist/general/types/castingTypes.d.ts +2 -2
  11. package/dist/general/types/castingTypes.d.ts.map +1 -1
  12. package/dist/general/types/configTypes.d.ts +10 -6
  13. package/dist/general/types/configTypes.d.ts.map +1 -1
  14. package/dist/general/types/generalTypes.d.ts +0 -8
  15. package/dist/general/types/generalTypes.d.ts.map +1 -1
  16. package/dist/general/types/moveErrorsInterface.d.ts +1 -1
  17. package/dist/general/types/moveErrorsInterface.d.ts.map +1 -1
  18. package/dist/general/utils/caller.d.ts +2 -34
  19. package/dist/general/utils/caller.d.ts.map +1 -1
  20. package/dist/general/utils/caller.js +12 -111
  21. package/dist/general/utils/casting.d.ts +5 -4
  22. package/dist/general/utils/casting.d.ts.map +1 -1
  23. package/dist/general/utils/casting.js +5 -4
  24. package/dist/general/utils/helpers.d.ts +0 -1
  25. package/dist/general/utils/helpers.d.ts.map +1 -1
  26. package/dist/general/utils/helpers.js +6 -38
  27. package/dist/general/wallet/wallet.d.ts +1 -1
  28. package/dist/general/wallet/wallet.d.ts.map +1 -1
  29. package/dist/packages/coin/coin.d.ts +1 -5
  30. package/dist/packages/coin/coin.d.ts.map +1 -1
  31. package/dist/packages/coin/coin.js +1 -7
  32. package/dist/packages/farms/api/farmsApiCasting.js +27 -27
  33. package/dist/packages/farms/farms.d.ts +1 -1
  34. package/dist/packages/farms/farms.d.ts.map +1 -1
  35. package/dist/packages/farms/farmsStakedPosition.d.ts +1 -1
  36. package/dist/packages/farms/farmsStakedPosition.d.ts.map +1 -1
  37. package/dist/packages/farms/farmsStakingPool.d.ts +1 -1
  38. package/dist/packages/farms/farmsStakingPool.d.ts.map +1 -1
  39. package/dist/packages/faucet/api/faucetApi.d.ts +17 -9
  40. package/dist/packages/faucet/api/faucetApi.d.ts.map +1 -1
  41. package/dist/packages/faucet/api/faucetApi.js +49 -44
  42. package/dist/packages/faucet/api/faucetApiCasting.d.ts.map +1 -1
  43. package/dist/packages/faucet/api/faucetApiCasting.js +7 -10
  44. package/dist/packages/faucet/api/faucetApiCastingTypes.d.ts +4 -1
  45. package/dist/packages/faucet/api/faucetApiCastingTypes.d.ts.map +1 -1
  46. package/dist/packages/faucet/faucet.d.ts +1 -1
  47. package/dist/packages/faucet/faucet.d.ts.map +1 -1
  48. package/dist/packages/faucet/faucet.js +1 -1
  49. package/dist/packages/faucet/faucetTypes.d.ts +3 -2
  50. package/dist/packages/faucet/faucetTypes.d.ts.map +1 -1
  51. package/dist/packages/leveragedStaking/api/leveragedStakingApiCasting.js +3 -3
  52. package/dist/packages/multisig/multisig.d.ts +1 -1
  53. package/dist/packages/multisig/multisig.d.ts.map +1 -1
  54. package/dist/packages/nftAmm/nftAmm.d.ts +1 -1
  55. package/dist/packages/nftAmm/nftAmm.d.ts.map +1 -1
  56. package/dist/packages/oracle/api/oracleApi.d.ts +21 -0
  57. package/dist/packages/oracle/api/oracleApi.d.ts.map +1 -0
  58. package/dist/packages/oracle/api/oracleApi.js +76 -0
  59. package/dist/packages/oracle/api/oracleApiCasting.d.ts +6 -0
  60. package/dist/packages/oracle/api/oracleApiCasting.d.ts.map +1 -0
  61. package/dist/packages/oracle/api/oracleApiCasting.js +25 -0
  62. package/dist/packages/oracle/oracle.d.ts +15 -0
  63. package/dist/packages/oracle/oracle.d.ts.map +1 -0
  64. package/dist/packages/oracle/oracle.js +46 -0
  65. package/dist/packages/oracle/oracleCastingTypes.d.ts +11 -0
  66. package/dist/packages/oracle/oracleCastingTypes.d.ts.map +1 -0
  67. package/dist/packages/oracle/oracleCastingTypes.js +2 -0
  68. package/dist/packages/oracle/oracleTypes.d.ts +10 -0
  69. package/dist/packages/oracle/oracleTypes.d.ts.map +1 -0
  70. package/dist/packages/oracle/oracleTypes.js +2 -0
  71. package/dist/packages/perpetuals/api/perpetualsApi.d.ts +203 -12
  72. package/dist/packages/perpetuals/api/perpetualsApi.d.ts.map +1 -1
  73. package/dist/packages/perpetuals/api/perpetualsApi.js +615 -926
  74. package/dist/packages/perpetuals/api/perpetualsApiCasting.d.ts +21 -10
  75. package/dist/packages/perpetuals/api/perpetualsApiCasting.d.ts.map +1 -1
  76. package/dist/packages/perpetuals/api/perpetualsApiCasting.js +238 -260
  77. package/dist/packages/perpetuals/index.d.ts +0 -1
  78. package/dist/packages/perpetuals/index.d.ts.map +1 -1
  79. package/dist/packages/perpetuals/index.js +0 -1
  80. package/dist/packages/perpetuals/perpetuals.d.ts +28 -813
  81. package/dist/packages/perpetuals/perpetuals.d.ts.map +1 -1
  82. package/dist/packages/perpetuals/perpetuals.js +70 -984
  83. package/dist/packages/perpetuals/perpetualsAccount.d.ts +170 -754
  84. package/dist/packages/perpetuals/perpetualsAccount.d.ts.map +1 -1
  85. package/dist/packages/perpetuals/perpetualsAccount.js +312 -1267
  86. package/dist/packages/perpetuals/perpetualsCastingTypes.d.ts +149 -82
  87. package/dist/packages/perpetuals/perpetualsCastingTypes.d.ts.map +1 -1
  88. package/dist/packages/perpetuals/perpetualsMarket.d.ts +27 -341
  89. package/dist/packages/perpetuals/perpetualsMarket.d.ts.map +1 -1
  90. package/dist/packages/perpetuals/perpetualsMarket.js +78 -411
  91. package/dist/packages/perpetuals/perpetualsTypes.d.ts +319 -2575
  92. package/dist/packages/perpetuals/perpetualsTypes.d.ts.map +1 -1
  93. package/dist/packages/perpetuals/perpetualsTypes.js +82 -92
  94. package/dist/packages/pools/api/poolsApiCasting.js +3 -3
  95. package/dist/packages/pools/pool.d.ts +1 -1
  96. package/dist/packages/pools/pool.d.ts.map +1 -1
  97. package/dist/packages/pools/pools.d.ts +1 -1
  98. package/dist/packages/pools/pools.d.ts.map +1 -1
  99. package/dist/packages/router/api/routerApiCasting.js +1 -1
  100. package/dist/packages/router/routerTypes.d.ts +1 -1
  101. package/dist/packages/router/routerTypes.d.ts.map +1 -1
  102. package/dist/packages/staking/api/stakingApiCasting.js +3 -3
  103. package/dist/packages/staking/staking.d.ts +1 -1
  104. package/dist/packages/staking/staking.d.ts.map +1 -1
  105. package/dist/packages/sui/sui.d.ts +1 -1
  106. package/dist/packages/sui/sui.d.ts.map +1 -1
  107. package/dist/packages/suiFrens/api/suiFrensApiCasting.js +4 -4
  108. package/dist/packages/suiFrens/stakedSuiFren.d.ts +1 -1
  109. package/dist/packages/suiFrens/stakedSuiFren.d.ts.map +1 -1
  110. package/dist/packages/suiFrens/suiFren.d.ts +1 -1
  111. package/dist/packages/suiFrens/suiFren.d.ts.map +1 -1
  112. package/dist/packages/suiFrens/suiFrens.d.ts +1 -1
  113. package/dist/packages/suiFrens/suiFrens.d.ts.map +1 -1
  114. package/dist/types.d.ts +1 -0
  115. package/dist/types.d.ts.map +1 -1
  116. package/dist/types.js +1 -0
  117. package/package.json +1 -1
  118. package/dist/packages/perpetuals/perpetualsVault.d.ts +0 -438
  119. package/dist/packages/perpetuals/perpetualsVault.d.ts.map +0 -1
  120. package/dist/packages/perpetuals/perpetualsVault.js +0 -601
@@ -8,1066 +8,152 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
- var __rest = (this && this.__rest) || function (s, e) {
12
- var t = {};
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
- t[p] = s[p];
15
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
- t[p[i]] = s[p[i]];
19
- }
20
- return t;
21
- };
11
+ var _a;
22
12
  Object.defineProperty(exports, "__esModule", { value: true });
23
13
  exports.Perpetuals = void 0;
24
14
  const caller_1 = require("../../general/utils/caller");
25
15
  const types_1 = require("../../types");
26
16
  const perpetualsMarket_1 = require("./perpetualsMarket");
27
17
  const perpetualsAccount_1 = require("./perpetualsAccount");
18
+ const iFixedUtils_1 = require("../../general/utils/iFixedUtils");
28
19
  const fixedUtils_1 = require("../../general/utils/fixedUtils");
29
- const utils_1 = require("./utils");
30
- const transactions_1 = require("@mysten/sui/transactions");
31
- const perpetualsVault_1 = require("./perpetualsVault");
32
- /**
33
- * High-level client for interacting with Aftermath Perpetuals.
34
- *
35
- * This class exposes a typed, ergonomic interface over the Perpetuals HTTP API
36
- * and websocket endpoints, including:
37
- *
38
- * - Market discovery (`getAllMarkets`, `getMarkets`, `getMarket`)
39
- * - Vault discovery (`getAllVaults`, `getVaults`, `getVault`)
40
- * - Account & position data (`getAccount`, `getAccounts`, `getAccountObjects`)
41
- * - Ownership queries (`getOwnedAccountCaps`, `getOwnedVaultCaps`)
42
- * - Historical data & stats (`getMarketCandleHistory`, `getMarkets24hrStats`)
43
- * - Pricing helpers (`getPrices`, `getLpCoinPrices`)
44
- * - Transaction builders (`getCreateAccountTx`, `getCreateVaultCapTx`, `getCreateVaultTx`)
45
- * - Websocket feeds (`openUpdatesWebsocketStream`, `openMarketCandlesWebsocketStream`)
46
- *
47
- * Typical usage via the root SDK:
48
- *
49
- * ```ts
50
- * import { Aftermath } from "@aftermath/sdk";
51
- *
52
- * const afSdk = new Aftermath("MAINNET");
53
- * await afSdk.init();
54
- *
55
- * const perps = afSdk.Perpetuals();
56
- *
57
- * // Fetch markets for a given collateral coin type
58
- * const markets = await perps.getAllMarkets({
59
- * collateralCoinType: "0x2::sui::SUI",
60
- * });
61
- *
62
- * // Fetch account + positions for a given account cap
63
- * const [accountCap] = await perps.getOwnedAccountCaps({
64
- * walletAddress: "0x...",
65
- * });
66
- *
67
- * const account = await perps.getAccount({ accountCap });
68
- *
69
- * // Build a create-account transaction (not signed or sent)
70
- * const createAccountTx = await perps.getCreateAccountTx({
71
- * walletAddress: "0x...",
72
- * collateralCoinType: "0x2::sui::SUI",
73
- * });
74
- * ```
75
- */
20
+ const utils_1 = require("../../general/utils");
21
+ const utils_2 = require("./utils");
76
22
  class Perpetuals extends caller_1.Caller {
77
23
  // =========================================================================
78
24
  // Constructor
79
25
  // =========================================================================
80
- /**
81
- * Creates a new Perpetuals client.
82
- *
83
- * @param config - Optional caller configuration (network, auth token, etc.).
84
- * @param Provider - Optional shared {@link AftermathApi} provider instance. When
85
- * provided, transaction-building helpers can derive serialized `txKind`
86
- * from a {@link Transaction} object via `Provider.Transactions().fetchBase64TxKindFromTx`.
87
- *
88
- * @remarks
89
- * This class extends {@link Caller} with the `"perpetuals"` route prefix, meaning:
90
- * - HTTP calls resolve under `/perpetuals/...`
91
- * - Websocket calls resolve under `/perpetuals/ws/...`
92
- */
93
- constructor(config, Provider) {
26
+ constructor(config) {
94
27
  super(config, "perpetuals");
95
- this.Provider = Provider;
96
28
  }
97
29
  // =========================================================================
98
- // Markets
30
+ // Class Objects
99
31
  // =========================================================================
100
- /**
101
- * Fetch all perpetual markets for a given collateral coin type.
102
- *
103
- * This method returns *wrapped* {@link PerpetualsMarket} instances, not the raw
104
- * market structs. Each instance provides additional helpers for pricing, margin,
105
- * and order parsing.
106
- *
107
- * @param inputs.collateralCoinType - Coin type used as collateral, e.g. `"0x2::sui::SUI"`.
108
- * @returns Object containing `markets`.
109
- *
110
- * @example
111
- * ```ts
112
- * const { markets } = await perps.getAllMarkets({
113
- * collateralCoinType: "0x2::sui::SUI",
114
- * });
115
- * ```
116
- */
117
32
  getAllMarkets(inputs) {
118
33
  return __awaiter(this, void 0, void 0, function* () {
119
- const res = yield this.fetchApi("all-markets", inputs);
120
- return {
121
- markets: res.markets.map((marketData) => new perpetualsMarket_1.PerpetualsMarket(marketData, this.config, this.Provider)),
122
- };
34
+ const { collateralCoinType } = inputs;
35
+ const marketDatas = yield this.fetchApi(`${collateralCoinType}/markets`);
36
+ return marketDatas.map((marketData) => new perpetualsMarket_1.PerpetualsMarket(marketData, this.config));
123
37
  });
124
38
  }
125
- /**
126
- * Fetch a single market by ID.
127
- *
128
- * Internally calls {@link getMarkets} and returns the first entry.
129
- *
130
- * @param inputs.marketId - The market (clearing house) object ID.
131
- * @returns Object containing `market`.
132
- *
133
- * @throws If the backend returns an empty list for the given `marketId`,
134
- * this will still attempt to return `markets[0]` (which would be `undefined`).
135
- * Callers may want to validate the result.
136
- *
137
- * @example
138
- * ```ts
139
- * const { market } = await perps.getMarket({ marketId: "0x..." });
140
- * ```
141
- */
142
39
  getMarket(inputs) {
143
40
  return __awaiter(this, void 0, void 0, function* () {
144
- const { markets } = yield this.getMarkets({
145
- marketIds: [inputs.marketId],
146
- });
147
- return {
148
- market: markets[0],
149
- };
41
+ const marketData = yield this.fetchApi(`${inputs.collateralCoinType}/markets/${inputs.marketId}`);
42
+ return new perpetualsMarket_1.PerpetualsMarket(marketData, this.config);
150
43
  });
151
44
  }
152
- /**
153
- * Fetch multiple markets by ID.
154
- *
155
- * Backend note:
156
- * - The API supports returning orderbooks. This SDK currently constructs
157
- * {@link PerpetualsMarket} from the returned `marketDatas[].market`.
158
- *
159
- * @param inputs.marketIds - Array of market object IDs to fetch.
160
- * @returns Object containing `markets` in the same order as `marketIds`.
161
- *
162
- * @example
163
- * ```ts
164
- * const { markets } = await perps.getMarkets({
165
- * marketIds: ["0x..A", "0x..B"],
166
- * });
167
- * ```
168
- */
169
45
  getMarkets(inputs) {
170
46
  return __awaiter(this, void 0, void 0, function* () {
171
- const res = yield this.fetchApi("markets", inputs);
172
- return {
173
- markets: res.marketDatas.map((marketData) => new perpetualsMarket_1.PerpetualsMarket(marketData.market, this.config, this.Provider)),
174
- };
175
- });
176
- }
177
- // =========================================================================
178
- // Vaults
179
- // =========================================================================
180
- /**
181
- * Fetch all vaults on the current network.
182
- *
183
- * Vaults are managed accounts that can hold positions; LPs deposit collateral
184
- * and receive an LP coin (see pricing helpers like {@link getLpCoinPrices}).
185
- *
186
- * @returns Object containing `vaults`.
187
- *
188
- * @example
189
- * ```ts
190
- * const { vaults } = await perps.getAllVaults();
191
- * ```
192
- */
193
- getAllVaults() {
194
- return __awaiter(this, void 0, void 0, function* () {
195
- const res = yield this.fetchApi("vaults", {});
196
- return {
197
- vaults: res.vaults.map((vaultObject) => new perpetualsVault_1.PerpetualsVault(vaultObject, this.config, this.Provider)),
198
- };
199
- });
200
- }
201
- /**
202
- * Fetch a single vault by ID.
203
- *
204
- * Internally calls {@link getVaults} and returns the first entry.
205
- *
206
- * @param inputs.vaultId - Vault object ID.
207
- * @returns Object containing `vault`.
208
- */
209
- getVault(inputs) {
210
- return __awaiter(this, void 0, void 0, function* () {
211
- const { vaults } = yield this.getVaults({
212
- vaultIds: [inputs.vaultId],
213
- });
214
- return {
215
- vault: vaults[0],
216
- };
217
- });
218
- }
219
- /**
220
- * Fetch multiple vaults by ID.
221
- *
222
- * @param inputs.vaultIds - Array of vault object IDs.
223
- * @returns Object containing `vaults` in the same order as `vaultIds`.
224
- */
225
- getVaults(inputs) {
226
- return __awaiter(this, void 0, void 0, function* () {
227
- const res = yield this.fetchApi("vaults", inputs);
228
- return {
229
- vaults: res.vaults.map((vaultObject) => new perpetualsVault_1.PerpetualsVault(vaultObject, this.config, this.Provider)),
230
- };
47
+ const { collateralCoinType } = inputs;
48
+ return Promise.all(inputs.marketIds.map((marketId) => this.getMarket({
49
+ marketId,
50
+ collateralCoinType,
51
+ })));
231
52
  });
232
53
  }
233
- // =========================================================================
234
- // Accounts
235
- // =========================================================================
236
- /**
237
- * Convenience helper to fetch a single account (positions + account object) from an account cap.
238
- *
239
- * Internally calls {@link getAccounts} and returns the first entry.
240
- *
241
- * @param inputs.accountCap - Account cap or partial vault cap object to derive account metadata from.
242
- * @param inputs.marketIds - Optional list of markets to filter positions by.
243
- * @returns Object containing `account`.
244
- *
245
- * @example
246
- * ```ts
247
- * const [accountCap] = await perps.getOwnedAccountCaps({ walletAddress: "0x..." });
248
- * const { account } = await perps.getAccount({ accountCap });
249
- * ```
250
- */
251
- // TODO: merge this with `getAccountObjects` as an option ?
252
54
  getAccount(inputs) {
253
55
  return __awaiter(this, void 0, void 0, function* () {
254
- const { accountCap, marketIds } = inputs;
255
- return {
256
- account: (yield this.getAccounts({
257
- accountCaps: [accountCap],
258
- marketIds,
259
- })).accounts[0],
260
- };
56
+ const { accountCap } = inputs;
57
+ const account = yield this.fetchApi(`${accountCap.collateralCoinType}/accounts/${accountCap.accountId}`);
58
+ return new perpetualsAccount_1.PerpetualsAccount(account, accountCap, this.config);
261
59
  });
262
60
  }
263
- /**
264
- * Fetch one or more accounts (positions + account objects) from account caps.
265
- *
266
- * This composes:
267
- * 1) {@link getAccountObjects} to fetch {@link PerpetualsAccountObject}s by account ID
268
- * 2) Local pairing of returned account objects with `accountCaps`
269
- *
270
- * The returned {@link PerpetualsAccount} instances encapsulate:
271
- * - The account snapshot (positions, balances, etc.)
272
- * - The ownership/cap metadata (accountId, collateral type, vaultId, etc.)
273
- *
274
- * @param inputs.accountCaps - Array of account caps or partial vault cap objects.
275
- * @param inputs.marketIds - Optional list of market IDs to filter positions by.
276
- * @returns Object containing `accounts` in the same order as `accountCaps`.
277
- *
278
- * @remarks
279
- * If `accountCaps` is empty, this returns `{ accounts: [] }` without making an API call.
280
- */
281
- getAccounts(inputs) {
61
+ getUserAccountCaps(inputs) {
282
62
  return __awaiter(this, void 0, void 0, function* () {
283
- const { accountCaps, marketIds } = inputs;
284
- if (accountCaps.length <= 0)
285
- return {
286
- accounts: [],
287
- };
288
- const accountObjects = (yield this.getAccountObjects({
289
- accountIds: accountCaps.map((accountCap) => accountCap.accountId),
290
- marketIds,
291
- })).accounts;
292
- return {
293
- accounts: accountObjects.map((account, index) => new perpetualsAccount_1.PerpetualsAccount(account, accountCaps[index], this.config, this.Provider)),
294
- };
295
- });
296
- }
297
- /**
298
- * Fetch raw account objects (including positions) for one or more account IDs.
299
- *
300
- * This is the lower-level primitive used by {@link getAccounts}.
301
- *
302
- * @param inputs.accountIds - List of account IDs to query.
303
- * @param inputs.marketIds - Optional list of market IDs to filter positions by.
304
- *
305
- * @returns {@link ApiPerpetualsAccountPositionsResponse} containing `accounts`.
306
- *
307
- * @remarks
308
- * If `accountIds` is empty, this returns `{ accounts: [] }` without making an API call.
309
- */
310
- getAccountObjects(inputs) {
311
- return __awaiter(this, void 0, void 0, function* () {
312
- const { accountIds, marketIds } = inputs;
313
- if (accountIds.length <= 0)
314
- return {
315
- accounts: [],
316
- };
317
- return this.fetchApi("accounts/positions", {
318
- accountIds,
319
- marketIds,
320
- });
321
- });
322
- }
323
- // =========================================================================
324
- // Ownership Queries
325
- // =========================================================================
326
- /**
327
- * Fetch all account caps (perpetuals accounts) owned by a wallet, optionally
328
- * filtered by collateral coin types.
329
- *
330
- * Returned values are “caps” (ownership objects), not full account snapshots.
331
- * To fetch account positions, use {@link getAccount} or {@link getAccounts}.
332
- *
333
- * @param inputs.walletAddress - Owner wallet address.
334
- * @param inputs.collateralCoinTypes - Optional list of collateral coin types to filter by.
335
- * @returns {@link ApiPerpetualsOwnedAccountCapsResponse} containing `accounts`.
336
- *
337
- * @example
338
- * ```ts
339
- * const { accounts } = await perps.getOwnedAccountCaps({
340
- * walletAddress: "0x...",
341
- * collateralCoinTypes: ["0x2::sui::SUI"],
342
- * });
343
- * ```
344
- */
345
- getOwnedAccountCaps(inputs) {
346
- return __awaiter(this, void 0, void 0, function* () {
347
- const { walletAddress, collateralCoinTypes } = inputs;
348
- return this.fetchApi("accounts/owned", {
63
+ const { collateralCoinType, walletAddress } = inputs;
64
+ return this.fetchApi(`${collateralCoinType}/accounts`, {
349
65
  walletAddress,
350
- collateralCoinTypes,
351
66
  });
352
67
  });
353
68
  }
354
- /**
355
- * Fetch all vault caps owned by a wallet.
356
- *
357
- * Vault caps represent ownership/administrative authority over a vault.
358
- *
359
- * @param inputs.walletAddress - Owner wallet address.
360
- * @returns {@link ApiPerpetualsOwnedVaultCapsResponse} containing vault caps.
361
- */
362
- getOwnedVaultCaps(inputs) {
363
- return __awaiter(this, void 0, void 0, function* () {
364
- return this.fetchApi("vaults/owned-vault-caps", inputs);
365
- });
366
- }
367
- /**
368
- * Fetch all pending vault withdrawal requests created by a given wallet.
369
- *
370
- * Withdraw requests are typically created when LPs request to exit a vault
371
- * and may be subject to lock periods / delays depending on vault configuration.
372
- *
373
- * @param inputs.walletAddress - Wallet address that created the withdraw requests.
374
- * @returns {@link ApiPerpetualsVaultOwnedWithdrawRequestsResponse} containing requests.
375
- */
376
- getOwnedVaultWithdrawRequests(inputs) {
377
- return __awaiter(this, void 0, void 0, function* () {
378
- return this.fetchApi("vaults/owned-withdraw-requests", Object.assign({}, inputs));
379
- });
380
- }
381
- /**
382
- * Fetch all Perpetuals vault LP coins owned by a wallet.
383
- *
384
- * This returns coin objects (or summaries) representing LP token holdings.
385
- * Use {@link getLpCoinPrices} to value them in collateral units.
386
- *
387
- * @param inputs - {@link ApiPerpetualsVaultOwnedLpCoinsBody}.
388
- * @returns {@link ApiPerpetualsVaultOwnedLpCoinsResponse}.
389
- */
390
- getOwnedVaultLpCoins(inputs) {
391
- return __awaiter(this, void 0, void 0, function* () {
392
- return this.fetchApi("vaults/owned-lp-coins", inputs);
393
- });
394
- }
395
- /**
396
- * Fetch account caps by their account IDs.
397
- *
398
- * @param inputs.accountCapIds - List of account IDs.
399
- * @returns {@link ApiPerpetualsAccountCapsResponse} containing caps.
400
- */
401
- getAdminAccountCaps(inputs) {
402
- return __awaiter(this, void 0, void 0, function* () {
403
- return this.fetchApi("accounts", inputs);
404
- });
405
- }
406
- // =========================================================================
407
- // Historical Data & Stats
408
- // =========================================================================
409
- /**
410
- * Fetch historical OHLCV candle data for a single market.
411
- *
412
- * @param inputs.marketId - Market ID to query.
413
- * @param inputs.fromTimestamp - Start timestamp (inclusive).
414
- * @param inputs.toTimestamp - End timestamp (exclusive).
415
- * @param inputs.intervalMs - Candle interval in milliseconds.
416
- *
417
- * @returns {@link ApiPerpetualsMarketCandleHistoryResponse} containing candle points.
418
- *
419
- * @remarks
420
- * This is currently implemented on the Perpetuals root client, but it may be
421
- * relocated to {@link PerpetualsMarket} in the future.
422
- */
423
- // TODO: move to market class ?
424
- getMarketCandleHistory(inputs) {
425
- const { marketId, fromTimestamp, toTimestamp, intervalMs } = inputs;
426
- return this.fetchApi("market/candle-history", {
427
- marketId,
428
- fromTimestamp,
429
- toTimestamp,
430
- intervalMs,
431
- });
432
- }
433
- /**
434
- * Fetch 24-hour stats for multiple markets.
435
- *
436
- * @param inputs.marketIds - Market IDs to query.
437
- * @returns {@link ApiPerpetualsMarkets24hrStatsResponse}.
438
- */
439
- getMarkets24hrStats(inputs) {
440
- return this.fetchApi("markets/24hr-stats", inputs);
441
- }
442
69
  // =========================================================================
443
- // Prices
70
+ // Data
444
71
  // =========================================================================
445
- /**
446
- * Fetch the latest oracle prices (base & collateral) for one or more markets.
447
- *
448
- * @param inputs.marketIds - List of market IDs to query.
449
- * @returns {@link ApiPerpetualsMarketsPricesResponse} containing `marketsPrices`.
450
- *
451
- * @remarks
452
- * If `marketIds` is empty, returns `{ marketsPrices: [] }` without making an API call.
453
- */
454
- getPrices(inputs) {
455
- return __awaiter(this, void 0, void 0, function* () {
456
- if (inputs.marketIds.length <= 0)
457
- return {
458
- marketsPrices: [],
459
- };
460
- return this.fetchApi("markets/prices", inputs);
461
- });
462
- }
463
- /**
464
- * Fetch LP coin prices (in collateral units) for a set of vaults.
465
- *
466
- * @param inputs.vaultIds - List of vault IDs to query.
467
- * @returns {@link ApiPerpetualsVaultLpCoinPricesResponse} containing `lpCoinPrices`.
468
- *
469
- * @remarks
470
- * If `vaultIds` is empty, returns `{ lpCoinPrices: [] }` without making an API call.
471
- */
472
- getLpCoinPrices(inputs) {
473
- return __awaiter(this, void 0, void 0, function* () {
474
- if (inputs.vaultIds.length <= 0)
475
- return {
476
- lpCoinPrices: [],
477
- };
478
- return this.fetchApi("vaults/lp-coin-prices", inputs);
479
- });
72
+ getMarketHistoricalData(inputs) {
73
+ const { collateralCoinType, marketId, fromTimestamp, toTimestamp, intervalMs, } = inputs;
74
+ return this.fetchApi(`${collateralCoinType}/markets/${marketId}/historical-data/${fromTimestamp}/${toTimestamp}/${intervalMs}`);
480
75
  }
481
76
  // =========================================================================
482
77
  // Transactions
483
78
  // =========================================================================
484
- /**
485
- * Build a `transfer-cap` transaction that transfers a Perpetuals capability object (cap)
486
- * to another wallet.
487
- *
488
- * Provide the `capObjectId` of the capability you want to transfer (e.g., an account cap
489
- * or vault cap) and the `recipientAddress` that should receive it.
490
- *
491
- * This endpoint builds a transaction only; it does not submit it on-chain.
492
- *
493
- * @param inputs.recipientAddress - Recipient wallet address that should receive the cap.
494
- * @param inputs.capObjectId - Object ID of the capability to transfer.
495
- * @param inputs.tx - Optional transaction to extend.
496
- *
497
- * @returns Transaction response containing a `tx`.
498
- */
499
- getTransferCapTx(inputs) {
500
- return __awaiter(this, void 0, void 0, function* () {
501
- var _a;
502
- const { tx, recipientAddress, capObjectId } = inputs;
503
- return this.fetchApiTxObject("transactions/transfer-cap", {
504
- recipientAddress,
505
- capObjectId,
506
- txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({
507
- tx: tx !== null && tx !== void 0 ? tx : new transactions_1.Transaction(),
508
- })),
509
- }, undefined, {
510
- txKind: true,
511
- });
512
- });
513
- }
514
- /**
515
- * Build a `create-account` transaction for Aftermath Perpetuals.
516
- *
517
- * @param inputs.walletAddress - Wallet address that will own the new account.
518
- * @param inputs.collateralCoinType - Collateral coin type used by the account.
519
- * @param inputs.tx - Optional {@link Transaction} to extend; if provided, the
520
- * create-account commands are appended to this transaction.
521
- *
522
- * @returns {@link SdkTransactionResponse} with `tx`.
523
- */
524
79
  getCreateAccountTx(inputs) {
525
80
  return __awaiter(this, void 0, void 0, function* () {
526
- var _a;
527
- const { walletAddress, collateralCoinType, tx } = inputs;
528
- return this.fetchApiTxObject("transactions/create-account", {
529
- walletAddress,
530
- collateralCoinType,
531
- txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx })),
532
- }, undefined, {
533
- txKind: true,
534
- });
535
- });
536
- }
537
- /**
538
- * Build a `create-vault-cap` transaction.
539
- *
540
- * A vault cap is an ownership/admin object for interacting with vault management
541
- * flows. This method returns a transaction kind that mints/creates that cap.
542
- *
543
- * @param inputs - {@link ApiPerpetualsCreateVaultCapBody}.
544
- * @returns {@link SdkTransactionResponse} with `tx`.
545
- */
546
- getCreateVaultCapTx(inputs) {
547
- return __awaiter(this, void 0, void 0, function* () {
548
- return this.fetchApiTxObject("vault/transactions/create-vault-cap", inputs, undefined, {
549
- txKind: true,
550
- });
551
- });
552
- }
553
- /**
554
- * Build a `create-vault` transaction.
555
- *
556
- * This creates a new vault plus its on-chain metadata and initial LP supply
557
- * seeded by the initial deposit.
558
- *
559
- * Deposit input:
560
- * - Use `initialDepositAmount` to have the API select/merge coins as needed, OR
561
- * - Use `initialDepositCoinArg` if you already have a coin argument in a larger tx.
562
- *
563
- * Metadata:
564
- * - Stored on-chain (or in a referenced object) as part of vault creation.
565
- * - `extraFields` allows forward-compatible additions (e.g. social links).
566
- *
567
- * @param inputs.walletAddress - Address of vault owner/curator.
568
- * @param inputs.metadata - Vault display metadata (name, description, curator info).
569
- * @param inputs.metadata - Vault display metadata (name, description, curator info).
570
- * @param inputs.coinMetadataId - Coin metadata object id obtained from create vault cap tx
571
- * @param inputs.treasuryCapId - Treasury cap object id obtained from create vault cap tx
572
- * @param inputs.collateralCoinType - Collateral coin type for deposits.
573
- * @param inputs.lockPeriodMs - Lock-in period for deposits in milliseconds.
574
- * @param inputs.performanceFeePercentage - Fraction of profits taken as curator fee.
575
- * @param inputs.forceWithdrawDelayMs - Delay before forced withdrawals can be processed.
576
- * @param inputs.isSponsoredTx - Whether this tx is sponsored (gas paid by another party).
577
- * @param inputs.initialDepositAmount - Initial deposit amount (mutually exclusive with `initialDepositCoinArg`).
578
- * @param inputs.initialDepositCoinArg - Transaction object argument referencing the deposit coin.
579
- * @param inputs.tx - Optional {@link Transaction} to extend.
580
- *
581
- * @returns {@link SdkTransactionResponse} with `tx`.
582
- */
583
- getCreateVaultTx(inputs) {
584
- return __awaiter(this, void 0, void 0, function* () {
585
- var _a;
586
- const { tx } = inputs, otherInputs = __rest(inputs, ["tx"]);
587
- return this.fetchApiTxObject("vault/transactions/create-vault", Object.assign(Object.assign({}, otherInputs), { txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx })) }), undefined, {
588
- txKind: true,
589
- });
81
+ return this.fetchApiTransaction("transactions/create-account", inputs);
590
82
  });
591
83
  }
592
84
  // =========================================================================
593
- // Builder Codes Transactions
85
+ // Public Static Functions
594
86
  // =========================================================================
595
- /**
596
- * Build a transaction to create an integrator configuration.
597
- *
598
- * This endpoint creates a transaction that allows a user to grant permission to an
599
- * integrator to receive fees on orders placed on their behalf. The user specifies
600
- * a maximum taker fee that the integrator can charge. The integrator can then
601
- * include their address and fee (up to the maximum) when placing orders for the user.
602
- *
603
- * The resulting transaction must be signed by the account owner and executed on-chain.
604
- *
605
- * @param inputs - {@link ApiPerpetualsBuilderCodesCreateIntegratorConfigTxBody}.
606
- * @returns {@link SdkTransactionResponse} with `tx`.
607
- *
608
- * @example
609
- * ```ts
610
- * const tx = await perps.getCreateBuilderCodeIntegratorConfigTx({
611
- * accountId: 123n,
612
- * integratorAddress: "0x...",
613
- * maxTakerFee: 0.001, // 0.1% max fee
614
- * });
615
- * ```
616
- */
617
- getCreateBuilderCodeIntegratorConfigTx(inputs) {
618
- return __awaiter(this, void 0, void 0, function* () {
619
- return this.fetchApiTxObject("builder-codes/transactions/create-integrator-config", inputs, undefined, {
620
- txKind: true,
621
- });
622
- });
623
- }
624
- /**
625
- * Build a transaction to remove an integrator configuration.
626
- *
627
- * This endpoint creates a transaction that removes an integrator's approval to
628
- * collect fees on orders placed on behalf of the user. Once revoked, the integrator
629
- * will no longer be able to submit orders with integrator fees for this account.
630
- * The user can re-approve the integrator at any time by calling
631
- * {@link getCreateIntegratorConfigTx} again.
632
- *
633
- * The resulting transaction must be signed by the account owner and executed on-chain.
634
- *
635
- * @param inputs - {@link ApiPerpetualsBuilderCodesRemoveIntegratorConfigTxBody}.
636
- * @returns {@link SdkTransactionResponse} with `tx`.
637
- *
638
- * @example
639
- * ```ts
640
- * const tx = await perps.getRemoveBuilderCodeIntegratorConfigTx({
641
- * accountId: 123n,
642
- * integratorAddress: "0x...",
643
- * });
644
- * ```
645
- */
646
- getRemoveBuilderCodeIntegratorConfigTx(inputs) {
647
- return __awaiter(this, void 0, void 0, function* () {
648
- return this.fetchApiTxObject("builder-codes/transactions/remove-integrator-config", inputs, undefined, {
649
- txKind: true,
650
- });
651
- });
652
- }
653
- /**
654
- * Build a transaction to initialize an integrator fee vault for a specific market.
655
- *
656
- * This endpoint creates a transaction that initializes a vault where an integrator's
657
- * fees will accumulate for a specific market (clearing house). This is a one-time
658
- * setup operation that must be performed before the integrator can claim fees from
659
- * that market. Once created, the vault will automatically collect fees as the
660
- * integrator submits orders on behalf of users in that market.
661
- *
662
- * The resulting transaction must be signed by the integrator and executed on-chain.
663
- *
664
- * @param inputs - {@link ApiPerpetualsBuilderCodesCreateIntegratorVaultTxBody}.
665
- * @returns {@link SdkTransactionResponse} with `tx`.
666
- *
667
- * @example
668
- * ```ts
669
- * const tx = await perps.getCreateBuilderCodeIntegratorVaultTx({
670
- * marketId: "0x...",
671
- * integratorAddress: "0x...",
672
- * });
673
- * ```
674
- */
675
- getCreateBuilderCodeIntegratorVaultTx(inputs) {
676
- return __awaiter(this, void 0, void 0, function* () {
677
- return this.fetchApiTxObject("builder-codes/transactions/create-integrator-vault", inputs, undefined, {
678
- txKind: true,
679
- });
680
- });
681
- }
682
- /**
683
- * Build a transaction to claim accumulated integrator fees from a vault.
684
- *
685
- * This endpoint creates a transaction that allows an integrator to claim the fees
686
- * they have earned from orders placed on behalf of users. Fees accumulate in a vault
687
- * specific to each market (clearing house) and can be claimed at any moment by the
688
- * integrator. The fees are proportional to the taker volume generated by the users'
689
- * orders that the integrator submitted.
690
- *
691
- * If a `recipientAddress` is provided, the claimed fees will be automatically
692
- * transferred to that address. Otherwise, the coin output is exposed as a transaction
693
- * argument for further use in the transaction.
694
- *
695
- * The resulting transaction must be signed by the integrator and executed on-chain.
696
- *
697
- * @param inputs - {@link ApiPerpetualsBuilderCodesClaimIntegratorVaultFeesTxBody}.
698
- * @returns {@link ApiPerpetualsBuilderCodesClaimIntegratorVaultFeesTxResponse} containing
699
- * `txKind` and optionally `coinOutArg`.
700
- *
701
- * @example
702
- * ```ts
703
- * // Claim with automatic transfer to recipient
704
- * const response = await perps.getClaimBuilderCodeIntegratorVaultFeesTx({
705
- * marketId: "0x...",
706
- * integratorAddress: "0x...",
707
- * recipientAddress: "0x...",
708
- * });
709
- *
710
- * // Claim with coin output for further use
711
- * const response = await perps.getClaimBuilderCodeIntegratorVaultFeesTx({
712
- * marketId: "0x...",
713
- * integratorAddress: "0x...",
714
- * });
715
- * // response.coinOutArg can be used in subsequent transaction commands
716
- * ```
717
- */
718
- getClaimBuilderCodeIntegratorVaultFeesTx(inputs) {
719
- return __awaiter(this, void 0, void 0, function* () {
720
- return this.fetchApiTxObject("builder-codes/transactions/claim-integrator-vault-fees", inputs, undefined, {
721
- txKind: true,
722
- });
723
- });
724
- }
725
87
  // =========================================================================
726
- // Builder Codes Inspections
88
+ // Helpers
727
89
  // =========================================================================
728
- /**
729
- * Fetch integrator configuration for a specific account and integrator.
730
- *
731
- * This endpoint queries whether an integrator has been approved by an account to collect
732
- * fees on orders placed on behalf of the account. If approved, it returns the maximum
733
- * taker fee the integrator is authorized to charge. This information is useful for:
734
- * - Verifying integrator permissions before placing orders
735
- * - Displaying authorized integrators and their fee limits in UIs
736
- * - Validating that an integrator's requested fee doesn't exceed the approved maximum
737
- *
738
- * @param inputs - {@link ApiPerpetualsBuilderCodesIntegratorConfigBody}.
739
- * @returns {@link ApiPerpetualsBuilderCodesIntegratorConfigResponse} containing
740
- * `maxTakerFee` and `exists` flag.
741
- *
742
- * @example
743
- * ```ts
744
- * const config = await perps.getBuilderCodeIntegratorConfig({
745
- * accountId: 123n,
746
- * integratorAddress: "0x...",
747
- * });
748
- *
749
- * if (config.exists) {
750
- * console.log(`Integrator is approved with max fee: ${config.maxTakerFee}`);
751
- * } else {
752
- * console.log("Integrator is not approved for this account");
753
- * }
754
- * ```
755
- */
756
- getBuilderCodeIntegratorConfig(inputs) {
757
- return __awaiter(this, void 0, void 0, function* () {
758
- return this.fetchApi("builder-codes/integrator-config", inputs);
759
- });
760
- }
761
- /**
762
- * Fetch accumulated integrator vault fees across multiple markets.
763
- *
764
- * This endpoint queries the total fees an integrator has earned and accumulated in their
765
- * vaults across one or more markets (clearing houses). Integrators earn fees proportional
766
- * to the taker volume generated by orders they submit on behalf of users. These fees
767
- * accumulate in per-market vaults and can be claimed at any time using
768
- * {@link getClaimIntegratorVaultFeesTx}.
769
- *
770
- * This information is useful for:
771
- * - Displaying total claimable fees to integrators in dashboards
772
- * - Monitoring fee accrual across different markets
773
- * - Determining which markets have fees ready to be claimed
774
- *
775
- * @param inputs - {@link ApiPerpetualsBuilderCodesIntegratorVaultsBody}.
776
- * @returns {@link ApiPerpetualsBuilderCodesIntegratorVaultsResponse} containing
777
- * a vector of market vault data with accumulated fees.
778
- *
779
- * @example
780
- * ```ts
781
- * const vaultFees = await perps.getBuilderCodeIntegratorVaults({
782
- * marketIds: ["0x...BTCUSD", "0x...SUIUSD"],
783
- * integratorAddress: "0x...",
784
- * });
785
- *
786
- * for (const vault of vaultFees.integratorVaults) {
787
- * console.log(`Market ${vault.marketId}: ${vault.fees} collateral units claimable`);
788
- * }
789
- *
790
- * const totalFees = vaultFees.integratorVaults.reduce((sum, vault) => sum + vault.fees, 0);
791
- * console.log(`Total claimable: ${totalFees}`);
792
- * ```
793
- */
794
- getBuilderCodeIntegratorVaults(inputs) {
795
- return __awaiter(this, void 0, void 0, function* () {
796
- return this.fetchApi("builder-codes/integrator-vaults", inputs);
797
- });
798
- }
799
- // =========================================================================
800
- // Public Static Helpers
801
- // =========================================================================
802
- /**
803
- * Determine the logical order side (Bid/Ask) from a signed base asset amount.
804
- *
805
- * @param inputs.baseAssetAmount - Position base size. Positive/zero => Bid (long), negative => Ask (short).
806
- * @returns {@link PerpetualsOrderSide}.
807
- */
808
90
  static positionSide(inputs) {
809
- const baseAmount = inputs.baseAssetAmount;
91
+ const baseAmount = iFixedUtils_1.IFixedUtils.numberFromIFixed(inputs.baseAssetAmount);
810
92
  const isLong = Math.sign(baseAmount);
811
93
  const side = isLong >= 0 ? types_1.PerpetualsOrderSide.Bid : types_1.PerpetualsOrderSide.Ask;
812
94
  return side;
813
95
  }
814
- /**
815
- * Compute the effective trade price from a {@link FilledTakerOrderEvent}.
816
- *
817
- * Uses the ratio: `quoteAssetDelta / baseAssetDelta`.
818
- *
819
- * @param inputs.orderEvent - Filled taker order event.
820
- * @returns Trade price.
821
- */
822
- static orderPriceFromEvent(inputs) {
96
+ static orderPrice(inputs) {
823
97
  const { orderEvent } = inputs;
824
- return orderEvent.quoteAssetDelta / orderEvent.baseAssetDelta;
98
+ return (iFixedUtils_1.IFixedUtils.numberFromIFixed(orderEvent.quoteAssetDelta) /
99
+ iFixedUtils_1.IFixedUtils.numberFromIFixed(orderEvent.baseAssetDelta));
825
100
  }
826
- /**
827
- * Extract the floating-point price from an encoded order ID.
828
- *
829
- * Internally uses {@link PerpetualsOrderUtils.price} and converts the fixed-point
830
- * {@link PerpetualsOrderPrice} into a `number`.
831
- *
832
- * @param inputs.orderId - Encoded order ID.
833
- * @returns Price as a `number`.
834
- */
835
- static orderPriceFromOrderId(inputs) {
836
- const { orderId } = inputs;
837
- const orderPrice = utils_1.PerpetualsOrderUtils.price(orderId);
838
- return this.orderPriceToPrice({ orderPrice });
839
- }
840
- /**
841
- * Convert a fixed-point lot/tick size (9 decimals) to a `number`.
842
- *
843
- * @param lotOrTickSize - Fixed-point size as `bigint`.
844
- * @returns Floating-point size.
845
- */
846
101
  static lotOrTickSizeToNumber(lotOrTickSize) {
847
102
  return Number(lotOrTickSize) / fixedUtils_1.FixedUtils.fixedOneN9;
848
103
  }
849
- /**
850
- * Convert a floating-point lot/tick size to its fixed-point representation (9 decimals).
851
- *
852
- * @param lotOrTickSize - Floating-point size.
853
- * @returns Fixed-point size as `bigint`.
854
- */
855
104
  static lotOrTickSizeToBigInt(lotOrTickSize) {
856
105
  return BigInt(Math.round(lotOrTickSize * fixedUtils_1.FixedUtils.fixedOneN9));
857
106
  }
858
107
  // =========================================================================
859
- // Websocket
108
+ // Calculations
860
109
  // =========================================================================
861
- /**
862
- * Open the main updates websocket: `/perpetuals/ws/updates`.
863
- *
864
- * The stream emits {@link PerpetualsWsUpdatesResponseMessage} envelopes and supports
865
- * multiple subscription types. This method returns a small controller with
866
- * convenience subscribe/unsubscribe functions.
867
- *
868
- * Subscription types supported by the controller:
869
- * - `market`: market state updates
870
- * - `user`: user account updates (optionally including stop orders)
871
- * - `oracle`: oracle price updates
872
- * - `orderbook`: orderbook deltas
873
- * - `marketOrders`: public market trades/orders
874
- * - `userOrders`: user trade/order events
875
- * - `userCollateralChanges`: user collateral change events
876
- *
877
- * @param args.onMessage - Handler for parsed messages from the websocket.
878
- * @param args.onOpen - Optional handler for the `open` event.
879
- * @param args.onError - Optional handler for the `error` event.
880
- * @param args.onClose - Optional handler for the `close` event.
881
- *
882
- * @returns A controller object containing:
883
- * - `ws`: underlying {@link WebSocket}
884
- * - subscribe/unsubscribe helpers for each subscription type
885
- * - `close()`: closes the websocket
886
- */
887
- openUpdatesWebsocketStream(args) {
888
- const { onMessage, onOpen, onError, onClose } = args;
889
- const ctl = this.openWsStream({
890
- path: "ws/updates",
891
- onMessage,
892
- onOpen,
893
- onError,
894
- onClose,
895
- });
896
- /**
897
- * Subscription helpers
898
- *
899
- * Each helper sends a structured subscription message of the form:
900
- * `{ action: "subscribe" | "unsubscribe", subscriptionType: { ... } }`
901
- */
902
- const subscribeMarket = ({ marketId, }) => ctl.send({
903
- action: "subscribe",
904
- subscriptionType: { market: { marketId } },
905
- });
906
- const unsubscribeMarket = ({ marketId, }) => ctl.send({
907
- action: "unsubscribe",
908
- subscriptionType: { market: { marketId } },
909
- });
910
- const subscribeUser = ({ accountId, withStopOrders, }) => ctl.send({
911
- action: "subscribe",
912
- subscriptionType: { user: { accountId, withStopOrders } },
913
- });
914
- const unsubscribeUser = ({ accountId, withStopOrders, }) => ctl.send({
915
- action: "unsubscribe",
916
- subscriptionType: { user: { accountId, withStopOrders } },
917
- });
918
- const subscribeOracle = ({ marketId, }) => ctl.send({
919
- action: "subscribe",
920
- subscriptionType: { oracle: { marketId } },
921
- });
922
- const unsubscribeOracle = ({ marketId, }) => ctl.send({
923
- action: "unsubscribe",
924
- subscriptionType: { oracle: { marketId } },
925
- });
926
- const subscribeOrderbook = ({ marketId, }) => ctl.send({
927
- action: "subscribe",
928
- subscriptionType: { orderbook: { marketId } },
929
- });
930
- const unsubscribeOrderbook = ({ marketId, }) => ctl.send({
931
- action: "unsubscribe",
932
- subscriptionType: { orderbook: { marketId } },
933
- });
934
- const subscribeMarketOrders = ({ marketId, }) => ctl.send({
935
- action: "subscribe",
936
- subscriptionType: { marketOrders: { marketId } },
937
- });
938
- const unsubscribeMarketOrders = ({ marketId, }) => ctl.send({
939
- action: "unsubscribe",
940
- subscriptionType: { marketOrders: { marketId } },
941
- });
942
- const subscribeUserOrders = ({ accountId, }) => ctl.send({
943
- action: "subscribe",
944
- subscriptionType: { userOrders: { accountId } },
945
- });
946
- const unsubscribeUserOrders = ({ accountId, }) => ctl.send({
947
- action: "unsubscribe",
948
- subscriptionType: { userOrders: { accountId } },
949
- });
950
- const subscribeUserCollateralChanges = ({ accountId, }) => ctl.send({
951
- action: "subscribe",
952
- subscriptionType: { userCollateralChanges: { accountId } },
953
- });
954
- const unsubscribeUserCollateralChanges = ({ accountId, }) => ctl.send({
955
- action: "unsubscribe",
956
- subscriptionType: { userCollateralChanges: { accountId } },
957
- });
958
- return {
959
- ws: ctl.ws,
960
- subscribeMarket,
961
- unsubscribeMarket,
962
- subscribeUser,
963
- unsubscribeUser,
964
- subscribeOracle,
965
- unsubscribeOracle,
966
- subscribeOrderbook,
967
- unsubscribeOrderbook,
968
- subscribeMarketOrders,
969
- unsubscribeMarketOrders,
970
- subscribeUserOrders,
971
- unsubscribeUserOrders,
972
- subscribeUserCollateralChanges,
973
- unsubscribeUserCollateralChanges,
974
- close: ctl.close,
975
- };
976
- }
977
- /**
978
- * Open a market-candles websocket stream for a single market/interval:
979
- * `/perpetuals/ws/market-candles/{market_id}/{interval_ms}`.
980
- *
981
- * The stream emits {@link PerpetualsWsCandleResponseMessage} messages,
982
- * typically containing the latest candle for the specified interval.
983
- *
984
- * @param args.marketId - Market ID to subscribe to.
985
- * @param args.intervalMs - Candle interval in milliseconds.
986
- * @param args.onMessage - Handler for incoming candle updates.
987
- * @param args.onOpen - Optional hook called when the websocket opens.
988
- * @param args.onError - Optional hook called on websocket error.
989
- * @param args.onClose - Optional hook called when the websocket closes.
990
- *
991
- * @returns A controller containing the raw websocket and a `close()` helper.
992
- *
993
- * @example
994
- * ```ts
995
- * const stream = perps.openMarketCandlesWebsocketStream({
996
- * marketId: "0x...",
997
- * intervalMs: 60_000,
998
- * onMessage: ({ lastCandle }) => console.log(lastCandle),
999
- * });
1000
- * ```
1001
- */
1002
- openMarketCandlesWebsocketStream(args) {
1003
- const { marketId, intervalMs, onMessage, onOpen, onError, onClose } = args;
1004
- const path = `ws/market-candles/${encodeURIComponent(marketId)}/${intervalMs}`;
1005
- const ctl = this.openWsStream({
1006
- path,
1007
- onMessage,
1008
- onOpen,
1009
- onError,
1010
- onClose,
1011
- });
1012
- return {
1013
- ws: ctl.ws,
1014
- close: ctl.close,
1015
- };
110
+ static calcEntryPrice(inputs) {
111
+ const { baseAssetAmount, quoteAssetNotionalAmount } = inputs;
112
+ const denominator = utils_1.Casting.IFixed.numberFromIFixed(baseAssetAmount);
113
+ if (!denominator)
114
+ return 0;
115
+ return Math.abs(utils_1.Casting.IFixed.numberFromIFixed(quoteAssetNotionalAmount) /
116
+ denominator);
1016
117
  }
1017
118
  }
1018
119
  exports.Perpetuals = Perpetuals;
120
+ _a = Perpetuals;
1019
121
  // =========================================================================
1020
122
  // Constants
1021
123
  // =========================================================================
1022
- /**
1023
- * Helper namespace for order-specific utilities such as parsing order IDs,
1024
- * extracting price bits, etc.
1025
- *
1026
- * This is a direct alias of {@link PerpetualsOrderUtils}.
1027
- */
1028
- Perpetuals.OrderUtils = utils_1.PerpetualsOrderUtils;
1029
- /**
1030
- * Convert a floating-point price into a fixed-point {@link PerpetualsOrderPrice}
1031
- * using 9 decimal places of precision.
1032
- *
1033
- * @param inputs.price - Price as a float.
1034
- * @returns Fixed-point order price.
1035
- */
124
+ Perpetuals.OrderUtils = utils_2.PerpetualsOrderUtils;
1036
125
  Perpetuals.priceToOrderPrice = (inputs) => {
1037
- const { price } = inputs;
1038
- return BigInt(Math.round(price * fixedUtils_1.FixedUtils.fixedOneN9));
126
+ const { price, lotSize, tickSize } = inputs;
127
+ const priceFixed = fixedUtils_1.FixedUtils.directUncast(price);
128
+ // convert f18 to b9 (assuming the former is positive)
129
+ const price9 = priceFixed / fixedUtils_1.FixedUtils.fixedOneB9;
130
+ const denominator = fixedUtils_1.FixedUtils.fixedOneB9 /
131
+ (typeof lotSize === "number"
132
+ ? _a.lotOrTickSizeToBigInt(lotSize)
133
+ : lotSize);
134
+ if (denominator <= BigInt(0))
135
+ return BigInt(0);
136
+ return (price9 /
137
+ (typeof tickSize === "number"
138
+ ? _a.lotOrTickSizeToBigInt(tickSize)
139
+ : tickSize) /
140
+ denominator);
1039
141
  };
1040
- /**
1041
- * Convert a fixed-point {@link PerpetualsOrderPrice} to a float price.
1042
- *
1043
- * @param inputs.orderPrice - Fixed-point order price.
1044
- * @returns Price as a float.
1045
- */
1046
142
  Perpetuals.orderPriceToPrice = (inputs) => {
1047
- const { orderPrice } = inputs;
1048
- return Number(orderPrice) / fixedUtils_1.FixedUtils.fixedOneN9;
143
+ const { orderPrice, lotSize, tickSize } = inputs;
144
+ const temp = fixedUtils_1.FixedUtils.fixedOneB9 /
145
+ (typeof lotSize === "number"
146
+ ? _a.lotOrTickSizeToBigInt(lotSize)
147
+ : lotSize);
148
+ return fixedUtils_1.FixedUtils.directCast(orderPrice *
149
+ (typeof tickSize === "number"
150
+ ? _a.lotOrTickSizeToBigInt(tickSize)
151
+ : tickSize) *
152
+ temp *
153
+ fixedUtils_1.FixedUtils.fixedOneB9);
1049
154
  };
1050
- /**
1051
- * Infer the order side from an encoded order ID.
1052
- *
1053
- * @param orderId - Encoded order ID.
1054
- * @returns {@link PerpetualsOrderSide}.
1055
- */
1056
155
  Perpetuals.orderIdToSide = (orderId) => {
1057
- return Perpetuals.OrderUtils.isAsk(orderId)
156
+ return _a.OrderUtils.isAsk(orderId)
1058
157
  ? types_1.PerpetualsOrderSide.Ask
1059
158
  : types_1.PerpetualsOrderSide.Bid;
1060
159
  };
1061
- /**
1062
- * Construct a collateral-specialized Move event type string.
1063
- *
1064
- * Many Move events are generic over a collateral coin type. This helper appends
1065
- * `<collateralCoinType>` to a base `eventType`.
1066
- *
1067
- * @param inputs.eventType - Base event type without type parameters.
1068
- * @param inputs.collateralCoinType - Collateral coin type (e.g. `"0x2::sui::SUI"`).
1069
- * @returns Fully-qualified event type string.
1070
- */
1071
- Perpetuals.eventTypeForCollateral = (inputs) => {
1072
- return `${inputs.eventType}<${inputs.collateralCoinType}>`;
1073
- };