@drift-labs/sdk 0.2.0-master.3 → 0.2.0-master.31

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 (208) hide show
  1. package/README.md +13 -13
  2. package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
  3. package/lib/accounts/bulkUserStatsSubscription.js +21 -0
  4. package/lib/accounts/bulkUserSubscription.js +0 -1
  5. package/lib/accounts/fetch.d.ts +2 -1
  6. package/lib/accounts/fetch.js +9 -1
  7. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +16 -16
  8. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +31 -28
  9. package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
  10. package/lib/accounts/pollingUserStatsAccountSubscriber.js +113 -0
  11. package/lib/accounts/types.d.ts +22 -11
  12. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +17 -17
  13. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +37 -35
  14. package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
  15. package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
  16. package/lib/addresses/marketAddresses.d.ts +1 -3
  17. package/lib/addresses/pda.d.ts +10 -4
  18. package/lib/addresses/pda.js +51 -14
  19. package/lib/admin.d.ts +42 -26
  20. package/lib/admin.js +228 -81
  21. package/lib/clearingHouse.d.ts +130 -49
  22. package/lib/clearingHouse.js +1256 -367
  23. package/lib/clearingHouseConfig.d.ts +4 -4
  24. package/lib/clearingHouseUser.d.ts +51 -39
  25. package/lib/clearingHouseUser.js +408 -191
  26. package/lib/clearingHouseUserStats.d.ts +18 -0
  27. package/lib/clearingHouseUserStats.js +49 -0
  28. package/lib/clearingHouseUserStatsConfig.d.ts +14 -0
  29. package/lib/clearingHouseUserStatsConfig.js +2 -0
  30. package/lib/config.d.ts +7 -9
  31. package/lib/config.js +21 -21
  32. package/lib/constants/numericConstants.d.ts +25 -12
  33. package/lib/constants/numericConstants.js +35 -21
  34. package/lib/constants/perpMarkets.d.ts +18 -0
  35. package/lib/constants/{markets.js → perpMarkets.js} +7 -7
  36. package/lib/constants/spotMarkets.d.ts +19 -0
  37. package/lib/constants/spotMarkets.js +53 -0
  38. package/lib/dlob/DLOB.d.ts +74 -0
  39. package/lib/dlob/DLOB.js +595 -0
  40. package/lib/dlob/DLOBNode.d.ts +54 -0
  41. package/lib/dlob/DLOBNode.js +85 -0
  42. package/lib/dlob/NodeList.d.ts +26 -0
  43. package/lib/dlob/NodeList.js +139 -0
  44. package/lib/events/eventList.js +3 -0
  45. package/lib/events/eventSubscriber.d.ts +4 -2
  46. package/lib/events/eventSubscriber.js +16 -9
  47. package/lib/events/fetchLogs.d.ts +10 -1
  48. package/lib/events/fetchLogs.js +27 -7
  49. package/lib/events/pollingLogProvider.d.ts +2 -1
  50. package/lib/events/pollingLogProvider.js +6 -2
  51. package/lib/events/sort.js +8 -11
  52. package/lib/events/types.d.ts +8 -2
  53. package/lib/events/types.js +6 -0
  54. package/lib/examples/makeTradeExample.js +20 -8
  55. package/lib/factory/bigNum.d.ts +2 -0
  56. package/lib/factory/bigNum.js +48 -10
  57. package/lib/idl/clearing_house.json +4889 -1529
  58. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  59. package/lib/index.d.ts +21 -6
  60. package/lib/index.js +25 -6
  61. package/lib/math/amm.d.ts +9 -6
  62. package/lib/math/amm.js +91 -66
  63. package/lib/math/auction.js +4 -1
  64. package/lib/math/conversion.js +1 -1
  65. package/lib/math/funding.d.ts +6 -6
  66. package/lib/math/funding.js +11 -10
  67. package/lib/math/insurance.d.ts +4 -0
  68. package/lib/math/insurance.js +27 -0
  69. package/lib/math/margin.d.ts +11 -0
  70. package/lib/math/margin.js +77 -0
  71. package/lib/math/market.d.ts +14 -9
  72. package/lib/math/market.js +72 -10
  73. package/lib/math/oracles.d.ts +4 -0
  74. package/lib/math/oracles.js +36 -8
  75. package/lib/math/orders.d.ts +6 -2
  76. package/lib/math/orders.js +78 -3
  77. package/lib/math/position.d.ts +21 -13
  78. package/lib/math/position.js +76 -36
  79. package/lib/math/repeg.js +14 -5
  80. package/lib/math/spotBalance.d.ts +22 -0
  81. package/lib/math/spotBalance.js +192 -0
  82. package/lib/math/spotMarket.d.ts +4 -0
  83. package/lib/math/spotMarket.js +8 -0
  84. package/lib/math/spotPosition.d.ts +6 -0
  85. package/lib/math/spotPosition.js +23 -0
  86. package/lib/math/trade.d.ts +10 -10
  87. package/lib/math/trade.js +32 -39
  88. package/lib/oracles/pythClient.js +1 -1
  89. package/lib/oracles/quoteAssetOracleClient.js +1 -1
  90. package/lib/oracles/switchboardClient.js +1 -1
  91. package/lib/orderParams.d.ts +14 -5
  92. package/lib/orderParams.js +12 -92
  93. package/lib/serum/serumSubscriber.d.ts +23 -0
  94. package/lib/serum/serumSubscriber.js +41 -0
  95. package/lib/serum/types.d.ts +11 -0
  96. package/lib/serum/types.js +2 -0
  97. package/lib/slot/SlotSubscriber.d.ts +7 -0
  98. package/lib/slot/SlotSubscriber.js +3 -0
  99. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  100. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  101. package/lib/tx/retryTxSender.d.ts +1 -1
  102. package/lib/tx/retryTxSender.js +13 -4
  103. package/lib/tx/types.d.ts +1 -1
  104. package/lib/tx/utils.js +1 -1
  105. package/lib/types.d.ts +566 -138
  106. package/lib/types.js +129 -5
  107. package/lib/userMap/userMap.d.ts +25 -0
  108. package/lib/userMap/userMap.js +73 -0
  109. package/lib/userMap/userStatsMap.d.ts +19 -0
  110. package/lib/userMap/userStatsMap.js +68 -0
  111. package/lib/util/computeUnits.js +1 -1
  112. package/lib/util/getTokenAddress.d.ts +2 -0
  113. package/lib/util/getTokenAddress.js +9 -0
  114. package/package.json +12 -6
  115. package/src/accounts/bulkUserStatsSubscription.ts +33 -0
  116. package/src/accounts/bulkUserSubscription.ts +0 -1
  117. package/src/accounts/fetch.ts +27 -2
  118. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +46 -42
  119. package/src/accounts/pollingUserStatsAccountSubscriber.ts +172 -0
  120. package/src/accounts/types.ts +31 -11
  121. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +64 -59
  122. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
  123. package/src/addresses/marketAddresses.ts +1 -2
  124. package/src/addresses/pda.ts +88 -14
  125. package/src/admin.ts +452 -147
  126. package/src/assert/assert.js +9 -0
  127. package/src/clearingHouse.ts +2066 -467
  128. package/src/clearingHouseConfig.ts +4 -3
  129. package/src/clearingHouseUser.ts +747 -294
  130. package/src/clearingHouseUserStats.ts +75 -0
  131. package/src/clearingHouseUserStatsConfig.ts +18 -0
  132. package/src/config.ts +30 -31
  133. package/src/constants/numericConstants.ts +48 -25
  134. package/src/constants/{markets.ts → perpMarkets.ts} +10 -10
  135. package/src/constants/spotMarkets.ts +73 -0
  136. package/src/dlob/DLOB.ts +953 -0
  137. package/src/dlob/DLOBNode.ts +167 -0
  138. package/src/dlob/NodeList.ts +189 -0
  139. package/src/events/eventList.js +77 -0
  140. package/src/events/eventList.ts +3 -0
  141. package/src/events/eventSubscriber.ts +20 -12
  142. package/src/events/fetchLogs.ts +35 -8
  143. package/src/events/pollingLogProvider.ts +10 -2
  144. package/src/events/sort.ts +11 -15
  145. package/src/events/types.ts +19 -1
  146. package/src/examples/makeTradeExample.js +157 -0
  147. package/src/examples/makeTradeExample.ts +32 -14
  148. package/src/factory/bigNum.ts +65 -13
  149. package/src/idl/clearing_house.json +4889 -1529
  150. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  151. package/src/index.ts +21 -6
  152. package/src/math/amm.ts +171 -88
  153. package/src/math/auction.ts +5 -1
  154. package/src/math/conversion.ts +2 -2
  155. package/src/math/funding.ts +20 -18
  156. package/src/math/insurance.ts +35 -0
  157. package/src/math/margin.ts +127 -0
  158. package/src/math/market.ts +145 -14
  159. package/src/math/oracles.ts +63 -9
  160. package/src/math/orders.ts +138 -4
  161. package/src/math/position.ts +119 -58
  162. package/src/math/repeg.ts +16 -6
  163. package/src/math/spotBalance.ts +319 -0
  164. package/src/math/spotMarket.ts +9 -0
  165. package/src/math/spotPosition.ts +47 -0
  166. package/src/math/trade.ts +53 -59
  167. package/src/oracles/pythClient.ts +2 -2
  168. package/src/oracles/quoteAssetOracleClient.ts +2 -2
  169. package/src/oracles/switchboardClient.ts +2 -2
  170. package/src/orderParams.ts +24 -137
  171. package/src/serum/serumSubscriber.ts +80 -0
  172. package/src/serum/types.ts +13 -0
  173. package/src/slot/SlotSubscriber.ts +11 -1
  174. package/src/token/index.js +38 -0
  175. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  176. package/src/tx/retryTxSender.ts +16 -5
  177. package/src/tx/types.js +2 -0
  178. package/src/tx/types.ts +2 -1
  179. package/src/tx/utils.js +17 -0
  180. package/src/tx/utils.ts +1 -1
  181. package/src/types.ts +533 -140
  182. package/src/userMap/userMap.ts +100 -0
  183. package/src/userMap/userStatsMap.ts +110 -0
  184. package/src/util/computeUnits.js +21 -11
  185. package/src/util/computeUnits.ts +1 -1
  186. package/src/util/getTokenAddress.js +9 -0
  187. package/src/util/getTokenAddress.ts +18 -0
  188. package/src/util/promiseTimeout.js +14 -0
  189. package/src/util/tps.js +27 -0
  190. package/tests/bn/test.ts +24 -10
  191. package/tests/dlob/helpers.ts +397 -0
  192. package/tests/dlob/test.ts +3688 -0
  193. package/lib/constants/banks.d.ts +0 -16
  194. package/lib/constants/banks.js +0 -34
  195. package/lib/constants/markets.d.ts +0 -19
  196. package/lib/math/bankBalance.d.ts +0 -9
  197. package/lib/math/bankBalance.js +0 -75
  198. package/lib/math/state.d.ts +0 -8
  199. package/lib/math/state.js +0 -15
  200. package/lib/orders.d.ts +0 -8
  201. package/lib/orders.js +0 -134
  202. package/src/constants/banks.ts +0 -43
  203. package/src/math/bankBalance.ts +0 -112
  204. package/src/math/state.ts +0 -14
  205. package/src/math/utils.js +0 -27
  206. package/src/math/utils.js.map +0 -1
  207. package/src/orders.ts +0 -244
  208. package/src/util/computeUnits.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  /// <reference types="bn.js" />
