aftermath-ts-sdk 1.3.22 → 1.3.23-perps.1

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 (128) hide show
  1. package/dist/general/apiHelpers/transactionsApiHelpers.d.ts +3 -0
  2. package/dist/general/apiHelpers/transactionsApiHelpers.d.ts.map +1 -1
  3. package/dist/general/apiHelpers/transactionsApiHelpers.js +12 -0
  4. package/dist/general/providers/aftermath.d.ts +0 -5
  5. package/dist/general/providers/aftermath.d.ts.map +1 -1
  6. package/dist/general/providers/aftermath.js +1 -6
  7. package/dist/general/providers/aftermathApi.d.ts +0 -10
  8. package/dist/general/providers/aftermathApi.d.ts.map +1 -1
  9. package/dist/general/providers/aftermathApi.js +0 -10
  10. package/dist/general/types/configTypes.d.ts +0 -10
  11. package/dist/general/types/configTypes.d.ts.map +1 -1
  12. package/dist/general/types/generalTypes.d.ts +4 -0
  13. package/dist/general/types/generalTypes.d.ts.map +1 -1
  14. package/dist/general/types/moveErrorsInterface.d.ts +1 -1
  15. package/dist/general/types/moveErrorsInterface.d.ts.map +1 -1
  16. package/dist/general/utils/caller.d.ts +17 -2
  17. package/dist/general/utils/caller.d.ts.map +1 -1
  18. package/dist/general/utils/caller.js +35 -2
  19. package/dist/general/utils/casting.d.ts +4 -5
  20. package/dist/general/utils/casting.d.ts.map +1 -1
  21. package/dist/general/utils/casting.js +4 -5
  22. package/dist/general/utils/helpers.d.ts +1 -0
  23. package/dist/general/utils/helpers.d.ts.map +1 -1
  24. package/dist/general/utils/helpers.js +35 -6
  25. package/dist/general/wallet/wallet.d.ts +1 -6
  26. package/dist/general/wallet/wallet.d.ts.map +1 -1
  27. package/dist/general/wallet/wallet.js +5 -19
  28. package/dist/packages/coin/coin.d.ts +1 -1
  29. package/dist/packages/coin/coin.d.ts.map +1 -1
  30. package/dist/packages/coin/coin.js +3 -1
  31. package/dist/packages/farms/api/farmsApi.d.ts +3 -0
  32. package/dist/packages/farms/api/farmsApi.d.ts.map +1 -1
  33. package/dist/packages/farms/api/farmsApi.js +3 -0
  34. package/dist/packages/farms/farms.d.ts +1 -1
  35. package/dist/packages/farms/farms.d.ts.map +1 -1
  36. package/dist/packages/farms/farms.js +2 -3
  37. package/dist/packages/farms/farmsStakedPosition.d.ts +1 -1
  38. package/dist/packages/farms/farmsStakedPosition.d.ts.map +1 -1
  39. package/dist/packages/farms/farmsStakingPool.d.ts +1 -1
  40. package/dist/packages/farms/farmsStakingPool.d.ts.map +1 -1
  41. package/dist/packages/faucet/api/faucetApi.d.ts +9 -17
  42. package/dist/packages/faucet/api/faucetApi.d.ts.map +1 -1
  43. package/dist/packages/faucet/api/faucetApi.js +44 -49
  44. package/dist/packages/faucet/api/faucetApiCasting.d.ts.map +1 -1
  45. package/dist/packages/faucet/api/faucetApiCasting.js +8 -5
  46. package/dist/packages/faucet/api/faucetApiCastingTypes.d.ts +1 -4
  47. package/dist/packages/faucet/api/faucetApiCastingTypes.d.ts.map +1 -1
  48. package/dist/packages/faucet/faucet.d.ts +1 -1
  49. package/dist/packages/faucet/faucet.d.ts.map +1 -1
  50. package/dist/packages/faucet/faucet.js +1 -1
  51. package/dist/packages/faucet/faucetTypes.d.ts +2 -3
  52. package/dist/packages/faucet/faucetTypes.d.ts.map +1 -1
  53. package/dist/packages/multisig/multisig.d.ts +1 -1
  54. package/dist/packages/multisig/multisig.d.ts.map +1 -1
  55. package/dist/packages/nftAmm/nftAmm.d.ts +1 -1
  56. package/dist/packages/nftAmm/nftAmm.d.ts.map +1 -1
  57. package/dist/packages/perpetuals/api/perpetualsApi.d.ts +11 -203
  58. package/dist/packages/perpetuals/api/perpetualsApi.d.ts.map +1 -1
  59. package/dist/packages/perpetuals/api/perpetualsApi.js +924 -615
  60. package/dist/packages/perpetuals/api/perpetualsApiCasting.d.ts +10 -21
  61. package/dist/packages/perpetuals/api/perpetualsApiCasting.d.ts.map +1 -1
  62. package/dist/packages/perpetuals/api/perpetualsApiCasting.js +243 -221
  63. package/dist/packages/perpetuals/index.d.ts +1 -0
  64. package/dist/packages/perpetuals/index.d.ts.map +1 -1
  65. package/dist/packages/perpetuals/index.js +1 -0
  66. package/dist/packages/perpetuals/perpetuals.d.ts +83 -14
  67. package/dist/packages/perpetuals/perpetuals.d.ts.map +1 -1
  68. package/dist/packages/perpetuals/perpetuals.js +158 -59
  69. package/dist/packages/perpetuals/perpetualsAccount.d.ts +158 -86
  70. package/dist/packages/perpetuals/perpetualsAccount.d.ts.map +1 -1
  71. package/dist/packages/perpetuals/perpetualsAccount.js +481 -141
  72. package/dist/packages/perpetuals/perpetualsCastingTypes.d.ts +82 -149
  73. package/dist/packages/perpetuals/perpetualsCastingTypes.d.ts.map +1 -1
  74. package/dist/packages/perpetuals/perpetualsMarket.d.ts +55 -20
  75. package/dist/packages/perpetuals/perpetualsMarket.d.ts.map +1 -1
  76. package/dist/packages/perpetuals/perpetualsMarket.js +110 -55
  77. package/dist/packages/perpetuals/perpetualsTypes.d.ts +586 -280
  78. package/dist/packages/perpetuals/perpetualsTypes.d.ts.map +1 -1
  79. package/dist/packages/perpetuals/perpetualsTypes.js +17 -81
  80. package/dist/packages/perpetuals/perpetualsVault.d.ts +109 -0
  81. package/dist/packages/perpetuals/perpetualsVault.d.ts.map +1 -0
  82. package/dist/packages/perpetuals/perpetualsVault.js +290 -0
  83. package/dist/packages/pools/pool.d.ts +1 -1
  84. package/dist/packages/pools/pool.d.ts.map +1 -1
  85. package/dist/packages/pools/pools.d.ts +1 -1
  86. package/dist/packages/pools/pools.d.ts.map +1 -1
  87. package/dist/packages/referralVault/referralVault.d.ts +1 -1
  88. package/dist/packages/referralVault/referralVault.d.ts.map +1 -1
  89. package/dist/packages/router/api/routerApi.d.ts +1 -7
  90. package/dist/packages/router/api/routerApi.d.ts.map +1 -1
  91. package/dist/packages/router/api/routerApi.js +6 -43
  92. package/dist/packages/staking/api/stakingApi.d.ts.map +1 -1
  93. package/dist/packages/staking/staking.d.ts +1 -1
  94. package/dist/packages/staking/staking.d.ts.map +1 -1
  95. package/dist/packages/sui/api/suiApi.d.ts +13 -0
  96. package/dist/packages/sui/api/suiApi.d.ts.map +1 -1
  97. package/dist/packages/sui/api/suiApi.js +13 -0
  98. package/dist/packages/sui/sui.d.ts +1 -6
  99. package/dist/packages/sui/sui.d.ts.map +1 -1
  100. package/dist/packages/sui/sui.js +1 -15
  101. package/dist/packages/suiFrens/stakedSuiFren.d.ts +1 -1
  102. package/dist/packages/suiFrens/stakedSuiFren.d.ts.map +1 -1
  103. package/dist/packages/suiFrens/suiFren.d.ts +1 -1
  104. package/dist/packages/suiFrens/suiFren.d.ts.map +1 -1
  105. package/dist/packages/suiFrens/suiFrens.d.ts +1 -1
  106. package/dist/packages/suiFrens/suiFrens.d.ts.map +1 -1
  107. package/dist/types.d.ts +0 -1
  108. package/dist/types.d.ts.map +1 -1
  109. package/dist/types.js +0 -1
  110. package/package.json +1 -1
  111. package/dist/packages/oracle/api/oracleApi.d.ts +0 -21
  112. package/dist/packages/oracle/api/oracleApi.d.ts.map +0 -1
  113. package/dist/packages/oracle/api/oracleApi.js +0 -76
  114. package/dist/packages/oracle/api/oracleApiCasting.d.ts +0 -6
  115. package/dist/packages/oracle/api/oracleApiCasting.d.ts.map +0 -1
  116. package/dist/packages/oracle/api/oracleApiCasting.js +0 -25
  117. package/dist/packages/oracle/oracle.d.ts +0 -15
  118. package/dist/packages/oracle/oracle.d.ts.map +0 -1
  119. package/dist/packages/oracle/oracle.js +0 -46
  120. package/dist/packages/oracle/oracleCastingTypes.d.ts +0 -11
  121. package/dist/packages/oracle/oracleCastingTypes.d.ts.map +0 -1
  122. package/dist/packages/oracle/oracleCastingTypes.js +0 -2
  123. package/dist/packages/oracle/oracleTypes.d.ts +0 -10
  124. package/dist/packages/oracle/oracleTypes.d.ts.map +0 -1
  125. package/dist/packages/oracle/oracleTypes.js +0 -2
  126. package/dist/packages/userData/api/userDataApi.d.ts +0 -6
  127. package/dist/packages/userData/api/userDataApi.d.ts.map +0 -1
  128. package/dist/packages/userData/api/userDataApi.js +0 -12
