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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +1 -0
  2. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +3 -0
  3. package/lib/accounts/types.d.ts +1 -0
  4. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +1 -0
  5. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +3 -0
  6. package/lib/admin.d.ts +5 -2
  7. package/lib/admin.js +30 -4
  8. package/lib/clearingHouse.d.ts +2 -0
  9. package/lib/clearingHouse.js +14 -1
  10. package/lib/clearingHouseUser.d.ts +11 -9
  11. package/lib/clearingHouseUser.js +182 -106
  12. package/lib/config.js +1 -1
  13. package/lib/dlob/DLOB.d.ts +73 -0
  14. package/lib/dlob/DLOB.js +557 -0
  15. package/lib/dlob/DLOBNode.d.ts +52 -0
  16. package/lib/dlob/DLOBNode.js +82 -0
  17. package/lib/dlob/NodeList.d.ts +26 -0
  18. package/lib/dlob/NodeList.js +138 -0
  19. package/lib/idl/clearing_house.json +122 -202
  20. package/lib/index.d.ts +5 -0
  21. package/lib/index.js +5 -0
  22. package/lib/math/market.d.ts +1 -1
  23. package/lib/math/market.js +1 -1
  24. package/lib/math/orders.d.ts +3 -3
  25. package/lib/math/orders.js +31 -16
  26. package/lib/math/spotBalance.d.ts +3 -0
  27. package/lib/math/spotBalance.js +18 -1
  28. package/lib/math/spotPosition.d.ts +5 -1
  29. package/lib/math/spotPosition.js +16 -1
  30. package/lib/types.d.ts +24 -23
  31. package/lib/types.js +9 -3
  32. package/lib/userMap/userMap.d.ts +25 -0
  33. package/lib/userMap/userMap.js +73 -0
  34. package/lib/userMap/userStatsMap.d.ts +19 -0
  35. package/lib/userMap/userStatsMap.js +68 -0
  36. package/package.json +6 -3
  37. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +4 -0
  38. package/src/accounts/types.ts +1 -0
  39. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +6 -0
  40. package/src/addresses/marketAddresses.js +26 -0
  41. package/src/admin.ts +50 -8
  42. package/src/assert/assert.js +1 -1
  43. package/src/clearingHouse.ts +23 -1
  44. package/src/clearingHouseUser.ts +364 -165
  45. package/src/config.ts +1 -1
  46. package/src/constants/banks.js +42 -0
  47. package/src/constants/{perpMarkets.js → markets.js} +11 -11
  48. package/src/dlob/DLOB.ts +884 -0
  49. package/src/dlob/DLOBNode.ts +163 -0
  50. package/src/dlob/NodeList.ts +185 -0
  51. package/src/events/eventList.js +23 -66
  52. package/src/events/txEventCache.js +19 -22
  53. package/src/examples/makeTradeExample.js +157 -0
  54. package/src/factory/bigNum.js +180 -183
  55. package/src/factory/oracleClient.js +9 -9
  56. package/src/idl/clearing_house.json +122 -202
  57. package/src/index.ts +5 -0
  58. package/src/math/auction.js +10 -10
  59. package/src/math/conversion.js +3 -4
  60. package/src/math/funding.js +175 -223
  61. package/src/math/market.ts +1 -1
  62. package/src/math/orders.ts +29 -21
  63. package/src/math/repeg.js +40 -40
  64. package/src/math/spotBalance.ts +26 -0
  65. package/src/math/spotPosition.ts +42 -1
  66. package/src/math/trade.js +74 -81
  67. package/src/math/utils.js +7 -8
  68. package/src/math/utils.js.map +1 -0
  69. package/src/oracles/oracleClientCache.js +9 -10
  70. package/src/oracles/pythClient.js +17 -52
  71. package/src/oracles/quoteAssetOracleClient.js +13 -44
  72. package/src/oracles/switchboardClient.js +37 -69
  73. package/src/oracles/types.js +1 -1
  74. package/src/token/index.js +4 -4
  75. package/src/tx/types.js +1 -1
  76. package/src/tx/utils.js +6 -7
  77. package/src/types.ts +25 -23
  78. package/src/userMap/userMap.ts +100 -0
  79. package/src/userMap/userStatsMap.ts +110 -0
  80. package/src/userName.js +5 -5
  81. package/src/util/computeUnits.js +11 -46
  82. package/src/util/getTokenAddress.js +9 -0
  83. package/src/util/promiseTimeout.js +5 -5
  84. package/src/util/tps.js +12 -46
  85. package/src/wallet.js +18 -55
  86. package/tests/bn/test.ts +2 -3
  87. package/tests/dlob/helpers.ts +322 -0
  88. package/tests/dlob/test.ts +2865 -0
  89. package/my-script/.env +0 -7
  90. package/my-script/getUserStats.ts +0 -106
  91. package/my-script/multiConnections.ts +0 -119
  92. package/my-script/test-regex.ts +0 -11
  93. package/my-script/utils.ts +0 -52
  94. package/src/accounts/bulkAccountLoader.js +0 -249
  95. package/src/accounts/bulkUserStatsSubscription.js +0 -75
  96. package/src/accounts/bulkUserSubscription.js +0 -75
  97. package/src/accounts/fetch.js +0 -92
  98. package/src/accounts/pollingClearingHouseAccountSubscriber.js +0 -465
  99. package/src/accounts/pollingOracleSubscriber.js +0 -156
  100. package/src/accounts/pollingTokenAccountSubscriber.js +0 -141
  101. package/src/accounts/pollingUserAccountSubscriber.js +0 -208
  102. package/src/accounts/pollingUserStatsAccountSubscriber.js +0 -208
  103. package/src/accounts/types.js +0 -28
  104. package/src/accounts/utils.js +0 -7
  105. package/src/accounts/webSocketAccountSubscriber.js +0 -138
  106. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +0 -433
  107. package/src/accounts/webSocketUserAccountSubscriber.js +0 -113
  108. package/src/accounts/webSocketUserStatsAccountSubsriber.js +0 -113
  109. package/src/addresses/pda.js +0 -186
  110. package/src/admin.js +0 -1284
  111. package/src/clearingHouse.js +0 -3433
  112. package/src/clearingHouseConfig.js +0 -2
  113. package/src/clearingHouseUser.js +0 -874
  114. package/src/clearingHouseUserConfig.js +0 -2
  115. package/src/clearingHouseUserStats.js +0 -115
  116. package/src/clearingHouseUserStatsConfig.js +0 -2
  117. package/src/config.js +0 -80
  118. package/src/constants/numericConstants.js +0 -48
  119. package/src/constants/spotMarkets.js +0 -51
  120. package/src/events/eventSubscriber.js +0 -202
  121. package/src/events/fetchLogs.js +0 -117
  122. package/src/events/pollingLogProvider.js +0 -113
  123. package/src/events/sort.js +0 -41
  124. package/src/events/types.js +0 -25
  125. package/src/events/webSocketLogProvider.js +0 -76
  126. package/src/index.js +0 -75
  127. package/src/math/amm.js +0 -422
  128. package/src/math/insurance.js +0 -27
  129. package/src/math/margin.js +0 -77
  130. package/src/math/market.js +0 -105
  131. package/src/math/oracles.js +0 -56
  132. package/src/math/orders.js +0 -153
  133. package/src/math/position.js +0 -172
  134. package/src/math/spotBalance.js +0 -176
  135. package/src/math/spotMarket.js +0 -8
  136. package/src/math/spotPosition.js +0 -8
  137. package/src/orderParams.js +0 -28
  138. package/src/serum/serumSubscriber.js +0 -102
  139. package/src/serum/types.js +0 -2
  140. package/src/slot/SlotSubscriber.js +0 -86
  141. package/src/tokenFaucet.js +0 -323
  142. package/src/tx/retryTxSender.js +0 -280
  143. package/src/types.js +0 -216