2
- import { BN } from '../';
2
+ import { BN, SpotMarketAccount } from '../';
3
3
  import { OraclePriceData } from '../oracles/types';
4
- import { MarketAccount, PositionDirection, UserPosition } from '../types';
4
+ import { PerpMarketAccount, PositionDirection, PerpPosition } from '../types';
5
5
  /**
6
6
  * calculateBaseAssetValue
7
7
  * = market value of closing entire position
@@ -10,30 +10,38 @@ import { MarketAccount, PositionDirection, UserPosition } from '../types';
10
10
  * @param oraclePriceData
11
11
  * @returns Base Asset Value. : Precision QUOTE_PRECISION
12
12
  */
13
- export declare function calculateBaseAssetValue(market: MarketAccount, userPosition: UserPosition, oraclePriceData: OraclePriceData): BN;
13
+ export declare function calculateBaseAssetValue(market: PerpMarketAccount, userPosition: PerpPosition, oraclePriceData: OraclePriceData, useSpread?: boolean, skipUpdate?: boolean): BN;
14
14
  /**
15
15
  * calculatePositionPNL
16
16
  * = BaseAssetAmount * (Avg Exit Price - Avg Entry Price)
17
17
  * @param market
18
- * @param marketPosition
18
+ * @param PerpPosition
19
19
  * @param withFunding (adds unrealized funding payment pnl to result)
20
+ * @param oraclePriceData
20
21
  * @returns BaseAssetAmount : Precision QUOTE_PRECISION
21
22
  */