@@ -23,29 +23,39 @@ Object.defineProperty(exports, "__esModule", { value: true });
23
23
  exports.PerpetualsAccount = void 0;
24
24
  const caller_1 = require("../../general/utils/caller");
25
25
  const types_1 = require("../../types");
26
- const iFixedUtils_1 = require("../../general/utils/iFixedUtils");
27
26
  const utils_1 = require("../../general/utils");
28
27
  const perpetuals_1 = require("./perpetuals");
29
28
  const __1 = require("..");
29
+ const transactions_1 = require("@mysten/sui/transactions");
30
+ // TODO: create refresh account positions function ?
30
31
  class PerpetualsAccount extends caller_1.Caller {
31
32
  // =========================================================================
32
33
  // Constructor
33
34
  // =========================================================================
34
- constructor(account, accountCap, config) {
35
+ constructor(account, accountCap, config, Provider) {
36
+ const vaultId = "vaultId" in accountCap ? accountCap.vaultId : undefined;
35
37
  super(config, "perpetuals");
36
38
  this.account = account;
37
39
  this.accountCap = accountCap;
40
+ this.Provider = Provider;
41
+ // public async getOwnedWithdrawRequests() {
42
+ // return new Perpetuals(
43
+ // this.config,
44
+ // this.Provider
45
+ // ).getOwnedWithdrawRequests({
46
+ // walletAddress: this.ownerAddress(),
47
+ // });
48
+ // }
38
49
  // =========================================================================
39
50
  // Calculations
40
51
  // =========================================================================
41
52
  this.calcFreeCollateralForPosition = (inputs) => {
42
53
  var _a, _b;
43
54
  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 });
55
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : inputs.market.emptyPosition();
45
56
  const funding = this.calcUnrealizedFundingsForPosition(inputs);
46
57
  const { pnl, minInitialMargin } = this.calcPnLAndMarginForPosition(inputs);
47
- let collateralUsd = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.collateral) *
48
- inputs.collateralPrice;
58
+ let collateralUsd = position.collateral * inputs.collateralPrice;
49
59
  collateralUsd += funding;
50
60
  let cappedMargin;
51
61
  if (pnl < 0) {
@@ -64,14 +74,12 @@ class PerpetualsAccount extends caller_1.Caller {
64
74
  var _a, _b;
65
75
  const { market, indexPrice, collateralPrice } = inputs;
66
76
  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 });
77
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : market.emptyPosition();
68
78
  const funding = this.calcUnrealizedFundingsForPosition({
69
79
  market,
70
80
  position,
71
81
  });
72
- const collateralUsd = iFixedUtils_1.IFixedUtils.numberFromIFixed(position === null || position === void 0 ? void 0 : position.collateral) *
73
- collateralPrice +
74
- funding;
82
+ const collateralUsd = (position === null || position === void 0 ? void 0 : position.collateral) * collateralPrice + funding;
75
83
  const { pnl, netAbsBaseValue } = this.calcPnLAndMarginForPosition({
76
84
  market,
77
85
  indexPrice,
@@ -96,31 +104,31 @@ class PerpetualsAccount extends caller_1.Caller {
96
104
  this.calcUnrealizedFundingsForPosition = (inputs) => {
97
105
  var _a, _b;
98
106
  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);
107
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : inputs.market.emptyPosition();
108
+ const baseAmount = position.baseAssetAmount;
101
109
  const isLong = Math.sign(baseAmount);
102
110
  if (isLong < 0) {
103
- const fundingShort = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.cumFundingRateShort);
104
- const marketFundingShort = iFixedUtils_1.IFixedUtils.numberFromIFixed(inputs.market.marketState.cumFundingRateShort);
111
+ const fundingShort = position.cumFundingRateShort;
112
+ const marketFundingShort = inputs.market.marketState.cumFundingRateShort;
105
113
  return -baseAmount * (marketFundingShort - fundingShort);
106
114
  }
107
115
  else {
108
- const fundingLong = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.cumFundingRateLong);
109
- const marketFundingLong = iFixedUtils_1.IFixedUtils.numberFromIFixed(inputs.market.marketState.cumFundingRateLong);
116
+ const fundingLong = position.cumFundingRateLong;
117
+ const marketFundingLong = inputs.market.marketState.cumFundingRateLong;
110
118
  return -baseAmount * (marketFundingLong - fundingLong);
111
119
  }
112
120
  };
113
121
  this.calcPnLAndMarginForPosition = (inputs) => {
114
122
  var _a, _b;
115
123
  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;
124
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : inputs.market.emptyPosition();
125
+ const marginRatioInitial = 1 / (position.leverage || 1);
118
126
  // 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);
127
+ const marginRatioMaintenance = inputs.market.marketParams.marginRatioMaintenance;
128
+ const baseAssetAmount = position.baseAssetAmount;
129
+ const quoteAssetAmount = position.quoteAssetNotionalAmount;
130
+ const bidsQuantity = position.bidsQuantity;
131
+ const asksQuantity = position.asksQuantity;
124
132
  const pnl = baseAssetAmount * inputs.indexPrice - quoteAssetAmount;
125
133
  const netAbs = Math.max(Math.abs(baseAssetAmount + bidsQuantity), Math.abs(baseAssetAmount - asksQuantity));
126
134
  const netAbsBaseValue = netAbs * inputs.indexPrice;
@@ -131,33 +139,30 @@ class PerpetualsAccount extends caller_1.Caller {
131
139
  this.calcLiquidationPriceForPosition = (inputs) => {
132
140
  var _a, _b;
133
141
  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 });
142
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : inputs.market.emptyPosition();
135
143
  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;
144
+ const baseAssetAmount = position.baseAssetAmount;
145
+ const quoteAssetAmount = position.quoteAssetNotionalAmount;
146
+ const numerator = position.collateral * inputs.collateralPrice +
147
+ funding -
148
+ quoteAssetAmount;
149
+ const MMR = inputs.market.marketParams.marginRatioMaintenance;
150
+ const bidsQuantity = position.bidsQuantity;
151
+ const asksQuantity = position.asksQuantity;
152
+ const netAbs = Math.max(Math.abs(baseAssetAmount + bidsQuantity), Math.abs(baseAssetAmount - asksQuantity));
153
+ const denominator = netAbs * MMR - baseAssetAmount;
154
+ if (!denominator)
155
+ return 0;
156
+ const liquidationPrice = numerator / denominator;
157
+ return liquidationPrice <= 0 ? 0 : liquidationPrice;
152
158
  };
153
159
  this.calcFreeMarginUsdForPosition = (inputs) => {
154
160
  var _a, _b;
155
161
  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 });
