@drift-labs/sdk 0.2.0-master.1 → 0.2.0-master.12

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 (142) hide show
  1. package/lib/accounts/types.d.ts +1 -0
  2. package/lib/admin.d.ts +8 -5
  3. package/lib/admin.js +43 -11
  4. package/lib/clearingHouse.d.ts +35 -20
  5. package/lib/clearingHouse.js +497 -154
  6. package/lib/clearingHouseUser.d.ts +12 -17
  7. package/lib/clearingHouseUser.js +97 -88
  8. package/lib/config.js +1 -1
  9. package/lib/constants/banks.d.ts +2 -2
  10. package/lib/constants/banks.js +12 -4
  11. package/lib/constants/numericConstants.d.ts +4 -0
  12. package/lib/constants/numericConstants.js +5 -1
  13. package/lib/events/eventList.js +3 -0
  14. package/lib/events/types.d.ts +2 -1
  15. package/lib/factory/bigNum.d.ts +9 -2
  16. package/lib/factory/bigNum.js +50 -16
  17. package/lib/idl/clearing_house.json +858 -177
  18. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  19. package/lib/index.d.ts +4 -2
  20. package/lib/index.js +8 -2
  21. package/lib/math/amm.d.ts +6 -1
  22. package/lib/math/amm.js +124 -41
  23. package/lib/math/auction.js +4 -1
  24. package/lib/math/bankBalance.d.ts +3 -1
  25. package/lib/math/bankBalance.js +54 -1
  26. package/lib/math/margin.d.ts +11 -0
  27. package/lib/math/margin.js +72 -0
  28. package/lib/math/market.d.ts +4 -1
  29. package/lib/math/market.js +35 -1
  30. package/lib/math/orders.d.ts +2 -2
  31. package/lib/math/orders.js +18 -11
  32. package/lib/math/position.d.ts +8 -0
  33. package/lib/math/position.js +44 -12
  34. package/lib/math/repeg.js +1 -1
  35. package/lib/math/trade.d.ts +1 -1
  36. package/lib/math/trade.js +7 -10
  37. package/lib/orderParams.d.ts +14 -5
  38. package/lib/orderParams.js +8 -96
  39. package/lib/orders.d.ts +2 -4
  40. package/lib/orders.js +7 -161
  41. package/lib/slot/SlotSubscriber.d.ts +7 -0
  42. package/lib/slot/SlotSubscriber.js +3 -0
  43. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  44. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  45. package/lib/tx/retryTxSender.js +9 -2
  46. package/lib/tx/utils.js +1 -1
  47. package/lib/types.d.ts +159 -15
  48. package/lib/types.js +59 -1
  49. package/lib/util/computeUnits.js +1 -1
  50. package/lib/util/getTokenAddress.d.ts +2 -0
  51. package/lib/util/getTokenAddress.js +9 -0
  52. package/package.json +3 -3
  53. package/src/accounts/bulkAccountLoader.js +197 -0
  54. package/src/accounts/bulkUserSubscription.js +33 -0
  55. package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
  56. package/src/accounts/pollingOracleSubscriber.js +93 -0
  57. package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
  58. package/src/accounts/pollingUserAccountSubscriber.js +132 -0
  59. package/src/accounts/types.js +10 -0
  60. package/src/accounts/utils.js +7 -0
  61. package/src/accounts/webSocketAccountSubscriber.js +93 -0
  62. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
  63. package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
  64. package/src/addresses/marketAddresses.js +26 -0
  65. package/src/admin.ts +66 -14
  66. package/src/assert/assert.js +9 -0
  67. package/src/clearingHouse.ts +836 -254
  68. package/src/clearingHouseConfig.js +2 -0
  69. package/src/clearingHouseUser.ts +219 -121
  70. package/src/clearingHouseUserConfig.js +2 -0
  71. package/src/config.ts +1 -1
  72. package/src/constants/banks.js +42 -0
  73. package/src/constants/banks.ts +14 -4
  74. package/src/constants/markets.js +42 -0
  75. package/src/constants/numericConstants.js +41 -0
  76. package/src/constants/numericConstants.ts +5 -0
  77. package/src/events/eventList.js +77 -0
  78. package/src/events/eventList.ts +3 -0
  79. package/src/events/eventSubscriber.js +139 -0
  80. package/src/events/fetchLogs.js +50 -0
  81. package/src/events/pollingLogProvider.js +64 -0
  82. package/src/events/sort.js +44 -0
  83. package/src/events/txEventCache.js +71 -0
  84. package/src/events/types.js +20 -0
  85. package/src/events/types.ts +2 -0
  86. package/src/events/webSocketLogProvider.js +41 -0
  87. package/src/examples/makeTradeExample.js +80 -0
  88. package/src/factory/bigNum.js +390 -0
  89. package/src/factory/bigNum.ts +65 -18
  90. package/src/factory/oracleClient.js +20 -0
  91. package/src/idl/clearing_house.json +858 -177
  92. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  93. package/src/index.js +69 -0
  94. package/src/index.ts +4 -2
  95. package/src/math/amm.js +369 -0
  96. package/src/math/amm.ts +207 -52
  97. package/src/math/auction.js +42 -0
  98. package/src/math/auction.ts +5 -1
  99. package/src/math/bankBalance.ts +98 -1
  100. package/src/math/conversion.js +11 -0
  101. package/src/math/funding.js +248 -0
  102. package/src/math/margin.ts +124 -0
  103. package/src/math/market.ts +66 -1
  104. package/src/math/oracles.js +26 -0
  105. package/src/math/orders.ts +17 -13
  106. package/src/math/position.ts +63 -9
  107. package/src/math/repeg.js +128 -0
  108. package/src/math/repeg.ts +2 -1
  109. package/src/math/state.js +15 -0
  110. package/src/math/trade.js +253 -0
  111. package/src/math/trade.ts +23 -25
  112. package/src/math/utils.js +0 -1
  113. package/src/mockUSDCFaucet.js +280 -0
  114. package/src/oracles/oracleClientCache.js +19 -0
  115. package/src/oracles/pythClient.js +46 -0
  116. package/src/oracles/quoteAssetOracleClient.js +32 -0
  117. package/src/oracles/switchboardClient.js +69 -0
  118. package/src/oracles/types.js +2 -0
  119. package/src/orderParams.js +20 -0
  120. package/src/orderParams.ts +20 -141
  121. package/src/orders.ts +10 -287
  122. package/src/slot/SlotSubscriber.js +39 -0
  123. package/src/slot/SlotSubscriber.ts +11 -1
  124. package/src/token/index.js +38 -0
  125. package/src/tokenFaucet.js +189 -0
  126. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  127. package/src/tx/retryTxSender.ts +11 -3
  128. package/src/tx/types.js +2 -0
  129. package/src/tx/utils.js +17 -0
  130. package/src/tx/utils.ts +1 -1
  131. package/src/types.js +125 -0
  132. package/src/types.ts +155 -17
  133. package/src/userName.js +20 -0
  134. package/src/util/computeUnits.js +21 -11
  135. package/src/util/computeUnits.ts +1 -1
  136. package/src/util/getTokenAddress.js +9 -0
  137. package/src/util/getTokenAddress.ts +18 -0
  138. package/src/util/promiseTimeout.js +14 -0
  139. package/src/util/tps.js +27 -0
  140. package/src/wallet.js +35 -0
  141. package/tests/bn/test.ts +2 -0
  142. package/src/util/computeUnits.js.map +0 -1
