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
@@ -22,82 +22,230 @@ var __rest = (this && this.__rest) || function (s, e) {
22
22
  Object.defineProperty(exports, "__esModule", { value: true });
23
23
  exports.PerpetualsAccount = void 0;
24
24
  const caller_1 = require("../../general/utils/caller");
25
+ const types_1 = require("../../types");
26
+ const iFixedUtils_1 = require("../../general/utils/iFixedUtils");
25
27
  const utils_1 = require("../../general/utils");
26
28
  const perpetuals_1 = require("./perpetuals");
27
- const transactions_1 = require("@mysten/sui/transactions");
28
- /**
29
- * Note on “refreshing” account state:
30
- *
31
- * This class is a thin wrapper around a snapshot of {@link PerpetualsAccountObject}
32
- * that is typically fetched via {@link Perpetuals.getAccount}. The transaction builders
33
- * use the current snapshot to derive fields like `hasPosition` and to construct
34
- * SL/TP helpers that depend on the position side.
35
- *
36
- * If your app is long-lived, you may want to periodically re-fetch the account
37
- * (and recreate this wrapper) to avoid stale local position/order state. For example:
38
- * - After placing/canceling orders
39
- * - After fills/liquidations/funding settlements
40
- * - After switching markets or wallets
41
- */
42
- /**
43
- * High-level wrapper around a single Perpetuals account or vault account.
44
- *
45
- * This class encapsulates:
46
- *
47
- * - Transaction builders for:
48
- * - Collateral actions (deposit, withdraw, allocate, deallocate, transfer)
49
- * - Orders (market/limit, cancel, stop orders, SL/TP, set leverage)
50
- * - Read-only account helpers:
51
- * - Stop-order message signing
52
- * - Order & stop-order metadata
53
- * - Collateral & trade history
54
- * - Convenience helpers to:
55
- * - Fetch and categorize SL/TP stop orders
56
- * - Resolve account/vault identifiers and owner addresses
57
- *
58
- * You typically do not construct `PerpetualsAccount` directly. Instead, use
59
- * {@link Perpetuals.getAccount} or {@link Perpetuals.getAccounts}, which
60
- * fetch all required on-chain data and wrap it for you:
61
- *
62
- * ```ts
63
- * const afSdk = new Aftermath("MAINNET");
64
- * await afSdk.init();
65
- *
66
- * const perps = afSdk.Perpetuals();
67
- * const [accountCap] = await perps.getOwnedAccountCaps({
68
- * walletAddress: "0x...",
69
- * });
70
- *
71
- * const account = await perps.getAccount({ accountCap });
72
- *
73
- * // Build a deposit transaction
74
- * const depositTx = await account.getDepositCollateralTx({
75
- * depositAmount: BigInt("1000000000"),
76
- * });
77
- * ```
78
- */
29
+ const __1 = require("..");
79
30
  class PerpetualsAccount extends caller_1.Caller {
80
31
  // =========================================================================
81
32
  // Constructor
82
33
  // =========================================================================
83
- /**
84
- * Create a new {@link PerpetualsAccount} wrapper.
85
- *
86
- * @param account - Raw account object with positions and equity data.
87
- * @param accountCap - Account cap or partial vault cap object containing
88
- * ownership and collateral metadata.
89
- * @param config - Optional {@link CallerConfig} (network, auth, etc.).
90
- * @param Provider - Optional shared {@link AftermathApi} provider instance
91
- * used to derive serialized transaction kinds (`txKind`) from
92
- * {@link Transaction} objects.
93
- */
94
- constructor(account, accountCap, config, Provider) {
95
- const vaultId = "vaultId" in accountCap ? accountCap.vaultId : undefined;
34
+ constructor(account, accountCap, config) {
96
35
  super(config, "perpetuals");
97
36
  this.account = account;
98
37
  this.accountCap = accountCap;
99
- this.Provider = Provider;
100
- this.vaultId = vaultId;
38
+ // =========================================================================
39
+ // Calculations
40
+ // =========================================================================
41
+ this.calcFreeCollateralForPosition = (inputs) => {
42
+ var _a, _b;
43
+ const marketId = inputs.market.marketId;
44
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : this.emptyPosition({ market: inputs.market });
45
+ const funding = this.calcUnrealizedFundingsForPosition(inputs);
46
+ const { pnl, minInitialMargin } = this.calcPnLAndMarginForPosition(inputs);
47
+ let collateralUsd = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.collateral) *
48
+ inputs.collateralPrice;
49
+ collateralUsd += funding;
50
+ let cappedMargin;
51
+ if (pnl < 0) {
52
+ cappedMargin = collateralUsd + pnl;
53
+ }
54
+ else {
55
+ cappedMargin = collateralUsd;
56
+ }
57
+ if (cappedMargin >= minInitialMargin) {
58
+ return (cappedMargin - minInitialMargin) / inputs.collateralPrice;
59
+ }
60
+ else
61
+ return 0;
62
+ };
63
+ this.calcMarginRatioAndLeverageForPosition = (inputs) => {
64
+ var _a, _b;
65
+ const { market, indexPrice, collateralPrice } = inputs;
66
+ const marketId = market.marketId;
67
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : this.emptyPosition({ market });
68
+ const funding = this.calcUnrealizedFundingsForPosition({
69
+ market,
70
+ position,
71
+ });
72
+ const collateralUsd = iFixedUtils_1.IFixedUtils.numberFromIFixed(position === null || position === void 0 ? void 0 : position.collateral) *
73
+ collateralPrice +
74
+ funding;
75
+ const { pnl, netAbsBaseValue } = this.calcPnLAndMarginForPosition({
76
+ market,
77
+ indexPrice,
78
+ position,
79
+ });
80
+ const marginRatio = netAbsBaseValue === 0 ? 0 : (collateralUsd + pnl) / netAbsBaseValue;
81
+ const leverage = marginRatio === 0 ? 0 : 1 / marginRatio;
82
+ return {
83
+ marginRatio,
84
+ leverage,
85
+ };
86
+ };
87
+ this.calcUnrealizedFundings = (inputs) => {
88
+ let totalFunding = 0;
89
+ inputs.markets.forEach((market) => {
90
+ totalFunding += this.calcUnrealizedFundingsForPosition({
91
+ market,
92
+ });
93
+ });
94
+ return totalFunding;
95
+ };
96
+ this.calcUnrealizedFundingsForPosition = (inputs) => {
97
+ var _a, _b;
98
+ const marketId = inputs.market.marketId;
99
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : this.emptyPosition({ market: inputs.market });
100
+ const baseAmount = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.baseAssetAmount);
101
+ const isLong = Math.sign(baseAmount);
102
+ if (isLong < 0) {
103
+ const fundingShort = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.cumFundingRateShort);
104
+ const marketFundingShort = iFixedUtils_1.IFixedUtils.numberFromIFixed(inputs.market.marketState.cumFundingRateShort);
105
+ return -baseAmount * (marketFundingShort - fundingShort);
106
+ }
107
+ else {
108
+ const fundingLong = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.cumFundingRateLong);
109
+ const marketFundingLong = iFixedUtils_1.IFixedUtils.numberFromIFixed(inputs.market.marketState.cumFundingRateLong);
110
+ return -baseAmount * (marketFundingLong - fundingLong);
111
+ }
112
+ };
113
+ this.calcPnLAndMarginForPosition = (inputs) => {
114
+ var _a, _b;
115
+ const marketId = inputs.market.marketId;
116
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : this.emptyPosition({ market: inputs.market });
117
+ const marginRatioInitial = 1 / position.leverage;
118
+ // const marginRatioInitial = inputs.market.initialMarginRatio();
119
+ const marginRatioMaintenance = iFixedUtils_1.IFixedUtils.numberFromIFixed(inputs.market.marketParams.marginRatioMaintenance);
120
+ const baseAssetAmount = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.baseAssetAmount);
121
+ const quoteAssetAmount = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.quoteAssetNotionalAmount);
122
+ const bidsQuantity = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.bidsQuantity);
123
+ const asksQuantity = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.asksQuantity);
124
+ const pnl = baseAssetAmount * inputs.indexPrice - quoteAssetAmount;
125
+ const netAbs = Math.max(Math.abs(baseAssetAmount + bidsQuantity), Math.abs(baseAssetAmount - asksQuantity));
126
+ const netAbsBaseValue = netAbs * inputs.indexPrice;
127
+ const minInitialMargin = netAbsBaseValue * marginRatioInitial;
128
+ const minMaintenanceMargin = netAbsBaseValue * marginRatioMaintenance;
129
+ return { pnl, minInitialMargin, minMaintenanceMargin, netAbsBaseValue };
130
+ };
131
+ this.calcLiquidationPriceForPosition = (inputs) => {
132
+ var _a, _b;
133
+ const marketId = inputs.market.marketId;
134
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : this.emptyPosition({ market: inputs.market });
135
+ const funding = this.calcUnrealizedFundingsForPosition(inputs);
136
+ const collateralUsd = iFixedUtils_1.IFixedUtils.numberFromIFixed(position === null || position === void 0 ? void 0 : position.collateral) *
137
+ inputs.collateralPrice +
138
+ funding;
139
+ const baseAssetAmount = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.baseAssetAmount);
140
+ const quoteAssetAmount = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.quoteAssetNotionalAmount);
141
+ const MMR = iFixedUtils_1.IFixedUtils.numberFromIFixed(inputs.market.marketParams.marginRatioMaintenance);
142
+ const numerator = collateralUsd - quoteAssetAmount;
143
+ const price = (() => {
144
+ if (baseAssetAmount > 0) {
145
+ return numerator / ((1 - MMR) * -baseAssetAmount);
146
+ }
147
+ else {
148
+ return numerator / ((1 + MMR) * -baseAssetAmount);
149
+ }
150
+ })();
151
+ return price < 0 ? 0 : price;
152
+ };
153
+ this.calcFreeMarginUsdForPosition = (inputs) => {
154
+ var _a, _b;
155
+ const marketId = inputs.market.marketId;
156
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : this.emptyPosition({ market: inputs.market });
157
+ const totalFunding = this.calcUnrealizedFundingsForPosition(inputs);
158
+ const { pnl, minInitialMargin } = this.calcPnLAndMarginForPosition(inputs);
159
+ let collateralUsd = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.collateral) *
160
+ inputs.collateralPrice;
161
+ const margin = collateralUsd + totalFunding + pnl;
162
+ if (margin >= minInitialMargin) {
163
+ return margin - minInitialMargin;
164
+ }
165
+ else
166
+ return 0;
167
+ };
168
+ this.calcAccountState = (inputs) => {
169
+ const zipped = utils_1.Helpers.zip(inputs.markets, inputs.indexPrices);
170
+ let accountEquity = 0;
171
+ let totalPnL = 0;
172
+ let totalFunding = 0;
173
+ let totalCollateralAllocated = 0;
174
+ zipped.forEach(([market, indexPrice]) => {
175
+ var _a;
176
+ const marketId = market.marketId;
177
+ const position = (_a = this.positionForMarketId({ marketId })) !== null && _a !== void 0 ? _a : this.emptyPosition({ market });
178
+ const funding = this.calcUnrealizedFundingsForPosition({
179
+ market,
180
+ position,
181
+ });
182
+ const { pnl } = this.calcPnLAndMarginForPosition({
183
+ market,
184
+ indexPrice,
185
+ position,
186
+ });
187
+ let collateralUsd = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.collateral) *
188
+ inputs.collateralPrice;
189
+ totalPnL += pnl;
190
+ totalFunding += funding;
191
+ totalCollateralAllocated += collateralUsd;
192
+ accountEquity += collateralUsd + funding + pnl;
193
+ });
194
+ return {
195
+ accountEquity,
196
+ totalPnL,
197
+ totalFunding,
198
+ totalCollateralAllocated,
199
+ };
200
+ };
201
+ this.closePositionTxInputs = (inputs) => {
202
+ var _a;
203
+ const { size, market, walletAddress, orderDatas, collateralPrice } = inputs;
204
+ const marketId = market.marketId;
205
+ const position = (_a = this.positionForMarketId({ marketId })) !== null && _a !== void 0 ? _a : this.emptyPosition({ market });
206
+ // TODO: move conversion to helper function, since used often
207
+ const ordersCollateral = __1.Coin.normalizeBalance(utils_1.Helpers.sum(orderDatas
208
+ .filter((orderData) => orderData.marketId === market.marketId)
209
+ .map((orderData) => market.calcCollateralUsedForOrder(Object.assign(Object.assign({}, inputs), { orderData, leverage: position.leverage })).collateral)), this.collateralDecimals());
210
+ const fullPositionCollateralChange = utils_1.Helpers.maxBigInt(BigInt(Math.floor(Number(__1.Coin.normalizeBalance(this.calcFreeMarginUsdForPosition(inputs) *
211
+ collateralPrice, this.collateralDecimals()) - ordersCollateral) *
212
+ (1 -
213
+ PerpetualsAccount.constants
214
+ .closePositionMarginOfError))), BigInt(0)) * BigInt(-1);
215
+ const positionSize = BigInt(Math.round(Math.abs(utils_1.Casting.IFixed.numberFromIFixed(position.baseAssetAmount) /
216
+ market.lotSize())));
217
+ const collateralChange = BigInt(Math.round(Number(fullPositionCollateralChange) *
218
+ (Number(size) / Number(positionSize))));
219
+ const positionSide = perpetuals_1.Perpetuals.positionSide(position);
220
+ return {
221
+ size,
222
+ marketId,
223
+ walletAddress,
224
+ collateralChange,
225
+ side: positionSide === types_1.PerpetualsOrderSide.Bid
226
+ ? types_1.PerpetualsOrderSide.Ask
227
+ : types_1.PerpetualsOrderSide.Bid,
228
+ hasPosition: this.positionForMarketId({ marketId }) !== undefined,
229
+ };
230
+ };
231
+ this.emptyPosition = (inputs) => {
232
+ const { market } = inputs;
233
+ return {
234
+ marketId: market.marketId,
235
+ collateralCoinType: this.accountCap.collateralCoinType,
236
+ collateral: BigInt(0),
237
+ baseAssetAmount: BigInt(0),
238
+ quoteAssetNotionalAmount: BigInt(0),
239
+ cumFundingRateLong: market.marketState.cumFundingRateLong,
240
+ cumFundingRateShort: market.marketState.cumFundingRateShort,
241
+ asksQuantity: BigInt(0),
242
+ bidsQuantity: BigInt(0),
243
+ pendingOrders: [],
244
+ makerFee: BigInt(1000000000000000000), // 100%
245
+ takerFee: BigInt(1000000000000000000), // 100%
246
+ leverage: 1,
247
+ };
248
+ };
101
249
  }