22
- export declare function calculatePositionPNL(market: MarketAccount, marketPosition: UserPosition, withFunding: boolean, oraclePriceData: OraclePriceData): BN;
23
+ export declare function calculatePositionPNL(market: PerpMarketAccount, perpPosition: PerpPosition, withFunding: boolean, oraclePriceData: OraclePriceData): BN;
24
+ export declare function calculateClaimablePnl(market: PerpMarketAccount, spotMarket: SpotMarketAccount, perpPosition: PerpPosition, oraclePriceData: OraclePriceData): BN;
23
25
  /**
24
26
  *
25
27
  * @param market
26
- * @param marketPosition
28
+ * @param PerpPosition
27
29
  * @returns // TODO-PRECISION
28
30
  */
29
- export declare function calculatePositionFundingPNL(market: MarketAccount, marketPosition: UserPosition): BN;
30
- export declare function positionIsAvailable(position: UserPosition): boolean;
31
+ export declare function calculatePositionFundingPNL(market: PerpMarketAccount, perpPosition: PerpPosition): BN;
32
+ export declare function positionIsAvailable(position: PerpPosition): boolean;
33
+ /**
34
+ *
35
+ * @param userPosition
36
+ * @returns Precision: PRICE_PRECISION (10^10)
37
+ */
38
+ export declare function calculateEntryPrice(userPosition: PerpPosition): BN;
31
39
  /**
32
40
  *
33
41
  * @param userPosition
34
- * @returns Precision: MARK_PRICE_PRECISION (10^10)
42
+ * @returns Precision: PRICE_PRECISION (10^10)
35
43
  */
36
- export declare function calculateEntryPrice(userPosition: UserPosition): BN;
37
- export declare function findDirectionToClose(userPosition: UserPosition): PositionDirection;
38
- export declare function positionCurrentDirection(userPosition: UserPosition): PositionDirection;
39
- export declare function isEmptyPosition(userPosition: UserPosition): boolean;
44
+ export declare function calculateCostBasis(userPosition: PerpPosition): BN;
45
+ export declare function findDirectionToClose(userPosition: PerpPosition): PositionDirection;
46
+ export declare function positionCurrentDirection(userPosition: PerpPosition): PositionDirection;
47
+ export declare function isEmptyPosition(userPosition: PerpPosition): boolean;
@@ -1,10 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isEmptyPosition = exports.positionCurrentDirection = exports.findDirectionToClose = exports.calculateEntryPrice = exports.positionIsAvailable = exports.calculatePositionFundingPNL = exports.calculatePositionPNL = exports.calculateBaseAssetValue = void 0;
3
+ exports.isEmptyPosition = exports.positionCurrentDirection = exports.findDirectionToClose = exports.calculateCostBasis = exports.calculateEntryPrice = exports.positionIsAvailable = exports.calculatePositionFundingPNL = exports.calculateClaimablePnl = exports.calculatePositionPNL = exports.calculateBaseAssetValue = void 0;
4
4
  const __1 = require("../");
5
5
  const numericConstants_1 = require("../constants/numericConstants");
6
6
  const types_1 = require("../types");
7
7
  const amm_1 = require("./amm");
8
+ const margin_1 = require("./margin");
9
+ const market_1 = require("./market");
8
10
  /**
9
11
  * calculateBaseAssetValue
10
12
  * = market value of closing entire position
@@ -13,23 +15,28 @@ const amm_1 = require("./amm");
13
15
  * @param oraclePriceData
14
16
  * @returns Base Asset Value. : Precision QUOTE_PRECISION
15
17
  */
16
- function calculateBaseAssetValue(market, userPosition, oraclePriceData) {
18
+ function calculateBaseAssetValue(market, userPosition, oraclePriceData, useSpread = true, skipUpdate = false) {
17
19
  if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
18
20
  return numericConstants_1.ZERO;
19
21
  }
20
22
  const directionToClose = findDirectionToClose(userPosition);
21
23
  let prepegAmm;
22
- if (market.amm.baseSpread > 0) {
23
- const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } = (0, amm_1.calculateUpdatedAMMSpreadReserves)(market.amm, directionToClose, oraclePriceData);
24
- prepegAmm = {
25
- baseAssetReserve,
26
- quoteAssetReserve,
27
- sqrtK: sqrtK,
28
- pegMultiplier: newPeg,
29
- };
24
+ if (!skipUpdate) {
25
+ if (market.amm.baseSpread > 0 && useSpread) {
26
+ const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } = (0, amm_1.calculateUpdatedAMMSpreadReserves)(market.amm, directionToClose, oraclePriceData);
27
+ prepegAmm = {
28
+ baseAssetReserve,
29
+ quoteAssetReserve,
30
+ sqrtK: sqrtK,
31
+ pegMultiplier: newPeg,
32
+ };
33
+ }
34
+ else {
35
+ prepegAmm = (0, amm_1.calculateUpdatedAMM)(market.amm, oraclePriceData);
36
+ }
30
37
  }
31
38
  else {
32
- prepegAmm = (0, amm_1.calculateUpdatedAMM)(market.amm, oraclePriceData);
39
+ prepegAmm = market.amm;
33
40
  }
34
41
  const [newQuoteAssetReserve, _] = (0, amm_1.calculateAmmReservesAfterSwap)(prepegAmm, 'base', userPosition.baseAssetAmount.abs(), (0, amm_1.getSwapDirection)('base', directionToClose));