162
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : inputs.market.emptyPosition();
157
163
  const totalFunding = this.calcUnrealizedFundingsForPosition(inputs);
158
164
  const { pnl, minInitialMargin } = this.calcPnLAndMarginForPosition(inputs);
159
- let collateralUsd = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.collateral) *
160
- inputs.collateralPrice;
165
+ let collateralUsd = position.collateral * inputs.collateralPrice;
161
166
  const margin = collateralUsd + totalFunding + pnl;
162
167
  if (margin >= minInitialMargin) {
163
168
  return margin - minInitialMargin;
@@ -174,7 +179,7 @@ class PerpetualsAccount extends caller_1.Caller {
174
179
  zipped.forEach(([market, indexPrice]) => {
175
180
  var _a;
176
181
  const marketId = market.marketId;
177
- const position = (_a = this.positionForMarketId({ marketId })) !== null && _a !== void 0 ? _a : this.emptyPosition({ market });
182
+ const position = (_a = this.positionForMarketId({ marketId })) !== null && _a !== void 0 ? _a : market.emptyPosition();
178
183
  const funding = this.calcUnrealizedFundingsForPosition({
179
184
  market,
180
185
  position,
@@ -184,8 +189,7 @@ class PerpetualsAccount extends caller_1.Caller {
184
189
  indexPrice,
185
190
  position,
186
191
  });
187
- let collateralUsd = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.collateral) *
188
- inputs.collateralPrice;
192
+ let collateralUsd = position.collateral * inputs.collateralPrice;
189
193
  totalPnL += pnl;
190
194
  totalFunding += funding;
191
195
  totalCollateralAllocated += collateralUsd;
@@ -200,9 +204,9 @@ class PerpetualsAccount extends caller_1.Caller {
200
204
  };
201
205
  this.closePositionTxInputs = (inputs) => {
202
206
  var _a;
203
- const { size, market, walletAddress, orderDatas, collateralPrice } = inputs;
207
+ const { size, market, orderDatas, collateralPrice } = inputs;
204
208
  const marketId = market.marketId;
205
- const position = (_a = this.positionForMarketId({ marketId })) !== null && _a !== void 0 ? _a : this.emptyPosition({ market });
209
+ const position = (_a = this.positionForMarketId({ marketId })) !== null && _a !== void 0 ? _a : market.emptyPosition();
206
210
  // TODO: move conversion to helper function, since used often
207
211
  const ordersCollateral = __1.Coin.normalizeBalance(utils_1.Helpers.sum(orderDatas
208
212
  .filter((orderData) => orderData.marketId === market.marketId)
@@ -212,40 +216,25 @@ class PerpetualsAccount extends caller_1.Caller {
212
216
  (1 -
213
217
  PerpetualsAccount.constants
214
218
  .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 positionSize = BigInt(Math.round(Math.abs(position.baseAssetAmount / market.lotSize())));
220
+ // NOTE: is this safe / correct ?
221
+ const collateralChange = __1.Coin.balanceWithDecimals(BigInt(Math.round(Number(fullPositionCollateralChange) *
222
+ (Number(size) / Number(positionSize)))), this.collateralDecimals());
219
223
  const positionSide = perpetuals_1.Perpetuals.positionSide(position);
220
224
  return {
221
225
  size,
222
226
  marketId,
223
- walletAddress,
224
227
  collateralChange,
228
+ // leverage: position.leverage || 1,
229
+ // leverage: undefined,
225
230
  side: positionSide === types_1.PerpetualsOrderSide.Bid
226
231
  ? types_1.PerpetualsOrderSide.Ask
227
232
  : 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,
233
+ // hasPosition: this.positionForMarketId({ marketId }) !== undefined,
234
+ reduceOnly: true,
247
235
  };
248
236
  };
237
+ this.vaultId = vaultId;
249
238
  }
250
239
  // =========================================================================
251
240
  // Transactions
@@ -255,29 +244,98 @@ class PerpetualsAccount extends caller_1.Caller {
255
244
  // =========================================================================
256
245
  getDepositCollateralTx(inputs) {
257
246
  return __awaiter(this, void 0, void 0, function* () {
258
- return this.fetchApiTransaction("transactions/deposit-collateral", Object.assign(Object.assign({}, inputs), { collateralCoinType: this.accountCap.collateralCoinType, accountCapId: this.accountCap.objectId }));
247
+ var _a;
248
+ const { tx } = inputs, otherInputs = __rest(inputs, ["tx"]);
249
+ // TODO: add vault support
250
+ if (this.vaultId)
251
+ throw new Error("this function is not supported for vaults");
252
+ return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
253
+ "transactions/deposit-collateral", Object.assign(Object.assign(Object.assign(Object.assign({}, otherInputs), { walletAddress: this.ownerAddress(), collateralCoinType: this.accountCap.collateralCoinType }), ("vaultId" in this.accountCap
254
+ ? {
255
+ vaultId: this.accountCap.vaultId,
256
+ }
257
+ : {
258
+ accountId: this.accountCap.accountId,
259
+ })), { txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({
260
+ tx: tx !== null && tx !== void 0 ? tx : new transactions_1.Transaction(),
261
+ })) }), undefined, {
262
+ txKind: true,
263
+ });
259
264
  });
260
265
  }
261
266
  getWithdrawCollateralTx(inputs) {
262
267
  return __awaiter(this, void 0, void 0, function* () {
263
- return this.fetchApiTransaction("transactions/withdraw-collateral", Object.assign(Object.assign({}, inputs), { collateralCoinType: this.accountCap.collateralCoinType, accountCapId: this.accountCap.objectId }));
268
+ var _a;
269
+ const { withdrawAmount, recipientAddress, tx: txFromInputs } = inputs;
270
+ // TODO: add vault support
271
+ if (this.vaultId)
272
+ throw new Error("this function is not supported for vaults");
273
+ return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
274
+ "transactions/withdraw-collateral", Object.assign(Object.assign({ withdrawAmount,
275
+ recipientAddress, walletAddress: this.ownerAddress(), collateralCoinType: this.accountCap.collateralCoinType }, ("vaultId" in this.accountCap
276
+ ? {
277
+ vaultId: this.accountCap.vaultId,
278
+ }
279
+ : {
280
+ accountId: this.accountCap.accountId,
281
+ })), { txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({
282
+ tx: txFromInputs !== null && txFromInputs !== void 0 ? txFromInputs : new transactions_1.Transaction(),
283
+ })) }), undefined, {
284
+ txKind: true,
285
+ });
264
286
  });
265
287
  }
266
288
  getAllocateCollateralTx(inputs) {
267
289
  return __awaiter(this, void 0, void 0, function* () {
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 }));
290
+ var _a;
291
+ const { tx, allocateAmount, marketId } = inputs;
292
+ return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
293
+ "transactions/allocate-collateral", Object.assign(Object.assign({ marketId,
294
+ allocateAmount }, ("vaultId" in this.accountCap
295
+ ? {
296
+ vaultId: this.accountCap.vaultId,
297
+ }
298
+ : {
299
+ accountId: this.accountCap.accountId,
300
+ })), { 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, {
301
+ txKind: true,
302
+ });
270
303
  });
271
304
  }
272
305
  getDeallocateCollateralTx(inputs) {
273
306
  return __awaiter(this, void 0, void 0, function* () {
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 }));
307
+ var _a;
308
+ const { tx, deallocateAmount, marketId } = inputs;
309
+ return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
310
+ "transactions/deallocate-collateral", Object.assign(Object.assign({ marketId,
311
+ deallocateAmount }, ("vaultId" in this.accountCap
312
+ ? {
313
+ vaultId: this.accountCap.vaultId,
314
+ }
315
+ : {
316
+ accountId: this.accountCap.accountId,
317
+ })), { 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, {
318
+ txKind: true,
319
+ });
276
320
  });
277
321
  }