102
250
  // =========================================================================
103
251
  // Transactions
@@ -105,1026 +253,174 @@ class PerpetualsAccount extends caller_1.Caller {
105
253
  // =========================================================================
106
254
  // Collateral Txs
107
255
  // =========================================================================
108
- /**
109
- * Build a `deposit-collateral` transaction for this account.
110
- *
111
- * For non-vault accounts, this endpoint constructs a transaction that:
112
- * - Optionally extends an existing {@link Transaction}, and
113
- * - Deposits collateral into the Perpetuals account.
114
- *
115
- * **Note:** Vault accounts are currently not supported and will throw.
116
- *
117
- * @param inputs.tx - Optional existing transaction to extend. If omitted,
118
- * a new {@link Transaction} is created under the hood.
119
- * @param inputs.isSponsoredTx - Optional flag indicating whether the
120
- * transaction is gas-sponsored.
121
- * @param inputs.depositAmount - Amount of collateral to deposit, if paying
122
- * directly from the wallet.
123
- * @param inputs.depositCoinArg - Transaction object argument referencing a
124
- * coin to deposit (mutually exclusive with `depositAmount`).
125
- *
126
- * @returns Transaction response containing a `tx`.
127
- *
128
- * @example
129
- * ```ts
130
- * const { tx } = await account.getDepositCollateralTx({
131
- * depositAmount: BigInt("1000000000"),
132
- * });
133
- * ```
134
- */
135
256
  getDepositCollateralTx(inputs) {
136
257
  return __awaiter(this, void 0, void 0, function* () {
137
- var _a;
138
- const { tx } = inputs, otherInputs = __rest(inputs, ["tx"]);
139
- if ("vaultId" in this.accountCap)
140
- throw new Error("`getDepositCollateralTx` not supported by vault accounts, please use method `getAdminDepositTx` on class `PerpetualsVault` instead");
141
- return this.fetchApiTxObject("account/transactions/deposit-collateral", Object.assign(Object.assign({}, otherInputs), { walletAddress: this.ownerAddress(), collateralCoinType: this.accountCap.collateralCoinType, accountId: this.accountCap.accountId, accountCapId: this.accountCap.objectId, txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({
142
- tx: tx !== null && tx !== void 0 ? tx : new transactions_1.Transaction(),
143
- })) }), undefined, {
144
- txKind: true,
145
- });
258
+ return this.fetchApiTransaction("transactions/deposit-collateral", Object.assign(Object.assign({}, inputs), { collateralCoinType: this.accountCap.collateralCoinType, accountCapId: this.accountCap.objectId }));
146
259
  });
147
260
  }
148
- /**
149
- * Build a `withdraw-collateral` transaction for this account.
150
- *
151
- * For non-vault accounts, this endpoint constructs a transaction to:
152
- * - Withdraw collateral from the Perpetuals account, and
153
- * - Optionally transfer it to a `recipientAddress` (otherwise coin is left
154
- * as a transaction argument).
155
- *
156
- * **Note:** Vault accounts are currently not supported and will throw.
157
- *
158
- * @param inputs.withdrawAmount - Amount of collateral to withdraw.
159
- * @param inputs.recipientAddress - Optional address to receive the withdrawn
160
- * coins directly.
161
- * @param inputs.tx - Optional transaction to extend (defaults to new `Transaction()`).
162
- *
163
- * @returns A response containing `tx` and the `coinOutArg` where the
164
- * withdrawn coins end up if `recipientAddress` is not used.
165
- *
166
- * @example
167
- * ```ts
168
- * const { tx, coinOutArg } = await account.getWithdrawCollateralTx({
169
- * withdrawAmount: BigInt("1000000000"),
170
- * });
171
- * ```
172
- */
173
261
  getWithdrawCollateralTx(inputs) {
174
262
  return __awaiter(this, void 0, void 0, function* () {
175
- var _a;
176
- const { withdrawAmount, recipientAddress, tx: txFromInputs } = inputs;
177
- if (this.vaultId)
178
- throw new Error("this method is not supported for vaults, please use method `getAdminWithdrawTx` on class `PerpetualsVault` instead");
179
- return this.fetchApiTxObject("account/transactions/withdraw-collateral", {
180
- withdrawAmount,
181
- recipientAddress,
182
- walletAddress: this.ownerAddress(),
183
- accountId: this.accountCap.accountId,
184
- txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({
185
- tx: txFromInputs !== null && txFromInputs !== void 0 ? txFromInputs : new transactions_1.Transaction(),
186
- })),
187
- }, undefined, {
188
- txKind: true,
189
- });
263
+ return this.fetchApiTransaction("transactions/withdraw-collateral", Object.assign(Object.assign({}, inputs), { collateralCoinType: this.accountCap.collateralCoinType, accountCapId: this.accountCap.objectId }));
190
264
  });
191
265
  }
