aftermath-ts-sdk 1.2.51 → 1.2.52-perps.4

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 (214) hide show
  1. package/README.md +62 -28
  2. package/dist/general/apiHelpers/eventsApiHelpers.d.ts +1 -1
  3. package/dist/general/apiHelpers/eventsApiHelpers.d.ts.map +1 -1
  4. package/dist/general/apiHelpers/eventsApiHelpers.js +4 -1
  5. package/dist/general/apiHelpers/transactionsApiHelpers.d.ts +6 -0
  6. package/dist/general/apiHelpers/transactionsApiHelpers.d.ts.map +1 -1
  7. package/dist/general/apiHelpers/transactionsApiHelpers.js +46 -0
  8. package/dist/general/dynamicGas/dynamicGas.d.ts +34 -0
  9. package/dist/general/dynamicGas/dynamicGas.d.ts.map +1 -1
  10. package/dist/general/dynamicGas/dynamicGas.js +34 -0
  11. package/dist/general/dynamicGas/dynamicGasTypes.d.ts +25 -0
  12. package/dist/general/dynamicGas/dynamicGasTypes.d.ts.map +1 -1
  13. package/dist/general/prices/coinGeckoTypes.d.ts +2 -0
  14. package/dist/general/prices/coinGeckoTypes.d.ts.map +1 -1
  15. package/dist/general/prices/prices.d.ts +73 -0
  16. package/dist/general/prices/prices.d.ts.map +1 -1
  17. package/dist/general/prices/prices.js +73 -0
  18. package/dist/general/providers/aftermath.d.ts +107 -27
  19. package/dist/general/providers/aftermath.d.ts.map +1 -1
  20. package/dist/general/providers/aftermath.js +110 -30
  21. package/dist/general/providers/aftermathApi.d.ts +128 -10
  22. package/dist/general/providers/aftermathApi.d.ts.map +1 -1
  23. package/dist/general/providers/aftermathApi.js +133 -14
  24. package/dist/general/types/castingTypes.d.ts +15 -7
  25. package/dist/general/types/castingTypes.d.ts.map +1 -1
  26. package/dist/general/types/castingTypes.js +6 -0
  27. package/dist/general/types/configTypes.d.ts +14 -8
  28. package/dist/general/types/configTypes.d.ts.map +1 -1
  29. package/dist/general/types/generalTypes.d.ts +229 -7
  30. package/dist/general/types/generalTypes.d.ts.map +1 -1
  31. package/dist/general/types/moveErrorsInterface.d.ts +1 -1
  32. package/dist/general/types/moveErrorsInterface.d.ts.map +1 -1
  33. package/dist/general/types/suiTypes.d.ts +0 -16
  34. package/dist/general/types/suiTypes.d.ts.map +1 -1
  35. package/dist/general/types/suiTypes.js +3 -25
  36. package/dist/general/utils/caller.d.ts +6 -3
  37. package/dist/general/utils/caller.d.ts.map +1 -1
  38. package/dist/general/utils/caller.js +22 -4
  39. package/dist/general/utils/casting.d.ts +156 -5
  40. package/dist/general/utils/casting.d.ts.map +1 -1
  41. package/dist/general/utils/casting.js +159 -18
  42. package/dist/general/utils/fixedUtils.d.ts +89 -2
  43. package/dist/general/utils/fixedUtils.d.ts.map +1 -1
  44. package/dist/general/utils/fixedUtils.js +81 -4
  45. package/dist/general/utils/helpers.d.ts +327 -10
  46. package/dist/general/utils/helpers.d.ts.map +1 -1
  47. package/dist/general/utils/helpers.js +409 -91
  48. package/dist/general/utils/iFixedUtils.d.ts +64 -0
  49. package/dist/general/utils/iFixedUtils.d.ts.map +1 -1
  50. package/dist/general/utils/iFixedUtils.js +64 -0
  51. package/dist/general/wallet/wallet.d.ts +76 -1
  52. package/dist/general/wallet/wallet.d.ts.map +1 -1
  53. package/dist/general/wallet/wallet.js +75 -5
  54. package/dist/packages/auth/auth.d.ts +113 -4
  55. package/dist/packages/auth/auth.d.ts.map +1 -1
  56. package/dist/packages/auth/auth.js +190 -59
  57. package/dist/packages/auth/authTypes.d.ts +66 -0
  58. package/dist/packages/auth/authTypes.d.ts.map +1 -1
  59. package/dist/packages/coin/api/coinApi.d.ts.map +1 -1
  60. package/dist/packages/coin/api/coinApi.js +29 -20
  61. package/dist/packages/coin/coin.d.ts +256 -1
  62. package/dist/packages/coin/coin.d.ts.map +1 -1
  63. package/dist/packages/coin/coin.js +246 -15
  64. package/dist/packages/coin/coinTypes.d.ts +95 -0
  65. package/dist/packages/coin/coinTypes.d.ts.map +1 -1
  66. package/dist/packages/dca/api/dcaApi.d.ts +2 -0
  67. package/dist/packages/dca/api/dcaApi.d.ts.map +1 -1
  68. package/dist/packages/dca/api/dcaApi.js +6 -3
  69. package/dist/packages/dca/dca.d.ts +125 -35
  70. package/dist/packages/dca/dca.d.ts.map +1 -1
  71. package/dist/packages/dca/dca.js +135 -43
  72. package/dist/packages/dca/dcaTypes.d.ts +217 -42
  73. package/dist/packages/dca/dcaTypes.d.ts.map +1 -1
  74. package/dist/packages/farms/api/farmsApi.d.ts +725 -58
  75. package/dist/packages/farms/api/farmsApi.d.ts.map +1 -1
  76. package/dist/packages/farms/api/farmsApi.js +1149 -153
  77. package/dist/packages/farms/api/farmsApiCasting.d.ts +34 -18
  78. package/dist/packages/farms/api/farmsApiCasting.d.ts.map +1 -1
  79. package/dist/packages/farms/api/farmsApiCasting.js +218 -17
  80. package/dist/packages/farms/api/farmsApiCastingTypes.d.ts +117 -21
  81. package/dist/packages/farms/api/farmsApiCastingTypes.d.ts.map +1 -1
  82. package/dist/packages/farms/farms.d.ts +200 -12
  83. package/dist/packages/farms/farms.d.ts.map +1 -1
  84. package/dist/packages/farms/farms.js +204 -50
  85. package/dist/packages/farms/farmsStakedPosition.d.ts +143 -8
  86. package/dist/packages/farms/farmsStakedPosition.d.ts.map +1 -1
  87. package/dist/packages/farms/farmsStakedPosition.js +243 -137
  88. package/dist/packages/farms/farmsStakingPool.d.ts +171 -3
  89. package/dist/packages/farms/farmsStakingPool.d.ts.map +1 -1
  90. package/dist/packages/farms/farmsStakingPool.js +233 -73
  91. package/dist/packages/farms/farmsTypes.d.ts +310 -2
  92. package/dist/packages/farms/farmsTypes.d.ts.map +1 -1
  93. package/dist/packages/farms/farmsTypes.js +47 -0
  94. package/dist/packages/faucet/api/faucetApi.d.ts +9 -17
  95. package/dist/packages/faucet/api/faucetApi.d.ts.map +1 -1
  96. package/dist/packages/faucet/api/faucetApi.js +44 -49
  97. package/dist/packages/faucet/api/faucetApiCasting.d.ts.map +1 -1
  98. package/dist/packages/faucet/api/faucetApiCasting.js +8 -5
  99. package/dist/packages/faucet/api/faucetApiCastingTypes.d.ts +1 -4
  100. package/dist/packages/faucet/api/faucetApiCastingTypes.d.ts.map +1 -1
  101. package/dist/packages/faucet/faucet.d.ts +1 -1
  102. package/dist/packages/faucet/faucet.d.ts.map +1 -1
  103. package/dist/packages/faucet/faucet.js +1 -1
  104. package/dist/packages/faucet/faucetTypes.d.ts +2 -3
  105. package/dist/packages/faucet/faucetTypes.d.ts.map +1 -1
  106. package/dist/packages/limitOrders/api/limitOrdersApi.d.ts +12 -0
  107. package/dist/packages/limitOrders/api/limitOrdersApi.d.ts.map +1 -0
  108. package/dist/packages/limitOrders/api/limitOrdersApi.js +25 -0
  109. package/dist/packages/limitOrders/index.d.ts +2 -0
  110. package/dist/packages/limitOrders/index.d.ts.map +1 -0
  111. package/dist/packages/limitOrders/index.js +17 -0
  112. package/dist/packages/limitOrders/limitOrders.d.ts +143 -0
  113. package/dist/packages/limitOrders/limitOrders.d.ts.map +1 -0
  114. package/dist/packages/limitOrders/limitOrders.js +190 -0
  115. package/dist/packages/limitOrders/limitOrdersTypes.d.ts +211 -0
  116. package/dist/packages/limitOrders/limitOrdersTypes.d.ts.map +1 -0
  117. package/dist/packages/multisig/multisig.d.ts +34 -5
  118. package/dist/packages/multisig/multisig.d.ts.map +1 -1
  119. package/dist/packages/multisig/multisig.js +33 -4
  120. package/dist/packages/multisig/multisigTypes.d.ts +17 -0
  121. package/dist/packages/multisig/multisigTypes.d.ts.map +1 -1
  122. package/dist/packages/nftAmm/nftAmm.d.ts +1 -1
  123. package/dist/packages/nftAmm/nftAmm.d.ts.map +1 -1
  124. package/dist/packages/perpetuals/api/perpetualsApi.d.ts +38 -23
  125. package/dist/packages/perpetuals/api/perpetualsApi.d.ts.map +1 -1
  126. package/dist/packages/perpetuals/api/perpetualsApi.js +740 -299
  127. package/dist/packages/perpetuals/api/perpetualsApiCasting.d.ts +10 -6
  128. package/dist/packages/perpetuals/api/perpetualsApiCasting.d.ts.map +1 -1
  129. package/dist/packages/perpetuals/api/perpetualsApiCasting.js +112 -42
  130. package/dist/packages/perpetuals/perpetuals.d.ts +33 -4
  131. package/dist/packages/perpetuals/perpetuals.d.ts.map +1 -1
  132. package/dist/packages/perpetuals/perpetuals.js +105 -18
  133. package/dist/packages/perpetuals/perpetualsAccount.d.ts +107 -33
  134. package/dist/packages/perpetuals/perpetualsAccount.d.ts.map +1 -1
  135. package/dist/packages/perpetuals/perpetualsAccount.js +569 -68
  136. package/dist/packages/perpetuals/perpetualsCastingTypes.d.ts +104 -25
  137. package/dist/packages/perpetuals/perpetualsCastingTypes.d.ts.map +1 -1
  138. package/dist/packages/perpetuals/perpetualsMarket.d.ts +31 -9
  139. package/dist/packages/perpetuals/perpetualsMarket.d.ts.map +1 -1
  140. package/dist/packages/perpetuals/perpetualsMarket.js +85 -77
  141. package/dist/packages/perpetuals/perpetualsTypes.d.ts +349 -379
  142. package/dist/packages/perpetuals/perpetualsTypes.d.ts.map +1 -1
  143. package/dist/packages/perpetuals/perpetualsTypes.js +43 -113
  144. package/dist/packages/pools/api/poolsApiCasting.d.ts.map +1 -1
  145. package/dist/packages/pools/api/poolsApiCasting.js +0 -1
  146. package/dist/packages/pools/pool.d.ts +333 -106
  147. package/dist/packages/pools/pool.d.ts.map +1 -1
  148. package/dist/packages/pools/pool.js +347 -119
  149. package/dist/packages/pools/pools.d.ts +307 -39
  150. package/dist/packages/pools/pools.d.ts.map +1 -1
  151. package/dist/packages/pools/pools.js +323 -54
  152. package/dist/packages/pools/poolsTypes.d.ts +267 -2
  153. package/dist/packages/pools/poolsTypes.d.ts.map +1 -1
  154. package/dist/packages/referralVault/referralVault.d.ts +38 -1
  155. package/dist/packages/referralVault/referralVault.d.ts.map +1 -1
  156. package/dist/packages/referralVault/referralVault.js +37 -0
  157. package/dist/packages/router/api/routerApi.d.ts +2 -2
  158. package/dist/packages/router/api/routerApi.d.ts.map +1 -1
  159. package/dist/packages/router/api/routerApi.js +19 -11
  160. package/dist/packages/router/router.d.ts +214 -18
  161. package/dist/packages/router/router.d.ts.map +1 -1
  162. package/dist/packages/router/router.js +216 -20
  163. package/dist/packages/router/routerTypes.d.ts +202 -17
  164. package/dist/packages/router/routerTypes.d.ts.map +1 -1
  165. package/dist/packages/staking/staking.d.ts +306 -45
  166. package/dist/packages/staking/staking.d.ts.map +1 -1
  167. package/dist/packages/staking/staking.js +313 -51
  168. package/dist/packages/staking/stakingTypes.d.ts +431 -6
  169. package/dist/packages/staking/stakingTypes.d.ts.map +1 -1
  170. package/dist/packages/staking/stakingTypes.js +19 -0
  171. package/dist/packages/sui/sui.d.ts +40 -1
  172. package/dist/packages/sui/sui.d.ts.map +1 -1
  173. package/dist/packages/sui/sui.js +39 -0
  174. package/dist/packages/suiFrens/stakedSuiFren.d.ts +1 -1
  175. package/dist/packages/suiFrens/stakedSuiFren.d.ts.map +1 -1
  176. package/dist/packages/suiFrens/suiFren.d.ts +1 -1
  177. package/dist/packages/suiFrens/suiFren.d.ts.map +1 -1
  178. package/dist/packages/suiFrens/suiFrens.d.ts +1 -1
  179. package/dist/packages/suiFrens/suiFrens.d.ts.map +1 -1
  180. package/dist/packages/userData/api/userDataApi.d.ts +6 -0
  181. package/dist/packages/userData/api/userDataApi.d.ts.map +1 -0
  182. package/dist/packages/userData/api/userDataApi.js +12 -0
  183. package/dist/packages/userData/index.d.ts +2 -0
  184. package/dist/packages/userData/index.d.ts.map +1 -0
  185. package/dist/packages/userData/index.js +17 -0
  186. package/dist/packages/userData/userData.d.ts +89 -0
  187. package/dist/packages/userData/userData.d.ts.map +1 -0
  188. package/dist/packages/userData/userData.js +119 -0
  189. package/dist/packages/userData/userDataTypes.d.ts +29 -0
  190. package/dist/packages/userData/userDataTypes.d.ts.map +1 -0
  191. package/dist/types.d.ts.map +1 -1
  192. package/dist/types.js +0 -1
  193. package/package.json +1 -1
  194. package/dist/general/historicalData/historicalData.d.ts +0 -15
  195. package/dist/general/historicalData/historicalData.d.ts.map +0 -1
  196. package/dist/general/historicalData/historicalData.js +0 -45
  197. package/dist/general/historicalData/historicalDataTypes.d.ts +0 -10
  198. package/dist/general/historicalData/historicalDataTypes.d.ts.map +0 -1
  199. package/dist/packages/dca/api/dcaApiCasting.d.ts +0 -11
  200. package/dist/packages/dca/api/dcaApiCasting.d.ts.map +0 -1
  201. package/dist/packages/dca/api/dcaApiCasting.js +0 -186
  202. package/dist/packages/dca/api/dcaApiCastingTypes.d.ts +0 -142
  203. package/dist/packages/dca/api/dcaApiCastingTypes.d.ts.map +0 -1
  204. package/dist/packages/oracle/api/oracleApi.d.ts +0 -13
  205. package/dist/packages/oracle/api/oracleApi.d.ts.map +0 -1
  206. package/dist/packages/oracle/api/oracleApi.js +0 -35
  207. package/dist/packages/oracle/oracle.d.ts +0 -15
  208. package/dist/packages/oracle/oracle.d.ts.map +0 -1
  209. package/dist/packages/oracle/oracle.js +0 -46
  210. package/dist/packages/oracle/oracleTypes.d.ts +0 -2
  211. package/dist/packages/oracle/oracleTypes.d.ts.map +0 -1
  212. package/dist/packages/oracle/oracleTypes.js +0 -2
  213. /package/dist/{general/historicalData/historicalDataTypes.js → packages/limitOrders/limitOrdersTypes.js} +0 -0
  214. /package/dist/packages/{dca/api/dcaApiCastingTypes.js → userData/userDataTypes.js} +0 -0