35
42
  switch (directionToClose) {
@@ -51,75 +58,108 @@ exports.calculateBaseAssetValue = calculateBaseAssetValue;
51
58
  * calculatePositionPNL
52
59
  * = BaseAssetAmount * (Avg Exit Price - Avg Entry Price)
53
60
  * @param market
54
- * @param marketPosition
61
+ * @param PerpPosition
55
62
  * @param withFunding (adds unrealized funding payment pnl to result)
63
+ * @param oraclePriceData
56
64
  * @returns BaseAssetAmount : Precision QUOTE_PRECISION
57
65
  */
58
- function calculatePositionPNL(market, marketPosition, withFunding = false, oraclePriceData) {
59
- if (marketPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
60
- return numericConstants_1.ZERO;
61
- }
62
- const baseAssetValue = calculateBaseAssetValue(market, marketPosition, oraclePriceData);
63
- let pnl;
64
- if (marketPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
65
- pnl = baseAssetValue.sub(marketPosition.quoteAssetAmount);
66
- }
67
- else {
68
- pnl = marketPosition.quoteAssetAmount.sub(baseAssetValue);
66
+ function calculatePositionPNL(market, perpPosition, withFunding = false, oraclePriceData) {
67
+ if (perpPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
68
+ return perpPosition.quoteAssetAmount;
69
69
  }
70
+ const baseAssetValue = (0, margin_1.calculateBaseAssetValueWithOracle)(market, perpPosition, oraclePriceData);
71
+ const baseAssetValueSign = perpPosition.baseAssetAmount.isNeg()
72
+ ? new __1.BN(-1)
73
+ : new __1.BN(1);
74
+ let pnl = baseAssetValue
75
+ .mul(baseAssetValueSign)
76
+ .add(perpPosition.quoteAssetAmount);
70
77
  if (withFunding) {
71
- const fundingRatePnL = calculatePositionFundingPNL(market, marketPosition).div(numericConstants_1.PRICE_TO_QUOTE_PRECISION);
78
+ const fundingRatePnL = calculatePositionFundingPNL(market, perpPosition);
72
79
  pnl = pnl.add(fundingRatePnL);
73
80
  }
74
81
  return pnl;
75
82
  }
76
83
  exports.calculatePositionPNL = calculatePositionPNL;
84
+ function calculateClaimablePnl(market, spotMarket, perpPosition, oraclePriceData) {
85
+ const unrealizedPnl = calculatePositionPNL(market, perpPosition, true, oraclePriceData);
86
+ const fundingPnL = calculatePositionFundingPNL(market, perpPosition);
87
+ let unsettledPnl = unrealizedPnl.add(fundingPnL);
88
+ if (unrealizedPnl.gt(numericConstants_1.ZERO)) {
89
+ const excessPnlPool = __1.BN.max(numericConstants_1.ZERO, (0, market_1.calculateNetUserPnlImbalance)(market, spotMarket, oraclePriceData).mul(new __1.BN(-1)));
90
+ const maxPositivePnl = __1.BN.max(perpPosition.quoteAssetAmount
91
+ .sub(perpPosition.quoteEntryAmount)
92
+ .add(excessPnlPool), numericConstants_1.ZERO);
93
+ unsettledPnl = __1.BN.min(maxPositivePnl, unrealizedPnl);
94
+ }
95
+ return unsettledPnl;
96
+ }
97
+ exports.calculateClaimablePnl = calculateClaimablePnl;
77
98
  /**
78
99
  *
79
100
  * @param market
80
- * @param marketPosition
101
+ * @param PerpPosition
81
102
  * @returns // TODO-PRECISION
82
103
  */
83
- function calculatePositionFundingPNL(market, marketPosition) {
84
- if (marketPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
104
+ function calculatePositionFundingPNL(market, perpPosition) {
105
+ if (perpPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
85
106
  return numericConstants_1.ZERO;
86
107
  }
87
108
  let ammCumulativeFundingRate;
88
- if (marketPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
109
+ if (perpPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
89
110
  ammCumulativeFundingRate = market.amm.cumulativeFundingRateLong;
90
111
  }
91
112
  else {
92
113
  ammCumulativeFundingRate = market.amm.cumulativeFundingRateShort;
93
114
  }
94
115
  const perPositionFundingRate = ammCumulativeFundingRate
95
- .sub(marketPosition.lastCumulativeFundingRate)
96
- .mul(marketPosition.baseAssetAmount)
116
+ .sub(perpPosition.lastCumulativeFundingRate)
117
+ .mul(perpPosition.baseAssetAmount)
97
118
  .div(numericConstants_1.AMM_RESERVE_PRECISION)
98
- .div(numericConstants_1.FUNDING_PAYMENT_PRECISION)
119
+ .div(numericConstants_1.FUNDING_RATE_BUFFER_PRECISION)
99
120
  .mul(new __1.BN(-1));
100
121
  return perPositionFundingRate;
101
122
  }
102
123
  exports.calculatePositionFundingPNL = calculatePositionFundingPNL;
103
124
  function positionIsAvailable(position) {
104
- return position.baseAssetAmount.eq(numericConstants_1.ZERO) && position.openOrders.eq(numericConstants_1.ZERO);
125
+ return (position.baseAssetAmount.eq(numericConstants_1.ZERO) &&
126
+ position.openOrders === 0 &&
127
+ position.quoteAssetAmount.eq(numericConstants_1.ZERO) &&
128
+ position.lpShares.eq(numericConstants_1.ZERO));
105
129
  }
106
130
  exports.positionIsAvailable = positionIsAvailable;
107
131
  /**
108
132
  *
109
133
  * @param userPosition
110
- * @returns Precision: MARK_PRICE_PRECISION (10^10)
134
+ * @returns Precision: PRICE_PRECISION (10^10)
111
135
  */
112
136
  function calculateEntryPrice(userPosition) {
113
137
  if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
114
138
  return numericConstants_1.ZERO;
115
139
  }
116
- return userPosition.quoteAssetAmount
117
- .mul(numericConstants_1.MARK_PRICE_PRECISION)
140
+ return userPosition.quoteEntryAmount
141
+ .mul(numericConstants_1.PRICE_PRECISION)
118
142
  .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
119
143
  .div(userPosition.baseAssetAmount)
120
144
  .abs();
121
145
  }
122
146
  exports.calculateEntryPrice = calculateEntryPrice;
147
+ /**
148
+ *
149
+ * @param userPosition
150
+ * @returns Precision: PRICE_PRECISION (10^10)
151
+ */
152
+ function calculateCostBasis(userPosition) {
153
+ if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
154
+ return numericConstants_1.ZERO;
155
+ }
156
+ return userPosition.quoteAssetAmount
157
+ .mul(numericConstants_1.PRICE_PRECISION)
158
+ .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
159
+ .div(userPosition.baseAssetAmount)
160
+ .abs();
161
+ }
162
+ exports.calculateCostBasis = calculateCostBasis;
123
163
  function findDirectionToClose(userPosition) {
124
164
  return userPosition.baseAssetAmount.gt(numericConstants_1.ZERO)
125
165
  ? types_1.PositionDirection.SHORT
@@ -133,6 +173,6 @@ function positionCurrentDirection(userPosition) {
133
173
  }
134
174
  exports.positionCurrentDirection = positionCurrentDirection;
135
175
  function isEmptyPosition(userPosition) {
136
- return (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO) && userPosition.openOrders.eq(numericConstants_1.ZERO));
176
+ return userPosition.baseAssetAmount.eq(numericConstants_1.ZERO) && userPosition.openOrders === 0;
137
177
  }
138
178
  exports.isEmptyPosition = isEmptyPosition;
package/lib/math/repeg.js CHANGED
@@ -18,13 +18,13 @@ function calculateAdjustKCost(amm, numerator, denomenator) {
18
18
  const d = amm.netBaseAssetAmount;
19
19
  const Q = amm.pegMultiplier;
20
20
  const quoteScale = y.mul(d).mul(Q); //.div(AMM_RESERVE_PRECISION);
21
- const p = numerator.mul(numericConstants_1.MARK_PRICE_PRECISION).div(denomenator);
21
+ const p = numerator.mul(numericConstants_1.PRICE_PRECISION).div(denomenator);
22
22
  const cost = quoteScale
23
23
  .div(x.add(d))
24
24
  .sub(quoteScale
25
25
  .mul(p)
26
- .div(numericConstants_1.MARK_PRICE_PRECISION)
27
- .div(x.mul(p).div(numericConstants_1.MARK_PRICE_PRECISION).add(d)))
26
+ .div(numericConstants_1.PRICE_PRECISION)
27
+ .div(x.mul(p).div(numericConstants_1.PRICE_PRECISION).add(d)))
28
28
  .div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
29
29
  .div(numericConstants_1.PEG_PRECISION);
30
30
  return cost.mul(new anchor_1.BN(-1));
@@ -71,6 +71,15 @@ function calculateBudgetedKBN(x, y, budget, Q, d) {
71
71
  .div(numericConstants_1.AMM_RESERVE_PRECISION)
72
72
  .div(numericConstants_1.QUOTE_PRECISION);
73
73
  const denom2 = pegged_y_d_d;
74
+ // protocol is spending to increase k
75
+ if (C.lt(numericConstants_1.ZERO)) {
76
+ // thus denom1 is negative and solution is unstable
77
+ if (denom1.abs().gt(denom2.abs())) {
78
+ console.log('denom1 > denom2', denom1.toString(), denom2.toString());
79
+ console.log('budget cost exceeds stable K solution');
80
+ return [new anchor_1.BN(10000), new anchor_1.BN(1)];
81
+ }
82
+ }
74
83
  const numerator = numer1.sub(numer2).div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
75
84
  const denominator = denom1.add(denom2).div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
76
85
  return [numerator, denominator];
@@ -121,8 +130,8 @@ function calculateBudgetedPeg(amm, cost, targetPrice) {
121
130
  if (deltaQuoteAssetReserves.eq(numericConstants_1.ZERO) || useTargetPeg) {
122
131
  return targetPeg;
123
132
  }
124
- const deltaPegMultiplier = C.mul(numericConstants_1.MARK_PRICE_PRECISION).div(deltaQuoteAssetReserves.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO));
125
- const newPeg = Q.sub(deltaPegMultiplier.mul(numericConstants_1.PEG_PRECISION).div(numericConstants_1.MARK_PRICE_PRECISION));
133
+ const deltaPegMultiplier = C.mul(numericConstants_1.PRICE_PRECISION).div(deltaQuoteAssetReserves.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO));
134
+ const newPeg = Q.sub(deltaPegMultiplier.mul(numericConstants_1.PEG_PRECISION).div(numericConstants_1.PRICE_PRECISION));
126
135
  return newPeg;
127
136
  }
128
137
  exports.calculateBudgetedPeg = calculateBudgetedPeg;
@@ -0,0 +1,22 @@
1
+ /// <reference types="bn.js" />
2
+ import { SpotMarketAccount, SpotBalanceType, MarginCategory } from '../types';
3
+ import { BN } from '@project-serum/anchor';
4
+ import { OraclePriceData } from '../oracles/types';
5
+ export declare function getBalance(tokenAmount: BN, spotMarket: SpotMarketAccount, balanceType: SpotBalanceType): BN;
6
+ export declare function getTokenAmount(balanceAmount: BN, spotMarket: SpotMarketAccount, balanceType: SpotBalanceType): BN;
7
+ export declare function getSignedTokenAmount(tokenAmount: BN, balanceType: SpotBalanceType): BN;
8
+ export declare function getTokenValue(tokenAmount: BN, spotDecimals: number, oraclePriceData: OraclePriceData): BN;
9
+ export declare function calculateAssetWeight(balanceAmount: BN, spotMarket: SpotMarketAccount, marginCategory: MarginCategory): BN;
10
+ export declare function calculateLiabilityWeight(balanceAmount: BN, spotMarket: SpotMarketAccount, marginCategory: MarginCategory): BN;
11
+ export declare function calculateUtilization(bank: SpotMarketAccount): BN;
12
+ export declare function calculateInterestRate(bank: SpotMarketAccount): BN;
13
+ export declare function calculateDepositRate(bank: SpotMarketAccount): BN;
14
+ export declare function calculateBorrowRate(bank: SpotMarketAccount): BN;
15
+ export declare function calculateInterestAccumulated(bank: SpotMarketAccount, now: BN): {
16
+ borrowInterest: BN;
17
+ depositInterest: BN;
18
+ };
19
+ export declare function calculateWithdrawLimit(spotMarket: SpotMarketAccount, now: BN): {
20
+ borrowLimit: BN;
21
+ withdrawLimit: BN;
22
+ };
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.calculateWithdrawLimit = exports.calculateInterestAccumulated = exports.calculateBorrowRate = exports.calculateDepositRate = exports.calculateInterestRate = exports.calculateUtilization = exports.calculateLiabilityWeight = exports.calculateAssetWeight = exports.getTokenValue = exports.getSignedTokenAmount = exports.getTokenAmount = exports.getBalance = void 0;
4
+ const types_1 = require("../types");
5
+ const anchor_1 = require("@project-serum/anchor");
6
+ const numericConstants_1 = require("../constants/numericConstants");
7
+ const margin_1 = require("./margin");
8
+ function getBalance(tokenAmount, spotMarket, balanceType) {
9
+ const precisionIncrease = numericConstants_1.TEN.pow(new anchor_1.BN(19 - spotMarket.decimals));
10
+ const cumulativeInterest = (0, types_1.isVariant)(balanceType, 'deposit')
11
+ ? spotMarket.cumulativeDepositInterest
12
+ : spotMarket.cumulativeBorrowInterest;
13
+ let balance = tokenAmount.mul(precisionIncrease).div(cumulativeInterest);
14
+ if (!balance.eq(numericConstants_1.ZERO) && (0, types_1.isVariant)(balanceType, 'borrow')) {
15
+ balance = balance.add(numericConstants_1.ONE);
16
+ }
17
+ return balance;
18
+ }
19
+ exports.getBalance = getBalance;
20
+ function getTokenAmount(balanceAmount, spotMarket, balanceType) {
21
+ const precisionDecrease = numericConstants_1.TEN.pow(new anchor_1.BN(19 - spotMarket.decimals));
22
+ const cumulativeInterest = (0, types_1.isVariant)(balanceType, 'deposit')
23
+ ? spotMarket.cumulativeDepositInterest
24
+ : spotMarket.cumulativeBorrowInterest;
25
+ return balanceAmount.mul(cumulativeInterest).div(precisionDecrease);
26
+ }
27
+ exports.getTokenAmount = getTokenAmount;
28
+ function getSignedTokenAmount(tokenAmount, balanceType) {
29
+ if ((0, types_1.isVariant)(balanceType, 'deposit')) {
30
+ return tokenAmount;
31
+ }
32
+ else {
33
+ return tokenAmount.abs().neg();
34
+ }
35
+ }
36
+ exports.getSignedTokenAmount = getSignedTokenAmount;
37
+ function getTokenValue(tokenAmount, spotDecimals, oraclePriceData) {
38
+ if (tokenAmount.eq(numericConstants_1.ZERO)) {
39
+ return numericConstants_1.ZERO;
40
+ }
41
+ const precisionDecrease = numericConstants_1.TEN.pow(new anchor_1.BN(spotDecimals));
42
+ return tokenAmount.mul(oraclePriceData.price).div(precisionDecrease);
43
+ }
44
+ exports.getTokenValue = getTokenValue;
45
+ function calculateAssetWeight(balanceAmount, spotMarket, marginCategory) {
46
+ const sizePrecision = numericConstants_1.TEN.pow(new anchor_1.BN(spotMarket.decimals));
47
+ let sizeInAmmReservePrecision;
48
+ if (sizePrecision.gt(numericConstants_1.AMM_RESERVE_PRECISION)) {
49
+ sizeInAmmReservePrecision = balanceAmount.div(sizePrecision.div(numericConstants_1.AMM_RESERVE_PRECISION));
50
+ }
51
+ else {
52
+ sizeInAmmReservePrecision = balanceAmount
53
+ .mul(numericConstants_1.AMM_RESERVE_PRECISION)
54
+ .div(sizePrecision);
55
+ }
56
+ let assetWeight;
57
+ switch (marginCategory) {
58
+ case 'Initial':
59
+ assetWeight = (0, margin_1.calculateSizeDiscountAssetWeight)(sizeInAmmReservePrecision, spotMarket.imfFactor, spotMarket.initialAssetWeight);
60
+ break;
61
+ case 'Maintenance':
62
+ assetWeight = (0, margin_1.calculateSizeDiscountAssetWeight)(sizeInAmmReservePrecision, spotMarket.imfFactor, spotMarket.maintenanceAssetWeight);
63
+ break;
64
+ default:
65
+ assetWeight = spotMarket.initialAssetWeight;
66
+ break;
67
+ }
68
+ return assetWeight;
69
+ }
70
+ exports.calculateAssetWeight = calculateAssetWeight;
71
+ function calculateLiabilityWeight(balanceAmount, spotMarket, marginCategory) {
72
+ const sizePrecision = numericConstants_1.TEN.pow(new anchor_1.BN(spotMarket.decimals));
73
+ let sizeInAmmReservePrecision;
74
+ if (sizePrecision.gt(numericConstants_1.AMM_RESERVE_PRECISION)) {
75
+ sizeInAmmReservePrecision = balanceAmount.div(sizePrecision.div(numericConstants_1.AMM_RESERVE_PRECISION));
76
+ }
77
+ else {
78
+ sizeInAmmReservePrecision = balanceAmount
79
+ .mul(numericConstants_1.AMM_RESERVE_PRECISION)
80
+ .div(sizePrecision);
81
+ }
82
+ let assetWeight;
83
+ switch (marginCategory) {
84
+ case 'Initial':
85
+ assetWeight = (0, margin_1.calculateSizePremiumLiabilityWeight)(sizeInAmmReservePrecision, spotMarket.imfFactor, spotMarket.initialLiabilityWeight, numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION);
86
+ break;
87
+ case 'Maintenance':
88
+ assetWeight = (0, margin_1.calculateSizePremiumLiabilityWeight)(sizeInAmmReservePrecision, spotMarket.imfFactor, spotMarket.maintenanceLiabilityWeight, numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION);
89
+ break;
90
+ default:
91
+ assetWeight = spotMarket.initialLiabilityWeight;
92
+ break;
93
+ }
94
+ return assetWeight;
95
+ }
96
+ exports.calculateLiabilityWeight = calculateLiabilityWeight;
97
+ function calculateUtilization(bank) {
98
+ const tokenDepositAmount = getTokenAmount(bank.depositBalance, bank, types_1.SpotBalanceType.DEPOSIT);
99
+ const tokenBorrowAmount = getTokenAmount(bank.borrowBalance, bank, types_1.SpotBalanceType.BORROW);
100
+ let utilization;
101
+ if (tokenBorrowAmount.eq(numericConstants_1.ZERO) && tokenDepositAmount.eq(numericConstants_1.ZERO)) {
102
+ utilization = numericConstants_1.ZERO;
103
+ }
104
+ else if (tokenDepositAmount.eq(numericConstants_1.ZERO)) {
105
+ utilization = numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION;
106
+ }
107
+ else {
108
+ utilization = tokenBorrowAmount
109
+ .mul(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION)
110
+ .div(tokenDepositAmount);
111
+ }
112
+ return utilization;
113
+ }
114
+ exports.calculateUtilization = calculateUtilization;
115
+ function calculateInterestRate(bank) {
116
+ const utilization = calculateUtilization(bank);
117
+ let interestRate;
118
+ if (utilization.gt(new anchor_1.BN(bank.optimalUtilization))) {
119
+ const surplusUtilization = utilization.sub(new anchor_1.BN(bank.optimalUtilization));
120
+ const borrowRateSlope = new anchor_1.BN(bank.maxBorrowRate - bank.optimalBorrowRate)
121
+ .mul(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION)
122
+ .div(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION.sub(new anchor_1.BN(bank.optimalUtilization)));
123
+ interestRate = new anchor_1.BN(bank.optimalBorrowRate).add(surplusUtilization
124
+ .mul(borrowRateSlope)
125
+ .div(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION));
126
+ }
127
+ else {
128
+ const borrowRateSlope = new anchor_1.BN(bank.optimalBorrowRate)
129
+ .mul(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION)
130
+ .div(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION.sub(new anchor_1.BN(bank.optimalUtilization)));
131
+ interestRate = utilization
132
+ .mul(borrowRateSlope)
133
+ .div(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION);
134
+ }
135
+ return interestRate;
136
+ }
137
+ exports.calculateInterestRate = calculateInterestRate;
138
+ function calculateDepositRate(bank) {
139
+ const utilization = calculateUtilization(bank);
140
+ const borrowRate = calculateBorrowRate(bank);
141
+ const depositRate = borrowRate
142
+ .mul(utilization)
143
+ .div(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION);
144
+ return depositRate;
145
+ }
146
+ exports.calculateDepositRate = calculateDepositRate;
147
+ function calculateBorrowRate(bank) {
148
+ return calculateInterestRate(bank);
149
+ }
150
+ exports.calculateBorrowRate = calculateBorrowRate;
151
+ function calculateInterestAccumulated(bank, now) {
152
+ const interestRate = calculateInterestRate(bank);
153
+ const timeSinceLastUpdate = now.sub(bank.lastInterestTs);
154
+ const modifiedBorrowRate = interestRate.mul(timeSinceLastUpdate);
155
+ const utilization = calculateUtilization(bank);
156
+ const modifiedDepositRate = modifiedBorrowRate
157
+ .mul(utilization)
158
+ .div(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION);
159
+ const borrowInterest = bank.cumulativeBorrowInterest
160
+ .mul(modifiedBorrowRate)
161
+ .div(numericConstants_1.ONE_YEAR)
162
+ .div(numericConstants_1.SPOT_MARKET_RATE_PRECISION)
163
+ .add(numericConstants_1.ONE);
164
+ const depositInterest = bank.cumulativeDepositInterest
165
+ .mul(modifiedDepositRate)
166
+ .div(numericConstants_1.ONE_YEAR)
167
+ .div(numericConstants_1.SPOT_MARKET_RATE_PRECISION);
168
+ return { borrowInterest, depositInterest };
169
+ }
170
+ exports.calculateInterestAccumulated = calculateInterestAccumulated;
171
+ function calculateWithdrawLimit(spotMarket, now) {
172
+ const marketDepositTokenAmount = getTokenAmount(spotMarket.depositBalance, spotMarket, types_1.SpotBalanceType.DEPOSIT);
173
+ const marketBorrowTokenAmount = getTokenAmount(spotMarket.borrowBalance, spotMarket, types_1.SpotBalanceType.BORROW);
174
+ const twentyFourHours = new anchor_1.BN(60 * 60 * 24);
175
+ const sinceLast = now.sub(spotMarket.lastTwapTs);
176
+ const sinceStart = anchor_1.BN.max(numericConstants_1.ZERO, twentyFourHours.sub(sinceLast));
177
+ const borrowTokenTwapLive = spotMarket.borrowTokenTwap
178
+ .mul(sinceStart)
179
+ .add(marketBorrowTokenAmount.mul(sinceLast))
180
+ .div(sinceLast.add(sinceLast));
181
+ const depositTokenTwapLive = spotMarket.depositTokenTwap
182
+ .mul(sinceStart)
183
+ .add(marketDepositTokenAmount.mul(sinceLast))
184
+ .div(sinceLast.add(sinceLast));
185
+ const maxBorrowTokens = anchor_1.BN.min(anchor_1.BN.max(marketDepositTokenAmount.div(new anchor_1.BN(6)), borrowTokenTwapLive.add(borrowTokenTwapLive.div(new anchor_1.BN(5)))), marketDepositTokenAmount.sub(marketDepositTokenAmount.div(new anchor_1.BN(10)))); // between ~15-90% utilization with friction on twap
186
+ const minDepositTokens = depositTokenTwapLive.sub(anchor_1.BN.min(anchor_1.BN.max(depositTokenTwapLive.div(new anchor_1.BN(5)), spotMarket.withdrawGuardThreshold), depositTokenTwapLive));
187
+ return {
188
+ borrowLimit: maxBorrowTokens.sub(marketBorrowTokenAmount),
189
+ withdrawLimit: marketDepositTokenAmount.sub(minDepositTokens),
190
+ };
191
+ }
192
+ exports.calculateWithdrawLimit = calculateWithdrawLimit;
@@ -0,0 +1,4 @@
1
+ /// <reference types="bn.js" />
2
+ import { BN } from '@project-serum/anchor';
3
+ import { SpotMarketAccount } from '../types';
4
+ export declare function castNumberToSpotPrecision(value: number, spotMarket: SpotMarketAccount): BN;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.castNumberToSpotPrecision = void 0;
4
+ const anchor_1 = require("@project-serum/anchor");
5
+ function castNumberToSpotPrecision(value, spotMarket) {
6
+ return new anchor_1.BN(value * Math.pow(10, spotMarket.decimals));
7
+ }
8
+ exports.castNumberToSpotPrecision = castNumberToSpotPrecision;
@@ -0,0 +1,6 @@
1
+ /// <reference types="bn.js" />
2
+ import { SpotMarketAccount, SpotPosition } from '../types';
3
+ import { BN } from '@project-serum/anchor';
4
+ import { OraclePriceData } from '../oracles/types';
5
+ export declare function isSpotPositionAvailable(position: SpotPosition): boolean;
6
+ export declare function getWorstCaseTokenAmounts(spotPosition: SpotPosition, spotMarketAccount: SpotMarketAccount, oraclePriceData: OraclePriceData): [BN, BN];
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getWorstCaseTokenAmounts = exports.isSpotPositionAvailable = void 0;
4
+ const numericConstants_1 = require("../constants/numericConstants");
5
+ const spotBalance_1 = require("./spotBalance");
6
+ function isSpotPositionAvailable(position) {
7
+ return position.balance.eq(numericConstants_1.ZERO) && position.openOrders === 0;
8
+ }
9
+ exports.isSpotPositionAvailable = isSpotPositionAvailable;
10
+ function getWorstCaseTokenAmounts(spotPosition, spotMarketAccount, oraclePriceData) {
11
+ const tokenAmount = (0, spotBalance_1.getSignedTokenAmount)((0, spotBalance_1.getTokenAmount)(spotPosition.balance, spotMarketAccount, spotPosition.balanceType), spotPosition.balanceType);
12
+ const tokenAmountAllBidsFill = tokenAmount.add(spotPosition.openBids);
13
+ const tokenAmountAllAsksFill = tokenAmount.add(spotPosition.openAsks);
14
+ if (tokenAmountAllAsksFill.abs().gt(tokenAmountAllBidsFill.abs())) {
15
+ const worstCaseQuoteTokenAmount = (0, spotBalance_1.getTokenValue)(spotPosition.openAsks.neg(), spotMarketAccount.decimals, oraclePriceData);
16
+ return [tokenAmountAllBidsFill, worstCaseQuoteTokenAmount];
17
+ }
18
+ else {
19
+ const worstCaseQuoteTokenAmount = (0, spotBalance_1.getTokenValue)(spotPosition.openBids.neg(), spotMarketAccount.decimals, oraclePriceData);
20
+ return [tokenAmountAllAsksFill, worstCaseQuoteTokenAmount];
21
+ }
22
+ }
23
+ exports.getWorstCaseTokenAmounts = getWorstCaseTokenAmounts;
@@ -1,5 +1,5 @@
1
1
  /// <reference types="bn.js" />
2
- import { MarketAccount, PositionDirection } from '../types';
2
+ import { PerpMarketAccount, PositionDirection } from '../types';
3
3
  import { BN } from '@project-serum/anchor';
4
4
  import { AssetType } from './amm';
5
5
  import { OraclePriceData } from '../oracles/types';
@@ -13,15 +13,15 @@ export declare type PriceImpactUnit = 'entryPrice' | 'maxPrice' | 'priceDelta' |
13
13
  * @param useSpread whether to consider spread with calculating slippage
14
14
  * @return [pctAvgSlippage, pctMaxSlippage, entryPrice, newPrice]
15
15
  *
16
- * 'pctAvgSlippage' => the percentage change to entryPrice (average est slippage in execution) : Precision MARK_PRICE_PRECISION
16
+ * 'pctAvgSlippage' => the percentage change to entryPrice (average est slippage in execution) : Precision PRICE_PRECISION
17
17
  *
18
- * 'pctMaxSlippage' => the percentage change to maxPrice (highest est slippage in execution) : Precision MARK_PRICE_PRECISION
18
+ * 'pctMaxSlippage' => the percentage change to maxPrice (highest est slippage in execution) : Precision PRICE_PRECISION
19
19
  *
20
- * 'entryPrice' => the average price of the trade : Precision MARK_PRICE_PRECISION
20
+ * 'entryPrice' => the average price of the trade : Precision PRICE_PRECISION
21
21
  *
22
- * 'newPrice' => the price of the asset after the trade : Precision MARK_PRICE_PRECISION
22
+ * 'newPrice' => the price of the asset after the trade : Precision PRICE_PRECISION
23
23
  */
24
- export declare function calculateTradeSlippage(direction: PositionDirection, amount: BN, market: MarketAccount, inputAssetType?: AssetType, oraclePriceData?: OraclePriceData, useSpread?: boolean): [BN, BN, BN, BN];
24
+ export declare function calculateTradeSlippage(direction: PositionDirection, amount: BN, market: PerpMarketAccount, inputAssetType?: AssetType, oraclePriceData?: OraclePriceData, useSpread?: boolean): [BN, BN, BN, BN];
25
25
  /**
26
26
  * Calculates acquired amounts for trade executed
27
27
  * @param direction
@@ -33,7 +33,7 @@ export declare function calculateTradeSlippage(direction: PositionDirection, amo
33
33
  * | 'acquiredBase' => positive/negative change in user's base : BN AMM_RESERVE_PRECISION
34
34
  * | 'acquiredQuote' => positive/negative change in user's quote : BN TODO-PRECISION
35
35
  */
36
- export declare function calculateTradeAcquiredAmounts(direction: PositionDirection, amount: BN, market: MarketAccount, inputAssetType: AssetType, oraclePriceData: OraclePriceData, useSpread?: boolean): [BN, BN];
36
+ export declare function calculateTradeAcquiredAmounts(direction: PositionDirection, amount: BN, market: PerpMarketAccount, inputAssetType: AssetType, oraclePriceData: OraclePriceData, useSpread?: boolean): [BN, BN, BN];
37
37
  /**
38
38
  * calculateTargetPriceTrade
39
39
  * simple function for finding arbitraging trades
@@ -47,8 +47,8 @@ export declare function calculateTradeAcquiredAmounts(direction: PositionDirecti
47
47
  * [
48
48
  * direction => direction of trade required, PositionDirection
49
49
  * tradeSize => size of trade required, TODO-PRECISION
50
- * entryPrice => the entry price for the trade, MARK_PRICE_PRECISION
51
- * targetPrice => the target price MARK_PRICE_PRECISION
50
+ * entryPrice => the entry price for the trade, PRICE_PRECISION
51
+ * targetPrice => the target price PRICE_PRECISION
52
52
  * ]
53
53
  */
54
- export declare function calculateTargetPriceTrade(market: MarketAccount, targetPrice: BN, pct?: BN, outputAssetType?: AssetType, oraclePriceData?: OraclePriceData, useSpread?: boolean): [PositionDirection, BN, BN, BN];
54
+ export declare function calculateTargetPriceTrade(market: PerpMarketAccount, targetPrice: BN, pct?: BN, outputAssetType?: AssetType, oraclePriceData?: OraclePriceData, useSpread?: boolean): [PositionDirection, BN, BN, BN];