@drift-labs/sdk 0.1.19-master.1 → 0.1.21-master.3

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/bulkAccountLoader.d.ts +31 -0
  2. package/lib/accounts/bulkAccountLoader.js +177 -0
  3. package/lib/accounts/bulkUserSubscription.d.ts +7 -0
  4. package/lib/accounts/bulkUserSubscription.js +28 -0
  5. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +49 -0
  6. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +228 -0
  7. package/lib/accounts/pollingTokenAccountSubscriber.d.ts +25 -0
  8. package/lib/accounts/pollingTokenAccountSubscriber.js +79 -0
  9. package/lib/accounts/pollingUserAccountSubscriber.d.ts +32 -0
  10. package/lib/accounts/pollingUserAccountSubscriber.js +136 -0
  11. package/lib/accounts/types.d.ts +38 -3
  12. package/lib/accounts/utils.d.ts +1 -0
  13. package/lib/accounts/utils.js +7 -0
  14. package/lib/accounts/webSocketAccountSubscriber.d.ts +6 -3
  15. package/lib/accounts/webSocketAccountSubscriber.js +43 -12
  16. package/lib/accounts/{defaultClearingHouseAccountSubscriber.d.ts → webSocketClearingHouseAccountSubscriber.d.ts} +8 -3
  17. package/lib/accounts/{defaultClearingHouseAccountSubscriber.js → webSocketClearingHouseAccountSubscriber.js} +30 -4
  18. package/lib/accounts/{defaultUserAccountSubscriber.d.ts → webSocketUserAccountSubscriber.d.ts} +6 -3
  19. package/lib/accounts/{defaultUserAccountSubscriber.js → webSocketUserAccountSubscriber.js} +16 -4
  20. package/lib/addresses.d.ts +4 -1
  21. package/lib/addresses.js +28 -1
  22. package/lib/admin.d.ts +10 -4
  23. package/lib/admin.js +54 -17
  24. package/lib/assert/assert.d.ts +0 -1
  25. package/lib/clearingHouse.d.ts +39 -4
  26. package/lib/clearingHouse.js +334 -23
  27. package/lib/clearingHouseUser.d.ts +26 -20
  28. package/lib/clearingHouseUser.js +149 -118
  29. package/lib/config.d.ts +0 -1
  30. package/lib/constants/markets.d.ts +2 -2
  31. package/lib/constants/markets.js +28 -15
  32. package/lib/constants/numericConstants.d.ts +4 -2
  33. package/lib/constants/numericConstants.js +16 -17
  34. package/lib/examples/makeTradeExample.d.ts +0 -1
  35. package/lib/examples/makeTradeExample.js +6 -6
  36. package/lib/factory/clearingHouse.d.ts +25 -0
  37. package/lib/factory/clearingHouse.js +64 -0
  38. package/lib/factory/clearingHouseUser.d.ts +19 -0
  39. package/lib/factory/clearingHouseUser.js +34 -0
  40. package/lib/idl/clearing_house.json +1066 -39
  41. package/lib/index.d.ts +11 -3
  42. package/lib/index.js +12 -2
  43. package/lib/math/amm.d.ts +1 -1
  44. package/lib/math/amm.js +38 -15
  45. package/lib/math/conversion.d.ts +1 -2
  46. package/lib/math/conversion.js +1 -1
  47. package/lib/math/funding.d.ts +0 -1
  48. package/lib/math/funding.js +1 -1
  49. package/lib/math/insuranceFund.d.ts +2 -2
  50. package/lib/math/insuranceFund.js +3 -6
  51. package/lib/math/market.d.ts +2 -2
  52. package/lib/math/market.js +12 -2
  53. package/lib/math/orders.d.ts +3 -0
  54. package/lib/math/orders.js +32 -0
  55. package/lib/math/position.d.ts +6 -3
  56. package/lib/math/position.js +21 -10
  57. package/lib/math/trade.d.ts +0 -1
  58. package/lib/math/trade.js +16 -16
  59. package/lib/math/utils.d.ts +2 -2
  60. package/lib/math/utils.js +3 -3
  61. package/lib/mockUSDCFaucet.d.ts +2 -2
  62. package/lib/orderParams.d.ts +7 -0
  63. package/lib/orderParams.js +108 -0
  64. package/lib/orders.d.ts +6 -0
  65. package/lib/orders.js +136 -0
  66. package/lib/pythClient.d.ts +0 -1
  67. package/lib/pythClient.js +1 -1
  68. package/lib/token/index.d.ts +3 -0
  69. package/lib/token/index.js +38 -0
  70. package/lib/tx/defaultTxSender.d.ts +0 -1
  71. package/lib/tx/types.d.ts +0 -1
  72. package/lib/tx/utils.d.ts +0 -1
  73. package/lib/types.d.ts +147 -3
  74. package/lib/types.js +36 -1
  75. package/lib/util/computeUnits.d.ts +0 -1
  76. package/lib/util/tps.d.ts +0 -1
  77. package/lib/wallet.d.ts +0 -1
  78. package/package.json +11 -3
  79. package/src/accounts/bulkAccountLoader.ts +215 -0
  80. package/src/accounts/bulkUserSubscription.ts +28 -0
  81. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +326 -0
  82. package/src/accounts/pollingTokenAccountSubscriber.ts +99 -0
  83. package/src/accounts/pollingUserAccountSubscriber.ts +194 -0
  84. package/src/accounts/types.ts +48 -1
  85. package/src/accounts/utils.ts +3 -0
  86. package/src/accounts/webSocketAccountSubscriber.ts +67 -17
  87. package/src/accounts/{defaultClearingHouseAccountSubscriber.ts → webSocketClearingHouseAccountSubscriber.ts} +51 -1
  88. package/src/accounts/{defaultUserAccountSubscriber.ts → webSocketUserAccountSubscriber.ts} +33 -3
  89. package/src/addresses.ts +37 -0
  90. package/src/admin.ts +92 -24
  91. package/src/clearingHouse.ts +455 -22
  92. package/src/clearingHouseUser.ts +190 -108
  93. package/src/constants/markets.ts +17 -1
  94. package/src/constants/numericConstants.ts +3 -1
  95. package/src/examples/makeTradeExample.ts +4 -1
  96. package/src/factory/clearingHouse.ts +125 -0
  97. package/src/factory/clearingHouseUser.ts +73 -0
  98. package/src/idl/clearing_house.json +1066 -39
  99. package/src/index.ts +11 -2
  100. package/src/math/amm.ts +47 -14
  101. package/src/math/conversion.ts +1 -1
  102. package/src/math/insuranceFund.ts +1 -1
  103. package/src/math/market.ts +28 -2
  104. package/src/math/orders.ts +44 -0
  105. package/src/math/position.ts +24 -4
  106. package/src/math/utils.ts +1 -1
  107. package/src/mockUSDCFaucet.ts +1 -1
  108. package/src/orderParams.ts +151 -0
  109. package/src/orders.ts +236 -0
  110. package/src/token/index.ts +37 -0
  111. package/src/types.ts +130 -2
  112. package/tsconfig.json +0 -1
  113. package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts.map +0 -1
  114. package/lib/accounts/defaultUserAccountSubscriber.d.ts.map +0 -1
  115. package/lib/accounts/types.d.ts.map +0 -1
  116. package/lib/accounts/webSocketAccountSubscriber.d.ts.map +0 -1
  117. package/lib/addresses.d.ts.map +0 -1
  118. package/lib/admin.d.ts.map +0 -1
  119. package/lib/assert/assert.d.ts.map +0 -1
  120. package/lib/clearingHouse.d.ts.map +0 -1
  121. package/lib/clearingHouseUser.d.ts.map +0 -1
  122. package/lib/config.d.ts.map +0 -1
  123. package/lib/constants/markets.d.ts.map +0 -1
  124. package/lib/constants/numericConstants.d.ts.map +0 -1
  125. package/lib/examples/makeTradeExample.d.ts.map +0 -1
  126. package/lib/index.d.ts.map +0 -1
  127. package/lib/math/amm.d.ts.map +0 -1
  128. package/lib/math/conversion.d.ts.map +0 -1
  129. package/lib/math/funding.d.ts.map +0 -1
  130. package/lib/math/insuranceFund.d.ts.map +0 -1
  131. package/lib/math/market.d.ts.map +0 -1
  132. package/lib/math/position.d.ts.map +0 -1
  133. package/lib/math/trade.d.ts.map +0 -1
  134. package/lib/math/utils.d.ts.map +0 -1
  135. package/lib/mockUSDCFaucet.d.ts.map +0 -1
  136. package/lib/pythClient.d.ts.map +0 -1
  137. package/lib/tx/defaultTxSender.d.ts.map +0 -1
  138. package/lib/tx/types.d.ts.map +0 -1
  139. package/lib/tx/utils.d.ts.map +0 -1
  140. package/lib/types.d.ts.map +0 -1
  141. package/lib/util/computeUnits.d.ts.map +0 -1
  142. package/lib/util/tps.d.ts.map +0 -1
  143. package/lib/wallet.d.ts.map +0 -1