@@ -0,0 +1,248 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.calculateFundingPool = exports.calculateLongShortFundingRateAndLiveTwaps = exports.calculateLongShortFundingRate = exports.calculateEstimatedFundingRate = exports.calculateAllEstimatedFundingRate = void 0;
13
+ const anchor_1 = require("@project-serum/anchor");
14
+ const numericConstants_1 = require("../constants/numericConstants");
15
+ const market_1 = require("./market");
16
+ /**
17
+ *
18
+ * @param market
19
+ * @param oraclePriceData
20
+ * @param periodAdjustment
21
+ * @returns Estimated funding rate. : Precision //TODO-PRECISION
22
+ */
23
+ function calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ // periodAdjustment
26
+ // 1: hourly
27
+ // 24: daily
28
+ // 24 * 365.25: annualized
29
+ const secondsInHour = new anchor_1.BN(3600);
30
+ const hoursInDay = new anchor_1.BN(24);
31
+ const ONE = new anchor_1.BN(1);
32
+ if (!market.initialized) {
33
+ return [numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO];
34
+ }
35
+ const payFreq = new anchor_1.BN(market.amm.fundingPeriod);
36
+ // todo: sufficiently differs from blockchain timestamp?
37
+ const now = new anchor_1.BN((Date.now() / 1000).toFixed(0));
38
+ const timeSinceLastUpdate = now.sub(market.amm.lastFundingRateTs);
39
+ // calculate real-time mark twap
40
+ const lastMarkTwapWithMantissa = market.amm.lastMarkPriceTwap;
41
+ const lastMarkPriceTwapTs = market.amm.lastMarkPriceTwapTs;
42
+ const timeSinceLastMarkChange = now.sub(lastMarkPriceTwapTs);
43
+ const markTwapTimeSinceLastUpdate = anchor_1.BN.max(secondsInHour, anchor_1.BN.max(numericConstants_1.ZERO, secondsInHour.sub(timeSinceLastMarkChange)));
44
+ const baseAssetPriceWithMantissa = market_1.calculateMarkPrice(market, oraclePriceData);
45
+ const markTwapWithMantissa = markTwapTimeSinceLastUpdate
46
+ .mul(lastMarkTwapWithMantissa)
47
+ .add(timeSinceLastMarkChange.mul(baseAssetPriceWithMantissa))
48
+ .div(timeSinceLastMarkChange.add(markTwapTimeSinceLastUpdate));
49
+ // calculate real-time (predicted) oracle twap
50
+ // note: oracle twap depends on `when the chord is struck` (market is trade)
51
+ const lastOracleTwapWithMantissa = market.amm.lastOraclePriceTwap;
52
+ const lastOraclePriceTwapTs = market.amm.lastOraclePriceTwapTs;
53
+ const oracleInvalidDuration = anchor_1.BN.max(numericConstants_1.ZERO, lastMarkPriceTwapTs.sub(lastOraclePriceTwapTs));
54
+ const timeSinceLastOracleTwapUpdate = now.sub(lastOraclePriceTwapTs);
55
+ const oracleTwapTimeSinceLastUpdate = anchor_1.BN.max(ONE, anchor_1.BN.min(secondsInHour, anchor_1.BN.max(ONE, secondsInHour.sub(timeSinceLastOracleTwapUpdate))));
56
+ let oracleTwapWithMantissa = lastOracleTwapWithMantissa;
57
+ // if passing live oracle data, improve predicted calc estimate
58
+ if (oraclePriceData) {
59
+ const oraclePrice = oraclePriceData.price;
60
+ const oracleLiveVsTwap = oraclePrice
61
+ .sub(lastOracleTwapWithMantissa)
62
+ .abs()
63
+ .mul(numericConstants_1.MARK_PRICE_PRECISION)
64
+ .mul(new anchor_1.BN(100))
65
+ .div(lastOracleTwapWithMantissa);
66
+ // verify pyth live input is within 10% of last twap for live update
67
+ if (oracleLiveVsTwap.lte(numericConstants_1.MARK_PRICE_PRECISION.mul(new anchor_1.BN(10)))) {
68
+ oracleTwapWithMantissa = oracleTwapTimeSinceLastUpdate
69
+ .mul(lastOracleTwapWithMantissa)
70
+ .add(timeSinceLastMarkChange.mul(oraclePrice))
71
+ .div(timeSinceLastMarkChange.add(oracleTwapTimeSinceLastUpdate));
72
+ }
73
+ }
74
+ const shrunkLastOracleTwapwithMantissa = oracleTwapTimeSinceLastUpdate
75
+ .mul(lastOracleTwapWithMantissa)
76
+ .add(oracleInvalidDuration.mul(lastMarkTwapWithMantissa))
77
+ .div(oracleTwapTimeSinceLastUpdate.add(oracleInvalidDuration));
78
+ const twapSpread = lastMarkTwapWithMantissa.sub(shrunkLastOracleTwapwithMantissa);
79
+ const twapSpreadPct = twapSpread
80
+ .mul(numericConstants_1.MARK_PRICE_PRECISION)
81
+ .mul(new anchor_1.BN(100))
82
+ .div(shrunkLastOracleTwapwithMantissa);
83
+ const lowerboundEst = twapSpreadPct
84
+ .mul(payFreq)
85
+ .mul(anchor_1.BN.min(secondsInHour, timeSinceLastUpdate))
86
+ .mul(periodAdjustment)
87
+ .div(secondsInHour)
88
+ .div(secondsInHour)
89
+ .div(hoursInDay);
90
+ const interpEst = twapSpreadPct.mul(periodAdjustment).div(hoursInDay);
91
+ const interpRateQuote = twapSpreadPct
92
+ .mul(periodAdjustment)
93
+ .div(hoursInDay)
94
+ .div(numericConstants_1.MARK_PRICE_PRECISION.div(numericConstants_1.QUOTE_PRECISION));
95
+ let feePoolSize = calculateFundingPool(market);
96
+ if (interpRateQuote.lt(new anchor_1.BN(0))) {
97
+ feePoolSize = feePoolSize.mul(new anchor_1.BN(-1));
98
+ }
99
+ let cappedAltEst;
100
+ let largerSide;
101
+ let smallerSide;
102
+ if (market.baseAssetAmountLong.gt(market.baseAssetAmountShort.abs())) {
103
+ largerSide = market.baseAssetAmountLong.abs();
104
+ smallerSide = market.baseAssetAmountShort.abs();
105
+ if (twapSpread.gt(new anchor_1.BN(0))) {
106
+ return [
107
+ markTwapWithMantissa,
108
+ oracleTwapWithMantissa,
109
+ lowerboundEst,
110
+ interpEst,
111
+ interpEst,
112
+ ];
113
+ }
114
+ }
115
+ else if (market.baseAssetAmountLong.lt(market.baseAssetAmountShort.abs())) {
116
+ largerSide = market.baseAssetAmountShort.abs();
117
+ smallerSide = market.baseAssetAmountLong.abs();
118
+ if (twapSpread.lt(new anchor_1.BN(0))) {
119
+ return [
120
+ markTwapWithMantissa,
121
+ oracleTwapWithMantissa,
122
+ lowerboundEst,
123
+ interpEst,
124
+ interpEst,
125
+ ];
126
+ }
127
+ }
128
+ else {
129
+ return [
130
+ markTwapWithMantissa,
131
+ oracleTwapWithMantissa,
132
+ lowerboundEst,
133
+ interpEst,
134
+ interpEst,
135
+ ];
136
+ }
137
+ if (largerSide.gt(numericConstants_1.ZERO)) {
138
+ // funding smaller flow
139
+ cappedAltEst = smallerSide.mul(twapSpread).div(hoursInDay);
140
+ const feePoolTopOff = feePoolSize
141
+ .mul(numericConstants_1.MARK_PRICE_PRECISION.div(numericConstants_1.QUOTE_PRECISION))
142
+ .mul(numericConstants_1.AMM_RESERVE_PRECISION);
143
+ cappedAltEst = cappedAltEst.add(feePoolTopOff).div(largerSide);
144
+ cappedAltEst = cappedAltEst
145
+ .mul(numericConstants_1.MARK_PRICE_PRECISION)
146
+ .mul(new anchor_1.BN(100))
147
+ .div(oracleTwapWithMantissa)
148
+ .mul(periodAdjustment);
149
+ if (cappedAltEst.abs().gte(interpEst.abs())) {
150
+ cappedAltEst = interpEst;
151
+ }
152
+ }
153
+ else {
154
+ cappedAltEst = interpEst;
155
+ }
156
+ return [
157
+ markTwapWithMantissa,
158
+ oracleTwapWithMantissa,
159
+ lowerboundEst,
160
+ cappedAltEst,
161
+ interpEst,
162
+ ];
163
+ });
164
+ }
165
+ exports.calculateAllEstimatedFundingRate = calculateAllEstimatedFundingRate;
166
+ /**
167
+ *
168
+ * @param market
169
+ * @param oraclePriceData
170
+ * @param periodAdjustment
171
+ * @param estimationMethod
172
+ * @returns Estimated funding rate. : Precision //TODO-PRECISION
173
+ */
174
+ function calculateEstimatedFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1), estimationMethod) {
175
+ return __awaiter(this, void 0, void 0, function* () {
176
+ const [_1, _2, lowerboundEst, cappedAltEst, interpEst] = yield calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment);
177
+ if (estimationMethod == 'lowerbound') {
178
+ //assuming remaining funding period has no gap
179
+ return lowerboundEst;
180
+ }
181
+ else if (estimationMethod == 'capped') {
182
+ return cappedAltEst;
183
+ }
184
+ else {
185
+ return interpEst;
186
+ }
187
+ });
188
+ }
189
+ exports.calculateEstimatedFundingRate = calculateEstimatedFundingRate;
190
+ /**
191
+ *
192
+ * @param market
193
+ * @param oraclePriceData
194
+ * @param periodAdjustment
195
+ * @returns Estimated funding rate. : Precision //TODO-PRECISION
196
+ */
197
+ function calculateLongShortFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
198
+ return __awaiter(this, void 0, void 0, function* () {
199
+ const [_1, _2, _, cappedAltEst, interpEst] = yield calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment);
200
+ if (market.baseAssetAmountLong.gt(market.baseAssetAmountShort)) {
201
+ return [cappedAltEst, interpEst];
202
+ }
203
+ else if (market.baseAssetAmountLong.lt(market.baseAssetAmountShort)) {
204
+ return [interpEst, cappedAltEst];
205
+ }
206
+ else {
207
+ return [interpEst, interpEst];
208
+ }
209
+ });
210
+ }
211
+ exports.calculateLongShortFundingRate = calculateLongShortFundingRate;
212
+ /**
213
+ *
214
+ * @param market
215
+ * @param oraclePriceData
216
+ * @param periodAdjustment
217
+ * @returns Estimated funding rate. : Precision //TODO-PRECISION
218
+ */
219
+ function calculateLongShortFundingRateAndLiveTwaps(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
220
+ return __awaiter(this, void 0, void 0, function* () {
221
+ const [markTwapLive, oracleTwapLive, _2, cappedAltEst, interpEst] = yield calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment);
222
+ if (market.baseAssetAmountLong.gt(market.baseAssetAmountShort.abs())) {
223
+ return [markTwapLive, oracleTwapLive, cappedAltEst, interpEst];
224
+ }
225
+ else if (market.baseAssetAmountLong.lt(market.baseAssetAmountShort.abs())) {
226
+ return [markTwapLive, oracleTwapLive, interpEst, cappedAltEst];
227
+ }
228
+ else {
229
+ return [markTwapLive, oracleTwapLive, interpEst, interpEst];
230
+ }
231
+ });
232
+ }
233
+ exports.calculateLongShortFundingRateAndLiveTwaps = calculateLongShortFundingRateAndLiveTwaps;
234
+ /**
235
+ *
236
+ * @param market
237
+ * @returns Estimated fee pool size
238
+ */
239
+ function calculateFundingPool(market) {
240
+ // todo
241
+ const totalFeeLB = market.amm.totalExchangeFee.div(new anchor_1.BN(2));
242
+ const feePool = anchor_1.BN.max(numericConstants_1.ZERO, market.amm.totalFeeMinusDistributions
243
+ .sub(totalFeeLB)
244
+ .mul(new anchor_1.BN(1))
245
+ .div(new anchor_1.BN(3)));
246
+ return feePool;
247
+ }
248
+ exports.calculateFundingPool = calculateFundingPool;
@@ -0,0 +1,124 @@
1
+ import { squareRootBN } from './utils';
2
+ import {
3
+ BANK_WEIGHT_PRECISION,
4
+ BANK_IMF_PRECISION,
5
+ ZERO,
6
+ BID_ASK_SPREAD_PRECISION,
7
+ AMM_TO_QUOTE_PRECISION_RATIO,
8
+ MARK_PRICE_PRECISION,
9
+ } from '../constants/numericConstants';
10
+ import { BN } from '@project-serum/anchor';
11
+ import { OraclePriceData } from '../oracles/types';
12
+ import { MarketAccount, UserPosition } from '..';
13
+
14
+ export function calculateSizePremiumLiabilityWeight(
15
+ size: BN, // AMM_RESERVE_PRECISION
16
+ imfFactor: BN,
17
+ liabilityWeight: BN,
18
+ precision: BN
19
+ ): BN {
20
+ if (imfFactor.eq(ZERO)) {
21
+ return liabilityWeight;
22
+ }
23
+
24
+ const sizeSqrt = squareRootBN(size.div(new BN(1000)).add(new BN(1))); //1e13 -> 1e10 -> 1e5
25
+ const liabilityWeightNumerator = liabilityWeight.sub(
26
+ liabilityWeight.div(BN.max(new BN(1), BANK_IMF_PRECISION.div(imfFactor)))
27
+ );
28
+
29
+ const sizePremiumLiabilityWeight = liabilityWeightNumerator.add(
30
+ sizeSqrt // 1e5
31
+ .mul(imfFactor)
32
+ .div(new BN(100_000).mul(BANK_IMF_PRECISION).div(precision)) // 1e5
33
+ );
34
+
35
+ const maxLiabilityWeight = BN.max(
36
+ liabilityWeight,
37
+ sizePremiumLiabilityWeight
38
+ );
39
+ return maxLiabilityWeight;
40
+ }
41
+
42
+ export function calculateSizeDiscountAssetWeight(
43
+ size: BN, // AMM_RESERVE_PRECISION
44
+ imfFactor: BN,
45
+ assetWeight: BN
46
+ ): BN {
47
+ if (imfFactor.eq(ZERO)) {
48
+ return assetWeight;
49
+ }
50
+
51
+ const sizeSqrt = squareRootBN(size.div(new BN(1000)).add(new BN(1))); //1e13 -> 1e10 -> 1e5
52
+ const imfNumerator = BANK_IMF_PRECISION.add(
53
+ BANK_IMF_PRECISION.div(new BN(10))
54
+ );
55
+
56
+ const sizeDiscountAssetWeight = imfNumerator.mul(BANK_WEIGHT_PRECISION).div(
57
+ BANK_IMF_PRECISION.add(
58
+ sizeSqrt // 1e5
59
+ .mul(imfFactor)
60
+ .div(new BN(100_000)) // 1e5
61
+ )
62
+ );
63
+
64
+ const minAssetWeight = BN.min(assetWeight, sizeDiscountAssetWeight);
65
+
66
+ return minAssetWeight;
67
+ }
68
+
69
+ export function calculateOraclePriceForPerpMargin(
70
+ marketPosition: UserPosition,
71
+ market: MarketAccount,
72
+ oraclePriceData: OraclePriceData
73
+ ): BN {
74
+ const oraclePriceOffset = BN.min(
75
+ new BN(market.amm.maxSpread)
76
+ .mul(oraclePriceData.price)
77
+ .div(BID_ASK_SPREAD_PRECISION),
78
+ oraclePriceData.confidence.add(
79
+ new BN(market.amm.baseSpread)
80
+ .mul(oraclePriceData.price)
81
+ .div(BID_ASK_SPREAD_PRECISION)
82
+ )
83
+ );
84
+
85
+ let marginPrice: BN;
86
+ if (marketPosition.baseAssetAmount.gt(ZERO)) {
87
+ marginPrice = oraclePriceData.price.sub(oraclePriceOffset);
88
+ } else {
89
+ marginPrice = oraclePriceData.price.add(oraclePriceOffset);
90
+ }
91
+
92
+ return marginPrice;
93
+ }
94
+
95
+ export function calculateMarginBaseAssetValue(
96
+ market: MarketAccount,
97
+ marketPosition: UserPosition,
98
+ oraclePriceData: OraclePriceData
99
+ ): BN {
100
+ const marginPrice = calculateOraclePriceForPerpMargin(
101
+ marketPosition,
102
+ market,
103
+ oraclePriceData
104
+ );
105
+ const baseAssetValue = marketPosition.baseAssetAmount
106
+ .abs()
107
+ .mul(marginPrice)
108
+ .div(AMM_TO_QUOTE_PRECISION_RATIO.mul(MARK_PRICE_PRECISION));
109
+
110
+ return baseAssetValue;
111
+ }
112
+
113
+ export function calculateWorstCaseBaseAssetAmount(
114
+ marketPosition: UserPosition
115
+ ): BN {
116
+ const allBids = marketPosition.baseAssetAmount.add(marketPosition.openBids);
117
+ const allAsks = marketPosition.baseAssetAmount.add(marketPosition.openAsks);
118
+
119
+ if (allBids.abs().gt(allAsks.abs())) {
120
+ return allBids;
121
+ } else {
122
+ return allAsks;
123
+ }
124
+ }
@@ -1,5 +1,11 @@
1
1
  import { BN } from '@project-serum/anchor';