@@ -1,56 +0,0 @@
1
- "use strict";
2
- exports.__esModule = true;
3
- exports.isOracleTooDivergent = exports.isOracleValid = exports.oraclePriceBands = void 0;
4
- var numericConstants_1 = require("../constants/numericConstants");
5
- var index_1 = require("../index");
6
- var assert_1 = require("../assert/assert");
7
- function oraclePriceBands(market, oraclePriceData) {
8
- var maxPercentDiff = market.marginRatioInitial - market.marginRatioMaintenance;
9
- var offset = oraclePriceData.price
10
- .mul(new index_1.BN(maxPercentDiff))
11
- .div(numericConstants_1.MARGIN_PRECISION);
12
- (0, assert_1.assert)(offset.gt(numericConstants_1.ZERO));
13
- return [oraclePriceData.price.sub(offset), oraclePriceData.price.add(offset)];
14
- }
15
- exports.oraclePriceBands = oraclePriceBands;
16
- function isOracleValid(amm, oraclePriceData, oracleGuardRails, slot) {
17
- var isOraclePriceNonPositive = oraclePriceData.price.lte(numericConstants_1.ZERO);
18
- var isOraclePriceTooVolatile = oraclePriceData.price
19
- .div(index_1.BN.max(numericConstants_1.ONE, amm.lastOraclePriceTwap))
20
- .gt(oracleGuardRails.validity.tooVolatileRatio) ||
21
- amm.lastOraclePriceTwap
22
- .div(index_1.BN.max(numericConstants_1.ONE, oraclePriceData.price))
23
- .gt(oracleGuardRails.validity.tooVolatileRatio);
24
- var isConfidenceTooLarge = new index_1.BN(amm.baseSpread)
25
- .add(index_1.BN.max(numericConstants_1.ONE, oraclePriceData.confidence))
26
- .mul(numericConstants_1.BID_ASK_SPREAD_PRECISION)
27
- .div(oraclePriceData.price)
28
- .gt(new index_1.BN(amm.maxSpread));
29
- var oracleIsStale = oraclePriceData.slot
30
- .sub(new index_1.BN(slot))
31
- .gt(oracleGuardRails.validity.slotsBeforeStale);
32
- return !(!oraclePriceData.hasSufficientNumberOfDataPoints ||
33
- oracleIsStale ||
34
- isOraclePriceNonPositive ||
35
- isOraclePriceTooVolatile ||
36
- isConfidenceTooLarge);
37
- }
38
- exports.isOracleValid = isOracleValid;
39
- function isOracleTooDivergent(amm, oraclePriceData, oracleGuardRails, now) {
40
- var sinceLastUpdate = now.sub(amm.lastOraclePriceTwapTs);
41
- var sinceStart = index_1.BN.max(numericConstants_1.ZERO, new index_1.BN(60 * 5).sub(sinceLastUpdate));
42
- var oracleTwap5min = amm.lastOraclePriceTwap5min
43
- .mul(sinceStart)
44
- .add(oraclePriceData.price)
45
- .mul(sinceLastUpdate)
46
- .div(sinceStart.add(sinceLastUpdate));
47
- var oracleSpread = oracleTwap5min.sub(oraclePriceData.price);
48
- var oracleSpreadPct = oracleSpread
49
- .mul(numericConstants_1.MARK_PRICE_PRECISION)
50
- .div(oracleTwap5min);
51
- var tooDivergent = oracleSpreadPct
52
- .abs()
53
- .gte(numericConstants_1.BID_ASK_SPREAD_PRECISION.mul(oracleGuardRails.priceDivergence.markOracleDivergenceNumerator).div(oracleGuardRails.priceDivergence.markOracleDivergenceDenominator));
54
- return tooDivergent;
55
- }
56
- exports.isOracleTooDivergent = isOracleTooDivergent;
@@ -1,153 +0,0 @@
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;
@@ -1,172 +0,0 @@
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;
@@ -1,176 +0,0 @@
1
- "use strict";
2
- exports.__esModule = true;
3
- exports.calculateWithdrawLimit = exports.calculateInterestAccumulated = exports.calculateBorrowRate = exports.calculateDepositRate = exports.calculateInterestRate = exports.calculateUtilization = exports.calculateLiabilityWeight = exports.calculateAssetWeight = exports.getTokenAmount = exports.getBalance = void 0;
4
- var types_1 = require("../types");
5
- var anchor_1 = require("@project-serum/anchor");
6
- var numericConstants_1 = require("../constants/numericConstants");
7
- var margin_1 = require("./margin");
8
- function getBalance(tokenAmount, spotMarket, balanceType) {
9
- var precisionIncrease = numericConstants_1.TEN.pow(new anchor_1.BN(16 - spotMarket.decimals));
10
- var cumulativeInterest = (0, types_1.isVariant)(balanceType, 'deposit')
11
- ? spotMarket.cumulativeDepositInterest
12
- : spotMarket.cumulativeBorrowInterest;
13
- var 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
- var precisionDecrease = numericConstants_1.TEN.pow(new anchor_1.BN(16 - spotMarket.decimals));
22
- var 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 calculateAssetWeight(balanceAmount, spotMarket, marginCategory) {
29
- var sizePrecision = numericConstants_1.TEN.pow(new anchor_1.BN(spotMarket.decimals));
30
- var sizeInAmmReservePrecision;
31
- if (sizePrecision.gt(numericConstants_1.AMM_RESERVE_PRECISION)) {
32
- sizeInAmmReservePrecision = balanceAmount.div(sizePrecision.div(numericConstants_1.AMM_RESERVE_PRECISION));
33
- }
34
- else {
35
- sizeInAmmReservePrecision = balanceAmount
36
- .mul(numericConstants_1.AMM_RESERVE_PRECISION)
37
- .div(sizePrecision);
38
- }
39
- var assetWeight;
40
- switch (marginCategory) {
41
- case 'Initial':
42
- assetWeight = (0, margin_1.calculateSizeDiscountAssetWeight)(sizeInAmmReservePrecision, spotMarket.imfFactor, spotMarket.initialAssetWeight);
43
- break;
44
- case 'Maintenance':
45
- assetWeight = (0, margin_1.calculateSizeDiscountAssetWeight)(sizeInAmmReservePrecision, spotMarket.imfFactor, spotMarket.maintenanceAssetWeight);
46
- break;
47
- default:
48
- assetWeight = spotMarket.initialAssetWeight;
49
- break;
50
- }
51
- return assetWeight;
52
- }
53
- exports.calculateAssetWeight = calculateAssetWeight;
54
- function calculateLiabilityWeight(balanceAmount, spotMarket, marginCategory) {
55
- var sizePrecision = numericConstants_1.TEN.pow(new anchor_1.BN(spotMarket.decimals));
56
- var sizeInAmmReservePrecision;
57
- if (sizePrecision.gt(numericConstants_1.AMM_RESERVE_PRECISION)) {
58
- sizeInAmmReservePrecision = balanceAmount.div(sizePrecision.div(numericConstants_1.AMM_RESERVE_PRECISION));
59
- }
60
- else {
61
- sizeInAmmReservePrecision = balanceAmount
62
- .mul(numericConstants_1.AMM_RESERVE_PRECISION)
63
- .div(sizePrecision);
64
- }
65
- var assetWeight;
66
- switch (marginCategory) {
67
- case 'Initial':
68
- assetWeight = (0, margin_1.calculateSizePremiumLiabilityWeight)(sizeInAmmReservePrecision, spotMarket.imfFactor, spotMarket.initialLiabilityWeight, numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION);
69
- break;
70
- case 'Maintenance':
71
- assetWeight = (0, margin_1.calculateSizePremiumLiabilityWeight)(sizeInAmmReservePrecision, spotMarket.imfFactor, spotMarket.maintenanceLiabilityWeight, numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION);
72
- break;
73
- default:
74
- assetWeight = spotMarket.initialLiabilityWeight;
75
- break;
76
- }
77
- return assetWeight;
78
- }
79
- exports.calculateLiabilityWeight = calculateLiabilityWeight;
80
- function calculateUtilization(bank) {
81
- var tokenDepositAmount = getTokenAmount(bank.depositBalance, bank, types_1.SpotBalanceType.DEPOSIT);
82
- var tokenBorrowAmount = getTokenAmount(bank.borrowBalance, bank, types_1.SpotBalanceType.BORROW);
83
- var utilization;
84
- if (tokenBorrowAmount.eq(numericConstants_1.ZERO) && tokenDepositAmount.eq(numericConstants_1.ZERO)) {
85
- utilization = numericConstants_1.ZERO;
86
- }
87
- else if (tokenDepositAmount.eq(numericConstants_1.ZERO)) {
88
- utilization = numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION;
89
- }
90
- else {
91
- utilization = tokenBorrowAmount
92
- .mul(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION)
93
- .div(tokenDepositAmount);
94
- }
95
- return utilization;
96
- }
97
- exports.calculateUtilization = calculateUtilization;
98
- function calculateInterestRate(bank) {
99
- var utilization = calculateUtilization(bank);
100
- var interestRate;
101
- if (utilization.gt(bank.optimalUtilization)) {
102
- var surplusUtilization = utilization.sub(bank.optimalUtilization);
103
- var borrowRateSlope = bank.maxBorrowRate
104
- .sub(bank.optimalBorrowRate)
105
- .mul(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION)
106
- .div(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION.sub(bank.optimalUtilization));
107
- interestRate = bank.optimalBorrowRate.add(surplusUtilization
108
- .mul(borrowRateSlope)
109
- .div(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION));
110
- }
111
- else {
112
- var borrowRateSlope = bank.optimalBorrowRate
113
- .mul(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION)
114
- .div(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION.sub(bank.optimalUtilization));
115
- interestRate = utilization
116
- .mul(borrowRateSlope)
117
- .div(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION);
118
- }
119
- return interestRate;
120
- }
121
- exports.calculateInterestRate = calculateInterestRate;
122
- function calculateDepositRate(bank) {
123
- var utilization = calculateUtilization(bank);
124
- var borrowRate = calculateBorrowRate(bank);
125
- var depositRate = borrowRate
126
- .mul(utilization)
127
- .div(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION);
128
- return depositRate;
129
- }
130
- exports.calculateDepositRate = calculateDepositRate;
131
- function calculateBorrowRate(bank) {
132
- return calculateInterestRate(bank);
133
- }
134
- exports.calculateBorrowRate = calculateBorrowRate;
135
- function calculateInterestAccumulated(bank, now) {
136
- var interestRate = calculateInterestRate(bank);
137
- var timeSinceLastUpdate = now.sub(bank.lastInterestTs);
138
- var modifiedBorrowRate = interestRate.mul(timeSinceLastUpdate);
139
- var utilization = calculateUtilization(bank);
140
- var modifiedDepositRate = modifiedBorrowRate
141
- .mul(utilization)
142
- .div(numericConstants_1.SPOT_MARKET_UTILIZATION_PRECISION);
143
- var borrowInterest = bank.cumulativeBorrowInterest
144
- .mul(modifiedBorrowRate)
145
- .div(numericConstants_1.ONE_YEAR)
146
- .div(numericConstants_1.SPOT_MARKET_INTEREST_PRECISION)
147
- .add(numericConstants_1.ONE);
148
- var depositInterest = bank.cumulativeDepositInterest
149
- .mul(modifiedDepositRate)
150
- .div(numericConstants_1.ONE_YEAR)
151
- .div(numericConstants_1.SPOT_MARKET_INTEREST_PRECISION);
152
- return { borrowInterest: borrowInterest, depositInterest: depositInterest };
153
- }
154
- exports.calculateInterestAccumulated = calculateInterestAccumulated;
155
- function calculateWithdrawLimit(spotMarket, now) {
156
- var marketDepositTokenAmount = getTokenAmount(spotMarket.depositBalance, spotMarket, types_1.SpotBalanceType.DEPOSIT);
157
- var marketBorrowTokenAmount = getTokenAmount(spotMarket.borrowBalance, spotMarket, types_1.SpotBalanceType.BORROW);
158
- var twentyFourHours = new anchor_1.BN(60 * 60 * 24);
159
- var sinceLast = now.sub(spotMarket.lastTwapTs);
160
- var sinceStart = anchor_1.BN.max(numericConstants_1.ZERO, twentyFourHours.sub(sinceLast));
161
- var borrowTokenTwapLive = spotMarket.borrowTokenTwap
162
- .mul(sinceStart)
163
- .add(marketBorrowTokenAmount.mul(sinceLast))
164
- .div(sinceLast.add(sinceLast));
165
- var depositTokenTwapLive = spotMarket.depositTokenTwap
166
- .mul(sinceStart)
167
- .add(marketDepositTokenAmount.mul(sinceLast))
168
- .div(sinceLast.add(sinceLast));
169
- var 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
170
- var minDepositTokens = depositTokenTwapLive.sub(anchor_1.BN.min(anchor_1.BN.max(depositTokenTwapLive.div(new anchor_1.BN(5)), spotMarket.withdrawGuardThreshold), depositTokenTwapLive));
171
- return {
172
- borrowLimit: maxBorrowTokens.sub(marketBorrowTokenAmount),
173
- withdrawLimit: marketDepositTokenAmount.sub(minDepositTokens)
174
- };
175
- }
176
- exports.calculateWithdrawLimit = calculateWithdrawLimit;
@@ -1,8 +0,0 @@
1
- "use strict";
2
- exports.__esModule = true;
3
- exports.castNumberToSpotPrecision = void 0;
4
- var 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;
@@ -1,8 +0,0 @@
1
- "use strict";
2
- exports.__esModule = true;
3
- exports.isSpotPositionAvailable = void 0;
4
- var numericConstants_1 = require("../constants/numericConstants");
5
- function isSpotPositionAvailable(position) {
6
- return position.balance.eq(numericConstants_1.ZERO) && position.openOrders === 0;
7
- }
8
- exports.isSpotPositionAvailable = isSpotPositionAvailable;
@@ -1,28 +0,0 @@
1
- "use strict";
2
- exports.__esModule = true;
3
- exports.getMarketOrderParams = exports.getTriggerLimitOrderParams = exports.getTriggerMarketOrderParams = exports.getLimitOrderParams = void 0;
4
- var types_1 = require("./types");
5
- function getLimitOrderParams(params) {
6
- return Object.assign({}, params, {
7
- orderType: types_1.OrderType.LIMIT
8
- });
9
- }
10
- exports.getLimitOrderParams = getLimitOrderParams;
11
- function getTriggerMarketOrderParams(params) {
12
- return Object.assign({}, params, {
13
- orderType: types_1.OrderType.TRIGGER_MARKET
14
- });
15
- }
16
- exports.getTriggerMarketOrderParams = getTriggerMarketOrderParams;
17
- function getTriggerLimitOrderParams(params) {
18
- return Object.assign({}, params, {
19
- orderType: types_1.OrderType.TRIGGER_LIMIT
20
- });
21
- }
22
- exports.getTriggerLimitOrderParams = getTriggerLimitOrderParams;
23
- function getMarketOrderParams(params) {
24
- return Object.assign({}, params, {
25
- orderType: types_1.OrderType.MARKET
26
- });
27
- }
28
- exports.getMarketOrderParams = getMarketOrderParams;