278
322
  getTransferCollateralTx(inputs) {
279
323
  return __awaiter(this, void 0, void 0, function* () {
280
- return this.fetchApiTransaction("transactions/transfer-collateral", Object.assign(Object.assign({}, inputs), { collateralCoinType: this.accountCap.collateralCoinType, fromAccountCapId: this.accountCap.objectId }));
324
+ var _a;
325
+ const { transferAmount, toAccountId, tx } = inputs;
326
+ if ("vaultId" in this.accountCap)
327
+ throw new Error("`getTransferCollateralTx` not supported by vault accounts");
328
+ return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
329
+ "transactions/transfer-collateral", {
330
+ transferAmount,
331
+ toAccountId,
332
+ walletAddress: this.ownerAddress(),
333
+ collateralCoinType: this.accountCap.collateralCoinType,
334
+ fromAccountId: this.accountCap.accountId,
335
+ 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() })),
336
+ }, undefined, {
337
+ txKind: true,
338
+ });
281
339
  });
282
340
  }
283
341
  // =========================================================================
@@ -285,33 +343,167 @@ class PerpetualsAccount extends caller_1.Caller {
285
343
  // =========================================================================
286
344
  getPlaceMarketOrderTx(inputs) {
287
345
  return __awaiter(this, void 0, void 0, function* () {
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 }));
346
+ var _a;
347
+ const { tx: txFromInputs, slTp } = inputs, otherInputs = __rest(inputs, ["tx", "slTp"]);
348
+ const tx = txFromInputs !== null && txFromInputs !== void 0 ? txFromInputs : new transactions_1.Transaction();
349
+ // tx.setSender(this.ownerAddress());
350
+ return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
351
+ "transactions/place-market-order", Object.assign(Object.assign(Object.assign(Object.assign({}, otherInputs), { slTp: slTp
352
+ ? Object.assign({ walletAddress: this.ownerAddress() }, slTp) : undefined, txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx })), walletAddress: this.ownerAddress() }), ("vaultId" in this.accountCap
353
+ ? {
354
+ vaultId: this.accountCap.vaultId,
355
+ }
356
+ : {
357
+ accountId: this.accountCap.accountId,
358
+ })), { hasPosition: this.positionForMarketId(otherInputs) !== undefined }), undefined, {
359
+ txKind: true,
360
+ });
289
361
  });
