@drift-labs/sdk 0.2.0-master.24 → 0.2.0-master.26

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 (193) hide show
  1. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +13 -13
  2. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +27 -27
  3. package/lib/accounts/types.d.ts +8 -9
  4. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +14 -14
  5. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +35 -34
  6. package/lib/addresses/pda.d.ts +8 -6
  7. package/lib/addresses/pda.js +35 -27
  8. package/lib/admin.d.ts +9 -6
  9. package/lib/admin.js +90 -54
  10. package/lib/clearingHouse.d.ts +71 -42
  11. package/lib/clearingHouse.js +765 -282
  12. package/lib/clearingHouseConfig.d.ts +2 -2
  13. package/lib/clearingHouseUser.d.ts +19 -17
  14. package/lib/clearingHouseUser.js +145 -123
  15. package/lib/config.d.ts +7 -7
  16. package/lib/config.js +21 -21
  17. package/lib/constants/numericConstants.d.ts +12 -12
  18. package/lib/constants/numericConstants.js +13 -13
  19. package/lib/constants/{markets.d.ts → perpMarkets.d.ts} +5 -5
  20. package/{src/constants/markets.js → lib/constants/perpMarkets.js} +4 -4
  21. package/lib/constants/{banks.d.ts → spotMarkets.d.ts} +6 -6
  22. package/lib/constants/{banks.js → spotMarkets.js} +16 -16
  23. package/lib/events/eventSubscriber.d.ts +4 -2
  24. package/lib/events/eventSubscriber.js +16 -9
  25. package/lib/events/fetchLogs.d.ts +10 -1
  26. package/lib/events/fetchLogs.js +27 -7
  27. package/lib/events/pollingLogProvider.d.ts +2 -1
  28. package/lib/events/pollingLogProvider.js +6 -2
  29. package/lib/events/types.d.ts +4 -2
  30. package/lib/events/types.js +2 -0
  31. package/lib/examples/makeTradeExample.js +18 -6
  32. package/lib/idl/clearing_house.json +1128 -347
  33. package/lib/index.d.ts +6 -3
  34. package/lib/index.js +6 -3
  35. package/lib/math/amm.d.ts +5 -3
  36. package/lib/math/amm.js +42 -4
  37. package/lib/math/funding.d.ts +6 -6
  38. package/lib/math/funding.js +2 -1
  39. package/lib/math/margin.d.ts +4 -4
  40. package/lib/math/margin.js +18 -11
  41. package/lib/math/market.d.ts +10 -9
  42. package/lib/math/market.js +29 -6
  43. package/lib/math/oracles.d.ts +2 -1
  44. package/lib/math/oracles.js +11 -1
  45. package/lib/math/orders.d.ts +5 -5
  46. package/lib/math/position.d.ts +13 -13
  47. package/lib/math/position.js +19 -19
  48. package/lib/math/spotBalance.d.ts +19 -0
  49. package/lib/math/spotBalance.js +176 -0
  50. package/lib/math/spotMarket.d.ts +4 -0
  51. package/lib/math/spotMarket.js +8 -0
  52. package/lib/math/spotPosition.d.ts +2 -0
  53. package/lib/math/spotPosition.js +8 -0
  54. package/lib/math/state.js +2 -2
  55. package/lib/math/trade.d.ts +4 -4
  56. package/lib/orderParams.d.ts +4 -4
  57. package/lib/orderParams.js +12 -4
  58. package/lib/serum/serumSubscriber.d.ts +23 -0
  59. package/lib/serum/serumSubscriber.js +41 -0
  60. package/lib/serum/types.d.ts +11 -0
  61. package/lib/serum/types.js +2 -0
  62. package/lib/tx/retryTxSender.d.ts +1 -1
  63. package/lib/tx/retryTxSender.js +4 -2
  64. package/lib/tx/types.d.ts +1 -1
  65. package/lib/types.d.ts +148 -39
  66. package/lib/types.js +37 -9
  67. package/my-script/.env +7 -0
  68. package/my-script/getUserStats.ts +106 -0
  69. package/my-script/multiConnections.ts +119 -0
  70. package/my-script/test-regex.ts +11 -0
  71. package/my-script/utils.ts +52 -0
  72. package/package.json +1 -1
  73. package/src/accounts/bulkAccountLoader.js +249 -0
  74. package/src/accounts/bulkUserStatsSubscription.js +75 -0
  75. package/src/accounts/bulkUserSubscription.js +75 -0
  76. package/src/accounts/fetch.js +92 -0
  77. package/src/accounts/pollingClearingHouseAccountSubscriber.js +465 -0
  78. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +38 -38
  79. package/src/accounts/pollingOracleSubscriber.js +156 -0
  80. package/src/accounts/pollingTokenAccountSubscriber.js +141 -0
  81. package/src/accounts/pollingUserAccountSubscriber.js +208 -0
  82. package/src/accounts/pollingUserStatsAccountSubscriber.js +208 -0
  83. package/src/accounts/types.js +28 -0
  84. package/src/accounts/types.ts +11 -9
  85. package/src/accounts/utils.js +7 -0
  86. package/src/accounts/webSocketAccountSubscriber.js +138 -0
  87. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +433 -0
  88. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +59 -52
  89. package/src/accounts/webSocketUserAccountSubscriber.js +113 -0
  90. package/src/accounts/webSocketUserStatsAccountSubsriber.js +113 -0
  91. package/src/addresses/pda.js +186 -0
  92. package/src/addresses/pda.ts +56 -42
  93. package/src/admin.js +1284 -0
  94. package/src/admin.ts +149 -75
  95. package/src/assert/assert.js +1 -1
  96. package/src/clearingHouse.js +3433 -0
  97. package/src/clearingHouse.ts +1097 -380
  98. package/src/clearingHouseConfig.js +2 -0
  99. package/src/clearingHouseConfig.ts +2 -2
  100. package/src/clearingHouseUser.js +874 -0
  101. package/src/clearingHouseUser.ts +237 -172
  102. package/src/clearingHouseUserConfig.js +2 -0
  103. package/src/clearingHouseUserStats.js +115 -0
  104. package/src/clearingHouseUserStatsConfig.js +2 -0
  105. package/src/config.js +80 -0
  106. package/src/config.ts +30 -30
  107. package/src/constants/numericConstants.js +18 -11
  108. package/src/constants/numericConstants.ts +17 -15
  109. package/{lib/constants/markets.js → src/constants/perpMarkets.js} +11 -11
  110. package/src/constants/{markets.ts → perpMarkets.ts} +5 -5
  111. package/src/constants/spotMarkets.js +51 -0
  112. package/src/constants/{banks.ts → spotMarkets.ts} +19 -19
  113. package/src/events/eventList.js +66 -23
  114. package/src/events/eventSubscriber.js +202 -0
  115. package/src/events/eventSubscriber.ts +20 -12
  116. package/src/events/fetchLogs.js +117 -0
  117. package/src/events/fetchLogs.ts +35 -8
  118. package/src/events/pollingLogProvider.js +113 -0
  119. package/src/events/pollingLogProvider.ts +10 -2
  120. package/src/events/sort.js +41 -0
  121. package/src/events/txEventCache.js +22 -19
  122. package/src/events/types.js +25 -0
  123. package/src/events/types.ts +7 -1
  124. package/src/events/webSocketLogProvider.js +76 -0
  125. package/src/examples/makeTradeExample.ts +27 -6
  126. package/src/factory/bigNum.js +183 -180
  127. package/src/factory/oracleClient.js +9 -9
  128. package/src/idl/clearing_house.json +1128 -347
  129. package/src/index.js +75 -0
  130. package/src/index.ts +6 -3
  131. package/src/math/amm.js +422 -0
  132. package/src/math/amm.ts +73 -5
  133. package/src/math/auction.js +10 -10
  134. package/src/math/conversion.js +4 -3
  135. package/src/math/funding.js +223 -175
  136. package/src/math/funding.ts +7 -7
  137. package/src/math/insurance.js +27 -0
  138. package/src/math/margin.js +77 -0
  139. package/src/math/margin.ts +34 -23
  140. package/src/math/market.js +105 -0
  141. package/src/math/market.ts +71 -19
  142. package/src/math/oracles.js +40 -10
  143. package/src/math/oracles.ts +18 -1
  144. package/src/math/orders.js +153 -0
  145. package/src/math/orders.ts +5 -5
  146. package/src/math/position.js +172 -0
  147. package/src/math/position.ts +31 -31
  148. package/src/math/repeg.js +40 -40
  149. package/src/math/spotBalance.js +176 -0
  150. package/src/math/spotBalance.ts +290 -0
  151. package/src/math/spotMarket.js +8 -0
  152. package/src/math/spotMarket.ts +9 -0
  153. package/src/math/spotPosition.js +8 -0
  154. package/src/math/spotPosition.ts +6 -0
  155. package/src/math/state.ts +2 -2
  156. package/src/math/trade.js +81 -74
  157. package/src/math/trade.ts +4 -4
  158. package/src/math/utils.js +8 -7
  159. package/src/oracles/oracleClientCache.js +10 -9
  160. package/src/oracles/pythClient.js +52 -17
  161. package/src/oracles/quoteAssetOracleClient.js +44 -13
  162. package/src/oracles/switchboardClient.js +69 -37
  163. package/src/oracles/types.js +1 -1
  164. package/src/orderParams.js +14 -6
  165. package/src/orderParams.ts +16 -8
  166. package/src/serum/serumSubscriber.js +102 -0
  167. package/src/serum/serumSubscriber.ts +80 -0
  168. package/src/serum/types.js +2 -0
  169. package/src/serum/types.ts +13 -0
  170. package/src/slot/SlotSubscriber.js +67 -20
  171. package/src/token/index.js +4 -4
  172. package/src/tokenFaucet.js +288 -154
  173. package/src/tx/retryTxSender.js +280 -0
  174. package/src/tx/retryTxSender.ts +5 -2
  175. package/src/tx/types.js +1 -1
  176. package/src/tx/types.ts +2 -1
  177. package/src/tx/utils.js +7 -6
  178. package/src/types.js +216 -0
  179. package/src/types.ts +131 -39
  180. package/src/userName.js +5 -5
  181. package/src/util/computeUnits.js +46 -11
  182. package/src/util/promiseTimeout.js +5 -5
  183. package/src/util/tps.js +46 -12
  184. package/src/wallet.js +55 -18
  185. package/lib/math/bankBalance.d.ts +0 -15
  186. package/lib/math/bankBalance.js +0 -150
  187. package/src/addresses/marketAddresses.js +0 -26
  188. package/src/constants/banks.js +0 -42
  189. package/src/examples/makeTradeExample.js +0 -80
  190. package/src/math/bankBalance.ts +0 -258
  191. package/src/math/state.js +0 -15
  192. package/src/math/utils.js.map +0 -1
  193. package/src/util/getTokenAddress.js +0 -9
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ exports.__esModule = true;
3
+ exports.isOrderExpired = exports.calculateBaseAssetAmountToFillUpToLimitPrice = exports.calculateBaseAssetAmountForAmmToFulfill = exports.isFillableByVAMM = exports.getLimitPrice = exports.standardizeBaseAssetAmount = exports.isOrderReduceOnly = exports.isOrderRiskIncreasingInSameDirection = exports.isOrderRiskIncreasing = void 0;
4
+ var types_1 = require("../types");
5
+ var numericConstants_1 = require("../constants/numericConstants");
6
+ var anchor_1 = require("@project-serum/anchor");
7
+ var auction_1 = require("./auction");
8
+ var market_1 = require("./market");
9
+ var amm_1 = require("./amm");
10
+ function isOrderRiskIncreasing(user, order) {
11
+ if ((0, types_1.isVariant)(order.status, 'init')) {
12
+ return false;
13
+ }
14
+ var position = user.getUserPosition(order.marketIndex) ||
15
+ user.getEmptyPosition(order.marketIndex);
16
+ // if no position exists, it's risk increasing
17
+ if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
18
+ return true;
19
+ }
20
+ // if position is long and order is long
21
+ if (position.baseAssetAmount.gt(numericConstants_1.ZERO) && (0, types_1.isVariant)(order.direction, 'long')) {
22
+ return true;
23
+ }
24
+ // if position is short and order is short
25
+ if (position.baseAssetAmount.lt(numericConstants_1.ZERO) &&
26
+ (0, types_1.isVariant)(order.direction, 'short')) {
27
+ return true;
28
+ }
29
+ var baseAssetAmountToFill = order.baseAssetAmount.sub(order.baseAssetAmountFilled);
30
+ // if order will flip position
31
+ if (baseAssetAmountToFill.gt(position.baseAssetAmount.abs().mul(numericConstants_1.TWO))) {
32
+ return true;
33
+ }
34
+ return false;
35
+ }
36
+ exports.isOrderRiskIncreasing = isOrderRiskIncreasing;
37
+ function isOrderRiskIncreasingInSameDirection(user, order) {
38
+ if ((0, types_1.isVariant)(order.status, 'init')) {
39
+ return false;
40
+ }
41
+ var position = user.getUserPosition(order.marketIndex) ||
42
+ user.getEmptyPosition(order.marketIndex);
43
+ // if no position exists, it's risk increasing
44
+ if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
45
+ return true;
46
+ }
47
+ // if position is long and order is long
48
+ if (position.baseAssetAmount.gt(numericConstants_1.ZERO) && (0, types_1.isVariant)(order.direction, 'long')) {
49
+ return true;
50
+ }
51
+ // if position is short and order is short
52
+ if (position.baseAssetAmount.lt(numericConstants_1.ZERO) &&
53
+ (0, types_1.isVariant)(order.direction, 'short')) {
54
+ return true;
55
+ }
56
+ return false;
57
+ }
58
+ exports.isOrderRiskIncreasingInSameDirection = isOrderRiskIncreasingInSameDirection;
59
+ function isOrderReduceOnly(user, order) {
60
+ if ((0, types_1.isVariant)(order.status, 'init')) {
61
+ return false;
62
+ }
63
+ var position = user.getUserPosition(order.marketIndex) ||
64
+ user.getEmptyPosition(order.marketIndex);
65
+ // if position is long and order is long
66
+ if (position.baseAssetAmount.gte(numericConstants_1.ZERO) &&
67
+ (0, types_1.isVariant)(order.direction, 'long')) {
68
+ return false;
69
+ }
70
+ // if position is short and order is short
71
+ if (position.baseAssetAmount.lte(numericConstants_1.ZERO) &&
72
+ (0, types_1.isVariant)(order.direction, 'short')) {
73
+ return false;
74
+ }
75
+ return true;
76
+ }
77
+ exports.isOrderReduceOnly = isOrderReduceOnly;
78
+ function standardizeBaseAssetAmount(baseAssetAmount, stepSize) {
79
+ var remainder = baseAssetAmount.mod(stepSize);
80
+ return baseAssetAmount.sub(remainder);
81
+ }
82
+ exports.standardizeBaseAssetAmount = standardizeBaseAssetAmount;
83
+ function getLimitPrice(order, market, oraclePriceData, slot) {
84
+ var limitPrice;
85
+ if (!order.oraclePriceOffset.eq(numericConstants_1.ZERO)) {
86
+ limitPrice = oraclePriceData.price.add(order.oraclePriceOffset);
87
+ }
88
+ else if ((0, types_1.isOneOfVariant)(order.orderType, ['market', 'triggerMarket'])) {
89
+ if (!(0, auction_1.isAuctionComplete)(order, slot)) {
90
+ limitPrice = (0, auction_1.getAuctionPrice)(order, slot);
91
+ }
92
+ else if (!order.price.eq(numericConstants_1.ZERO)) {
93
+ limitPrice = order.price;
94
+ }
95
+ else if ((0, types_1.isVariant)(order.direction, 'long')) {
96
+ var askPrice = (0, market_1.calculateAskPrice)(market, oraclePriceData);
97
+ var delta = askPrice.div(new anchor_1.BN(market.amm.maxSlippageRatio));
98
+ limitPrice = askPrice.add(delta);
99
+ }
100
+ else {
101
+ var bidPrice = (0, market_1.calculateBidPrice)(market, oraclePriceData);
102
+ var delta = bidPrice.div(new anchor_1.BN(market.amm.maxSlippageRatio));
103
+ limitPrice = bidPrice.sub(delta);
104
+ }
105
+ }
106
+ else {
107
+ limitPrice = order.price;
108
+ }
109
+ return limitPrice;
110
+ }
111
+ exports.getLimitPrice = getLimitPrice;
112
+ function isFillableByVAMM(order, market, oraclePriceData, slot, maxAuctionDuration) {
113
+ return (((0, auction_1.isAuctionComplete)(order, slot) &&
114
+ !calculateBaseAssetAmountForAmmToFulfill(order, market, oraclePriceData, slot).eq(numericConstants_1.ZERO)) ||
115
+ isOrderExpired(order, slot, maxAuctionDuration));
116
+ }
117
+ exports.isFillableByVAMM = isFillableByVAMM;
118
+ function calculateBaseAssetAmountForAmmToFulfill(order, market, oraclePriceData, slot) {
119
+ if ((0, types_1.isOneOfVariant)(order.orderType, ['triggerMarket', 'triggerLimit']) &&
120
+ order.triggered === false) {
121
+ return numericConstants_1.ZERO;
122
+ }
123
+ var limitPrice = getLimitPrice(order, market, oraclePriceData, slot);
124
+ var baseAssetAmount = calculateBaseAssetAmountToFillUpToLimitPrice(order, market, limitPrice, oraclePriceData);
125
+ var maxBaseAssetAmount = (0, amm_1.calculateMaxBaseAssetAmountFillable)(market.amm, order.direction);
126
+ return anchor_1.BN.min(maxBaseAssetAmount, baseAssetAmount);
127
+ }
128
+ exports.calculateBaseAssetAmountForAmmToFulfill = calculateBaseAssetAmountForAmmToFulfill;
129
+ function calculateBaseAssetAmountToFillUpToLimitPrice(order, market, limitPrice, oraclePriceData) {
130
+ var _a = (0, amm_1.calculateMaxBaseAssetAmountToTrade)(market.amm, limitPrice, order.direction, oraclePriceData), maxAmountToTrade = _a[0], direction = _a[1];
131
+ var baseAssetAmount = standardizeBaseAssetAmount(maxAmountToTrade, market.amm.baseAssetAmountStepSize);
132
+ // Check that directions are the same
133
+ var sameDirection = isSameDirection(direction, order.direction);
134
+ if (!sameDirection) {
135
+ return numericConstants_1.ZERO;
136
+ }
137
+ return baseAssetAmount.gt(order.baseAssetAmount)
138
+ ? order.baseAssetAmount
139
+ : baseAssetAmount;
140
+ }
141
+ exports.calculateBaseAssetAmountToFillUpToLimitPrice = calculateBaseAssetAmountToFillUpToLimitPrice;
142
+ function isSameDirection(firstDirection, secondDirection) {
143
+ return (((0, types_1.isVariant)(firstDirection, 'long') && (0, types_1.isVariant)(secondDirection, 'long')) ||
144
+ ((0, types_1.isVariant)(firstDirection, 'short') && (0, types_1.isVariant)(secondDirection, 'short')));
145
+ }
146
+ function isOrderExpired(order, slot, maxAuctionDuration) {
147
+ if (!(0, types_1.isVariant)(order.orderType, 'market') ||
148
+ !(0, types_1.isVariant)(order.status, 'open')) {
149
+ return false;
150
+ }
151
+ return new anchor_1.BN(slot).sub(order.slot).gt(new anchor_1.BN(maxAuctionDuration));
152
+ }
153
+ exports.isOrderExpired = isOrderExpired;
@@ -2,7 +2,7 @@ import { ClearingHouseUser } from '../clearingHouseUser';
2
2
  import {
3
3
  isOneOfVariant,
4
4
  isVariant,
5
- MarketAccount,
5
+ PerpMarketAccount,
6
6
  Order,
7
7
  PositionDirection,
8
8
  } from '../types';