package/lib/index.d.ts CHANGED
@@ -1,14 +1,20 @@
1
1
  import { BN } from '@project-serum/anchor';
2
+ import { PublicKey } from '@solana/web3.js';
2
3
  export * from './mockUSDCFaucet';
3
4
  export * from './pythClient';
4
5
  export * from './types';
5
6
  export * from './constants/markets';
6
- export * from './accounts/defaultClearingHouseAccountSubscriber';
7
+ export * from './accounts/webSocketClearingHouseAccountSubscriber';
8
+ export * from './accounts/bulkAccountLoader';
9
+ export * from './accounts/pollingClearingHouseAccountSubscriber';
10
+ export * from './accounts/pollingTokenAccountSubscriber';
7
11
  export * from './accounts/types';
8
12
  export * from './addresses';
9
13
  export * from './admin';
10
14
  export * from './clearingHouseUser';
11
15
  export * from './clearingHouse';
16
+ export * from './factory/clearingHouse';
17
+ export * from './factory/clearingHouseUser';
12
18
  export * from './math/conversion';
13
19
  export * from './math/funding';
14
20
  export * from './math/insuranceFund';
@@ -16,6 +22,9 @@ export * from './math/market';
16
22
  export * from './math/position';
17
23
  export * from './math/amm';
18
24
  export * from './math/trade';
25
+ export * from './math/orders';
26
+ export * from './orders';
27
+ export * from './orderParams';
19
28
  export * from './wallet';
20
29
  export * from './types';
21
30
  export * from './math/utils';
@@ -23,5 +32,4 @@ export * from './config';
23
32
  export * from './constants/numericConstants';
24
33
  export * from './util/computeUnits';
25
34
  export * from './util/tps';