290
362
  }
291
363
  getPlaceLimitOrderTx(inputs) {
292
364
  return __awaiter(this, void 0, void 0, function* () {
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 }));
365
+ var _a;
366
+ const { tx: txFromInputs, slTp } = inputs, otherInputs = __rest(inputs, ["tx", "slTp"]);
367
+ const tx = txFromInputs !== null && txFromInputs !== void 0 ? txFromInputs : new transactions_1.Transaction();
368
+ // tx.setSender(this.ownerAddress());
369
+ return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
370
+ "transactions/place-limit-order", Object.assign(Object.assign(Object.assign(Object.assign({}, otherInputs), { slTp: slTp
371
+ ? Object.assign({ walletAddress: this.ownerAddress() }, slTp) : undefined, txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx })), walletAddress: this.ownerAddress() }), ("vaultId" in this.accountCap
372
+ ? {
373
+ vaultId: this.accountCap.vaultId,
374
+ }
375
+ : {
376
+ accountId: this.accountCap.accountId,
377
+ })), { hasPosition: this.positionForMarketId(otherInputs) !== undefined }), undefined, {
378
+ txKind: true,
379
+ });
380
+ });
381
+ }
382
+ getCancelOrdersTx(inputs) {
383
+ return __awaiter(this, void 0, void 0, function* () {
384
+ var _a;
385
+ const { tx } = inputs, otherInputs = __rest(inputs, ["tx"]);
386
+ return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
387
+ "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
388
+ ? {
389
+ vaultId: this.accountCap.vaultId,
390
+ }
391
+ : {
392
+ accountId: this.accountCap.accountId,
393
+ })), undefined, {
394
+ txKind: true,
395
+ });
294
396
  });
295
397
  }
296
- getPlaceSLTPOrder(inputs) {
398
+ getCancelStopOrdersTx(inputs) {
297
399
  return __awaiter(this, void 0, void 0, function* () {
298
- return this.fetchApiTransaction("transactions/sltp-order", Object.assign(Object.assign({}, inputs), { accountObjectId: this.accountCap.objectId, accountObjectVersion: this.accountCap.objectVersion, accountObjectDigest: this.accountCap.objectDigest }));
400
+ var _a;
401
+ const { tx } = inputs, otherInputs = __rest(inputs, ["tx"]);
402
+ return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
403
+ "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
404
+ ? {
405
+ vaultId: this.accountCap.vaultId,
406
+ }
407
+ : {
408
+ accountId: this.accountCap.accountId,
409
+ })), undefined, {
410
+ txKind: true,
411
+ });
299
412
  });
300
413
  }
301
- getCancelOrderTx(inputs) {
414
+ getPlaceStopOrdersTx(inputs) {
302
415
  return __awaiter(this, void 0, void 0, function* () {
303
- return this.fetchApiTransaction("transactions/cancel-order", Object.assign(Object.assign({}, inputs), { collateralCoinType: this.accountCap.collateralCoinType, accountCapId: this.accountCap.objectId }));
416
+ var _a;
417
+ const { tx: txFromInputs, isSponsoredTx, stopOrders, gasCoinArg, } = inputs;
418
+ const tx = txFromInputs !== null && txFromInputs !== void 0 ? txFromInputs : new transactions_1.Transaction();
419
+ // tx.setSender(this.ownerAddress());
420
+ return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
421
+ "transactions/place-stop-orders", Object.assign({ stopOrders,
422
+ gasCoinArg,
423
+ isSponsoredTx, txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx })), walletAddress: this.ownerAddress() }, ("vaultId" in this.accountCap
424
+ ? {
425
+ vaultId: this.accountCap.vaultId,
426
+ }
427
+ : {
428
+ accountId: this.accountCap.accountId,
429
+ })), undefined, {
430
+ txKind: true,
431
+ });
304
432
  });