@@ -131,7 +131,7 @@ export function standardizeBaseAssetAmount(
131
131
 
132
132
  export function getLimitPrice(
133
133
  order: Order,
134
- market: MarketAccount,
134
+ market: PerpMarketAccount,
135
135
  oraclePriceData: OraclePriceData,
136
136
  slot: number
137
137
  ): BN {
@@ -161,7 +161,7 @@ export function getLimitPrice(
161
161
 
162
162
  export function isFillableByVAMM(
163
163
  order: Order,
164
- market: MarketAccount,
164
+ market: PerpMarketAccount,
165
165
  oraclePriceData: OraclePriceData,
166
166
  slot: number,
167
167
  maxAuctionDuration: number
@@ -180,7 +180,7 @@ export function isFillableByVAMM(
180
180
 
181
181
  export function calculateBaseAssetAmountForAmmToFulfill(
182
182
  order: Order,
183
- market: MarketAccount,
183
+ market: PerpMarketAccount,
184
184
  oraclePriceData: OraclePriceData,
185
185
  slot: number
186
186
  ): BN {
@@ -209,7 +209,7 @@ export function calculateBaseAssetAmountForAmmToFulfill(
209
209
 
210
210
  export function calculateBaseAssetAmountToFillUpToLimitPrice(
211
211
  order: Order,
212
- market: MarketAccount,
212
+ market: PerpMarketAccount,
213
213
  limitPrice: BN,
214
214
  oraclePriceData: OraclePriceData
215
215
  ): BN {
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ exports.__esModule = true;
3
+ exports.isEmptyPosition = exports.positionCurrentDirection = exports.findDirectionToClose = exports.calculateCostBasis = exports.calculateEntryPrice = exports.positionIsAvailable = exports.calculatePositionFundingPNL = exports.calculateUnsettledPnl = exports.calculatePositionPNL = exports.calculateBaseAssetValue = void 0;
4
+ var __1 = require("../");
5
+ var numericConstants_1 = require("../constants/numericConstants");
6
+ var types_1 = require("../types");
7
+ var amm_1 = require("./amm");
8
+ var margin_1 = require("./margin");
9
+ /**
10
+ * calculateBaseAssetValue
11
+ * = market value of closing entire position
12
+ * @param market
13
+ * @param userPosition
14
+ * @param oraclePriceData
15
+ * @returns Base Asset Value. : Precision QUOTE_PRECISION
16
+ */
17
+ function calculateBaseAssetValue(market, userPosition, oraclePriceData) {
18
+ if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
19
+ return numericConstants_1.ZERO;
20
+ }
21
+ var directionToClose = findDirectionToClose(userPosition);
22
+ var prepegAmm;
23
+ if (market.amm.baseSpread > 0) {
24
+ var _a = (0, amm_1.calculateUpdatedAMMSpreadReserves)(market.amm, directionToClose, oraclePriceData), baseAssetReserve = _a.baseAssetReserve, quoteAssetReserve = _a.quoteAssetReserve, sqrtK = _a.sqrtK, newPeg = _a.newPeg;
25
+ prepegAmm = {
26
+ baseAssetReserve: baseAssetReserve,
27
+ quoteAssetReserve: quoteAssetReserve,
28
+ sqrtK: sqrtK,
29
+ pegMultiplier: newPeg
30
+ };
31
+ }
32
+ else {
33
+ prepegAmm = (0, amm_1.calculateUpdatedAMM)(market.amm, oraclePriceData);
34
+ }
35
+ var _b = (0, amm_1.calculateAmmReservesAfterSwap)(prepegAmm, 'base', userPosition.baseAssetAmount.abs(), (0, amm_1.getSwapDirection)('base', directionToClose)), newQuoteAssetReserve = _b[0], _ = _b[1];
36
+ switch (directionToClose) {
37
+ case types_1.PositionDirection.SHORT:
38
+ return prepegAmm.quoteAssetReserve
39
+ .sub(newQuoteAssetReserve)
40
+ .mul(prepegAmm.pegMultiplier)
41
+ .div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
42
+ case types_1.PositionDirection.LONG:
43
+ return newQuoteAssetReserve
44
+ .sub(prepegAmm.quoteAssetReserve)
45
+ .mul(prepegAmm.pegMultiplier)
46
+ .div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO)
47
+ .add(numericConstants_1.ONE);
48
+ }
49
+ }
50
+ exports.calculateBaseAssetValue = calculateBaseAssetValue;
51
+ /**
52
+ * calculatePositionPNL
53
+ * = BaseAssetAmount * (Avg Exit Price - Avg Entry Price)
54
+ * @param market
55
+ * @param PerpPosition
56
+ * @param withFunding (adds unrealized funding payment pnl to result)
57
+ * @param oraclePriceData
58
+ * @returns BaseAssetAmount : Precision QUOTE_PRECISION
59
+ */
60
+ function calculatePositionPNL(market, perpPosition, withFunding, oraclePriceData) {
61
+ if (withFunding === void 0) { withFunding = false; }
62
+ if (perpPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
63
+ return perpPosition.quoteAssetAmount;
64
+ }
65
+ var baseAssetValue = (0, margin_1.calculateBaseAssetValueWithOracle)(market, perpPosition, oraclePriceData);
66
+ var baseAssetValueSign = perpPosition.baseAssetAmount.isNeg()
67
+ ? new __1.BN(-1)
68
+ : new __1.BN(1);
69
+ var pnl = baseAssetValue
70
+ .mul(baseAssetValueSign)
71
+ .add(perpPosition.quoteAssetAmount);
72
+ if (withFunding) {
73
+ var fundingRatePnL = calculatePositionFundingPNL(market, perpPosition).div(numericConstants_1.PRICE_TO_QUOTE_PRECISION);
74
+ pnl = pnl.add(fundingRatePnL);
75
+ }
76
+ return pnl;
77
+ }
78
+ exports.calculatePositionPNL = calculatePositionPNL;
79
+ function calculateUnsettledPnl(market, perpPosition, oraclePriceData) {
80
+ var unrealizedPnl = calculatePositionPNL(market, perpPosition, true, oraclePriceData);
81
+ var unsettledPnl = unrealizedPnl;
82
+ if (unrealizedPnl.gt(numericConstants_1.ZERO)) {
83
+ var fundingPnL = calculatePositionFundingPNL(market, perpPosition).div(numericConstants_1.PRICE_TO_QUOTE_PRECISION);
84
+ var maxPositivePnl = __1.BN.max(perpPosition.quoteAssetAmount
85
+ .sub(perpPosition.quoteEntryAmount)
86
+ .add(fundingPnL), numericConstants_1.ZERO);
87
+ unsettledPnl = __1.BN.min(maxPositivePnl, unrealizedPnl);
88
+ }
89
+ return unsettledPnl;
90
+ }
91
+ exports.calculateUnsettledPnl = calculateUnsettledPnl;
92
+ /**
93
+ *
94
+ * @param market
95
+ * @param PerpPosition
96
+ * @returns // TODO-PRECISION
97
+ */
98
+ function calculatePositionFundingPNL(market, perpPosition) {
99
+ if (perpPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
100
+ return numericConstants_1.ZERO;
101
+ }
102
+ var ammCumulativeFundingRate;
103
+ if (perpPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
104
+ ammCumulativeFundingRate = market.amm.cumulativeFundingRateLong;
105
+ }
106
+ else {
107
+ ammCumulativeFundingRate = market.amm.cumulativeFundingRateShort;
108
+ }
109
+ var perPositionFundingRate = ammCumulativeFundingRate
110
+ .sub(perpPosition.lastCumulativeFundingRate)
111
+ .mul(perpPosition.baseAssetAmount)
112
+ .div(numericConstants_1.AMM_RESERVE_PRECISION)
113
+ .div(numericConstants_1.FUNDING_PAYMENT_PRECISION)
114
+ .mul(new __1.BN(-1));
115
+ return perPositionFundingRate;
116
+ }
117
+ exports.calculatePositionFundingPNL = calculatePositionFundingPNL;
118
+ function positionIsAvailable(position) {
119
+ return (position.baseAssetAmount.eq(numericConstants_1.ZERO) &&
120
+ position.openOrders.eq(numericConstants_1.ZERO) &&
121
+ position.quoteAssetAmount.eq(numericConstants_1.ZERO) &&
122
+ position.lpShares.eq(numericConstants_1.ZERO));
123
+ }
124
+ exports.positionIsAvailable = positionIsAvailable;
125
+ /**
126
+ *
127
+ * @param userPosition
128
+ * @returns Precision: MARK_PRICE_PRECISION (10^10)
129
+ */
130
+ function calculateEntryPrice(userPosition) {
131
+ if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
132
+ return numericConstants_1.ZERO;
133
+ }
134
+ return userPosition.quoteEntryAmount
135
+ .mul(numericConstants_1.MARK_PRICE_PRECISION)
136
+ .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
137
+ .div(userPosition.baseAssetAmount)
138
+ .abs();
139
+ }
140
+ exports.calculateEntryPrice = calculateEntryPrice;
141
+ /**
142
+ *
143
+ * @param userPosition
144
+ * @returns Precision: MARK_PRICE_PRECISION (10^10)
145
+ */
146
+ function calculateCostBasis(userPosition) {
147
+ if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
148
+ return numericConstants_1.ZERO;
149
+ }
150
+ return userPosition.quoteAssetAmount
151
+ .mul(numericConstants_1.MARK_PRICE_PRECISION)
152
+ .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
153
+ .div(userPosition.baseAssetAmount)
154
+ .abs();
155
+ }
156
+ exports.calculateCostBasis = calculateCostBasis;
157
+ function findDirectionToClose(userPosition) {
158
+ return userPosition.baseAssetAmount.gt(numericConstants_1.ZERO)
159
+ ? types_1.PositionDirection.SHORT
160
+ : types_1.PositionDirection.LONG;
161
+ }
162
+ exports.findDirectionToClose = findDirectionToClose;
163
+ function positionCurrentDirection(userPosition) {
164
+ return userPosition.baseAssetAmount.gte(numericConstants_1.ZERO)
165
+ ? types_1.PositionDirection.LONG
166
+ : types_1.PositionDirection.SHORT;
167
+ }
168
+ exports.positionCurrentDirection = positionCurrentDirection;
169
+ function isEmptyPosition(userPosition) {
170
+ return (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO) && userPosition.openOrders.eq(numericConstants_1.ZERO));
171
+ }
172
+ exports.isEmptyPosition = isEmptyPosition;
@@ -10,7 +10,7 @@ import {
10
10
  ZERO,
11
11
  } from '../constants/numericConstants';
12
12
  import { OraclePriceData } from '../oracles/types';
13
- import { MarketAccount, PositionDirection, UserPosition } from '../types';
13
+ import { PerpMarketAccount, PositionDirection, PerpPosition } from '../types';
14
14
  import {
15
15
  calculateUpdatedAMM,
16
16
  calculateUpdatedAMMSpreadReserves,
@@ -29,8 +29,8 @@ import { calculateBaseAssetValueWithOracle } from './margin';
29
29
  * @returns Base Asset Value. : Precision QUOTE_PRECISION
30
30
  */
31
31
  export function calculateBaseAssetValue(
32
- market: MarketAccount,
33
- userPosition: UserPosition,
32
+ market: PerpMarketAccount,
33
+ userPosition: PerpPosition,
34
34
  oraclePriceData: OraclePriceData
35
35
  ): BN {
36
36
  if (userPosition.baseAssetAmount.eq(ZERO)) {
@@ -84,38 +84,38 @@ export function calculateBaseAssetValue(
84
84
  * calculatePositionPNL
85
85
  * = BaseAssetAmount * (Avg Exit Price - Avg Entry Price)
86
86
  * @param market
87
- * @param marketPosition
87
+ * @param PerpPosition
88
88
  * @param withFunding (adds unrealized funding payment pnl to result)
89
89
  * @param oraclePriceData
90
90
  * @returns BaseAssetAmount : Precision QUOTE_PRECISION
91
91
  */
92
92
  export function calculatePositionPNL(
93
- market: MarketAccount,
94
- marketPosition: UserPosition,
93
+ market: PerpMarketAccount,
94
+ perpPosition: PerpPosition,
95
95
  withFunding = false,
96
96
  oraclePriceData: OraclePriceData
97
97
  ): BN {
98
- if (marketPosition.baseAssetAmount.eq(ZERO)) {
99
- return marketPosition.quoteAssetAmount;
98
+ if (perpPosition.baseAssetAmount.eq(ZERO)) {
99
+ return perpPosition.quoteAssetAmount;
100
100
  }
101
101
 
102
102
  const baseAssetValue = calculateBaseAssetValueWithOracle(
103
103
  market,
104
- marketPosition,
104
+ perpPosition,
105
105
  oraclePriceData
106
106
  );
107
107
 
108
- const baseAssetValueSign = marketPosition.baseAssetAmount.isNeg()
108
+ const baseAssetValueSign = perpPosition.baseAssetAmount.isNeg()
109
109
  ? new BN(-1)
110
110
  : new BN(1);
111
111
  let pnl = baseAssetValue
112
112
  .mul(baseAssetValueSign)
113
- .add(marketPosition.quoteAssetAmount);
113
+ .add(perpPosition.quoteAssetAmount);
114
114
 
115
115
  if (withFunding) {
116
116
  const fundingRatePnL = calculatePositionFundingPNL(
117
117
  market,
118
- marketPosition
118
+ perpPosition
119
119
  ).div(PRICE_TO_QUOTE_PRECISION);
120
120
 
121
121
  pnl = pnl.add(fundingRatePnL);
@@ -125,26 +125,26 @@ export function calculatePositionPNL(
125
125
  }
126
126
 
127
127
  export function calculateUnsettledPnl(
128
- market: MarketAccount,
129
- marketPosition: UserPosition,
128
+ market: PerpMarketAccount,
129
+ perpPosition: PerpPosition,
130
130
  oraclePriceData: OraclePriceData
131
131
  ): BN {
132
132
  const unrealizedPnl = calculatePositionPNL(
133
133
  market,
134
- marketPosition,
134
+ perpPosition,
135
135
  true,
136
136
  oraclePriceData
137
137
  );
138
138
 
139
139
  let unsettledPnl = unrealizedPnl;
140
140
  if (unrealizedPnl.gt(ZERO)) {
141
- const fundingPnL = calculatePositionFundingPNL(market, marketPosition).div(
141
+ const fundingPnL = calculatePositionFundingPNL(market, perpPosition).div(
142
142
  PRICE_TO_QUOTE_PRECISION
143
143
  );
144
144
 
145
145
  const maxPositivePnl = BN.max(
146
- marketPosition.quoteAssetAmount
147
- .sub(marketPosition.quoteEntryAmount)
146
+ perpPosition.quoteAssetAmount
147
+ .sub(perpPosition.quoteEntryAmount)
148
148
  .add(fundingPnL),
149
149
  ZERO
150
150
  );
@@ -157,27 +157,27 @@ export function calculateUnsettledPnl(
157
157
  /**
158
158
  *
159
159
  * @param market
160
- * @param marketPosition
160
+ * @param PerpPosition
161
161
  * @returns // TODO-PRECISION
162
162
  */
163
163
  export function calculatePositionFundingPNL(
164
- market: MarketAccount,
165
- marketPosition: UserPosition
164
+ market: PerpMarketAccount,
165
+ perpPosition: PerpPosition
166
166
  ): BN {
167
- if (marketPosition.baseAssetAmount.eq(ZERO)) {
167
+ if (perpPosition.baseAssetAmount.eq(ZERO)) {
168
168
  return ZERO;
169
169
  }
170
170
 
171
171
  let ammCumulativeFundingRate: BN;
172
- if (marketPosition.baseAssetAmount.gt(ZERO)) {
172
+ if (perpPosition.baseAssetAmount.gt(ZERO)) {
173
173
  ammCumulativeFundingRate = market.amm.cumulativeFundingRateLong;
174
174
  } else {
175
175
  ammCumulativeFundingRate = market.amm.cumulativeFundingRateShort;
176
176
  }
177
177
 
178
178
  const perPositionFundingRate = ammCumulativeFundingRate
179
- .sub(marketPosition.lastCumulativeFundingRate)
180
- .mul(marketPosition.baseAssetAmount)
179
+ .sub(perpPosition.lastCumulativeFundingRate)
180
+ .mul(perpPosition.baseAssetAmount)
181
181
  .div(AMM_RESERVE_PRECISION)
182
182
  .div(FUNDING_PAYMENT_PRECISION)
183
183
  .mul(new BN(-1));
@@ -185,7 +185,7 @@ export function calculatePositionFundingPNL(
185
185
  return perPositionFundingRate;
186
186
  }
187
187
 
188
- export function positionIsAvailable(position: UserPosition): boolean {
188
+ export function positionIsAvailable(position: PerpPosition): boolean {
189
189
  return (
190
190
  position.baseAssetAmount.eq(ZERO) &&
191
191
  position.openOrders.eq(ZERO) &&
@@ -199,7 +199,7 @@ export function positionIsAvailable(position: UserPosition): boolean {
199
199
  * @param userPosition
200
200
  * @returns Precision: MARK_PRICE_PRECISION (10^10)
201
201
  */
202
- export function calculateEntryPrice(userPosition: UserPosition): BN {
202
+ export function calculateEntryPrice(userPosition: PerpPosition): BN {
203
203
  if (userPosition.baseAssetAmount.eq(ZERO)) {
204
204
  return ZERO;
205
205
  }
@@ -216,7 +216,7 @@ export function calculateEntryPrice(userPosition: UserPosition): BN {
216
216
  * @param userPosition
217
217
  * @returns Precision: MARK_PRICE_PRECISION (10^10)
218
218
  */
219
- export function calculateCostBasis(userPosition: UserPosition): BN {
219
+ export function calculateCostBasis(userPosition: PerpPosition): BN {
220
220
  if (userPosition.baseAssetAmount.eq(ZERO)) {
221
221
  return ZERO;
222
222
  }
@@ -229,7 +229,7 @@ export function calculateCostBasis(userPosition: UserPosition): BN {
229
229
  }
230
230
 
231
231
  export function findDirectionToClose(
232
- userPosition: UserPosition
232
+ userPosition: PerpPosition
233
233
  ): PositionDirection {
234
234
  return userPosition.baseAssetAmount.gt(ZERO)
235
235
  ? PositionDirection.SHORT
@@ -237,14 +237,14 @@ export function findDirectionToClose(
237
237
  }
238
238
 
239
239
  export function positionCurrentDirection(
240
- userPosition: UserPosition
240
+ userPosition: PerpPosition
241
241
  ): PositionDirection {
242
242
  return userPosition.baseAssetAmount.gte(ZERO)
243
243
  ? PositionDirection.LONG
244
244
  : PositionDirection.SHORT;
245
245
  }
246
246
 
247
- export function isEmptyPosition(userPosition: UserPosition): boolean {
247
+ export function isEmptyPosition(userPosition: PerpPosition): boolean {
248
248
  return (
249
249
  userPosition.baseAssetAmount.eq(ZERO) && userPosition.openOrders.eq(ZERO)
250
250
  );