192
- /**
193
- * Build an `allocate-collateral` transaction, moving collateral from this
194
- * account into a specific market (clearing house).
195
- *
196
- * Works for both account-backed and vault-backed accounts.
197
- *
198
- * @param inputs.marketId - Market to allocate collateral to.
199
- * @param inputs.allocateAmount - Amount of collateral to allocate.
200
- * @param inputs.tx - Optional transaction to extend.
201
- *
202
- * @returns Transaction response containing a `tx`.
203
- */
204
266
  getAllocateCollateralTx(inputs) {
205
267
  return __awaiter(this, void 0, void 0, function* () {
206
- var _a;
207
- const { tx, allocateAmount, marketId } = inputs;
208
- return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
209
- "transactions/allocate-collateral", Object.assign(Object.assign({ marketId,
210
- allocateAmount }, ("vaultId" in this.accountCap
211
- ? {
212
- vaultId: this.accountCap.vaultId,
213
- accountId: undefined,
214
- }
215
- : {
216
- accountId: this.accountCap.accountId,
217
- accountCapId: this.accountCap.objectId,
218
- vaultId: undefined,
219
- })), { walletAddress: this.ownerAddress(), txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx: tx !== null && tx !== void 0 ? tx : new transactions_1.Transaction() })) }), undefined, {
220
- txKind: true,
221
- });
268
+ const { market } = inputs;
269
+ return this.fetchApiTransaction("transactions/allocate-collateral", Object.assign(Object.assign({}, inputs), { packageId: market.marketData.packageId, marketInitialSharedVersion: market.marketData.initialSharedVersion, marketId: market.marketId, collateralCoinType: this.accountCap.collateralCoinType, accountCapId: this.accountCap.objectId }));
222
270
  });
223
271
  }
224
- /**
225
- * Build a `deallocate-collateral` transaction, moving collateral from a
226
- * specific market back to this account.
227
- *
228
- * Works for both account-backed and vault-backed accounts.
229
- *
230
- * @param inputs.marketId - Market to deallocate collateral from.
231
- * @param inputs.deallocateAmount - Amount of collateral to deallocate.
232
- * @param inputs.tx - Optional transaction to extend.
233
- *
234
- * @returns Transaction response containing a `tx`.
235
- */
236
272
  getDeallocateCollateralTx(inputs) {
237
273
  return __awaiter(this, void 0, void 0, function* () {
238
- var _a;
239
- const { tx, deallocateAmount, marketId } = inputs;
240
- return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
241
- "transactions/deallocate-collateral", Object.assign(Object.assign({ marketId,
242
- deallocateAmount }, ("vaultId" in this.accountCap
243
- ? {
244
- vaultId: this.accountCap.vaultId,
245
- accountId: undefined,
246
- }
247
- : {
248
- accountId: this.accountCap.accountId,
249
- accountCapId: this.accountCap.objectId,
250
- vaultId: undefined,
251
- })), { walletAddress: this.ownerAddress(), txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx: tx !== null && tx !== void 0 ? tx : new transactions_1.Transaction() })) }), undefined, {
252
- txKind: true,
253
- });
274
+ const { market } = inputs;
275
+ return this.fetchApiTransaction("transactions/deallocate-collateral", Object.assign(Object.assign({}, inputs), { packageId: market.marketData.packageId, marketInitialSharedVersion: market.marketData.initialSharedVersion, marketId: market.marketId, basePriceFeedId: market.marketParams.basePriceFeedId, collateralPriceFeedId: market.marketParams.collateralPriceFeedId, collateralCoinType: this.accountCap.collateralCoinType, accountCapId: this.accountCap.objectId }));
254
276
  });
255
277
  }
256
- /**
257
- * Build a `transfer-collateral` transaction between two Perpetuals accounts.
258
- *
259
- * Only supported for direct accounts, **not** vault-backed accounts.
260
- *
261
- * @param inputs.transferAmount - Amount of collateral to transfer.
262
- * @param inputs.toAccountId - Destination account ID.
263
- * @param inputs.tx - Optional transaction to extend.
264
- *
265
- * @returns Transaction response containing a `tx`.
266
- */
267
278
  getTransferCollateralTx(inputs) {
268
279
  return __awaiter(this, void 0, void 0, function* () {
269
- var _a;
270
- const { transferAmount, toAccountId, toAccountCapId, tx } = inputs;
271
- if ("vaultId" in this.accountCap)
272
- throw new Error("`getTransferCollateralTx` not supported by vault accounts");
273
- return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
274
- "transactions/transfer-collateral", {
275
- transferAmount,
276
- toAccountId,
277
- toAccountCapId,
278
- walletAddress: this.ownerAddress(),
279
- fromAccountId: this.accountCap.accountId,
280
- fromAccountCapId: this.accountCap.objectId,
281
- txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx: tx !== null && tx !== void 0 ? tx : new transactions_1.Transaction() })),
282
- }, undefined, {
283
- txKind: true,
284
- });
280
+ return this.fetchApiTransaction("transactions/transfer-collateral", Object.assign(Object.assign({}, inputs), { collateralCoinType: this.accountCap.collateralCoinType, fromAccountCapId: this.accountCap.objectId }));
285
281
  });
286
282
  }
287
283
  // =========================================================================
288
284
  // Order Txs
289
285
  // =========================================================================
290
- /**
291
- * Build a `place-market-order` transaction for this account.
292
- *
293
- * This is the primary entrypoint for opening/closing positions via market orders.
294
- * It automatically:
295
- * - Injects the account/vault identity into the payload.
296
- * - Derives `hasPosition` based on the current account state for the given market.
297
- * - Optionally attaches SL/TP stop orders via the `slTp` input.
298
- *
299
- * Important behavioral notes:
300
- * - `hasPosition` is derived from the local {@link PerpetualsAccountObject} snapshot.
301
- * If the snapshot is stale, consider re-fetching the account first.
302
- * - For vault-backed accounts, the API routes to `/perpetuals/vault/...` and uses
303
- * `vaultId` as the identity discriminator. For direct accounts, it uses `accountId`.
304
- *
305
- * @param inputs - See {@link SdkPerpetualsPlaceMarketOrderInputs} for details.
306
- * Notably:
307
- * - `marketId`, `side`, `size`, `collateralChange`, `reduceOnly`
308
- * - Optional `leverage`
309
- * - Optional `slTp` params
310
- * - Optional `tx` to extend
311
- *
312
- * @returns Transaction response containing `tx`.
313
- *
314
- * @example
315
- * ```ts
316
- * const { tx } = await account.getPlaceMarketOrderTx({
317
- * marketId: "0x...",
318
- * side: PerpetualsOrderSide.Bid,
319
- * size: BigInt("1000000000"),
320
- * collateralChange: 10,
321
- * reduceOnly: false,
322
- * });
323
- * ```
324
- */
325
286
  getPlaceMarketOrderTx(inputs) {
326
287
  return __awaiter(this, void 0, void 0, function* () {
327
- var _a;
328
- const { tx: txFromInputs } = inputs, otherInputs = __rest(inputs, ["tx"]);
329
- const tx = txFromInputs !== null && txFromInputs !== void 0 ? txFromInputs : new transactions_1.Transaction();
330
- // tx.setSender(this.ownerAddress());
331
- return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
332
- "transactions/place-market-order", Object.assign(Object.assign(Object.assign({}, otherInputs), { txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx })), walletAddress: this.ownerAddress() }), ("vaultId" in this.accountCap
333
- ? {
334
- vaultId: this.accountCap.vaultId,
335
- accountId: undefined,
336
- }
337
- : {
338
- accountId: this.accountCap.accountId,
339
- accountCapId: this.accountCap.objectId,
340
- vaultId: undefined,
341
- })), undefined, {
342
- txKind: true,
343
- });
288
+ return this.fetchApiTransaction("transactions/market-order", Object.assign(Object.assign({}, inputs), { accountObjectId: this.accountCap.objectId, accountObjectVersion: this.accountCap.objectVersion, accountObjectDigest: this.accountCap.objectDigest, hasPosition: this.positionForMarketId(inputs) !== undefined }));
344
289
  });
345
290
  }
346
- /**
347
- * Build a `place-limit-order` transaction for this account.
348
- *
349
- * Similar to {@link getPlaceMarketOrderTx}, but uses limit order semantics:
350
- * - Requires `price` and `orderType`.
351
- * - Supports reduce-only flags, expiry, optional leverage, and SL/TP stop orders.
352
- *
353
- * Notes:
354
- * - `hasPosition` is derived from local account state; refresh the account if needed.
355
- * - This method does not validate tick/lot sizing locally; the API/on-chain
356
- * will enforce market constraints.
357
- *
358
- * @param inputs - See {@link SdkPerpetualsPlaceLimitOrderInputs}.
359
- *
360
- * @returns Transaction response containing `tx`.
361
- */
362
291
  getPlaceLimitOrderTx(inputs) {
363
292
  return __awaiter(this, void 0, void 0, function* () {
364
- var _a;
365
- const { tx: txFromInputs } = inputs, otherInputs = __rest(inputs, ["tx"]);
366
- const tx = txFromInputs !== null && txFromInputs !== void 0 ? txFromInputs : new transactions_1.Transaction();
367
- // tx.setSender(this.ownerAddress());
368
- return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
369
- "transactions/place-limit-order", Object.assign(Object.assign(Object.assign({}, otherInputs), { txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx })), walletAddress: this.ownerAddress() }), ("vaultId" in this.accountCap
370
- ? {
371
- vaultId: this.accountCap.vaultId,
372
- accountId: undefined,
373
- }
374
- : {
375
- accountId: this.accountCap.accountId,
376
- accountCapId: this.accountCap.objectId,
377
- vaultId: undefined,
378
- })), undefined, {
379
- txKind: true,
380
- });
293
+ return this.fetchApiTransaction("transactions/limit-order", Object.assign(Object.assign({}, inputs), { accountObjectId: this.accountCap.objectId, accountObjectVersion: this.accountCap.objectVersion, accountObjectDigest: this.accountCap.objectDigest, hasPosition: this.positionForMarketId(inputs) !== undefined }));
381
294
  });
382
295
  }