305
433
  }
306
- getCancelOrdersTx(inputs) {
434
+ getPlaceSlTpOrdersTx(inputs) {
435
+ return __awaiter(this, void 0, void 0, function* () {
436
+ var _a;
437
+ const { tx: txFromInputs, isSponsoredTx, marketId } = inputs, slTpInputs = __rest(inputs, ["tx", "isSponsoredTx", "marketId"]);
438
+ const position = this.positionForMarketId({ marketId });
439
+ if (!position)
440
+ throw new Error("you have no position for this market");
441
+ const tx = txFromInputs !== null && txFromInputs !== void 0 ? txFromInputs : new transactions_1.Transaction();
442
+ // tx.setSender(this.ownerAddress());
443
+ return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
444
+ "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
445
+ ? {
446
+ vaultId: this.accountCap.vaultId,
447
+ }
448
+ : {
449
+ accountId: this.accountCap.accountId,
450
+ })), { positionSide: perpetuals_1.Perpetuals.positionSide({
451
+ baseAssetAmount: position.baseAssetAmount,
452
+ }) }), undefined, {
453
+ txKind: true,
454
+ });
455
+ });
456
+ }
457
+ getEditStopOrdersTx(inputs) {
458
+ return __awaiter(this, void 0, void 0, function* () {
459
+ var _a;
460
+ const { tx: txFromInputs, stopOrders } = inputs;
461
+ const tx = txFromInputs !== null && txFromInputs !== void 0 ? txFromInputs : new transactions_1.Transaction();
462
+ // tx.setSender(this.ownerAddress());
463
+ return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
464
+ "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
465
+ ? {
466
+ vaultId: this.accountCap.vaultId,
467
+ }
468
+ : {
469
+ accountId: this.accountCap.accountId,
470
+ })), undefined, {
471
+ txKind: true,
472
+ });
473
+ });
474
+ }
475
+ getReduceOrderTx(inputs) {
307
476
  return __awaiter(this, void 0, void 0, function* () {
308
- return this.fetchApiTransaction("transactions/cancel-orders", Object.assign(Object.assign({}, inputs), { collateralCoinType: this.accountCap.collateralCoinType, accountCapId: this.accountCap.objectId }));
477
+ var _a;
478
+ const { tx } = inputs, otherInputs = __rest(inputs, ["tx"]);
479
+ return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
480
+ "transactions/reduce-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
481
+ ? {
482
+ vaultId: this.accountCap.vaultId,
483
+ }
484
+ : {
485
+ accountId: this.accountCap.accountId,
486
+ })), undefined, {
487
+ txKind: true,
488
+ });
309
489
  });
310
490
  }
311
- getReduceOrdersTx(inputs) {
491
+ getSetLeverageTx(inputs) {
312
492
  return __awaiter(this, void 0, void 0, function* () {
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 }));
493
+ var _a;
494
+ const { leverage, tx, collateralChange, marketId } = inputs;
495
+ return this.fetchApiTxObject(`${this.vaultId ? "vault" : "account"}/` +
496
+ "transactions/set-leverage", Object.assign({ leverage,
497
+ marketId,
498
+ collateralChange, txKind: yield ((_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Transactions().fetchBase64TxKindFromTx({ tx })), walletAddress: this.ownerAddress() }, ("vaultId" in this.accountCap
499
+ ? {
500
+ vaultId: this.accountCap.vaultId,
501
+ }
502
+ : {
503
+ accountId: this.accountCap.accountId,
504
+ })), undefined, {
505
+ txKind: true,
506
+ });
315
507
  });
316
508
  }
317
509
  // =========================================================================
@@ -319,77 +511,117 @@ class PerpetualsAccount extends caller_1.Caller {
319
511
  // =========================================================================
320
512
  getClosePositionTx(inputs) {
321
513
  return __awaiter(this, void 0, void 0, function* () {
322
- return this.getPlaceMarketOrderTx(this.closePositionTxInputs(inputs));
514
+ return this.getPlaceMarketOrderTx(Object.assign({}, this.closePositionTxInputs(inputs)));
323
515
  });
324
516
  }
325
517
  // =========================================================================
326
- // Inspections
518
+ // Interactions
327
519
  // =========================================================================
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
- });
520
+ getStopOrdersMessageToSign(inputs) {
521
+ var _a;
522
+ return {
523
+ action: "GET_STOP_ORDERS",
524
+ account_id: this.accountCap.accountId
525
+ .toString()
526
+ .replaceAll("n", ""),
527
+ clearing_house_ids: (_a = inputs === null || inputs === void 0 ? void 0 : inputs.marketIds) !== null && _a !== void 0 ? _a : [],
528
+ };
332
529
  }
333
- // public async getAllPositionLeverages(): Promise<
334
- // {
335
- // marketId: PerpetualsMarketId;
336
- // leverage: number;
337
- // }[]
530
+ // public async getPlaceOrderPreview(
531
+ // inputs: SdkPerpetualsPlaceOrderPreviewInputs,
532
+ // abortSignal?: AbortSignal
533
+ // ): Promise<
534
+ // | {
535
+ // error: string;
536
+ // }
537
+ // | {
538
+ // positionAfterOrder: PerpetualsPosition;
539
+ // priceSlippage: number;
540
+ // percentSlippage: Percentage;
541
+ // filledSize: number;
542
+ // filledSizeUsd: number;
543
+ // postedSize: number;
544
+ // postedSizeUsd: number;
545
+ // collateralChange: number;
546
+ // executionPrice: number;
547
+ // }
338
548
  // > {