26
- export { BN };
27
- //# sourceMappingURL=index.d.ts.map
35
+ export { BN, PublicKey };
package/lib/index.js CHANGED
@@ -10,19 +10,26 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
10
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.BN = void 0;
13
+ exports.PublicKey = exports.BN = void 0;
14
14
  const anchor_1 = require("@project-serum/anchor");
15
15
  Object.defineProperty(exports, "BN", { enumerable: true, get: function () { return anchor_1.BN; } });
16
+ const web3_js_1 = require("@solana/web3.js");
17
+ Object.defineProperty(exports, "PublicKey", { enumerable: true, get: function () { return web3_js_1.PublicKey; } });
16
18
  __exportStar(require("./mockUSDCFaucet"), exports);
17
19
  __exportStar(require("./pythClient"), exports);
18
20
  __exportStar(require("./types"), exports);
19
21
  __exportStar(require("./constants/markets"), exports);
20
- __exportStar(require("./accounts/defaultClearingHouseAccountSubscriber"), exports);
22
+ __exportStar(require("./accounts/webSocketClearingHouseAccountSubscriber"), exports);
23
+ __exportStar(require("./accounts/bulkAccountLoader"), exports);
24
+ __exportStar(require("./accounts/pollingClearingHouseAccountSubscriber"), exports);
25
+ __exportStar(require("./accounts/pollingTokenAccountSubscriber"), exports);
21
26
  __exportStar(require("./accounts/types"), exports);
22
27
  __exportStar(require("./addresses"), exports);
23
28
  __exportStar(require("./admin"), exports);
24
29
  __exportStar(require("./clearingHouseUser"), exports);
25
30
  __exportStar(require("./clearingHouse"), exports);
31
+ __exportStar(require("./factory/clearingHouse"), exports);
32
+ __exportStar(require("./factory/clearingHouseUser"), exports);
26
33
  __exportStar(require("./math/conversion"), exports);
27
34
  __exportStar(require("./math/funding"), exports);
28
35
  __exportStar(require("./math/insuranceFund"), exports);
@@ -30,6 +37,9 @@ __exportStar(require("./math/market"), exports);
30
37
  __exportStar(require("./math/position"), exports);
31
38
  __exportStar(require("./math/amm"), exports);
32
39
  __exportStar(require("./math/trade"), exports);
40
+ __exportStar(require("./math/orders"), exports);
41
+ __exportStar(require("./orders"), exports);
42
+ __exportStar(require("./orderParams"), exports);
33
43
  __exportStar(require("./wallet"), exports);
34
44
  __exportStar(require("./types"), exports);
35
45
  __exportStar(require("./math/utils"), exports);