383
- /**
384
- * Build a `cancel-orders` transaction for this account.
385
- *
386
- * Each market in `marketIdsToData` supplies:
387
- * - `orderIds`: the orders to cancel in that market
388
- * - `collateralChange`: collateral adjustment to apply alongside cancellation
389
- * - `leverage`: leverage context used for estimating/validating constraints server-side
390
- *
391
- * Notes:
392
- * - Cancels are applied per market; some markets may succeed while others fail
393
- * depending on API/on-chain validation (returned as a transaction failure at execution).
394
- * - If you need to understand the effect prior to building a tx, use
395
- * {@link getCancelOrdersPreview}.
396
- *
397
- * @param inputs.tx - Optional transaction to extend.
398
- * @param inputs.marketIdsToData - Mapping from market IDs to cancel payloads.
399
- *
400
- * @returns Transaction response containing `tx`.
401
- */
402
- getCancelOrdersTx(inputs) {
296
+ getPlaceSLTPOrder(inputs) {
403
297
  return __awaiter(this, void 0, void 0, function* () {
404
- var _a;
405
- const { tx } = inputs, otherInputs = __rest(inputs, ["tx"]);
406
- return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
407
- "transactions/cancel-orders", Object.assign(Object.assign(Object.assign({}, otherInputs), { txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx })), walletAddress: this.ownerAddress() }), ("vaultId" in this.accountCap
408
- ? {
409
- vaultId: this.accountCap.vaultId,
410
- accountId: undefined,
411
- }
412
- : {
413
- accountId: this.accountCap.accountId,
414
- accountCapId: this.accountCap.objectId,
415
- vaultId: undefined,
416
- })), undefined, {
417
- txKind: true,
418
- });
298
+ return this.fetchApiTransaction("transactions/sltp-order", Object.assign(Object.assign({}, inputs), { accountObjectId: this.accountCap.objectId, accountObjectVersion: this.accountCap.objectVersion, accountObjectDigest: this.accountCap.objectDigest }));
419
299
  });
420
300
  }
421
- /**
422
- * Build a `cancel-stop-orders` transaction for this account.
423
- *
424
- * This cancels stop-order *objects/tickets* by their object IDs. These IDs are
425
- * returned by stop-order query endpoints (see {@link getStopOrderDatas}).
426
- *
427
- * @param inputs.tx - Optional transaction to extend.
428
- * @param inputs.stopOrderIds - Array of stop-order ticket IDs to cancel.
429
- *
430
- * @returns Transaction response containing `tx`.
431
- */
432
- getCancelStopOrdersTx(inputs) {
301
+ getCancelOrderTx(inputs) {
433
302
  return __awaiter(this, void 0, void 0, function* () {
434
- var _a;
435
- const { tx } = inputs, otherInputs = __rest(inputs, ["tx"]);
436
- return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
437
- "transactions/cancel-stop-orders", Object.assign(Object.assign(Object.assign({}, otherInputs), { txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx })), walletAddress: this.ownerAddress() }), ("vaultId" in this.accountCap
438
- ? {
439
- vaultId: this.accountCap.vaultId,
440
- accountId: undefined,
441
- }
442
- : {
443
- accountId: this.accountCap.accountId,
444
- accountCapId: this.accountCap.objectId,
445
- vaultId: undefined,
446
- })), undefined, {
447
- txKind: true,
448
- });
303
+ return this.fetchApiTransaction("transactions/cancel-order", Object.assign(Object.assign({}, inputs), { collateralCoinType: this.accountCap.collateralCoinType, accountCapId: this.accountCap.objectId }));
449
304
  });
450
305
  }
451
- /**
452
- * Build a `place-stop-orders` transaction for this account.
453
- *
454
- * This allows placing one or more stop orders in a single transaction,
455
- * optionally with a dedicated gas coin and a sponsored gas flag.
456
- *
457
- * Typical usage:
458
- * - Construct stop order payload(s) client-side
459
- * - Call this method to build a transaction kind
460
- * - Sign/execute the transaction via Sui
461
- *
462
- * @param inputs - See {@link SdkPerpetualsPlaceStopOrdersInputs}.
463
- *
464
- * @returns Transaction response containing `tx`.
465
- */
466
- getPlaceStopOrdersTx(inputs) {
467
- return __awaiter(this, void 0, void 0, function* () {
468
- var _a;
469
- const { tx: txFromInputs, isSponsoredTx, stopOrders, gasCoinArg, } = inputs;
470
- const tx = txFromInputs !== null && txFromInputs !== void 0 ? txFromInputs : new transactions_1.Transaction();
471
- // tx.setSender(this.ownerAddress());
472
- return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
473
- "transactions/place-stop-orders", Object.assign({ stopOrders,
474
- gasCoinArg,
475
- isSponsoredTx, txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx })), walletAddress: this.ownerAddress() }, ("vaultId" in this.accountCap
476
- ? {
477
- vaultId: this.accountCap.vaultId,
478
- accountId: undefined,
479
- }
480
- : {
481
- accountId: this.accountCap.accountId,
482
- accountCapId: this.accountCap.objectId,
483
- vaultId: undefined,
484
- })), undefined, {
485
- txKind: true,
486
- });
487
- });
488
- }
489
- /**
490
- * Build a `place-sl-tp-orders` transaction for this account.
491
- *
492
- * This helper constructs SL/TP stop orders for an **existing** position
493
- * in a given market. If the account has no position for `marketId`, this
494
- * throws an error.
495
- *
496
- * Implementation details:
497
- * - Determines the current position side from the account snapshot.
498
- * - Sets `positionSide` for the API so SL/TP orders are bound to closing logic
499
- * (i.e. they should trigger on the opposite side of the open position).
500
- *
501
- * @param inputs - See {@link SdkPerpetualsPlaceSlTpOrdersInputs}.
502
- *
503
- * @returns Transaction response containing `tx`.
504
- */
505
- getPlaceSlTpOrdersTx(inputs) {
506
- return __awaiter(this, void 0, void 0, function* () {
507
- var _a;
508
- const { tx: txFromInputs, isSponsoredTx, marketId } = inputs, slTpInputs = __rest(inputs, ["tx", "isSponsoredTx", "marketId"]);
509
- const position = this.positionForMarketId({ marketId });
510
- if (!position)
511
- throw new Error("you have no position for this market");
512
- const tx = txFromInputs !== null && txFromInputs !== void 0 ? txFromInputs : new transactions_1.Transaction();
513
- // tx.setSender(this.ownerAddress());
514
- return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
515
- "transactions/place-sl-tp-orders", Object.assign(Object.assign(Object.assign(Object.assign({}, slTpInputs), { marketId, txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx })), walletAddress: this.ownerAddress() }), ("vaultId" in this.accountCap
516
- ? {
517
- vaultId: this.accountCap.vaultId,
518
- accountId: undefined,
519
- }
520
- : {
521
- accountId: this.accountCap.accountId,
522
- accountCapId: this.accountCap.objectId,
523
- vaultId: undefined,
524
- })), { positionSide: perpetuals_1.Perpetuals.positionSide({
525
- baseAssetAmount: position.baseAssetAmount,
526
- }) }), undefined, {
527
- txKind: true,
528
- });
529
- });
530
- }
531
- /**
532
- * Build an `edit-stop-orders` transaction for this account.
533
- *
534
- * This endpoint lets you update existing stop orders in batch.
535
- *
536
- * Notes:
537
- * - You must provide the full updated stop-order objects (including object IDs).
538
- * - This is typically used to adjust trigger prices, sizes, expiries, or the
539
- * embedded limit-order parameters.
540
- *
541
- * @param inputs.stopOrders - Full updated stop-order payloads to apply.
542
- * @param inputs.tx - Optional transaction to extend.
543
- *
544
- * @returns Transaction response containing `tx`.
545
- */
546
- getEditStopOrdersTx(inputs) {
306
+ getCancelOrdersTx(inputs) {
547
307
  return __awaiter(this, void 0, void 0, function* () {
548
- var _a;
549
- const { tx: txFromInputs, stopOrders } = inputs;
550
- const tx = txFromInputs !== null && txFromInputs !== void 0 ? txFromInputs : new transactions_1.Transaction();
551
- // tx.setSender(this.ownerAddress());
552
- return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
553
- "transactions/edit-stop-orders", Object.assign({ stopOrders, txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx })), walletAddress: this.ownerAddress() }, ("vaultId" in this.accountCap
554
- ? {
555
- vaultId: this.accountCap.vaultId,
556
- accountId: undefined,
557
- }
558
- : {
559
- accountId: this.accountCap.accountId,
560
- accountCapId: this.accountCap.objectId,
561
- vaultId: undefined,
562
- })), undefined, {
563
- txKind: true,
564
- });
308
+ return this.fetchApiTransaction("transactions/cancel-orders", Object.assign(Object.assign({}, inputs), { collateralCoinType: this.accountCap.collateralCoinType, accountCapId: this.accountCap.objectId }));
565
309
  });
566
310
  }
567
- // public async getReduceOrderTx(inputs: {
568
- // tx?: Transaction;
569
- // collateralChange: number;
570
- // marketId: PerpetualsMarketId;
571
- // orderId: PerpetualsOrderId;
572
- // sizeToSubtract: bigint;
573
- // leverage?: number;
574
- // }) {
575
- // const { tx, ...otherInputs } = inputs;
576
- // return this.fetchApiTxObject<
577
- // ApiPerpetualsReduceOrderBody,
578
- // ApiTransactionResponse
579
- // >(
580
- // `${this.vaultId ? "vault" : "account"}/` +
581
- // "transactions/reduce-order",
582
- // {
583
- // ...otherInputs,
584
- // txKind: await this.Provider?.Transactions().fetchBase64TxKindFromTx(
585
- // { tx }
586
- // ),
587
- // walletAddress: this.ownerAddress(),
588
- // ...("vaultId" in this.accountCap
589
- // ? {
590
- // vaultId: this.accountCap.vaultId,
591
- // accountId: undefined,
592
- // }
593
- // : {
594
- // accountId: this.accountCap.accountId,
595
- // vaultId: undefined,
596
- // }),
597
- // },
598
- // undefined,
599
- // {
600
- // txKind: true,
601
- // }
602
- // );
603
- // }
604
- /**
605
- * Build a `set-leverage` transaction for a given market.
606
- *
607
- * This updates the effective leverage for the position (or potential position)
608
- * in `marketId`, and optionally adjusts collateral in tandem.
609
- *
610
- * Notes:
611
- * - Leverage changes may be constrained by protocol risk limits and current
612
- * position state.
613
- * - If you want to understand the effect first, use {@link getSetLeveragePreview}.
614
- *
615
- * @param inputs.tx - Optional transaction to extend.
616
- * @param inputs.leverage - Target leverage value.
617
- * @param inputs.collateralChange - Net collateral change to apply alongside
618
- * the leverage update.
619
- * @param inputs.marketId - Market whose leverage to adjust.
620
- *
621
- * @returns Transaction response containing `tx`.
622
- */
623
- getSetLeverageTx(inputs) {
311
+ getReduceOrdersTx(inputs) {
624
312
  return __awaiter(this, void 0, void 0, function* () {
625
- var _a;
626
- const { leverage, tx, collateralChange, marketId } = inputs;
627
- return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
628
- "transactions/set-leverage", Object.assign({ leverage,
629
- marketId,
630
- collateralChange, txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx })), walletAddress: this.ownerAddress() }, ("vaultId" in this.accountCap
631
- ? {
632
- vaultId: this.accountCap.vaultId,
633
- accountId: undefined,
634
- }
635
- : {
636
- accountId: this.accountCap.accountId,
637
- accountCapId: this.accountCap.objectId,
638
- vaultId: undefined,
639
- })), undefined, {
640
- txKind: true,
641
- });
313
+ const { market, orderDatas } = inputs;
314
+ return this.fetchApiTransaction("transactions/reduce-orders", Object.assign(Object.assign({}, inputs), { orderIds: orderDatas.map((order) => order.orderId), sizesToSubtract: orderDatas.map((order) => order.sizeToSubtract), packageId: market.marketData.packageId, marketInitialSharedVersion: market.marketData.initialSharedVersion, marketId: market.marketId, basePriceFeedId: market.marketParams.basePriceFeedId, collateralPriceFeedId: market.marketParams.collateralPriceFeedId, collateralCoinType: this.accountCap.collateralCoinType, accountCapId: this.accountCap.objectId }));
642
315
  });