339
- // return this.fetchApi(
340
- // `${this.accountCap.collateralCoinType}/accounts/${this.accountCap.accountId}/position-leverages`
549
+ // return this.fetchApi<
550
+ // ApiPerpetualsPreviewOrderResponse,
551
+ // ApiPerpetualsPreviewOrderBody
552
+ // >(
553
+ // `${this.vaultId ? "vault" : "account"}/` +"previews/place-order",
554
+ // {
555
+ // ...inputs,
556
+ // accountId: this.accountCap.accountId,
557
+ // collateralCoinType: this.accountCap.collateralCoinType,
558
+ // },
559
+ // abortSignal
341
560
  // );
342
561
  // }
343
- getPositionLeverages(inputs) {
562
+ getPlaceMarketOrderPreview(inputs, abortSignal) {
344
563
  return __awaiter(this, void 0, void 0, function* () {
345
- return this.fetchApi(`${this.accountCap.collateralCoinType}/accounts/${this.accountCap.accountId}/position-leverages/${JSON.stringify(inputs.marketIds)}`);
564
+ return this.fetchApi(`${this.vaultId ? "vault" : "account"}/` +
565
+ "previews/place-market-order", Object.assign(Object.assign(Object.assign({}, inputs), ("vaultId" in this.accountCap
566
+ ? {
567
+ vaultId: this.accountCap.vaultId,
568
+ }
569
+ : {
570
+ accountId: this.accountCap.accountId,
571
+ })), { collateralCoinType: this.accountCap.collateralCoinType }), abortSignal);
346
572
  });
347
573
  }
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) {
574
+ getPlaceLimitOrderPreview(inputs, abortSignal) {
356
575
  return __awaiter(this, void 0, void 0, function* () {
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()) });
576
+ return this.fetchApi(`${this.vaultId ? "vault" : "account"}/` +
577
+ "previews/place-limit-order", Object.assign(Object.assign(Object.assign({}, inputs), ("vaultId" in this.accountCap
578
+ ? {
579
+ vaultId: this.accountCap.vaultId,
580
+ }
581
+ : {
582
+ accountId: this.accountCap.accountId,
583
+ })), { collateralCoinType: this.accountCap.collateralCoinType }), abortSignal);
362
584
  });
363
585
  }
364
- getCancelOrdersPreview(inputs) {
586
+ getCancelOrdersPreview(inputs, abortSignal) {
365
587
  return __awaiter(this, void 0, void 0, function* () {
366
588
  // NOTE: should this case return an error instead ?
367
589
  if (Object.keys(inputs.marketIdsToData).length <= 0)
368
590
  return {
369
- collateralChange: BigInt(0),
591
+ collateralChange: 0,
370
592
  marketIdsToPositionAfterCancelOrders: {},
371
593
  };
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
- };
594
+ return this.fetchApi(`${this.vaultId ? "vault" : "account"}/` + "previews/cancel-orders", Object.assign(Object.assign(Object.assign({}, inputs), ("vaultId" in this.accountCap
595
+ ? {
596
+ vaultId: this.accountCap.vaultId,
597
+ }
598
+ : {
599
+ accountId: this.accountCap.accountId,
600
+ })), { collateralCoinType: this.accountCap.collateralCoinType }), abortSignal);
379
601
  });
380
602
  }
381
- getReduceOrdersPreview(inputs) {
603
+ getReduceOrderPreview(inputs, abortSignal) {
382
604
  return __awaiter(this, void 0, void 0, function* () {
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
- };
605
+ return this.fetchApi(`${this.vaultId ? "vault" : "account"}/` + "previews/reduce-order", Object.assign(Object.assign(Object.assign({}, inputs), ("vaultId" in this.accountCap
606
+ ? {
607
+ vaultId: this.accountCap.vaultId,
608
+ }
609
+ : {
610
+ accountId: this.accountCap.accountId,
611
+ })), { collateralCoinType: this.accountCap.collateralCoinType }), abortSignal);
612
+ });
613
+ }
614
+ getSetLeveragePreview(inputs, abortSignal) {
615
+ return __awaiter(this, void 0, void 0, function* () {
616
+ const { marketId, leverage } = inputs;
617
+ return this.fetchApi(`${this.vaultId ? "vault" : "account"}/` + "previews/set-leverage", Object.assign(Object.assign({ marketId,
618
+ leverage }, ("vaultId" in this.accountCap
619
+ ? {
620
+ vaultId: this.accountCap.vaultId,
621
+ }
622
+ : {
623
+ accountId: this.accountCap.accountId,
624
+ })), { collateralCoinType: this.accountCap.collateralCoinType }), abortSignal);
393
625
  });
394
626
  }
395
627
  getOrderDatas() {
@@ -403,19 +635,40 @@ class PerpetualsAccount extends caller_1.Caller {
403
635
  ], []);
404
636
  if (orderDatas.length <= 0)
405
637
  return [];
406
- return this.fetchApi(`${this.accountCap.collateralCoinType}/accounts/${this.accountCap.accountId}/order-datas`, {
638
+ return this.fetchApi("account/order-datas", {
639
+ accountId: this.accountCap.accountId,
407
640
  orderDatas,
408
641
  });
409
642
  });
410
643
  }
644
+ getStopOrderDatas(inputs) {
645
+ return __awaiter(this, void 0, void 0, function* () {
646
+ const { bytes, signature, marketIds } = inputs;
647
+ return this.fetchApi("account/stop-order-datas", {
648
+ bytes,
649
+ signature,
650
+ accountId: this.accountCap.accountId,
651
+ walletAddress: this.ownerAddress(),
652
+ marketIds: marketIds !== null && marketIds !== void 0 ? marketIds : [],
653
+ });
654
+ });
655
+ }
411
656
  getCollateralHistory(inputs) {
412
657
  return __awaiter(this, void 0, void 0, function* () {
413
- return this.fetchApi(`${this.accountCap.collateralCoinType}/accounts/${this.accountCap.accountId}/collateral-history`, inputs);
658
+ return this.fetchApi("account/collateral-history", Object.assign(Object.assign({}, inputs), { accountId: this.accountCap.accountId, collateralCoinType: this.accountCap.collateralCoinType }));
414
659
  });
415
660
  }