@@ -27,21 +27,25 @@ const iFixedUtils_1 = require("../../general/utils/iFixedUtils");
27
27
  const utils_1 = require("../../general/utils");
28
28
  const perpetuals_1 = require("./perpetuals");
29
29
  const __1 = require("..");
30
+ const transactions_1 = require("@mysten/sui/transactions");
31
+ const transactionsApiHelpers_1 = require("../../general/apiHelpers/transactionsApiHelpers");
32
+ // TODO: create refresh account positions function ?
30
33
  class PerpetualsAccount extends caller_1.Caller {
31
34
  // =========================================================================
32
35
  // Constructor
33
36
  // =========================================================================
34
- constructor(account, accountCap, config) {
37
+ constructor(account, accountCap, config, Provider) {
35
38
  super(config, "perpetuals");
36
39
  this.account = account;
37
40
  this.accountCap = accountCap;
41
+ this.Provider = Provider;
38
42
  // =========================================================================
39
43
  // Calculations
40
44
  // =========================================================================
41
45
  this.calcFreeCollateralForPosition = (inputs) => {
42
46
  var _a, _b;
43
47
  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({ marketId });
48
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : inputs.market.emptyPosition();
45
49
  const funding = this.calcUnrealizedFundingsForPosition(inputs);
46
50
  const { pnl, minInitialMargin } = this.calcPnLAndMarginForPosition(inputs);
47
51
  let collateralUsd = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.collateral) *
@@ -64,7 +68,7 @@ class PerpetualsAccount extends caller_1.Caller {
64
68
  var _a, _b;
65
69
  const { market, indexPrice, collateralPrice } = inputs;
66
70
  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({ marketId });
71
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : market.emptyPosition();
68
72
  const funding = this.calcUnrealizedFundingsForPosition({
69
73
  market,
70
74
  position,
@@ -96,7 +100,7 @@ class PerpetualsAccount extends caller_1.Caller {
96
100
  this.calcUnrealizedFundingsForPosition = (inputs) => {
97
101
  var _a, _b;
98
102
  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({ marketId });
103
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : inputs.market.emptyPosition();
100
104
  const baseAmount = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.baseAssetAmount);
101
105
  const isLong = Math.sign(baseAmount);
102
106
  if (isLong < 0) {
@@ -113,8 +117,8 @@ class PerpetualsAccount extends caller_1.Caller {
113
117
  this.calcPnLAndMarginForPosition = (inputs) => {
114
118
  var _a, _b;
115
119
  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({ marketId });
117
- const marginRatioInitial = 1 / position.leverage;
120
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : inputs.market.emptyPosition();
121
+ const marginRatioInitial = 1 / (position.leverage || 1);
118
122
  // const marginRatioInitial = inputs.market.initialMarginRatio();
119
123
  const marginRatioMaintenance = iFixedUtils_1.IFixedUtils.numberFromIFixed(inputs.market.marketParams.marginRatioMaintenance);
120
124
  const baseAssetAmount = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.baseAssetAmount);
@@ -131,29 +135,28 @@ class PerpetualsAccount extends caller_1.Caller {
131
135
  this.calcLiquidationPriceForPosition = (inputs) => {
132
136
  var _a, _b;
133
137
  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({ marketId });
138
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : inputs.market.emptyPosition();
135
139
  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
140
  const baseAssetAmount = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.baseAssetAmount);
140
141
  const quoteAssetAmount = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.quoteAssetNotionalAmount);
142
+ const numerator = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.collateral) *
143
+ inputs.collateralPrice +
144
+ funding -
145
+ quoteAssetAmount;
141
146
  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;
147
+ const bidsQuantity = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.bidsQuantity);
148
+ const asksQuantity = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.asksQuantity);
149
+ const netAbs = Math.max(Math.abs(baseAssetAmount + bidsQuantity), Math.abs(baseAssetAmount - asksQuantity));
150
+ const denominator = netAbs * MMR - baseAssetAmount;
151
+ if (!denominator)
152
+ return 0;
153
+ const liquidationPrice = numerator / denominator;
154
+ return liquidationPrice <= 0 ? 0 : liquidationPrice;
152
155
  };
153
156
  this.calcFreeMarginUsdForPosition = (inputs) => {
154
157
  var _a, _b;
155
158
  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({ marketId });
159
+ const position = (_b = (_a = inputs.position) !== null && _a !== void 0 ? _a : this.positionForMarketId({ marketId })) !== null && _b !== void 0 ? _b : inputs.market.emptyPosition();
157
160
  const totalFunding = this.calcUnrealizedFundingsForPosition(inputs);
158
161
  const { pnl, minInitialMargin } = this.calcPnLAndMarginForPosition(inputs);
159
162
  let collateralUsd = iFixedUtils_1.IFixedUtils.numberFromIFixed(position.collateral) *
@@ -174,7 +177,7 @@ class PerpetualsAccount extends caller_1.Caller {
174
177
  zipped.forEach(([market, indexPrice]) => {
175
178
  var _a;
176
179
  const marketId = market.marketId;
177
- const position = (_a = this.positionForMarketId({ marketId })) !== null && _a !== void 0 ? _a : this.emptyPosition({ marketId });
180
+ const position = (_a = this.positionForMarketId({ marketId })) !== null && _a !== void 0 ? _a : market.emptyPosition();
178
181
  const funding = this.calcUnrealizedFundingsForPosition({
179
182
  market,
180
183
  position,
@@ -200,9 +203,9 @@ class PerpetualsAccount extends caller_1.Caller {
200
203
  };
201
204
  this.closePositionTxInputs = (inputs) => {
202
205
  var _a;
203
- const { size, market, walletAddress, orderDatas, collateralPrice } = inputs;
206
+ const { size, market, orderDatas, collateralPrice } = inputs;
204
207
  const marketId = market.marketId;
205
- const position = (_a = this.positionForMarketId({ marketId })) !== null && _a !== void 0 ? _a : this.emptyPosition({ marketId });
208
+ const position = (_a = this.positionForMarketId({ marketId })) !== null && _a !== void 0 ? _a : market.emptyPosition();
206
209
  // TODO: move conversion to helper function, since used often
207
210
  const ordersCollateral = __1.Coin.normalizeBalance(utils_1.Helpers.sum(orderDatas
208
211
  .filter((orderData) => orderData.marketId === market.marketId)
@@ -220,31 +223,34 @@ class PerpetualsAccount extends caller_1.Caller {
220
223
  return {
221
224
  size,
222
225
  marketId,
223
- walletAddress,
224
226
  collateralChange,
227
+ accountId: this.accountCap.accountId,
228
+ walletAddress: this.accountCap.walletAddress,
229
+ leverage: position.leverage || 1,
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,
233
+ // hasPosition: this.positionForMarketId({ marketId }) !== undefined,
229
234
  };
230
235
  };
231
- this.emptyPosition = (inputs) => {
232
- const { marketId } = inputs;
233
- return {
234
- marketId,
235
- collateralCoinType: this.accountCap.collateralCoinType,
236
- collateral: BigInt(0),
237
- baseAssetAmount: BigInt(0),
238
- quoteAssetNotionalAmount: BigInt(0),
239
- cumFundingRateLong: BigInt(0),
240
- cumFundingRateShort: BigInt(0),
241
- asksQuantity: BigInt(0),
242
- bidsQuantity: BigInt(0),
243
- pendingOrders: [],
244
- makerFee: BigInt(1000000000000000000),
245
- takerFee: BigInt(1000000000000000000),
246
- leverage: 1,
247
- };
236
+ this.getTxKind = (inputs) => __awaiter(this, void 0, void 0, function* () {
237
+ var _a;
238
+ const { tx } = inputs;
239
+ if (!tx)
240
+ return;
241
+ const txBytes = yield tx.build({
242
+ // NOTE: is this safe ?
243
+ client: (_a = this.Provider) === null || _a === void 0 ? void 0 : _a.provider,
244
+ onlyTransactionKind: true,
245
+ });
246
+ return Buffer.from(txBytes).toString("base64");
247
+ });
248
+ this.useProvider = () => {
249
+ var _a;
250
+ const provider = (_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Perpetuals();
251
+ if (!provider)
252
+ throw new Error("missing AftermathApi Provider");
253
+ return provider;
248
254
  };
249
255
  }
250
256
  // =========================================================================
@@ -255,17 +261,80 @@ class PerpetualsAccount extends caller_1.Caller {
255
261
  // =========================================================================
256
262
  getDepositCollateralTx(inputs) {
257
263
  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 }));
264
+ // return this.fetchApiTransaction<ApiPerpetualsDepositCollateralBody>(
265
+ // "transactions/deposit-collateral",
266
+ // {
267
+ // ...inputs,
268
+ // collateralCoinType: this.accountCap.collateralCoinType,
269
+ // accountCapId: this.accountCap.objectId,
270
+ // }
271
+ // );
272
+ return this.useProvider().fetchBuildDepositCollateralTx(Object.assign(Object.assign({}, inputs), { walletAddress: this.accountCap.walletAddress, collateralCoinType: this.accountCap.collateralCoinType, accountCapId: this.accountCap.objectId }));
259
273
  });
260
274
  }
261
275
  getWithdrawCollateralTx(inputs) {
262
276
  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 }));
277
+ // return this.fetchApiTransaction<ApiPerpetualsWithdrawCollateralBody>(
278
+ // "transactions/withdraw-collateral",
279
+ // {
280
+ // ...inputs,
281
+ // collateralCoinType: this.accountCap.collateralCoinType,
282
+ // accountCapId: this.accountCap.objectId,
283
+ // }
284
+ // );
285
+ return this.useProvider().buildWithdrawCollateralTx(Object.assign(Object.assign({}, inputs), { walletAddress: this.accountCap.walletAddress, collateralCoinType: this.accountCap.collateralCoinType, accountCapId: this.accountCap.objectId }));
286
+ });
287
+ }
288
+ getAllocateCollateralTx(inputs) {
289
+ return __awaiter(this, void 0, void 0, function* () {
290
+ const { market } = inputs;
291
+ // return this.fetchApiTransaction<ApiPerpetualsAllocateCollateralBody>(
292
+ // "transactions/allocate-collateral",
293
+ // {
294
+ // ...inputs,
295
+ // packageId: market.marketData.packageId,
296
+ // marketInitialSharedVersion:
297
+ // market.marketData.initialSharedVersion,
298
+ // marketId: market.marketId,
299
+ // collateralCoinType: this.accountCap.collateralCoinType,
300
+ // accountCapId: this.accountCap.objectId,
301
+ // }
302
+ // );
303
+ return this.useProvider().buildAllocateCollateralTx(Object.assign(Object.assign({}, inputs), { walletAddress: this.accountCap.walletAddress, packageId: market.marketData.packageId, marketInitialSharedVersion: market.marketData.initialSharedVersion, marketId: market.marketId, collateralCoinType: this.accountCap.collateralCoinType, accountCapId: this.accountCap.objectId }));
304
+ });
305
+ }
306
+ getDeallocateCollateralTx(inputs) {
307
+ return __awaiter(this, void 0, void 0, function* () {
308
+ const { market } = inputs;
309
+ // return this.fetchApiTransaction<ApiPerpetualsDeallocateCollateralBody>(
310
+ // "transactions/deallocate-collateral",
311
+ // {
312
+ // ...inputs,
313
+ // packageId: market.marketData.packageId,
314
+ // marketInitialSharedVersion:
315
+ // market.marketData.initialSharedVersion,
316
+ // marketId: market.marketId,
317
+ // basePriceFeedId: market.marketParams.basePriceFeedId,
318
+ // collateralPriceFeedId:
319
+ // market.marketParams.collateralPriceFeedId,
320
+ // collateralCoinType: this.accountCap.collateralCoinType,
321
+ // accountCapId: this.accountCap.objectId,
322
+ // }
323
+ // );
324
+ return this.useProvider().buildDeallocateCollateralTx(Object.assign(Object.assign({}, inputs), { walletAddress: this.accountCap.walletAddress, 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 }));
264
325
  });
265
326
  }
266
327
  getTransferCollateralTx(inputs) {
267
328
  return __awaiter(this, void 0, void 0, function* () {
268
- return this.fetchApiTransaction("transactions/transfer-collateral", Object.assign(Object.assign({}, inputs), { collateralCoinType: this.accountCap.collateralCoinType, fromAccountCapId: this.accountCap.objectId }));
329
+ // return this.fetchApiTransaction<ApiPerpetualsTransferCollateralBody>(
330
+ // "transactions/transfer-collateral",
331
+ // {
332
+ // ...inputs,
333
+ // collateralCoinType: this.accountCap.collateralCoinType,
334
+ // fromAccountCapId: this.accountCap.objectId,
335
+ // }
336
+ // );
337
+ return this.useProvider().buildTransferCollateralTx(Object.assign(Object.assign({}, inputs), { walletAddress: this.accountCap.walletAddress, collateralCoinType: this.accountCap.collateralCoinType, fromAccountCapId: this.accountCap.objectId }));
269
338
  });
270
339
  }
271
340
  // =========================================================================
@@ -273,27 +342,132 @@ class PerpetualsAccount extends caller_1.Caller {
273
342
  // =========================================================================
274
343
  getPlaceMarketOrderTx(inputs) {
275
344
  return __awaiter(this, void 0, void 0, function* () {
276
- 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 }));
345
+ const { tx: txFromInputs, stopLoss, takeProfit, isSponsoredTx } = inputs, otherInputs = __rest(inputs, ["tx", "stopLoss", "takeProfit", "isSponsoredTx"]);
346
+ const tx = txFromInputs !== null && txFromInputs !== void 0 ? txFromInputs : new transactions_1.Transaction();
347
+ // tx.setSender(this.accountCap.walletAddress);
348
+ const slTpArgs = yield this.getSlTpArgs({
349
+ tx,
350
+ stopLoss,
351
+ takeProfit,
352
+ isSponsoredTx,
353
+ });
354
+ return this.fetchApiTransaction("transactions/market-order", Object.assign(Object.assign(Object.assign({}, otherInputs), slTpArgs), { txKind: yield this.getTxKind({ tx }), walletAddress: this.accountCap.walletAddress, accountObjectId: this.accountCap.objectId, accountObjectVersion: this.accountCap.objectVersion, accountObjectDigest: this.accountCap.objectDigest, hasPosition: this.positionForMarketId(otherInputs) !== undefined }), undefined, {
355
+ txKind: true,
356
+ });
277
357
  });
278
358
  }
279
359
  getPlaceLimitOrderTx(inputs) {
280
360
  return __awaiter(this, void 0, void 0, function* () {
281
- 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 }));
361
+ const { tx: txFromInputs, stopLoss, takeProfit, isSponsoredTx } = inputs, otherInputs = __rest(inputs, ["tx", "stopLoss", "takeProfit", "isSponsoredTx"]);
362
+ const tx = txFromInputs !== null && txFromInputs !== void 0 ? txFromInputs : new transactions_1.Transaction();
363
+ // tx.setSender(this.accountCap.walletAddress);
364
+ const slTpArgs = yield this.getSlTpArgs({
365
+ tx,
366
+ stopLoss,
367
+ takeProfit,
368
+ isSponsoredTx,
369
+ });
370
+ return this.fetchApiTransaction("transactions/limit-order", Object.assign(Object.assign(Object.assign({}, otherInputs), slTpArgs), { txKind: yield this.getTxKind({ tx }), walletAddress: this.accountCap.walletAddress, accountObjectId: this.accountCap.objectId, accountObjectVersion: this.accountCap.objectVersion, accountObjectDigest: this.accountCap.objectDigest, hasPosition: this.positionForMarketId(otherInputs) !== undefined }), undefined, {
371
+ txKind: true,
372
+ });
373
+ });
374
+ }
375
+ getCancelOrdersTx(inputs) {
376
+ return __awaiter(this, void 0, void 0, function* () {
377
+ const { tx } = inputs, otherInputs = __rest(inputs, ["tx"]);
378
+ return this.fetchApiTransaction("transactions/cancel-orders", Object.assign(Object.assign({}, otherInputs), { txKind: yield this.getTxKind({ tx }), walletAddress: this.accountCap.walletAddress, accountObjectId: this.accountCap.objectId, accountObjectVersion: this.accountCap.objectVersion, accountObjectDigest: this.accountCap.objectDigest }), undefined, {
379
+ txKind: true,
380
+ });
282
381
  });
283
382
  }
284
- getPlaceSLTPOrder(inputs) {
383
+ getCancelStopOrdersTx(inputs) {
285
384
  return __awaiter(this, void 0, void 0, function* () {
286
- return this.fetchApiTransaction("transactions/sltp-order", Object.assign(Object.assign({}, inputs), { accountObjectId: this.accountCap.objectId, accountObjectVersion: this.accountCap.objectVersion, accountObjectDigest: this.accountCap.objectDigest }));
385
+ const { tx } = inputs, otherInputs = __rest(inputs, ["tx"]);
386
+ return this.fetchApiTransaction("transactions/cancel-stop-orders", Object.assign(Object.assign({}, otherInputs), { txKind: yield this.getTxKind({ tx }), walletAddress: this.accountCap.walletAddress, accountObjectId: this.accountCap.objectId, accountObjectVersion: this.accountCap.objectVersion, accountObjectDigest: this.accountCap.objectDigest }), undefined, {
387
+ txKind: true,
388
+ });
287
389
  });
288
390
  }
289
- getCancelOrderTx(inputs) {
391
+ getPlaceStopOrdersTx(inputs) {
290
392
  return __awaiter(this, void 0, void 0, function* () {
291
- return this.fetchApiTransaction("transactions/cancel-order", Object.assign(Object.assign({}, inputs), { collateralCoinType: this.accountCap.collateralCoinType, accountCapId: this.accountCap.objectId }));
393
+ const { tx: txFromInputs, isSponsoredTx, stopOrders } = inputs;
394
+ const tx = txFromInputs !== null && txFromInputs !== void 0 ? txFromInputs : new transactions_1.Transaction();
395
+ // tx.setSender(this.accountCap.walletAddress);
396
+ if (!this.Provider)
397
+ throw new Error("missing AftermathApi Provider");
398
+ // TODO: handle case of user passed gas coin object(s)
399
+ const gasCoins = yield this.Provider.Coin().fetchCoinsWithAmountTx({
400
+ tx,
401
+ isSponsoredTx,
402
+ coinTypes: inputs.stopOrders.map(() => __1.Coin.constants.suiCoinType),
403
+ walletAddress: this.accountCap.walletAddress,
404
+ coinAmounts: inputs.stopOrders.map(() => perpetuals_1.Perpetuals.constants.stopOrderGasCostSUI),
405
+ });
406
+ return this.fetchApiTransaction("transactions/stop-orders", {
407
+ stopOrders: stopOrders.map((stopOrder, index) => (Object.assign(Object.assign({}, stopOrder), { gasCoin: transactionsApiHelpers_1.TransactionsApiHelpers.serviceCoinDataFromCoinTxArg({
408
+ coinTxArg: gasCoins[index],
409
+ }) }))),
410
+ txKind: yield this.getTxKind({ tx }),
411
+ walletAddress: this.accountCap.walletAddress,
412
+ accountObjectId: this.accountCap.objectId,
413
+ accountObjectVersion: this.accountCap.objectVersion,
414
+ accountObjectDigest: this.accountCap.objectDigest,
415
+ }, undefined, {
416
+ txKind: true,
417
+ });
292
418
  });
293
419
  }
294
- getCancelOrdersTx(inputs) {
420
+ getUpdateStopOrdersTx(inputs) {
295
421
  return __awaiter(this, void 0, void 0, function* () {
296
- return this.fetchApiTransaction("transactions/cancel-orders", Object.assign(Object.assign({}, inputs), { collateralCoinType: this.accountCap.collateralCoinType, accountCapId: this.accountCap.objectId }));
422
+ const { tx: txFromInputs, stopOrders } = inputs;
423
+ const tx = txFromInputs !== null && txFromInputs !== void 0 ? txFromInputs : new transactions_1.Transaction();
424
+ // tx.setSender(this.accountCap.walletAddress);
425
+ return this.fetchApiTransaction("transactions/update-stop-orders", {
426
+ stopOrders,
427
+ txKind: yield this.getTxKind({ tx }),
428
+ walletAddress: this.accountCap.walletAddress,
429
+ accountObjectId: this.accountCap.objectId,
430
+ accountObjectVersion: this.accountCap.objectVersion,
431
+ accountObjectDigest: this.accountCap.objectDigest,
432
+ }, undefined, {
433
+ txKind: true,
434
+ });
435
+ });
436
+ }
437
+ getReduceOrderTx(inputs) {
438
+ var _a;
439
+ return __awaiter(this, void 0, void 0, function* () {
440
+ const { tx } = inputs, otherInputs = __rest(inputs, ["tx"]);
441
+ return this.fetchApiTransaction("transactions/reduce-order", Object.assign(Object.assign({}, otherInputs), { txKind: yield this.getTxKind({ tx }), walletAddress: this.accountCap.walletAddress, accountObjectId: this.accountCap.objectId, accountObjectVersion: this.accountCap.objectVersion, accountObjectDigest: this.accountCap.objectDigest, leverage: ((_a = this.positionForMarketId({ marketId: otherInputs.marketId })) === null || _a === void 0 ? void 0 : _a.leverage) || 1 }), undefined, {
442
+ txKind: true,
443
+ });
444
+ });
445
+ }
446
+ executeSetLeverageTx(inputs) {
447
+ return __awaiter(this, void 0, void 0, function* () {
448
+ const { leverage, tx: txFromInputs } = inputs, otherInputs = __rest(inputs, ["leverage", "tx"]);
449
+ if (inputs.collateralChange === BigInt(0))
450
+ throw new Error("collateralChange cannot be 0");
451
+ const tx = yield this.fetchApiTransaction("transactions/set-leverage", Object.assign(Object.assign({}, otherInputs), { leverage, txKind: yield (() => __awaiter(this, void 0, void 0, function* () {
452
+ var _a;
453
+ if (!txFromInputs)
454
+ return;
455
+ const txBytes = yield txFromInputs.build({
456
+ // NOTE: is this safe ?
457
+ client: (_a = this.Provider) === null || _a === void 0 ? void 0 : _a.provider,
458
+ onlyTransactionKind: true,
459
+ });
460
+ return Buffer.from(txBytes).toString("base64");
461
+ }))(), walletAddress: this.accountCap.walletAddress, accountObjectId: this.accountCap.objectId, accountObjectVersion: this.accountCap.objectVersion, accountObjectDigest: this.accountCap.objectDigest }), undefined, {
462
+ txKind: true,
463
+ });
464
+ const { txDigest } = yield inputs.executeTxCallback({ tx });
465
+ yield this.fetchApi("account/set-position-leverage-from-tx", {
466
+ txDigest,
467
+ leverage,
468
+ accountId: this.accountCap.accountId,
469
+ marketId: inputs.marketId,
470
+ });
297
471
  });
298
472
  }
299
473
  // =========================================================================
@@ -301,15 +475,50 @@ class PerpetualsAccount extends caller_1.Caller {
301
475
  // =========================================================================
302
476
  getClosePositionTx(inputs) {
303
477
  return __awaiter(this, void 0, void 0, function* () {
304
- return this.getPlaceMarketOrderTx(this.closePositionTxInputs(inputs));
478
+ return this.getPlaceMarketOrderTx(Object.assign({}, this.closePositionTxInputs(inputs)));
305
479
  });
306
480
  }
307
481
  // =========================================================================
308
- // Inspections
482
+ // Interactions
309
483
  // =========================================================================
484
+ getStopOrdersMessageToSign(inputs) {
485
+ var _a;
486
+ return {
487
+ action: "GET_STOP_ORDERS",
488
+ account_id: this.accountCap.accountId
489
+ .toString()
490
+ .replaceAll("n", ""),
491
+ clearing_house_ids: (_a = inputs === null || inputs === void 0 ? void 0 : inputs.marketIds) !== null && _a !== void 0 ? _a : [],
492
+ };
493
+ }
494
+ // public cancelStopOrdersMessageToSign(inputs: {
495
+ // orderIds: PerpetualsOrderId[];
496
+ // }): {
497
+ // action: string;
498
+ // order_object_ids: string[];
499
+ // } {
500
+ // return {
501
+ // action: "CANCEL_STOP_ORDERS",
502
+ // order_object_ids: inputs.orderIds.map((orderId) =>
503
+ // orderId.toString().replaceAll("n", "")
504
+ // ),
505
+ // };
506
+ // }
507
+ // public async cancelStopOrders(inputs: {
508
+ // bytes: string;
509
+ // signature: string;
510
+ // }): Promise<boolean> {
511
+ // return this.fetchApi<boolean, ApiPerpetualsCancelStopOrdersBody>(
512
+ // "account/cancel-stop-orders",
513
+ // {
514
+ // ...inputs,
515
+ // walletAddress: this.accountCap.walletAddress,
516
+ // }
517
+ // );
518
+ // }
310
519
  setPositionLeverage(inputs) {
311
520
  return __awaiter(this, void 0, void 0, function* () {
312
- return this.fetchApi(`${this.accountCap.collateralCoinType}/accounts/${this.accountCap.accountId}/set-position-leverage`, inputs);
521
+ return this.fetchApi("account/set-position-leverage", Object.assign(Object.assign({}, inputs), { walletAddress: this.accountCap.walletAddress }));
313
522
  });
314
523
  }
315
524
  // public async getAllPositionLeverages(): Promise<
@@ -324,7 +533,8 @@ class PerpetualsAccount extends caller_1.Caller {
324
533
  // }
325
534
  getPositionLeverages(inputs) {
326
535
  return __awaiter(this, void 0, void 0, function* () {
327
- return this.fetchApi(`${this.accountCap.collateralCoinType}/accounts/${this.accountCap.accountId}/position-leverages/${JSON.stringify(inputs.marketIds)}`);
536
+ // if (inputs.marketIds.length <= 0) return [];
537
+ return this.fetchApi("account/position-leverages", Object.assign(Object.assign({}, inputs), { accountId: this.accountCap.accountId }));
328
538
  });
329
539
  }
330
540
  setPositionLeverageMessageToSign(inputs) {
@@ -334,13 +544,38 @@ class PerpetualsAccount extends caller_1.Caller {
334
544
  leverage: inputs.leverage,
335
545
  };
336
546
  }
337
- getOrderPreview(inputs, abortSignal) {
547
+ getPlaceOrderPreview(inputs, abortSignal) {
548
+ return __awaiter(this, void 0, void 0, function* () {
549
+ return this.fetchApi("previews/place-order", Object.assign(Object.assign({}, inputs), { accountId: this.accountCap.accountId, collateralCoinType: this.accountCap.collateralCoinType, collateral: this.collateralBalance() }), abortSignal);
550
+ });
551
+ }
552
+ getCancelOrdersPreview(inputs, abortSignal) {
553
+ return __awaiter(this, void 0, void 0, function* () {
554
+ // NOTE: should this case return an error instead ?
555
+ if (Object.keys(inputs.marketIdsToData).length <= 0)
556
+ return {
557
+ collateralChange: BigInt(0),
558
+ marketIdsToPositionAfterCancelOrders: {},
559
+ };
560
+ return this.fetchApi("previews/cancel-orders", Object.assign(Object.assign({}, inputs), { accountId: this.accountCap.accountId, collateralCoinType: this.accountCap.collateralCoinType, collateral: this.collateralBalance() }), abortSignal);
561
+ });
562
+ }
563
+ getReduceOrderPreview(inputs, abortSignal) {
564
+ var _a;
338
565
  return __awaiter(this, void 0, void 0, function* () {
339
- const response = yield this.fetchApi("preview-order", Object.assign(Object.assign({}, inputs), { accountId: this.accountCap.accountId, collateralCoinType: this.accountCap.collateralCoinType }), abortSignal);
340
- if ("error" in response)
341
- return response;
342
- const { collateralChange } = response, remainingResponse = __rest(response, ["collateralChange"]);
343
- return Object.assign(Object.assign({}, remainingResponse), { collateralChange: __1.Coin.normalizeBalance(collateralChange, this.collateralDecimals()) });
566
+ return this.fetchApi("previews/reduce-order", Object.assign(Object.assign({}, inputs), { accountId: this.accountCap.accountId, collateralCoinType: this.accountCap.collateralCoinType, collateral: this.collateralBalance(), leverage: ((_a = this.positionForMarketId({ marketId: inputs.marketId })) === null || _a === void 0 ? void 0 : _a.leverage) || 1 }), abortSignal);
567
+ });
568
+ }
569
+ getSetLeveragePreview(inputs, abortSignal) {
570
+ return __awaiter(this, void 0, void 0, function* () {
571
+ const { marketId, leverage } = inputs;
572
+ return this.fetchApi("previews/set-leverage", {
573
+ marketId,
574
+ leverage,
575
+ accountId: this.accountCap.accountId,
576
+ collateralCoinType: this.accountCap.collateralCoinType,
577
+ collateral: this.collateralBalance(),
578
+ }, abortSignal);
344
579
  });
345
580
  }
346
581
  getOrderDatas() {
@@ -354,20 +589,30 @@ class PerpetualsAccount extends caller_1.Caller {
354
589
  ], []);
355
590
  if (orderDatas.length <= 0)
356
591
  return [];
357
- return this.fetchApi(`${this.accountCap.collateralCoinType}/accounts/${this.accountCap.accountId}/order-datas`, {
592
+ return this.fetchApi("account/order-datas", {
593
+ accountId: this.accountCap.accountId,
358
594
  orderDatas,
359
- accountCapId: this.accountCap.objectId,
595
+ });
596
+ });
597
+ }
598
+ getStopOrderDatas(inputs) {
599
+ return __awaiter(this, void 0, void 0, function* () {
600
+ const { bytes, signature } = inputs;
601
+ return this.fetchApi("account/stop-order-datas", {
602
+ walletAddress: this.accountCap.walletAddress,
603
+ bytes,
604
+ signature,
360
605
  });
361
606
  });
362
607
  }
363
608
  getCollateralHistory(inputs) {
364
609
  return __awaiter(this, void 0, void 0, function* () {
365
- return this.fetchApi(`${this.accountCap.collateralCoinType}/accounts/${this.accountCap.accountId}/collateral-history`, Object.assign(Object.assign({}, inputs), { accountCapId: this.accountCap.objectId }));
610
+ return this.fetchApi("account/collateral-history", Object.assign(Object.assign({}, inputs), { accountId: this.accountCap.accountId, collateralCoinType: this.accountCap.collateralCoinType }));
366
611
  });
367
612
  }
368
613
  getOrderHistory(inputs) {
369
614
  return __awaiter(this, void 0, void 0, function* () {
370
- return this.fetchApi(`${this.accountCap.collateralCoinType}/accounts/${this.accountCap.accountId}/order-history`, Object.assign(Object.assign({}, inputs), { accountCapId: this.accountCap.objectId }));
615
+ return this.fetchApi("account/trade-history", Object.assign(Object.assign({}, inputs), { accountId: this.accountCap.accountId }));
371
616
  });
372
617
  }
373
618
  // =========================================================================
@@ -381,6 +626,200 @@ class PerpetualsAccount extends caller_1.Caller {
381
626
  return undefined;
382
627
  }
383
628
  }
629
+ nonSlTpStopOrderDatas(inputs) {
630
+ const { stopOrderDatas } = inputs;
631
+ const slTpOrders = this.slTpStopOrderDatas(inputs);
632
+ const stopOrders = stopOrderDatas.filter((stopOrder) => !(slTpOrders !== null && slTpOrders !== void 0 ? slTpOrders : [])
633
+ .map((slTpOrder) => JSON.stringify(slTpOrder))
634
+ .includes(JSON.stringify(stopOrder)));
635
+ return stopOrders.length <= 0 ? undefined : stopOrders;
636
+ }
637
+ slTpStopOrderDatas(inputs) {
638
+ const { stopOrderDatas } = inputs;
639
+ let slTpOrders = [];
640
+ for (const { marketId } of this.account.positions) {
641
+ const { fullSlOrder, fullTpOrder, partialSlOrders, partialTpOrders, } = this.slTpStopOrderDatasForMarketId({
642
+ marketId,
643
+ stopOrderDatas,
644
+ });
645
+ slTpOrders = [
646
+ ...slTpOrders,
647
+ ...(fullSlOrder ? [fullSlOrder] : []),
648
+ ...(fullTpOrder ? [fullTpOrder] : []),
649
+ ...(partialSlOrders !== null && partialSlOrders !== void 0 ? partialSlOrders : []),
650
+ ...(partialTpOrders !== null && partialTpOrders !== void 0 ? partialTpOrders : []),
651
+ ];
652
+ }
653
+ return slTpOrders.length <= 0 ? undefined : slTpOrders;
654
+ }
655
+ nonSlTpStopOrderDatasForMarketId(inputs) {
656
+ const { marketId, stopOrderDatas } = inputs;
657
+ const position = this.positionForMarketId({ marketId });
658
+ if (!position)
659
+ return undefined;
660
+ const { fullSlOrder, fullTpOrder, partialSlOrders, partialTpOrders } = this.slTpStopOrderDatasForMarketId(inputs);
661
+ const stopOrders = stopOrderDatas.filter((stopOrder) => ![
662
+ ...(fullSlOrder ? [fullSlOrder] : []),
663
+ ...(fullTpOrder ? [fullTpOrder] : []),
664
+ ...(partialSlOrders !== null && partialSlOrders !== void 0 ? partialSlOrders : []),
665
+ ...(partialTpOrders !== null && partialTpOrders !== void 0 ? partialTpOrders : []),
666
+ ]
667
+ .map((slTpOrder) => JSON.stringify(slTpOrder))
668
+ .includes(JSON.stringify(stopOrder)));
669
+ return stopOrders.length <= 0 ? undefined : stopOrders;
670
+ }
671
+ slTpStopOrderDatasForMarketId(inputs) {
672
+ const { marketId, stopOrderDatas } = inputs;
673
+ const position = this.positionForMarketId({ marketId });
674
+ if (!position || position.baseAssetAmount === BigInt(0)) {
675
+ return {
676
+ fullSlOrder: undefined,
677
+ fullTpOrder: undefined,
678
+ partialSlOrders: undefined,
679
+ partialTpOrders: undefined,
680
+ };
681
+ }
682
+ const side = !position ? undefined : perpetuals_1.Perpetuals.positionSide(position);
683
+ // TODO: clean this up
684
+ const fullSlOrder = side === undefined || !position
685
+ ? // TODO: check if at least one order present ? -- if only one order then use that side ?
686
+ stopOrderDatas.find((order) => order.marketId === marketId &&
687
+ // order.side !== side &&
688
+ !("limitOrder" in order) &&
689
+ order.expiryTimestamp >=
690
+ BigInt(Number.MAX_SAFE_INTEGER) &&
691
+ // order.triggerIfGeStopIndexPrice ===
692
+ // (side === PerpetualsOrderSide.Ask) &&
693
+ order.size >= utils_1.Casting.u64MaxBigInt &&
694
+ // (side === PerpetualsOrderSide.Bid
695
+ // ? order.stopIndexPrice < indexPrice
696
+ // : order.stopIndexPrice > indexPrice)
697
+ ((!order.triggerIfGeStopIndexPrice &&
698
+ // order.stopIndexPrice < indexPrice &&
699
+ order.side === types_1.PerpetualsOrderSide.Ask) ||
700
+ (order.triggerIfGeStopIndexPrice &&
701
+ // order.stopIndexPrice > indexPrice &&
702
+ order.side === types_1.PerpetualsOrderSide.Bid)) &&
703
+ order.reduceOnly)
704
+ : stopOrderDatas.find((order) => order.marketId === marketId &&
705
+ order.side !== side &&
706
+ !("limitOrder" in order) &&
707
+ order.expiryTimestamp >=
708
+ BigInt(Number.MAX_SAFE_INTEGER) &&
709
+ order.triggerIfGeStopIndexPrice ===
710
+ (side === types_1.PerpetualsOrderSide.Ask) &&
711
+ order.size >= utils_1.Casting.u64MaxBigInt &&
712
+ (side === types_1.PerpetualsOrderSide.Bid
713
+ ? order.stopIndexPrice <
714
+ perpetuals_1.Perpetuals.calcEntryPrice(position)
715
+ : order.stopIndexPrice >
716
+ perpetuals_1.Perpetuals.calcEntryPrice(position)) &&
717
+ order.reduceOnly);
718
+ const fullTpOrder = side === undefined || !position
719
+ ? // TODO: check if at least one order present ? -- if only one order then use that side ?
720
+ stopOrderDatas.find((order) => order.marketId === marketId &&
721
+ // order.side !== side &&
722
+ !("limitOrder" in order) &&
723
+ order.expiryTimestamp >=
724
+ BigInt(Number.MAX_SAFE_INTEGER) &&
725
+ // order.triggerIfGeStopIndexPrice ===
726
+ // (side === PerpetualsOrderSide.Bid) &&
727
+ order.size >= utils_1.Casting.u64MaxBigInt &&
728
+ // (side === PerpetualsOrderSide.Bid
729
+ // ? order.stopIndexPrice > indexPrice
730
+ // : order.stopIndexPrice < indexPrice)
731
+ ((!order.triggerIfGeStopIndexPrice &&
732
+ // order.stopIndexPrice < indexPrice &&
733
+ order.side === types_1.PerpetualsOrderSide.Bid) ||
734
+ (order.triggerIfGeStopIndexPrice &&
735
+ // order.stopIndexPrice > indexPrice &&
736
+ order.side === types_1.PerpetualsOrderSide.Ask)) &&
737
+ order.reduceOnly)
738
+ : stopOrderDatas.find((order) => order.marketId === marketId &&
739
+ order.side !== side &&
740
+ !("limitOrder" in order) &&
741
+ order.expiryTimestamp >=
742
+ BigInt(Number.MAX_SAFE_INTEGER) &&
743
+ order.triggerIfGeStopIndexPrice ===
744
+ (side === types_1.PerpetualsOrderSide.Bid) &&
745
+ order.size >= utils_1.Casting.u64MaxBigInt &&
746
+ (side === types_1.PerpetualsOrderSide.Bid
747
+ ? order.stopIndexPrice >
748
+ perpetuals_1.Perpetuals.calcEntryPrice(position)
749
+ : order.stopIndexPrice <
750
+ perpetuals_1.Perpetuals.calcEntryPrice(position)) &&
751
+ order.reduceOnly);
752
+ const partialSlOrders = side === undefined || !position
753
+ ? // TODO: check if at least one order present ? -- if only one order then use that side ?
754
+ stopOrderDatas.filter((order) => order.marketId === marketId &&
755
+ // order.side !== side &&
756
+ !("limitOrder" in order) &&
757
+ order.expiryTimestamp >=
758
+ BigInt(Number.MAX_SAFE_INTEGER) &&
759
+ // order.triggerIfGeStopIndexPrice ===
760
+ // (side === PerpetualsOrderSide.Ask) &&
761
+ // (side === PerpetualsOrderSide.Bid
762
+ // ? order.stopIndexPrice < indexPrice
763
+ // : order.stopIndexPrice > indexPrice)
764
+ ((!order.triggerIfGeStopIndexPrice &&
765
+ // order.stopIndexPrice < indexPrice &&
766
+ order.side === types_1.PerpetualsOrderSide.Ask) ||
767
+ (order.triggerIfGeStopIndexPrice &&
768
+ // order.stopIndexPrice > indexPrice &&
769
+ order.side === types_1.PerpetualsOrderSide.Bid)) &&
770
+ order.reduceOnly)
771
+ : stopOrderDatas.filter((order) => order.marketId === marketId &&
772
+ order.side !== side &&
773
+ !("limitOrder" in order) &&
774
+ order.expiryTimestamp >=
775
+ BigInt(Number.MAX_SAFE_INTEGER) &&
776
+ order.triggerIfGeStopIndexPrice ===
777
+ (side === types_1.PerpetualsOrderSide.Ask) &&
778
+ (side === types_1.PerpetualsOrderSide.Bid
779
+ ? order.stopIndexPrice <
780
+ perpetuals_1.Perpetuals.calcEntryPrice(position)
781
+ : order.stopIndexPrice >
782
+ perpetuals_1.Perpetuals.calcEntryPrice(position)) &&
783
+ order.reduceOnly);
784
+ const partialTpOrders = side === undefined || !position
785
+ ? // TODO: check if at least one order present ? -- if only one order then use that side ?
786
+ stopOrderDatas.filter((order) => order.marketId === marketId &&
787
+ // order.side !== side &&
788
+ !("limitOrder" in order) &&
789
+ order.expiryTimestamp >=
790
+ BigInt(Number.MAX_SAFE_INTEGER) &&
791
+ // order.triggerIfGeStopIndexPrice ===
792
+ // (side === PerpetualsOrderSide.Bid) &&
793
+ // (side === PerpetualsOrderSide.Bid
794
+ // ? order.stopIndexPrice > indexPrice
795
+ // : order.stopIndexPrice < indexPrice)
796
+ ((!order.triggerIfGeStopIndexPrice &&
797
+ // order.stopIndexPrice < indexPrice &&
798
+ order.side === types_1.PerpetualsOrderSide.Bid) ||
799
+ (order.triggerIfGeStopIndexPrice &&
800
+ // order.stopIndexPrice > indexPrice &&
801
+ order.side === types_1.PerpetualsOrderSide.Ask)) &&
802
+ order.reduceOnly)
803
+ : stopOrderDatas.filter((order) => order.marketId === marketId &&
804
+ order.side !== side &&
805
+ !("limitOrder" in order) &&
806
+ order.expiryTimestamp >=
807
+ BigInt(Number.MAX_SAFE_INTEGER) &&
808
+ order.triggerIfGeStopIndexPrice ===
809
+ (side === types_1.PerpetualsOrderSide.Bid) &&
810
+ (side === types_1.PerpetualsOrderSide.Bid
811
+ ? order.stopIndexPrice >
812
+ perpetuals_1.Perpetuals.calcEntryPrice(position)
813
+ : order.stopIndexPrice <
814
+ perpetuals_1.Perpetuals.calcEntryPrice(position)) &&
815
+ order.reduceOnly);
816
+ return {
817
+ fullSlOrder,
818
+ fullTpOrder,
819
+ partialSlOrders: partialSlOrders.length <= 0 ? undefined : partialSlOrders,
820
+ partialTpOrders: partialTpOrders.length <= 0 ? undefined : partialTpOrders,
821
+ };
822
+ }
384
823
  collateral() {
385
824
  return utils_1.Casting.IFixed.numberFromIFixed(this.accountCap.collateral);
386
825
  }
@@ -390,6 +829,68 @@ class PerpetualsAccount extends caller_1.Caller {
390
829
  collateralBalance() {
391
830
  return __1.Coin.normalizeBalance(this.collateral(), this.collateralDecimals());
392
831
  }
832
+ // =========================================================================
833
+ // Private Helpers
834
+ // =========================================================================
835
+ getSlTpArgs(inputs) {
836
+ return __awaiter(this, void 0, void 0, function* () {
837
+ const { tx, stopLoss, takeProfit, isSponsoredTx } = inputs;
838
+ if (!this.Provider)
839
+ throw new Error("missing AftermathApi Provider");
840
+ if (!stopLoss && !takeProfit)
841
+ return {};
842
+ let slGasCoin = undefined;
843
+ let tpGasCoin = undefined;
844
+ if (stopLoss && takeProfit) {
845
+ [slGasCoin, tpGasCoin] =
846
+ yield this.Provider.Coin().fetchCoinsWithAmountTx({
847
+ tx,
848
+ isSponsoredTx,
849
+ coinTypes: [
850
+ __1.Coin.constants.suiCoinType,
851
+ __1.Coin.constants.suiCoinType,
852
+ ],
853
+ walletAddress: this.accountCap.walletAddress,
854
+ coinAmounts: [
855
+ perpetuals_1.Perpetuals.constants.stopOrderGasCostSUI,
856
+ perpetuals_1.Perpetuals.constants.stopOrderGasCostSUI,
857
+ ],
858
+ });
859
+ }
860
+ else if (stopLoss) {
861
+ slGasCoin = yield this.Provider.Coin().fetchCoinWithAmountTx({
862
+ tx,
863
+ isSponsoredTx,
864
+ coinType: __1.Coin.constants.suiCoinType,
865
+ walletAddress: this.accountCap.walletAddress,
866
+ coinAmount: perpetuals_1.Perpetuals.constants.stopOrderGasCostSUI,
867
+ });
868
+ }
869
+ else {
870
+ // take profit
871
+ tpGasCoin = yield this.Provider.Coin().fetchCoinWithAmountTx({
872
+ tx,
873
+ isSponsoredTx,
874
+ coinType: __1.Coin.constants.suiCoinType,
875
+ walletAddress: this.accountCap.walletAddress,
876
+ coinAmount: perpetuals_1.Perpetuals.constants.stopOrderGasCostSUI,
877
+ });
878
+ }
879
+ const [stopLossArgs, takeProfitArgs] = [
880
+ stopLoss
881
+ ? {
882
+ stopLoss: Object.assign(Object.assign({}, stopLoss), { gasCoin: transactionsApiHelpers_1.TransactionsApiHelpers.serviceCoinDataFromCoinTxArg({ coinTxArg: slGasCoin }) }),
883
+ }
884
+ : undefined,
885
+ takeProfit
886
+ ? {
887
+ takeProfit: Object.assign(Object.assign({}, takeProfit), { gasCoin: transactionsApiHelpers_1.TransactionsApiHelpers.serviceCoinDataFromCoinTxArg({ coinTxArg: tpGasCoin }) }),
888
+ }
889
+ : undefined,
890
+ ];
891
+ return Object.assign(Object.assign({}, (stopLossArgs !== null && stopLossArgs !== void 0 ? stopLossArgs : {})), (takeProfitArgs !== null && takeProfitArgs !== void 0 ? takeProfitArgs : {}));
892
+ });
893
+ }
393
894
  }
394
895
  exports.PerpetualsAccount = PerpetualsAccount;
395
896
  // =========================================================================