2
- import { MarketAccount, PositionDirection } from '../types';
2
+ import {
3
+ MarketAccount,
4
+ PositionDirection,
5
+ MarginCategory,
6
+ BankAccount,
7
+ BankBalanceType,
8
+ } from '../types';
3
9
  import {
4
10
  calculateAmmReservesAfterSwap,
5
11
  calculatePrice,
@@ -7,7 +13,13 @@ import {
7
13
  getSwapDirection,
8
14
  calculateUpdatedAMM,
9
15
  } from './amm';
16
+ import {
17
+ calculateSizeDiscountAssetWeight,
18
+ calculateSizePremiumLiabilityWeight,
19
+ } from './margin';
10
20
  import { OraclePriceData } from '../oracles/types';
21
+ import { MARGIN_PRECISION } from '../constants/numericConstants';
22
+ import { getTokenAmount } from './bankBalance';
11
23
 
12
24
  /**
13
25
  * Calculates market mark price
@@ -103,3 +115,56 @@ export function calculateOracleSpread(
103
115
  ): BN {
104
116
  return price.sub(oraclePriceData.price);
105
117
  }
118
+
119
+ export function calculateMarketMarginRatio(
120
+ market: MarketAccount,
121
+ size: BN,
122
+ marginCategory: MarginCategory
123
+ ): number {
124
+ let marginRatio;
125
+ switch (marginCategory) {
126
+ case 'Initial':
127
+ marginRatio = calculateSizePremiumLiabilityWeight(
128
+ size,
129
+ market.imfFactor,
130
+ new BN(market.marginRatioInitial),
131
+ MARGIN_PRECISION
132
+ ).toNumber();
133
+ break;
134
+ case 'Maintenance':
135
+ marginRatio = market.marginRatioMaintenance;
136
+ break;
137
+ }
138
+
139
+ return marginRatio;
140
+ }
141
+
142
+ export function calculateUnsettledAssetWeight(
143
+ market: MarketAccount,
144
+ unsettledPnl: BN,
145
+ marginCategory: MarginCategory
146
+ ): BN {
147
+ let assetWeight: BN;
148
+
149
+ switch (marginCategory) {
150
+ case 'Initial':
151
+ assetWeight = calculateSizeDiscountAssetWeight(
152
+ unsettledPnl,
153
+ market.unsettledImfFactor,
154
+ new BN(market.unsettledInitialAssetWeight)
155
+ );
156
+ break;
157
+ case 'Maintenance':
158
+ assetWeight = new BN(market.unsettledMaintenanceAssetWeight);
159
+ break;
160
+ }
161
+
162
+ return assetWeight;
163
+ }
164
+
165
+ export function calculateMarketAvailablePNL(
166
+ market: MarketAccount,
167
+ bank: BankAccount
168
+ ): BN {
169
+ return getTokenAmount(market.pnlPool.balance, bank, BankBalanceType.DEPOSIT);
170
+ }
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isOracleValid = void 0;
4
+ const numericConstants_1 = require("../constants/numericConstants");
5
+ const index_1 = require("../index");
6
+ function isOracleValid(amm, oraclePriceData, oracleGuardRails, slot) {
7
+ const isOraclePriceNonPositive = oraclePriceData.price.lt(numericConstants_1.ZERO);
8
+ const isOraclePriceTooVolatile = oraclePriceData.price
9
+ .div(index_1.BN.max(numericConstants_1.ONE, amm.lastOraclePriceTwap))
10
+ .gt(oracleGuardRails.validity.tooVolatileRatio) ||
11
+ amm.lastOraclePriceTwap
12
+ .div(index_1.BN.max(numericConstants_1.ONE, oraclePriceData.price))
13
+ .gt(oracleGuardRails.validity.tooVolatileRatio);
14
+ const isConfidenceTooLarge = oraclePriceData.price
15
+ .div(index_1.BN.max(numericConstants_1.ONE, oraclePriceData.confidence))
16
+ .lt(oracleGuardRails.validity.confidenceIntervalMaxSize);
17
+ const oracleIsStale = oraclePriceData.slot
18
+ .sub(new index_1.BN(slot))
19
+ .gt(oracleGuardRails.validity.slotsBeforeStale);
20
+ return !(!oraclePriceData.hasSufficientNumberOfDataPoints ||
21
+ oracleIsStale ||
22
+ isOraclePriceNonPositive ||
23
+ isOraclePriceTooVolatile ||
24
+ isConfidenceTooLarge);
25
+ }
26
+ exports.isOracleValid = isOracleValid;
@@ -1,9 +1,10 @@
1
1
  import { ClearingHouseUser } from '../clearingHouseUser';
2
- import { isVariant, Order } from '../types';
2
+ import { isOneOfVariant, isVariant, MarketAccount, Order } from '../types';
3
3
  import { ZERO, TWO } from '../constants/numericConstants';
4
4
  import { BN } from '@project-serum/anchor';
5
5
  import { OraclePriceData } from '../oracles/types';
6
- import { getAuctionPrice } from './auction';
6
+ import { getAuctionPrice, isAuctionComplete } from './auction';
7
+ import { calculateAskPrice, calculateBidPrice } from './market';
7
8
 
8
9
  export function isOrderRiskIncreasing(
9
10
  user: ClearingHouseUser,
@@ -120,24 +121,27 @@ export function standardizeBaseAssetAmount(
120
121
 
121
122
  export function getLimitPrice(
122
123
  order: Order,
124
+ market: MarketAccount,
123
125
  oraclePriceData: OraclePriceData,
124
126
  slot: number
125
127
  ): BN {
126
128
  let limitPrice;
127
129
  if (!order.oraclePriceOffset.eq(ZERO)) {
128
- const floatingPrice = oraclePriceData.price.add(order.oraclePriceOffset);
129
- if (order.postOnly) {
130
- limitPrice = isVariant(order.direction, 'long')
131
- ? BN.min(order.price, floatingPrice)
132
- : BN.max(order.price, floatingPrice);
130
+ limitPrice = oraclePriceData.price.add(order.oraclePriceOffset);
131
+ } else if (isOneOfVariant(order.orderType, ['market', 'triggerMarket'])) {
132
+ if (isAuctionComplete(order, slot)) {
133
+ limitPrice = getAuctionPrice(order, slot);
134
+ } else if (!order.price.eq(ZERO)) {
135
+ limitPrice = order.price;
136
+ } else if (isVariant(order.direction, 'long')) {
137
+ const askPrice = calculateAskPrice(market, oraclePriceData);
138
+ const delta = askPrice.div(new BN(market.amm.maxSlippageRatio));
139
+ limitPrice = askPrice.add(delta);
133
140
  } else {
134
- limitPrice = floatingPrice;
141
+ const bidPrice = calculateBidPrice(market, oraclePriceData);
142
+ const delta = bidPrice.div(new BN(market.amm.maxSlippageRatio));
143
+ limitPrice = bidPrice.sub(delta);
135
144
  }
136
- } else if (
137
- isVariant(order.orderType, 'market') ||
138
- isVariant(order.orderType, 'triggerMarket')
139
- ) {
140
- limitPrice = getAuctionPrice(order, slot);
141
145
  } else {
142
146
  limitPrice = order.price;
143
147
  }
@@ -18,6 +18,8 @@ import {
18
18
  getSwapDirection,
19
19
  } from './amm';
20
20
 
21
+ import { calculateMarginBaseAssetValue } from './margin';
22
+
21
23
  /**
22
24
  * calculateBaseAssetValue
23
25
  * = market value of closing entire position
@@ -84,6 +86,7 @@ export function calculateBaseAssetValue(
84
86
  * @param market
85
87
  * @param marketPosition
86
88
  * @param withFunding (adds unrealized funding payment pnl to result)
89
+ * @param oraclePriceData
87
90
  * @returns BaseAssetAmount : Precision QUOTE_PRECISION
88
91
  */
89
92
  export function calculatePositionPNL(
@@ -93,21 +96,21 @@ export function calculatePositionPNL(
93
96
  oraclePriceData: OraclePriceData
94
97
  ): BN {
95
98
  if (marketPosition.baseAssetAmount.eq(ZERO)) {
96
- return ZERO;
99
+ return marketPosition.quoteAssetAmount;
97
100
  }
98
101
 
99
- const baseAssetValue = calculateBaseAssetValue(
102
+ const baseAssetValue = calculateMarginBaseAssetValue(
100
103
  market,
101
104
  marketPosition,
102
105
  oraclePriceData
103
106
  );
104
107
 
105
- let pnl;
106
- if (marketPosition.baseAssetAmount.gt(ZERO)) {
107
- pnl = baseAssetValue.sub(marketPosition.quoteAssetAmount);
108
- } else {
109
- pnl = marketPosition.quoteAssetAmount.sub(baseAssetValue);
110
- }
108
+ const baseAssetValueSign = marketPosition.baseAssetAmount.isNeg()
109
+ ? new BN(-1)
110
+ : new BN(1);
111
+ let pnl = baseAssetValue
112
+ .mul(baseAssetValueSign)
113
+ .add(marketPosition.quoteAssetAmount);
111
114
 
112
115
  if (withFunding) {
113
116
  const fundingRatePnL = calculatePositionFundingPNL(
@@ -121,6 +124,36 @@ export function calculatePositionPNL(
121
124
  return pnl;
122
125
  }
123
126
 
127
+ export function calculateUnsettledPnl(
128
+ market: MarketAccount,
129
+ marketPosition: UserPosition,
130
+ oraclePriceData: OraclePriceData
131
+ ): BN {
132
+ const unrealizedPnl = calculatePositionPNL(
133
+ market,
134
+ marketPosition,
135
+ true,
136
+ oraclePriceData
137
+ );
138
+
139
+ let unsettledPnl = unrealizedPnl;
140
+ if (unrealizedPnl.gt(ZERO)) {
141
+ const fundingPnL = calculatePositionFundingPNL(market, marketPosition).div(
142
+ PRICE_TO_QUOTE_PRECISION
143
+ );
144
+
145
+ const maxPositivePnl = BN.max(
146
+ marketPosition.quoteAssetAmount
147
+ .add(marketPosition.quoteEntryAmount)
148
+ .add(fundingPnL),
149
+ ZERO
150
+ );
151
+
152
+ unsettledPnl = BN.min(maxPositivePnl, unrealizedPnl);
153
+ }
154
+ return unsettledPnl;
155
+ }
156
+
124
157
  /**
125
158
  *
126
159
  * @param market
@@ -153,7 +186,11 @@ export function calculatePositionFundingPNL(
153
186
  }
154
187
 
155
188
  export function positionIsAvailable(position: UserPosition): boolean {
156
- return position.baseAssetAmount.eq(ZERO) && position.openOrders.eq(ZERO);
189
+ return (
190
+ position.baseAssetAmount.eq(ZERO) &&
191
+ position.openOrders.eq(ZERO) &&
192
+ position.quoteAssetAmount.eq(ZERO)
193
+ );
157
194
  }
158
195
 
159
196
  /**
@@ -166,6 +203,23 @@ export function calculateEntryPrice(userPosition: UserPosition): BN {
166
203
  return ZERO;
167
204
  }
168
205
 
206
+ return userPosition.quoteEntryAmount
207
+ .mul(MARK_PRICE_PRECISION)
208
+ .mul(AMM_TO_QUOTE_PRECISION_RATIO)
209
+ .div(userPosition.baseAssetAmount)
210
+ .abs();
211
+ }
212
+
213
+ /**
214
+ *
215
+ * @param userPosition
216
+ * @returns Precision: MARK_PRICE_PRECISION (10^10)
217
+ */
218
+ export function calculateCostBasis(userPosition: UserPosition): BN {
219
+ if (userPosition.baseAssetAmount.eq(ZERO)) {
220
+ return ZERO;
221
+ }
222
+
169
223
  return userPosition.quoteAssetAmount
170
224
  .mul(MARK_PRICE_PRECISION)
171
225
  .mul(AMM_TO_QUOTE_PRECISION_RATIO)