416
661
  getOrderHistory(inputs) {
417
662
  return __awaiter(this, void 0, void 0, function* () {
418
- return this.fetchApi(`${this.accountCap.collateralCoinType}/accounts/${this.accountCap.accountId}/order-history`, inputs);
663
+ return this.fetchApi("account/trade-history", Object.assign(Object.assign({}, inputs), { accountId: this.accountCap.accountId }));
664
+ });
665
+ }
666
+ getMarginHistory() {
667
+ return __awaiter(this, void 0, void 0, function* () {
668
+ return this.fetchApi("account/margin-history", {
669
+ accountId: this.accountCap.accountId,
670
+ collateralCoinType: this.accountCap.collateralCoinType,
671
+ });
419
672
  });
420
673
  }
421
674
  // =========================================================================
@@ -429,8 +682,74 @@ class PerpetualsAccount extends caller_1.Caller {
429
682
  return undefined;
430
683
  }
431
684
  }
685
+ nonSlTpStopOrderDatas(inputs) {
686
+ const { stopOrderDatas } = inputs;
687
+ const slTpOrders = this.slTpStopOrderDatas(inputs);
688
+ const stopOrders = stopOrderDatas.filter((stopOrder) => !(slTpOrders !== null && slTpOrders !== void 0 ? slTpOrders : [])
689
+ .map((slTpOrder) => JSON.stringify(slTpOrder))
690
+ .includes(JSON.stringify(stopOrder)));
691
+ return stopOrders.length <= 0 ? undefined : stopOrders;
692
+ }
693
+ slTpStopOrderDatas(inputs) {
694
+ const { stopOrderDatas } = inputs;
695
+ let slTpOrders = [];
696
+ for (const { marketId } of this.account.positions) {
697
+ const { fullSlTpOrder, partialSlTpOrders } = this.slTpStopOrderDatasForMarketId({
698
+ marketId,
699
+ stopOrderDatas,
700
+ });
701
+ slTpOrders = [
702
+ ...slTpOrders,
703
+ ...(fullSlTpOrder ? [fullSlTpOrder] : []),
704
+ ...(partialSlTpOrders !== null && partialSlTpOrders !== void 0 ? partialSlTpOrders : []),
705
+ ];
706
+ }
707
+ return slTpOrders.length <= 0 ? undefined : slTpOrders;
708
+ }
709
+ nonSlTpStopOrderDatasForMarketId(inputs) {
710
+ const { marketId, stopOrderDatas } = inputs;
711
+ const position = this.positionForMarketId({ marketId });
712
+ if (!position)
713
+ return undefined;
714
+ const { fullSlTpOrder, partialSlTpOrders } = this.slTpStopOrderDatasForMarketId(inputs);
715
+ const stopOrders = stopOrderDatas.filter((stopOrder) => ![
716
+ ...(fullSlTpOrder ? [fullSlTpOrder] : []),
717
+ ...(partialSlTpOrders !== null && partialSlTpOrders !== void 0 ? partialSlTpOrders : []),
718
+ ]
719
+ .map((slTpOrder) => JSON.stringify(slTpOrder))
720
+ .includes(JSON.stringify(stopOrder)));
721
+ return stopOrders.length <= 0 ? undefined : stopOrders;
722
+ }
723
+ slTpStopOrderDatasForMarketId(inputs) {
724
+ const { marketId, stopOrderDatas } = inputs;
725
+ const position = this.positionForMarketId({ marketId });
726
+ if (!position || position.baseAssetAmount === 0) {
727
+ return {
728
+ fullSlTpOrder: undefined,
729
+ partialSlTpOrders: undefined,
730
+ };
731
+ }
732
+ const side = !position ? undefined : perpetuals_1.Perpetuals.positionSide(position);
733
+ // TODO: clean this up
734
+ const fullSlTpOrder = stopOrderDatas.find((order) => order.marketId === marketId &&
735
+ order.slTp &&
736
+ order.side !== side &&
737
+ (order.slTp.stopLossIndexPrice ||
738
+ order.slTp.takeProfitIndexPrice) &&
739
+ order.size >= utils_1.Casting.i64MaxBigInt);
740
+ const partialSlTpOrders = stopOrderDatas.filter((order) => order.marketId === marketId &&
741
+ order.slTp &&
742
+ order.side !== side &&
743
+ (order.slTp.stopLossIndexPrice ||
744
+ order.slTp.takeProfitIndexPrice) &&
745
+ order.size < utils_1.Casting.i64MaxBigInt);
746
+ return {
747
+ fullSlTpOrder,
748
+ partialSlTpOrders: partialSlTpOrders.length <= 0 ? undefined : partialSlTpOrders,
749
+ };
750
+ }
432
751
  collateral() {
433
- return utils_1.Casting.IFixed.numberFromIFixed(this.accountCap.collateral);
752
+ return this.account.availableCollateral;
434
753
  }
435
754
  collateralDecimals() {
436
755
  return this.accountCap.collateralDecimals;
@@ -438,6 +757,27 @@ class PerpetualsAccount extends caller_1.Caller {
438
757
  collateralBalance() {
439
758
  return __1.Coin.normalizeBalance(this.collateral(), this.collateralDecimals());
440
759
  }
760
+ isVault() {
761
+ return this.isVault !== undefined;
762
+ }
763
+ ownerAddress() {
764
+ return "walletAddress" in this.accountCap
765
+ ? // TODO: change to ownerAddress ?
766
+ this.accountCap.walletAddress
767
+ : this.accountCap.ownerAddress;
768
+ }
769
+ accountObjectId() {
770
+ return this.accountCap.accountObjectId;
771
+ }
772
+ accountId() {
773
+ return this.accountCap.accountId;
774
+ }
775
+ // TODO: make this work with vaults
776
+ accountCapId() {
777
+ if ("vaultId" in this.accountCap)
778
+ throw new Error("not account cap id present on vault owned account");
779
+ return this.accountCap.objectId;
780
+ }
441
781
  }
442
782
  exports.PerpetualsAccount = PerpetualsAccount;
443
783
  // =========================================================================