package/lib/math/amm.d.ts CHANGED
@@ -63,4 +63,4 @@ export declare function calculateRepegCost(market: Market, marketIndex: BN, newP
63
63
  * @returns cost : Precision MARK_PRICE_PRECISION
64
64
  */
65
65
  export declare function calculateTerminalPrice(market: Market): BN;
66
- //# sourceMappingURL=amm.d.ts.map
66
+ export declare function calculateMaxBaseAssetAmountToTrade(amm: AMM, limit_price: BN): [BN, PositionDirection];
package/lib/math/amm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculateTerminalPrice = exports.calculateRepegCost = exports.calculateAdjustKCost = exports.getSwapDirection = exports.calculateSwapOutput = exports.calculateAmmReservesAfterSwap = exports.calculatePrice = void 0;
3
+ exports.calculateMaxBaseAssetAmountToTrade = exports.calculateTerminalPrice = exports.calculateRepegCost = exports.calculateAdjustKCost = exports.getSwapDirection = exports.calculateSwapOutput = exports.calculateAmmReservesAfterSwap = exports.calculatePrice = void 0;
4
4
  const anchor_1 = require("@project-serum/anchor");
5
5
  const numericConstants_1 = require("../constants/numericConstants");
6
6
  const position_1 = require("./position");
@@ -36,7 +36,7 @@ exports.calculatePrice = calculatePrice;
36
36
  * @returns quoteAssetReserve and baseAssetReserve after swap. : Precision AMM_RESERVE_PRECISION
37
37
  */
38
38
  function calculateAmmReservesAfterSwap(amm, inputAssetType, swapAmount, swapDirection) {
39
- (0, assert_1.assert)(swapAmount.gte(numericConstants_1.ZERO), 'swapAmount must be greater than 0');
39
+ assert_1.assert(swapAmount.gte(numericConstants_1.ZERO), 'swapAmount must be greater than 0');
40
40
  let newQuoteAssetReserve;
41
41
  let newBaseAssetReserve;
42
42
  if (inputAssetType === 'quote') {
@@ -79,12 +79,10 @@ exports.calculateSwapOutput = calculateSwapOutput;
79
79
  * @param positionDirection
80
80
  */
81
81
  function getSwapDirection(inputAssetType, positionDirection) {
82
- if (positionDirection === types_1.PositionDirection.LONG &&
83
- inputAssetType === 'base') {
82
+ if (types_1.isVariant(positionDirection, 'long') && inputAssetType === 'base') {
84
83
  return types_1.SwapDirection.REMOVE;
85
84
  }
86
- if (positionDirection === types_1.PositionDirection.SHORT &&
87
- inputAssetType === 'quote') {
85
+ if (types_1.isVariant(positionDirection, 'short') && inputAssetType === 'quote') {
88
86
  return types_1.SwapDirection.REMOVE;
89
87
  }
90
88
  return types_1.SwapDirection.ADD;
@@ -104,8 +102,9 @@ function calculateAdjustKCost(market, marketIndex, numerator, denomenator) {
104
102
  lastCumulativeFundingRate: market.amm.cumulativeFundingRate,
105
103
  marketIndex: new anchor_1.BN(marketIndex),
106
104
  quoteAssetAmount: new anchor_1.BN(0),
105
+ openOrders: new anchor_1.BN(0),
107
106
  };
108
- const currentValue = (0, position_1.calculateBaseAssetValue)(market, netUserPosition);
107
+ const currentValue = position_1.calculateBaseAssetValue(market, netUserPosition);
109
108
  const marketNewK = Object.assign({}, market);
110
109
  marketNewK.amm = Object.assign({}, market.amm);
111
110
  marketNewK.amm.baseAssetReserve = market.amm.baseAssetReserve
@@ -116,7 +115,7 @@ function calculateAdjustKCost(market, marketIndex, numerator, denomenator) {
116
115
  .div(denomenator);
117
116
  marketNewK.amm.sqrtK = market.amm.sqrtK.mul(numerator).div(denomenator);
118
117
  netUserPosition.quoteAssetAmount = currentValue;
119
- const cost = (0, __1.calculatePositionPNL)(marketNewK, netUserPosition);
118
+ const cost = __1.calculatePositionPNL(marketNewK, netUserPosition);
120
119
  return cost;
121
120
  }
122
121
  exports.calculateAdjustKCost = calculateAdjustKCost;
@@ -134,16 +133,17 @@ function calculateRepegCost(market, marketIndex, newPeg) {
134
133
  lastCumulativeFundingRate: market.amm.cumulativeFundingRate,
135
134
  marketIndex: new anchor_1.BN(marketIndex),
136
135
  quoteAssetAmount: new anchor_1.BN(0),
136
+ openOrders: new anchor_1.BN(0),
137
137
  };
138
- const currentValue = (0, position_1.calculateBaseAssetValue)(market, netUserPosition);
138
+ const currentValue = position_1.calculateBaseAssetValue(market, netUserPosition);
139
139
  netUserPosition.quoteAssetAmount = currentValue;
140
- const prevMarketPrice = (0, __1.calculateMarkPrice)(market);
140
+ const prevMarketPrice = __1.calculateMarkPrice(market);
141
141
  const marketNewPeg = Object.assign({}, market);
142
142
  marketNewPeg.amm = Object.assign({}, market.amm);
143
143
  // const marketNewPeg = JSON.parse(JSON.stringify(market));
144
144
  marketNewPeg.amm.pegMultiplier = newPeg;
145
- console.log('Price moves from', (0, __1.convertToNumber)(prevMarketPrice), 'to', (0, __1.convertToNumber)((0, __1.calculateMarkPrice)(marketNewPeg)));
146
- const cost = (0, __1.calculatePositionPNL)(marketNewPeg, netUserPosition);
145
+ console.log('Price moves from', __1.convertToNumber(prevMarketPrice), 'to', __1.convertToNumber(__1.calculateMarkPrice(marketNewPeg)));
146
+ const cost = __1.calculatePositionPNL(marketNewPeg, netUserPosition);
147
147
  return cost;
148
148
  }
149
149
  exports.calculateRepegCost = calculateRepegCost;
@@ -154,9 +154,6 @@ exports.calculateRepegCost = calculateRepegCost;
154
154
  * @returns cost : Precision MARK_PRICE_PRECISION
155
155
  */
156
156
  function calculateTerminalPrice(market) {
157
- if (!market.initialized) {
158
- return new anchor_1.BN(0);
159
- }
160
157
  const directionToClose = market.baseAssetAmount.gt(numericConstants_1.ZERO)
161
158
  ? types_1.PositionDirection.SHORT
162
159
  : types_1.PositionDirection.LONG;
@@ -169,3 +166,29 @@ function calculateTerminalPrice(market) {
169
166
  return terminalPrice;
170
167
  }
171
168
  exports.calculateTerminalPrice = calculateTerminalPrice;
169
+ function calculateMaxBaseAssetAmountToTrade(amm, limit_price) {
170
+ const invariant = amm.sqrtK.mul(amm.sqrtK);
171
+ const newBaseAssetReserveSquared = invariant
172
+ .mul(numericConstants_1.MARK_PRICE_PRECISION)
173
+ .mul(amm.pegMultiplier)
174
+ .div(limit_price)
175
+ .div(numericConstants_1.PEG_PRECISION);
176
+ const newBaseAssetReserve = __1.squareRootBN(newBaseAssetReserveSquared);
177
+ if (newBaseAssetReserve.gt(amm.baseAssetReserve)) {
178
+ return [
179
+ newBaseAssetReserve.sub(amm.baseAssetReserve),
180
+ types_1.PositionDirection.SHORT,
181
+ ];
182
+ }
183
+ else if (newBaseAssetReserve.lt(amm.baseAssetReserve)) {
184
+ return [
185
+ amm.baseAssetReserve.sub(newBaseAssetReserve),
186
+ types_1.PositionDirection.LONG,
187
+ ];
188
+ }
189
+ else {
190
+ console.log('tradeSize Too Small');
191
+ return [new anchor_1.BN(0), types_1.PositionDirection.LONG];
192
+ }
193
+ }
194
+ exports.calculateMaxBaseAssetAmountToTrade = calculateMaxBaseAssetAmountToTrade;
@@ -1,4 +1,3 @@
1
- import BN from 'bn.js';
1
+ import { BN } from '../';
2
2
  export declare const convertToNumber: (bigNumber: BN, precision?: BN) => number;
3
3
  export declare const convertBaseAssetAmountToNumber: (baseAssetAmount: BN) => number;
4
- //# sourceMappingURL=conversion.d.ts.map
@@ -10,6 +10,6 @@ const convertToNumber = (bigNumber, precision = numericConstants_1.MARK_PRICE_PR
10
10
  };
11
11
  exports.convertToNumber = convertToNumber;
12
12
  const convertBaseAssetAmountToNumber = (baseAssetAmount) => {
13
- return (0, exports.convertToNumber)(baseAssetAmount, numericConstants_1.MARK_PRICE_PRECISION.mul(numericConstants_1.PEG_PRECISION));
13
+ return exports.convertToNumber(baseAssetAmount, numericConstants_1.MARK_PRICE_PRECISION.mul(numericConstants_1.PEG_PRECISION));
14
14
  };
15
15
  exports.convertBaseAssetAmountToNumber = convertBaseAssetAmountToNumber;
@@ -41,4 +41,3 @@ export declare function calculateLongShortFundingRateAndLiveTwaps(market: Market
41
41
  * @returns Estimated fee pool size
42
42
  */
43
43
  export declare function calculateFundingPool(market: Market): BN;
44
- //# sourceMappingURL=funding.d.ts.map
@@ -40,7 +40,7 @@ function calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustm
40
40
  const lastMarkPriceTwapTs = market.amm.lastMarkPriceTwapTs;
41
41
  const timeSinceLastMarkChange = now.sub(lastMarkPriceTwapTs);
42
42
  const markTwapTimeSinceLastUpdate = anchor_1.BN.max(secondsInHour, secondsInHour.sub(timeSinceLastMarkChange));
43
- const baseAssetPriceWithMantissa = (0, market_1.calculateMarkPrice)(market);
43
+ const baseAssetPriceWithMantissa = market_1.calculateMarkPrice(market);
44
44
  const markTwapWithMantissa = markTwapTimeSinceLastUpdate
45
45
  .mul(lastMarkTwapWithMantissa)
46
46
  .add(timeSinceLastMarkChange.mul(baseAssetPriceWithMantissa))
@@ -1,5 +1,6 @@
1
+ /// <reference types="bn.js" />
1
2
  import { MarketsAccount, StateAccount } from '../types';
2
- import BN from 'bn.js';
3
+ import { BN } from '../';
3
4
  import { Connection } from '@solana/web3.js';
4
5
  /**
5
6
  * In the case of a levered loss, the exchange first pays out undistributed fees and then the insurance fund.
@@ -12,4 +13,3 @@ import { Connection } from '@solana/web3.js';
12
13
  * @returns Precision : QUOTE_ASSET_PRECISION
13
14
  */
14
15
  export declare function calculateInsuranceFundSize(connection: Connection, state: StateAccount, marketsAccount: MarketsAccount): Promise<BN>;
15
- //# sourceMappingURL=insuranceFund.d.ts.map
@@ -8,12 +8,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
11
  Object.defineProperty(exports, "__esModule", { value: true });
15
12
  exports.calculateInsuranceFundSize = void 0;
16
- const bn_js_1 = __importDefault(require("bn.js"));
13
+ const __1 = require("../");
17
14
  /**
18
15
  * In the case of a levered loss, the exchange first pays out undistributed fees and then the insurance fund.
19
16
  * Thus the de facto size of the insurance fund is the amount in the insurance vault plus the sum of each markets
@@ -27,9 +24,9 @@ const bn_js_1 = __importDefault(require("bn.js"));
27
24
  function calculateInsuranceFundSize(connection, state, marketsAccount) {
28
25
  return __awaiter(this, void 0, void 0, function* () {
29
26
  const insuranceVaultPublicKey = state.insuranceVault;
30
- const insuranceVaultAmount = new bn_js_1.default((yield connection.getTokenAccountBalance(insuranceVaultPublicKey)).value.amount);
27
+ const insuranceVaultAmount = new __1.BN((yield connection.getTokenAccountBalance(insuranceVaultPublicKey)).value.amount);
31
28
  return marketsAccount.markets.reduce((insuranceVaultAmount, market) => {
32
- return insuranceVaultAmount.add(market.amm.totalFee.div(new bn_js_1.default(2)));
29
+ return insuranceVaultAmount.add(market.amm.totalFee.div(new __1.BN(2)));
33
30
  }, insuranceVaultAmount);
34
31
  });
35
32
  }
@@ -1,6 +1,6 @@
1
1
  /// <reference types="bn.js" />
2
2
  import { BN } from '@project-serum/anchor';
3
- import { Market } from '../types';
3
+ import { Market, PositionDirection } from '../types';
4
4
  /**
5
5
  * Calculates market mark price
6
6
  *
@@ -8,4 +8,4 @@ import { Market } from '../types';
8
8
  * @return markPrice : Precision MARK_PRICE_PRECISION
9
9
  */
10
10
  export declare function calculateMarkPrice(market: Market): BN;
11
- //# sourceMappingURL=market.d.ts.map
11
+ export declare function calculateNewMarketAfterTrade(baseAssetAmount: BN, direction: PositionDirection, market: Market): Market;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculateMarkPrice = void 0;
3
+ exports.calculateNewMarketAfterTrade = exports.calculateMarkPrice = void 0;
4
4
  const amm_1 = require("./amm");
5
5
  /**
6
6
  * Calculates market mark price
@@ -9,6 +9,16 @@ const amm_1 = require("./amm");
9
9
  * @return markPrice : Precision MARK_PRICE_PRECISION
10
10
  */
11
11
  function calculateMarkPrice(market) {
12
- return (0, amm_1.calculatePrice)(market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier);
12
+ return amm_1.calculatePrice(market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier);
13
13
  }
14
14
  exports.calculateMarkPrice = calculateMarkPrice;
15
+ function calculateNewMarketAfterTrade(baseAssetAmount, direction, market) {
16
+ const [newQuoteAssetReserve, newBaseAssetReserve] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'base', baseAssetAmount.abs(), amm_1.getSwapDirection('base', direction));
17
+ const newAmm = Object.assign({}, market.amm);
18
+ const newMarket = Object.assign({}, market);
19
+ newMarket.amm = newAmm;
20
+ newMarket.amm.quoteAssetReserve = newQuoteAssetReserve;
21
+ newMarket.amm.baseAssetReserve = newBaseAssetReserve;
22
+ return newMarket;
23
+ }
24
+ exports.calculateNewMarketAfterTrade = calculateNewMarketAfterTrade;
@@ -0,0 +1,3 @@
1
+ import { ClearingHouseUser } from '../clearingHouseUser';
2
+ import { Order } from '../types';
3
+ export declare function isOrderRiskIncreasing(user: ClearingHouseUser, order: Order): boolean;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isOrderRiskIncreasing = void 0;
4
+ const types_1 = require("../types");
5
+ const numericConstants_1 = require("../constants/numericConstants");
6
+ function isOrderRiskIncreasing(user, order) {
7
+ if (types_1.isVariant(order.status, 'init')) {
8
+ return false;
9
+ }
10
+ const position = user.getUserPosition(order.marketIndex) ||
11
+ user.getEmptyPosition(order.marketIndex);
12
+ // if no position exists, it's risk increasing
13
+ if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
14
+ return true;
15
+ }
16
+ // if position is long and order is long
17
+ if (position.baseAssetAmount.gt(numericConstants_1.ZERO) && types_1.isVariant(order.direction, 'long')) {
18
+ return true;
19
+ }
20
+ // if position is short and order is short
21
+ if (position.baseAssetAmount.lt(numericConstants_1.ZERO) &&
22
+ types_1.isVariant(order.direction, 'short')) {
23
+ return true;
24
+ }
25
+ const baseAssetAmountToFill = order.baseAssetAmount.sub(order.baseAssetAmountFilled);
26
+ // if order will flip position
27
+ if (baseAssetAmountToFill.gt(position.baseAssetAmount.abs().mul(numericConstants_1.TWO))) {
28
+ return true;
29
+ }
30
+ return false;
31
+ }
32
+ exports.isOrderRiskIncreasing = isOrderRiskIncreasing;
@@ -1,5 +1,6 @@
1
- import BN from 'bn.js';
2
- import { Market, UserPosition } from '../types';
1
+ /// <reference types="bn.js" />
2
+ import { BN } from '../';
3
+ import { Market, PositionDirection, UserPosition } from '../types';
3
4
  /**
4
5
  * calculateBaseAssetValue
5
6
  * = market value of closing entire position
@@ -30,4 +31,6 @@ export declare function calculatePositionFundingPNL(market: Market, marketPositi
30
31
  * @returns Precision: MARK_PRICE_PRECISION (10^10)
31
32
  */
32
33
  export declare function calculateEntryPrice(userPosition: UserPosition): BN;
33
- //# sourceMappingURL=position.d.ts.map
34
+ export declare function findDirectionToClose(userPosition: UserPosition): PositionDirection;
35
+ export declare function positionCurrentDirection(userPosition: UserPosition): PositionDirection;
36
+ export declare function isEmptyPosition(userPosition: UserPosition): boolean;
@@ -1,10 +1,7 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.calculateEntryPrice = exports.calculatePositionFundingPNL = exports.calculatePositionPNL = exports.calculateBaseAssetValue = void 0;
7
- const bn_js_1 = __importDefault(require("bn.js"));
3
+ exports.isEmptyPosition = exports.positionCurrentDirection = exports.findDirectionToClose = exports.calculateEntryPrice = exports.calculatePositionFundingPNL = exports.calculatePositionPNL = exports.calculateBaseAssetValue = void 0;
4
+ const __1 = require("../");
8
5
  const numericConstants_1 = require("../constants/numericConstants");
9
6
  const types_1 = require("../types");
10
7
  const amm_1 = require("./amm");
@@ -19,10 +16,8 @@ function calculateBaseAssetValue(market, userPosition) {
19
16
  if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
20
17
  return numericConstants_1.ZERO;
21
18
  }
22
- const directionToClose = userPosition.baseAssetAmount.gt(numericConstants_1.ZERO)
23
- ? types_1.PositionDirection.SHORT
24
- : types_1.PositionDirection.LONG;
25
- const [newQuoteAssetReserve, _] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, 'base', userPosition.baseAssetAmount.abs(), (0, amm_1.getSwapDirection)('base', directionToClose));
19
+ const directionToClose = findDirectionToClose(userPosition);
20
+ const [newQuoteAssetReserve, _] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'base', userPosition.baseAssetAmount.abs(), amm_1.getSwapDirection('base', directionToClose));
26
21
  switch (directionToClose) {
27
22
  case types_1.PositionDirection.SHORT:
28
23
  return market.amm.quoteAssetReserve
@@ -86,7 +81,7 @@ function calculatePositionFundingPNL(market, marketPosition) {
86
81
  .mul(marketPosition.baseAssetAmount)
87
82
  .div(numericConstants_1.AMM_RESERVE_PRECISION)
88
83
  .div(numericConstants_1.FUNDING_PAYMENT_PRECISION)
89
- .mul(new bn_js_1.default(-1));
84
+ .mul(new __1.BN(-1));
90
85
  return perPositionFundingRate;
91
86
  }
92
87
  exports.calculatePositionFundingPNL = calculatePositionFundingPNL;
@@ -106,3 +101,19 @@ function calculateEntryPrice(userPosition) {
106
101
  .abs();
107
102
  }
108
103
  exports.calculateEntryPrice = calculateEntryPrice;
104
+ function findDirectionToClose(userPosition) {
105
+ return userPosition.baseAssetAmount.gt(numericConstants_1.ZERO)
106
+ ? types_1.PositionDirection.SHORT
107
+ : types_1.PositionDirection.LONG;
108
+ }
109
+ exports.findDirectionToClose = findDirectionToClose;
110
+ function positionCurrentDirection(userPosition) {
111
+ return userPosition.baseAssetAmount.gte(numericConstants_1.ZERO)
112
+ ? types_1.PositionDirection.LONG
113
+ : types_1.PositionDirection.SHORT;
114
+ }
115
+ exports.positionCurrentDirection = positionCurrentDirection;
116
+ function isEmptyPosition(userPosition) {
117
+ return (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO) && userPosition.openOrders.eq(numericConstants_1.ZERO));
118
+ }
119
+ exports.isEmptyPosition = isEmptyPosition;
@@ -45,4 +45,3 @@ export declare function calculateTradeAcquiredAmounts(direction: PositionDirecti
45
45
  * ]
46
46
  */
47
47
  export declare function calculateTargetPriceTrade(market: Market, targetPrice: BN, pct?: BN, outputAssetType?: AssetType): [PositionDirection, BN, BN, BN];
48
- //# sourceMappingURL=trade.d.ts.map
package/lib/math/trade.js CHANGED
@@ -25,18 +25,18 @@ const MAXPCT = new anchor_1.BN(1000); //percentage units are [0,1000] => [0,1]
25
25
  * 'newPrice' => the price of the asset after the trade : Precision MARK_PRICE_PRECISION
26
26
  */
27
27
  function calculateTradeSlippage(direction, amount, market, inputAssetType = 'quote') {
28
- const oldPrice = (0, market_1.calculateMarkPrice)(market);
28
+ const oldPrice = market_1.calculateMarkPrice(market);
29
29
  if (amount.eq(numericConstants_1.ZERO)) {
30
30
  return [numericConstants_1.ZERO, numericConstants_1.ZERO, oldPrice, oldPrice];
31
31
  }
32
32
  const [acquiredBase, acquiredQuote] = calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType);
33
- const entryPrice = (0, amm_1.calculatePrice)(acquiredBase, acquiredQuote, market.amm.pegMultiplier).mul(new anchor_1.BN(-1));
34
- const newPrice = (0, amm_1.calculatePrice)(market.amm.baseAssetReserve.sub(acquiredBase), market.amm.quoteAssetReserve.sub(acquiredQuote), market.amm.pegMultiplier);
33
+ const entryPrice = amm_1.calculatePrice(acquiredBase, acquiredQuote, market.amm.pegMultiplier).mul(new anchor_1.BN(-1));
34
+ const newPrice = amm_1.calculatePrice(market.amm.baseAssetReserve.sub(acquiredBase), market.amm.quoteAssetReserve.sub(acquiredQuote), market.amm.pegMultiplier);
35
35
  if (direction == types_1.PositionDirection.SHORT) {
36
- (0, assert_1.assert)(newPrice.lt(oldPrice));
36
+ assert_1.assert(newPrice.lt(oldPrice));
37
37
  }
38
38
  else {
39
- (0, assert_1.assert)(oldPrice.lt(newPrice));
39
+ assert_1.assert(oldPrice.lt(newPrice));
40
40
  }
41
41
  const pctMaxSlippage = newPrice
42
42
  .sub(oldPrice)
@@ -64,7 +64,7 @@ function calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType
64
64
  if (amount.eq(numericConstants_1.ZERO)) {
65
65
  return [numericConstants_1.ZERO, numericConstants_1.ZERO];
66
66
  }
67
- const [newQuoteAssetReserve, newBaseAssetReserve] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, inputAssetType, amount, (0, amm_1.getSwapDirection)(inputAssetType, direction));
67
+ const [newQuoteAssetReserve, newBaseAssetReserve] = amm_1.calculateAmmReservesAfterSwap(market.amm, inputAssetType, amount, amm_1.getSwapDirection(inputAssetType, direction));
68
68
  const acquiredBase = market.amm.baseAssetReserve.sub(newBaseAssetReserve);
69
69
  const acquiredQuote = market.amm.quoteAssetReserve.sub(newQuoteAssetReserve);
70
70
  return [acquiredBase, acquiredQuote];
@@ -86,10 +86,10 @@ exports.calculateTradeAcquiredAmounts = calculateTradeAcquiredAmounts;
86
86
  * ]
87
87
  */
88
88
  function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAssetType = 'quote') {
89
- (0, assert_1.assert)(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
90
- (0, assert_1.assert)(targetPrice.gt(numericConstants_1.ZERO));
91
- (0, assert_1.assert)(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
92
- const markPriceBefore = (0, market_1.calculateMarkPrice)(market);
89
+ assert_1.assert(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
90
+ assert_1.assert(targetPrice.gt(numericConstants_1.ZERO));
91
+ assert_1.assert(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
92
+ const markPriceBefore = market_1.calculateMarkPrice(market);
93
93
  if (targetPrice.gt(markPriceBefore)) {
94
94
  const priceGap = targetPrice.sub(markPriceBefore);
95
95
  const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
@@ -114,11 +114,11 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
114
114
  let markPriceAfter;
115
115
  if (markPriceBefore.gt(targetPrice)) {
116
116
  // overestimate y2
117
- baseAssetReserveAfter = (0, utils_1.squareRootBN)(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
117
+ baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
118
118
  quoteAssetReserveAfter = k
119
119
  .div(numericConstants_1.MARK_PRICE_PRECISION)
120
120
  .div(baseAssetReserveAfter);
121
- markPriceAfter = (0, amm_1.calculatePrice)(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
121
+ markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
122
122
  direction = types_1.PositionDirection.SHORT;
123
123
  tradeSize = quoteAssetReserveBefore
124
124
  .sub(quoteAssetReserveAfter)
@@ -129,11 +129,11 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
129
129
  }
130
130
  else if (markPriceBefore.lt(targetPrice)) {
131
131
  // underestimate y2
132
- baseAssetReserveAfter = (0, utils_1.squareRootBN)(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
132
+ baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
133
133
  quoteAssetReserveAfter = k
134
134
  .div(numericConstants_1.MARK_PRICE_PRECISION)
135
135
  .div(baseAssetReserveAfter);
136
- markPriceAfter = (0, amm_1.calculatePrice)(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
136
+ markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
137
137
  direction = types_1.PositionDirection.LONG;
138
138
  tradeSize = quoteAssetReserveAfter
139
139
  .sub(quoteAssetReserveBefore)
@@ -160,8 +160,8 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
160
160
  .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
161
161
  .mul(numericConstants_1.MARK_PRICE_PRECISION)
162
162
  .div(baseSize.abs());
163
- (0, assert_1.assert)(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
164
- (0, assert_1.assert)(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
163
+ assert_1.assert(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
164
+ assert_1.assert(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
165
165
  tp2.toString() +
166
166
  '>=' +
167
167
  tp1.toString() +
@@ -1,3 +1,3 @@
1
1
  /// <reference types="bn.js" />
2
- export declare const squareRootBN: (n: any, closeness?: import("bn.js")) => any;
3
- //# sourceMappingURL=utils.d.ts.map
2
+ import { BN } from '../';
3
+ export declare const squareRootBN: (n: any, closeness?: BN) => any;
package/lib/math/utils.js CHANGED
@@ -1,15 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.squareRootBN = void 0;
4
- const bn_js_1 = require("bn.js");
5
- const squareRootBN = (n, closeness = new bn_js_1.BN(1)) => {
4
+ const __1 = require("../");
5
+ const squareRootBN = (n, closeness = new __1.BN(1)) => {
6
6
  // Assuming the sqrt of n as n only
7
7
  let x = n;
8
8
  // The closed guess will be stored in the root
9
9
  let root;
10
10
  // To count the number of iterations
11
11
  let count = 0;
12
- const TWO = new bn_js_1.BN(2);
12
+ const TWO = new __1.BN(2);
13
13
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
14
14
  while (count < Number.MAX_SAFE_INTEGER) {
15
15
  count++;
@@ -1,8 +1,9 @@
1
+ /// <reference types="bn.js" />
1
2
  import * as anchor from '@project-serum/anchor';
2
3
  import { Program, Provider } from '@project-serum/anchor';
3
4
  import { AccountInfo } from '@solana/spl-token';
4
5
  import { ConfirmOptions, Connection, PublicKey, TransactionInstruction, TransactionSignature } from '@solana/web3.js';
5
- import BN from 'bn.js';
6
+ import { BN } from '.';
6
7
  import { IWallet } from './types';
7
8
  export declare class MockUSDCFaucet {
8
9
  connection: Connection;
@@ -33,4 +34,3 @@ export declare class MockUSDCFaucet {
33
34
  callback: (accountInfo: AccountInfo) => void;
34
35
  }): Promise<boolean>;
35
36
  }
36
- //# sourceMappingURL=mockUSDCFaucet.d.ts.map
@@ -0,0 +1,7 @@
1
+ /// <reference types="bn.js" />
2
+ import { OrderParams, OrderTriggerCondition, PositionDirection } from './types';
3
+ import { BN } from '@project-serum/anchor';
4
+ export declare function getLimitOrderParams(marketIndex: BN, direction: PositionDirection, baseAssetAmount: BN, price: BN, reduceOnly: boolean, discountToken?: boolean, referrer?: boolean, userOrderId?: number): OrderParams;
5
+ export declare function getTriggerMarketOrderParams(marketIndex: BN, direction: PositionDirection, baseAssetAmount: BN, triggerPrice: BN, triggerCondition: OrderTriggerCondition, reduceOnly: boolean, discountToken?: boolean, referrer?: boolean, userOrderId?: number): OrderParams;
6
+ export declare function getTriggerLimitOrderParams(marketIndex: BN, direction: PositionDirection, baseAssetAmount: BN, price: BN, triggerPrice: BN, triggerCondition: OrderTriggerCondition, reduceOnly: boolean, discountToken?: boolean, referrer?: boolean, userOrderId?: number): OrderParams;
7
+ export declare function getMarketOrderParams(marketIndex: BN, direction: PositionDirection, quoteAssetAmount: BN, baseAssetAmount: BN, reduceOnly: boolean, price?: BN, discountToken?: boolean, referrer?: boolean): OrderParams;