643
316
  }
644
317
  // =========================================================================
645
318
  // Position Txs
646
319
  // =========================================================================
647
- // public async getClosePositionTx(inputs: {
648
- // size: bigint;
649
- // market: PerpetualsMarket;
650
- // orderDatas: PerpetualsOrderData[];
651
- // indexPrice: number;
652
- // collateralPrice: number;
653
- // }) {
654
- // throw new Error("TODO");
655
- // // return this.getPlaceMarketOrderTx({
656
- // // ...this.closePositionTxInputs(inputs),
657
- // // });
658
- // }
320
+ getClosePositionTx(inputs) {
321
+ return __awaiter(this, void 0, void 0, function* () {
322
+ return this.getPlaceMarketOrderTx(this.closePositionTxInputs(inputs));
323
+ });
324
+ }
659
325
  // =========================================================================
660
- // Interactions
326
+ // Inspections
661
327
  // =========================================================================
662
- /**
663
- * Build a deterministic message payload to sign when querying stop orders
664
- * from the backend.
665
- *
666
- * This payload is intended to be signed off-chain and then submitted to
667
- * `getStopOrderDatas` as a proof of account ownership.
668
- *
669
- * Important:
670
- * - The returned payload is *not* a Sui transaction; it is an off-chain
671
- * “authentication” message.
672
- * - The backend expects `account_id` to be a decimal string. This code
673
- * normalizes the bigint `accountId` by stripping the trailing `n`.
674
- *
675
- * @param inputs.marketIds - Optional list of market IDs to scope the query.
676
- *
677
- * @returns An object describing the action and account/market IDs, suitable
678
- * for message signing.
679
- *
680
- * @example
681
- * ```ts
682
- * const message = account.getStopOrdersMessageToSign({ marketIds: ["0x..."] });
683
- * const { signature } = await wallet.signMessage({
684
- * message: new TextEncoder().encode(JSON.stringify(message)),
685
- * });
686
- * ```
687
- */
688
- getStopOrdersMessageToSign(inputs) {
689
- var _a;
690
- return {
691
- action: "GET_STOP_ORDERS",
692
- account_id: this.accountCap.accountId
693
- .toString()
694
- .replaceAll("n", ""),
695
- clearing_house_ids: (_a = inputs === null || inputs === void 0 ? void 0 : inputs.marketIds) !== null && _a !== void 0 ? _a : [],
696
- };
328
+ setPositionLeverage(inputs) {
329
+ return __awaiter(this, void 0, void 0, function* () {
330
+ return this.fetchApi(`${this.accountCap.collateralCoinType}/accounts/${this.accountCap.accountId}/set-position-leverage`, inputs);
331
+ });
697
332
  }
698
- // public async getPlaceOrderPreview(
699
- // inputs: SdkPerpetualsPlaceOrderPreviewInputs,
700
- // abortSignal?: AbortSignal
701
- // ): Promise<
702
- // | {
703
- // error: string;
704
- // }
705
- // | {
706
- // updatedPosition: PerpetualsPosition;
707
- // priceSlippage: number;
708
- // percentSlippage: Percentage;
709
- // filledSize: number;
710
- // filledSizeUsd: number;
711
- // postedSize: number;
712
- // postedSizeUsd: number;
713
- // collateralChange: number;
714
- // executionPrice: number;
715
- // }
333
+ // public async getAllPositionLeverages(): Promise<
334
+ // {
335
+ // marketId: PerpetualsMarketId;
336
+ // leverage: number;
337
+ // }[]
716
338
  // > {
717
- // return this.fetchApi<
718
- // ApiPerpetualsPreviewOrderResponse,
719
- // ApiPerpetualsPreviewOrderBody
720
- // >(
721
- // `${this.vaultId ? "vault" : "account"}/` +"previews/place-order",
722
- // {
723
- // ...inputs,
724
- // accountId: this.accountCap.accountId,
725
- // collateralCoinType: this.accountCap.collateralCoinType,
726
- // },
727
- // abortSignal
339
+ // return this.fetchApi(
340
+ // `${this.accountCap.collateralCoinType}/accounts/${this.accountCap.accountId}/position-leverages`
728
341
  // );
729
342
  // }
730
- /**
731
- * Preview the effects of placing a market order (without building a tx).
732
- *
733
- * This is a read-only API call that runs the protocol’s pricing / margin /
734
- * slippage logic against the current market state and your account/vault context.
735
- *
736
- * @param inputs - See {@link SdkPerpetualsPlaceMarketOrderPreviewInputs}.
737
- * @param abortSignal - Optional `AbortSignal` to cancel the request.
738
- *
739
- * @returns Either an error message or a preview including:
740
- * - `updatedPosition`
741
- * - `priceSlippage`, `percentSlippage`
742
- * - `filledSize`, `filledSizeUsd`
743
- * - `postedSize`, `postedSizeUsd`
744
- * - `collateralChange`
745
- * - `executionPrice`
746
- */
747
- getPlaceMarketOrderPreview(inputs, abortSignal) {
343
+ getPositionLeverages(inputs) {
748
344
  return __awaiter(this, void 0, void 0, function* () {
749
- return this.fetchApi(`${this.vaultId ? "vault" : "account"}/` +
750
- "previews/place-market-order", Object.assign(Object.assign({}, inputs), ("vaultId" in this.accountCap
751
- ? {
752
- vaultId: this.accountCap.vaultId,
753
- accountId: undefined,
754
- }
755
- : {
756
- accountId: this.accountCap.accountId,
757
- accountCapId: this.accountCap.objectId,
758
- vaultId: undefined,
759
- })), abortSignal);
345
+ return this.fetchApi(`${this.accountCap.collateralCoinType}/accounts/${this.accountCap.accountId}/position-leverages/${JSON.stringify(inputs.marketIds)}`);
760
346
  });
761
347
  }
762
- /**
763
- * Preview the effects of placing a limit order (without building a tx).
764
- *
765
- * The preview simulates:
766
- * - How much size would execute immediately vs post to the book
767
- * - Expected slippage and execution price
768
- * - Resulting position and margin impact
769
- *
770
- * @param inputs - See {@link SdkPerpetualsPlaceLimitOrderPreviewInputs}.
771
- * @param abortSignal - Optional `AbortSignal` to cancel the request.
772
- *
773
- * @returns Either an error message or a preview object similar to
774
- * {@link getPlaceMarketOrderPreview}.
775
- */
776
- getPlaceLimitOrderPreview(inputs, abortSignal) {
348
+ setPositionLeverageMessageToSign(inputs) {
349
+ return {
350
+ account_id: Number(this.accountCap.accountId),
351
+ market_id: inputs.marketId,
352
+ leverage: inputs.leverage,
353
+ };
354
+ }
355
+ getOrderPreview(inputs, abortSignal) {
777
356
  return __awaiter(this, void 0, void 0, function* () {
778
- return this.fetchApi(`${this.vaultId ? "vault" : "account"}/` +
779
- "previews/place-limit-order", Object.assign(Object.assign({}, inputs), ("vaultId" in this.accountCap
780
- ? {
781
- vaultId: this.accountCap.vaultId,
782
- accountId: undefined,
783
- }
784
- : {
785
- accountId: this.accountCap.accountId,
786
- accountCapId: this.accountCap.objectId,
787
- vaultId: undefined,
788
- })), abortSignal);
357
+ const response = yield this.fetchApi("preview-order", Object.assign(Object.assign({}, inputs), { accountId: this.accountCap.accountId, collateralCoinType: this.accountCap.collateralCoinType }), abortSignal);
358
+ if ("error" in response)
359
+ return response;
360
+ const { collateralChange } = response, remainingResponse = __rest(response, ["collateralChange"]);
361
+ return Object.assign(Object.assign({}, remainingResponse), { collateralChange: __1.Coin.normalizeBalance(collateralChange, this.collateralDecimals()) });
789
362
  });
790
363
  }
791
- /**
792
- * Preview the effects of canceling orders across one or more markets.
793
- *
794
- * This is commonly used to:
795
- * - Validate that cancels are allowed under current margin constraints
796
- * - Estimate how collateral/margin would change after canceling (and applying
797
- * the associated `collateralChange` values)
798
- *
799
- * If `marketIdsToData` is empty, this returns a trivial preview with:
800
- * - `marketIdsToData: {}`
801
- *
802
- * @param inputs - See {@link SdkPerpetualsCancelOrdersPreviewInputs}.
803
- * @param abortSignal - Optional `AbortSignal` to cancel the request.
804
- *
805
- * @returns Either:
806
- * - `{ marketIdsToData }`, or
807
- * - `{ error }`.
808
- */
809
- getCancelOrdersPreview(inputs, abortSignal) {
364
+ getCancelOrdersPreview(inputs) {
810
365
  return __awaiter(this, void 0, void 0, function* () {
811
366
  // NOTE: should this case return an error instead ?
812
367
  if (Object.keys(inputs.marketIdsToData).length <= 0)
813
368
  return {
814
- marketIdsToData: {},
369
+ collateralChange: BigInt(0),
370
+ marketIdsToPositionAfterCancelOrders: {},
815
371
  };
816
- return this.fetchApi(`${this.vaultId ? "vault" : "account"}/` + "previews/cancel-orders", Object.assign(Object.assign({}, inputs), ("vaultId" in this.accountCap
817
- ? {
818
- vaultId: this.accountCap.vaultId,
819
- accountId: undefined,
820
- }
821
- : {
822
- accountId: this.accountCap.accountId,
823
- accountCapId: this.accountCap.objectId,
824
- vaultId: undefined,
825
- })), abortSignal);
826
- });
827
- }
828
- // public async getReduceOrderPreview(
829
- // inputs: {
830
- // marketId: PerpetualsMarketId;
831
- // orderId: PerpetualsOrderId;
832
- // sizeToSubtract: bigint;
833
- // leverage?: number;
834
- // },
835
- // abortSignal?: AbortSignal
836
- // ): Promise<
837
- // | {
838
- // positionAfterReduceOrder: PerpetualsPosition;
839
- // collateralChange: number;
840
- // }
841
- // | {
842
- // error: string;
843
- // }
844
- // > {
845
- // return this.fetchApi<
846
- // ApiPerpetualsPreviewReduceOrderResponse,
847
- // ApiPerpetualsPreviewReduceOrderBody
848
- // >(
849
- // `${this.vaultId ? "vault" : "account"}/` + "previews/reduce-order",
850
- // {
851
- // ...inputs,
852
- // ...("vaultId" in this.accountCap
853
- // ? {
854
- // vaultId: this.accountCap.vaultId,
855
- // accountId: undefined,
856
- // }
857
- // : {
858
- // accountId: this.accountCap.accountId,
859
- // vaultId: undefined,
860
- // }),
861
- // },
862
- // abortSignal
863
- // );
864
- // }
865
- /**
866
- * Preview the effects of setting leverage for a given market.
867
- *
868
- * The preview returns:
869
- * - The position after the leverage change (`updatedPosition`)
870
- * - The collateral delta required/produced (`collateralChange`)
871
- *
872
- * @param inputs.marketId - Market whose leverage you want to adjust.
873
- * @param inputs.leverage - Target leverage value.
874
- * @param abortSignal - Optional `AbortSignal` to cancel the request.
875
- *
876
- * @returns Either:
877
- * - `{ updatedPosition, collateralChange }`, or
878
- * - `{ error }`.
879
- */
880
- getSetLeveragePreview(inputs, abortSignal) {
881
- return __awaiter(this, void 0, void 0, function* () {
882
- const { marketId, leverage } = inputs;
883
- return this.fetchApi(`${this.vaultId ? "vault" : "account"}/` + "previews/set-leverage", Object.assign({ marketId,
884
- leverage }, ("vaultId" in this.accountCap
885
- ? {
886
- vaultId: this.accountCap.vaultId,
887
- accountId: undefined,
888
- }
889
- : {
890
- accountId: this.accountCap.accountId,
891
- accountCapId: this.accountCap.objectId,
892
- vaultId: undefined,
893
- })), abortSignal);
372
+ const response = yield this.fetchApi("preview-cancel-orders", Object.assign(Object.assign({}, inputs), { accountId: this.accountCap.accountId, collateralCoinType: this.accountCap.collateralCoinType }));
373
+ if ("error" in response)
374
+ return response;
375
+ return {
376
+ marketIdsToPositionAfterCancelOrders: response.marketIdsToPositionAfterCancelOrders,
377
+ collateralChange: __1.Coin.normalizeBalance(response.collateralChange, this.collateralDecimals()),
378
+ };
894
379
  });
895
380
  }
896
- /**
897
- * Preview the effects of allocating/deallocating collateral for the position in
898
- * a given market.
899
- *
900
- * Semantics:
901
- * - Positive `collateralChange` previews allocation (moving collateral into the market).
902
- * - Negative `collateralChange` previews deallocation (moving collateral out of the market).
903
- *
904
- * @param inputs.marketId - Market of whose position you want to allocate/deallocate
905
- * collateral to/from.
906
- * @param inputs.collateralChange - The target collateral change (a positive number
907
- * for allocating collateral, negative for deallocating collateral).
908
- * @param abortSignal - Optional `AbortSignal` to cancel the request.
909
- *
910
- * @returns Either:
911
- * - `{ updatedPosition, collateralChange }`, or
912
- * - `{ error }`.
913
- */
914
- getEditCollateralPreview(inputs, abortSignal) {
381
+ getReduceOrdersPreview(inputs) {
915
382
  return __awaiter(this, void 0, void 0, function* () {
916
- const { marketId, collateralChange } = inputs;
917
- return this.fetchApi(`${this.vaultId ? "vault" : "account"}/` +
918
- "previews/edit-collateral", Object.assign({ marketId,
919
- collateralChange }, ("vaultId" in this.accountCap
920
- ? {
921
- vaultId: this.accountCap.vaultId,
922
- accountId: undefined,
923
- }
924
- : {
925
- accountId: this.accountCap.accountId,
926
- accountCapId: this.accountCap.objectId,
927
- vaultId: undefined,
928
- })), abortSignal);
383
+ // NOTE: should this case not throw an error instead ?
384
+ if (Object.keys(inputs.orderDatas).length <= 0)
385
+ throw new Error("no orderDatas provided");
386
+ const response = yield this.fetchApi("preview-reduce-orders", Object.assign(Object.assign({}, inputs), { orderIds: inputs.orderDatas.map((order) => order.orderId), sizesToSubtract: inputs.orderDatas.map((order) => order.sizeToSubtract), accountId: this.accountCap.accountId, collateralCoinType: this.accountCap.collateralCoinType }));
387
+ if ("error" in response)
388
+ return response;
389
+ return {
390
+ positionAfterReduceOrders: response.positionAfterReduceOrders,
391
+ collateralChange: __1.Coin.normalizeBalance(response.collateralChange, this.collateralDecimals()),
392
+ };
929
393
  });
930
394
  }
931
- // public getPlaceClosePositionOrderPreview = async (
932
- // inputs: {
933
- // size: bigint;
934
- // marketId: PerpetualsMarketId;
935
- // leverage?: number;
936
- // } & (
937
- // | {
938
- // accountId: PerpetualsAccountId;
939
- // }
940
- // | {
941
- // vaultId: ObjectId;
942
- // }
943
- // ),
944
- // abortSignal?: AbortSignal
945
- // ): Promise<ReturnType<PerpetualsAccount["getPlaceMarketOrderPreview"]>> => {
946
- // // TODO: make this fetch instead ?
947
- // const position = this.positionForMarketId({
948
- // marketId: inputs.marketId,
949
- // });
950
- // if (!position)
951
- // throw new Error(
952
- // `Account has no position for market id: ${inputs.marketId}`
953
- // );
954
- // return this.getPlaceMarketOrderPreview(
955
- // {
956
- // ...inputs,
957
- // reduceOnly: true,
958
- // side:
959
- // Perpetuals.positionSide(position) ===
960
- // PerpetualsOrderSide.Ask
961
- // ? PerpetualsOrderSide.Bid
962
- // : PerpetualsOrderSide.Ask,
963
- // },
964
- // abortSignal
965
- // );
966
- // };
967
- /**
968
- * Fetch stop-order ticket data for this account, using an off-chain signed
969
- * payload.
970
- *
971
- * Typical flow:
972
- * 1) Call {@link getStopOrdersMessageToSign} to construct a deterministic payload
973
- * 2) Sign the payload with the wallet
974
- * 3) Provide the signed payload to this method to fetch stop order data
975
- *
976
- * @param inputs.bytes - Serialized message that was signed (e.g. JSON string).
977
- * @param inputs.signature - Signature over `bytes`.
978
- * @param inputs.marketIds - Optional subset of markets to filter results by.
979
- *
980
- * @returns {@link ApiPerpetualsStopOrderDatasResponse} containing `stopOrderDatas`.
981
- */
982
- getStopOrderDatas(inputs) {
395
+ getOrderDatas() {
983
396
  return __awaiter(this, void 0, void 0, function* () {
984
- const { bytes, signature, marketIds } = inputs;
985
- return this.fetchApi(`${this.vaultId ? "vault" : "account"}/` + "stop-order-datas", Object.assign({ bytes,
986
- signature, walletAddress: this.ownerAddress(), marketIds: marketIds !== null && marketIds !== void 0 ? marketIds : [] }, ("vaultId" in this.accountCap
987
- ? {
988
- vaultId: this.accountCap.vaultId,
989
- accountId: undefined,
990
- }
991
- : {
992
- accountId: this.accountCap.accountId,
993
- accountCapId: this.accountCap.objectId,
994
- vaultId: undefined,
995
- })));
397
+ const orderDatas = this.account.positions.reduce((acc, position) => [
398
+ ...acc,
399
+ ...position.pendingOrders.map((order) => ({
400
+ orderId: order.orderId,
401
+ currentSize: order.size,
402
+ })),
403
+ ], []);
404
+ if (orderDatas.length <= 0)
405
+ return [];
406
+ return this.fetchApi(`${this.accountCap.collateralCoinType}/accounts/${this.accountCap.accountId}/order-datas`, {
407
+ orderDatas,
408
+ });
996
409
  });
997
410
  }
998
- /**
999
- * Fetch paginated collateral-change history for this account, including
1000
- * deposits, withdrawals, funding settlements, liquidations, etc.
1001
- *
1002
- * Pagination:
1003
- * - Use `beforeTimestampCursor` to fetch older entries.
1004
- * - The API returns a `nextBeforeTimestampCursor` to continue pagination.
1005
- *
1006
- * @param inputs.beforeTimestampCursor - Optional cursor for pagination.
1007
- * @param inputs.limit - Optional limit per page.
1008
- *
1009
- * @returns {@link ApiPerpetualsAccountCollateralHistoryResponse} containing
1010
- * an array of changes and a `nextBeforeTimestampCursor`.
1011
- */
1012
411
  getCollateralHistory(inputs) {
1013
412
  return __awaiter(this, void 0, void 0, function* () {
1014
- return this.fetchApi("account/collateral-history", Object.assign(Object.assign({}, inputs), { accountId: this.accountCap.accountId }));
413
+ return this.fetchApi(`${this.accountCap.collateralCoinType}/accounts/${this.accountCap.accountId}/collateral-history`, inputs);
1015
414
  });
1016
415
  }
1017
- /**
1018
- * Fetch paginated order history for this account.
1019
- *
1020
- * This endpoint is distinct from {@link getOrderDatas}:
1021
- * - `getOrderDatas` resolves current/pending orders based on the snapshot.
1022
- * - `getOrderHistory` returns historical order events (fills, cancels, etc.)
1023
- * over time with cursor-based pagination.
1024
- *
1025
- * @param inputs.beforeTimestampCursor - Optional cursor for pagination.
1026
- * @param inputs.limit - Optional limit per page.
1027
- *
1028
- * @returns {@link ApiPerpetualsAccountOrderHistoryResponse} containing a list of
1029
- * orders and a `nextBeforeTimestampCursor`.
1030
- */
1031
416
  getOrderHistory(inputs) {
1032
417
  return __awaiter(this, void 0, void 0, function* () {
1033
- return this.fetchApi("account/order-history", Object.assign(Object.assign({}, inputs), { accountId: this.accountCap.accountId }));
1034
- });
1035
- }
1036
- /**
1037
- * Fetch historical margin snapshots for this account over a time range.
1038
- *
1039
- * This endpoint returns time-series margin data suitable for charting UI
1040
- * such as equity and available collateral over time.
1041
- *
1042
- * Notes:
1043
- * - This is an account-level view (aggregated across markets).
1044
- *
1045
- * @param inputs - {@link ApiPerpetualsAccountMarginHistoryBody} without `accountId`.
1046
- * @returns {@link ApiPerpetualsAccountMarginHistoryResponse} containing `marginHistoryDatas`.
1047
- */
1048
- getMarginHistory(inputs) {
1049
- return __awaiter(this, void 0, void 0, function* () {
1050
- return this.fetchApi("account/margin-history", Object.assign(Object.assign({}, inputs), { accountId: this.accountCap.accountId }));
1051
- });
1052
- }
1053
- // public async getOwnedWithdrawRequests() {
1054
- // return new Perpetuals(
1055
- // this.config,
1056
- // this.Provider
1057
- // ).getOwnedWithdrawRequests({
1058
- // walletAddress: this.ownerAddress(),
1059
- // });
1060
- // }
1061
- /**
1062
- * Build a transaction that grants an Agent Wallet (assistant permissions) for this perpetuals account.
1063
- *
1064
- * The returned transaction must be signed and submitted by the **account admin** wallet.
1065
- * After execution, `recipientAddress` can execute supported trading actions on behalf of this account.
1066
- *
1067
- * Agent wallets can perform all supported actions **except**:
1068
- * - withdrawing collateral, and
1069
- * - granting or revoking other agent wallets.
1070
- *
1071
- * @param inputs.recipientAddress Wallet address to receive agent permissions.
1072
- * @param inputs.tx Optional existing {@link Transaction} to append to. If omitted, a new Transaction is used.
1073
- * @throws If this instance represents a vault account (agent wallets are account-only).
1074
- */
1075
- getGrantAgentWalletTx(inputs) {
1076
- return __awaiter(this, void 0, void 0, function* () {
1077
- var _a;
1078
- const { tx, recipientAddress } = inputs;
1079
- if ("vaultId" in this.accountCap)
1080
- throw new Error("`getGrantAgentWalletTx` not supported by vault accounts");
1081
- return this.fetchApiTxObject("account/transactions/grant-agent-wallet", {
1082
- recipientAddress,
1083
- accountId: this.accountCap.accountId,
1084
- txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({
1085
- tx: tx !== null && tx !== void 0 ? tx : new transactions_1.Transaction(),
1086
- })),
1087
- }, undefined, {
1088
- txKind: true,
1089
- });
1090
- });
1091
- }
1092
- /**
1093
- * Build a transaction that revokes an Agent Wallet (assistant capability) from this perpetuals account.
1094
- *
1095
- * The returned transaction must be signed and submitted by the **account admin** wallet.
1096
- * After execution, the revoked wallet immediately loses its delegated permissions.
1097
- *
1098
- * @param inputs.accountCapId Object ID of the assistant capability to revoke.
1099
- * @param inputs.tx Optional existing {@link Transaction} to append to. If omitted, a new Transaction is used.
1100
- * @throws If this instance represents a vault account (agent wallets are account-only).
1101
- */
1102
- getRevokeAgentWalletTx(inputs) {
1103
- return __awaiter(this, void 0, void 0, function* () {
1104
- var _a;
1105
- const { tx, accountCapId } = inputs;
1106
- if ("vaultId" in this.accountCap)
1107
- throw new Error("`getRevokeAgentWalletTx` not supported by vault accounts");
1108
- return this.fetchApiTxObject("account/transactions/revoke-agent-wallet", {
1109
- accountCapId,
1110
- accountId: this.accountCap.accountId,
1111
- txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({
1112
- tx: tx !== null && tx !== void 0 ? tx : new transactions_1.Transaction(),
1113
- })),
1114
- }, undefined, {
1115
- txKind: true,
1116
- });
418
+ return this.fetchApi(`${this.accountCap.collateralCoinType}/accounts/${this.accountCap.accountId}/order-history`, inputs);
1117
419
  });
1118
420
  }
1119
421
  // =========================================================================
1120
422
  // Helpers
1121
423
  // =========================================================================
1122
- /**
1123
- * Find the current position for a given market ID, if any.
1124
- *
1125
- * @param inputs.marketId - Market ID to search for.
1126
- * @returns {@link PerpetualsPosition} if found, otherwise `undefined`.
1127
- */
1128
424
  positionForMarketId(inputs) {
1129
425
  try {
1130
426
  return this.account.positions.find((pos) => pos.marketId === inputs.marketId);
@@ -1133,271 +429,20 @@ class PerpetualsAccount extends caller_1.Caller {
1133
429
  return undefined;
1134
430
  }
1135
431
  }
1136
- /**
1137
- * Filter a list of stop orders to only include non-SL/TP orders.
1138
- *
1139
- * A stop order is considered SL/TP if it appears in the combined set of
1140
- * SL/TP orders across **all** markets (see {@link slTpStopOrderDatas}).
1141
- *
1142
- * Note:
1143
- * - This implementation uses JSON string equality to compare objects.
1144
- * This is pragmatic but assumes stable field ordering and identical shapes.
1145
- *
1146
- * @param inputs.stopOrderDatas - Full array of stop-order ticket data.
1147
- * @returns An array of non-SL/TP stop orders, or `undefined` if none exist.
1148
- */
1149
- nonSlTpStopOrderDatas(inputs) {
1150
- const { stopOrderDatas } = inputs;
1151
- const slTpOrders = this.slTpStopOrderDatas(inputs);
1152
- const stopOrders = stopOrderDatas.filter((stopOrder) => !(slTpOrders !== null && slTpOrders !== void 0 ? slTpOrders : [])
1153
- .map((slTpOrder) => JSON.stringify(slTpOrder))
1154
- .includes(JSON.stringify(stopOrder)));
1155
- return stopOrders.length <= 0 ? undefined : stopOrders;
1156
- }
1157
- /**
1158
- * Extract all SL/TP-style stop orders across **all** markets for this
1159
- * account.
1160
- *
1161
- * SL/TP orders are stop orders which:
1162
- * - Have an `slTp` payload, and
1163
- * - Target the opposite side of the current position.
1164
- *
1165
- * This combines:
1166
- * - "Full" SL/TP orders (size >= `i64MaxBigInt`)
1167
- * - "Partial" SL/TP orders (size < `i64MaxBigInt`)
1168
- *
1169
- * The "full vs partial" distinction is a protocol convention: some systems
1170
- * encode “close entire position” using a sentinel max size.
1171
- *
1172
- * @param inputs.stopOrderDatas - Full list of stop-order tickets.
1173
- * @returns Array of SL/TP stop orders, or `undefined` if none exist.
1174
- */
1175
- slTpStopOrderDatas(inputs) {
1176
- const { stopOrderDatas } = inputs;
1177
- let slTpOrders = [];
1178
- for (const { marketId } of this.account.positions) {
1179
- const { fullSlTpOrder, partialSlTpOrders } = this.slTpStopOrderDatasForPosition({
1180
- marketId,
1181
- stopOrderDatas,
1182
- });
1183
- slTpOrders = [
1184
- ...slTpOrders,
1185
- ...(fullSlTpOrder ? [fullSlTpOrder] : []),
1186
- ...(partialSlTpOrders !== null && partialSlTpOrders !== void 0 ? partialSlTpOrders : []),
1187
- ];
1188
- }
1189
- for (const limitOrderId of utils_1.Helpers.uniqueArray(stopOrderDatas.map((stopOrder) => { var _a; return (_a = stopOrder.slTp) === null || _a === void 0 ? void 0 : _a.limitOrderId; }))) {
1190
- if (limitOrderId === undefined)
1191
- continue;
1192
- const { fullSlTpOrder, partialSlTpOrders } = this.slTpStopOrderDatasForLimitOrder({
1193
- limitOrderId,
1194
- stopOrderDatas,
1195
- });
1196
- slTpOrders = [
1197
- ...slTpOrders,
1198
- ...(fullSlTpOrder ? [fullSlTpOrder] : []),
1199
- ...(partialSlTpOrders !== null && partialSlTpOrders !== void 0 ? partialSlTpOrders : []),
1200
- ];
1201
- }
1202
- return slTpOrders.length <= 0 ? undefined : slTpOrders;
1203
- }
1204
- /**
1205
- * Filter stop orders for a single market to only include non-SL/TP orders.
1206
- *
1207
- * Uses {@link slTpStopOrderDatasForPosition} under the hood.
1208
- *
1209
- * @param inputs.marketId - Market ID to filter for.
1210
- * @param inputs.stopOrderDatas - Full list of stop orders.
1211
- * @returns Non-SL/TP stop orders for the given market, or `undefined` if none exist.
1212
- */
1213
- nonSlTpStopOrderDatasForPosition(inputs) {
1214
- const { marketId, stopOrderDatas } = inputs;
1215
- const position = this.positionForMarketId({ marketId });
1216
- if (!position)
1217
- return undefined;
1218
- const { fullSlTpOrder, partialSlTpOrders } = this.slTpStopOrderDatasForPosition(inputs);
1219
- const stopOrders = stopOrderDatas.filter((stopOrder) => ![
1220
- ...(fullSlTpOrder ? [fullSlTpOrder] : []),
1221
- ...(partialSlTpOrders !== null && partialSlTpOrders !== void 0 ? partialSlTpOrders : []),
1222
- ]
1223
- .map((slTpOrder) => JSON.stringify(slTpOrder))
1224
- .includes(JSON.stringify(stopOrder)));
1225
- return stopOrders.length <= 0 ? undefined : stopOrders;
1226
- }
1227
- /**
1228
- * Categorize stop orders for a specific market into:
1229
- * - A "full" SL/TP order (size >= `i64MaxBigInt`) if any.
1230
- * - A set of "partial" SL/TP orders (size < `i64MaxBigInt`).
1231
- *
1232
- * SL/TP stop orders are defined as:
1233
- * - Market ID matches the input market.
1234
- * - `slTp` field is present.
1235
- * - Order side is opposite of the position side.
1236
- * - At least a `stopLossIndexPrice` or `takeProfitIndexPrice` is set.
1237
- *
1238
- * Notes on matching:
1239
- * - The side comparison uses the current position side derived from the account snapshot.
1240
- * - If `baseAssetAmount === 0` (no effective position), the method returns no SL/TP orders.
1241
- *
1242
- * @param inputs.marketId - Market to categorize stop orders for.
1243
- * @param inputs.stopOrderDatas - Full list of stop orders.
1244
- *
1245
- * @returns Object containing:
1246
- * - `fullSlTpOrder` (if any)
1247
- * - `partialSlTpOrders` (if any, otherwise `undefined`)
1248
- */
1249
- slTpStopOrderDatasForPosition(inputs) {
1250
- const { marketId, stopOrderDatas } = inputs;
1251
- const position = this.positionForMarketId({ marketId });
1252
- if (!position || position.baseAssetAmount === 0) {
1253
- return {
1254
- fullSlTpOrder: undefined,
1255
- partialSlTpOrders: undefined,
1256
- };
1257
- }
1258
- const side = !position ? undefined : perpetuals_1.Perpetuals.positionSide(position);
1259
- /**
1260
- * Implementation note:
1261
- *
1262
- * This method uses a pair of predicates that differ only by the `size` threshold
1263
- * to split “full close” SL/TP from “partial close” SL/TP. The sentinel threshold
1264
- * is {@link Casting.i64MaxBigInt}. Keeping the logic explicit (rather than
1265
- * abstracting into helpers) makes it easier to reason about protocol conventions.
1266
- */
1267
- const fullSlTpOrder = stopOrderDatas.find((order) => order.marketId === marketId &&
1268
- order.slTp &&
1269
- order.side !== side &&
1270
- (order.slTp.stopLossIndexPrice ||
1271
- order.slTp.takeProfitIndexPrice) &&
1272
- order.size >= utils_1.Casting.i64MaxBigInt);
1273
- const partialSlTpOrders = stopOrderDatas.filter((order) => order.marketId === marketId &&
1274
- order.slTp &&
1275
- order.side !== side &&
1276
- (order.slTp.stopLossIndexPrice ||
1277
- order.slTp.takeProfitIndexPrice) &&
1278
- order.size < utils_1.Casting.i64MaxBigInt);
1279
- return {
1280
- fullSlTpOrder,
1281
- partialSlTpOrders: partialSlTpOrders.length <= 0 ? undefined : partialSlTpOrders,
1282
- };
1283
- }
1284
- slTpStopOrderDatasForLimitOrder(inputs) {
1285
- const { stopOrderDatas, limitOrderId } = inputs;
1286
- /**
1287
- * Implementation note:
1288
- *
1289
- * This method uses a pair of predicates that differ only by the `size` threshold
1290
- * to split “full close” SL/TP from “partial close” SL/TP. The sentinel threshold
1291
- * is {@link Casting.i64MaxBigInt}. Keeping the logic explicit (rather than
1292
- * abstracting into helpers) makes it easier to reason about protocol conventions.
1293
- */
1294
- const fullSlTpOrder = stopOrderDatas.find((order) => order.slTp &&
1295
- order.slTp.limitOrderId === limitOrderId &&
1296
- (order.slTp.stopLossIndexPrice ||
1297
- order.slTp.takeProfitIndexPrice) &&
1298
- order.size >= utils_1.Casting.i64MaxBigInt);
1299
- const partialSlTpOrders = stopOrderDatas.filter((order) => order.slTp &&
1300
- order.slTp.limitOrderId === limitOrderId &&
1301
- (order.slTp.stopLossIndexPrice ||
1302
- order.slTp.takeProfitIndexPrice) &&
1303
- order.size < utils_1.Casting.i64MaxBigInt);
1304
- return {
1305
- fullSlTpOrder,
1306
- partialSlTpOrders: partialSlTpOrders.length <= 0 ? undefined : partialSlTpOrders,
1307
- };
1308
- }
1309
- orderDatas() {
1310
- return this.account.positions.reduce((acc, position) => [
1311
- ...acc,
1312
- ...position.pendingOrders.map((order) => ({
1313
- orderId: order.orderId,
1314
- currentSize: order.currentSize,
1315
- initialSize: order.initialSize,
1316
- side: perpetuals_1.Perpetuals.orderIdToSide(order.orderId),
1317
- marketId: position.marketId,
1318
- })),
1319
- ], []);
1320
- }
1321
- /**
1322
- * Convenience accessor for the account's available collateral (in coin units).
1323
- *
1324
- * This is the amount of collateral not currently locked/allocated across markets,
1325
- * as represented by the backend response.
1326
- *
1327
- * @returns Available collateral as a `number`.
1328
- */
1329
432
  collateral() {
1330
- return this.account.availableCollateral;
433
+ return utils_1.Casting.IFixed.numberFromIFixed(this.accountCap.collateral);
1331
434
  }
1332
- // public collateralDecimals(): CoinDecimal {
1333
- // return this.accountCap.collateralDecimals;
1334
- // }
1335
- // public collateralBalance(): Balance {
1336
- // return Coin.normalizeBalance(
1337
- // this.collateral(),
1338
- // this.collateralDecimals()
1339
- // );
1340
- // }
1341
- /**
1342
- * Check whether this {@link PerpetualsAccount} is vault-backed.
1343
- *
1344
- * @returns `true` if the underlying `accountCap` is a vault cap; otherwise `false`.
1345
- */
1346
- isVault() {
1347
- return "vaultId" in this.accountCap;
435
+ collateralDecimals() {
436
+ return this.accountCap.collateralDecimals;
1348
437
  }
1349
- /**
1350
- * Resolve the owner wallet address of this account or vault.
1351
- *
1352
- * - For direct accounts, returns the cap's `walletAddress` field.
1353
- * - For vault-backed accounts, returns the vault cap's `ownerAddress`.
1354
- *
1355
- * Naming note:
1356
- * - Some types use `walletAddress` for direct ownership. For vault-backed accounts
1357
- * the analogous field is `ownerAddress`.
1358
- *
1359
- * @returns Owner wallet {@link SuiAddress}.
1360
- */
1361
- ownerAddress() {
1362
- return "walletAddress" in this.accountCap
1363
- ? // NOTE: direct accounts expose `walletAddress`; vault accounts expose `ownerAddress`.
1364
- this.accountCap.walletAddress
1365
- : this.accountCap.ownerAddress;
1366
- }
1367
- /**
1368
- * Get the underlying account object ID.
1369
- *
1370
- * This is the on-chain object that holds the account's state and positions.
1371
- *
1372
- * @returns {@link ObjectId} of the account object.
1373
- */
1374
- accountObjectId() {
1375
- return this.accountCap.accountObjectId;
1376
- }
1377
- /**
1378
- * Get the numeric perpetuals account ID.
1379
- *
1380
- * This is the protocol-level identifier (bigint-derived) used across API calls.
1381
- *
1382
- * @returns {@link PerpetualsAccountId} for this account.
1383
- */
1384
- accountId() {
1385
- return this.accountCap.accountId;
1386
- }
1387
- /**
1388
- * Get the account cap object ID, if this is a direct account.
1389
- *
1390
- * Direct accounts are controlled via an on-chain “cap” object. Vault-backed
1391
- * accounts are controlled via vault caps and do not expose a direct account-cap ID.
1392
- *
1393
- * @throws If called for a vault-backed account.
1394
- *
1395
- * @returns {@link ObjectId} of the account cap.
1396
- */
1397
- accountCapId() {
1398
- if ("vaultId" in this.accountCap)
1399
- throw new Error("not account cap id present on vault owned account");
1400
- return this.accountCap.objectId;
438
+ collateralBalance() {
439
+ return __1.Coin.normalizeBalance(this.collateral(), this.collateralDecimals());
1401
440
  }
1402
441
  }
1403
442
  exports.PerpetualsAccount = PerpetualsAccount;
443
+ // =========================================================================
444
+ // Private Constants
445
+ // =========================================================================
446
+ PerpetualsAccount.constants = {
447
+ closePositionMarginOfError: 0.1, // 10%
448
+ };