@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
package/src/math/repeg.js CHANGED
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
- exports.__esModule = true;
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.calculateBudgetedPeg = exports.calculateBudgetedK = exports.calculateBudgetedKBN = exports.calculateRepegCost = exports.calculateAdjustKCost = void 0;
4
- var anchor_1 = require("@project-serum/anchor");
5
- var assert_1 = require("../assert/assert");
6
- var numericConstants_1 = require("../constants/numericConstants");
4
+ const anchor_1 = require("@project-serum/anchor");
5
+ const assert_1 = require("../assert/assert");
6
+ const numericConstants_1 = require("../constants/numericConstants");
7
7
  /**
8
8
  * Helper function calculating adjust k cost
9
9
  * @param amm
@@ -13,13 +13,13 @@ var numericConstants_1 = require("../constants/numericConstants");
13
13
  */
14
14
  function calculateAdjustKCost(amm, numerator, denomenator) {
15
15
  // const k = market.amm.sqrtK.mul(market.amm.sqrtK);
16
- var x = amm.baseAssetReserve;
17
- var y = amm.quoteAssetReserve;
18
- var d = amm.netBaseAssetAmount;
19
- var Q = amm.pegMultiplier;
20
- var quoteScale = y.mul(d).mul(Q); //.div(AMM_RESERVE_PRECISION);
21
- var p = numerator.mul(numericConstants_1.MARK_PRICE_PRECISION).div(denomenator);
22
- var cost = quoteScale
16
+ const x = amm.baseAssetReserve;
17
+ const y = amm.quoteAssetReserve;
18
+ const d = amm.netBaseAssetAmount;
19
+ const Q = amm.pegMultiplier;
20
+ const quoteScale = y.mul(d).mul(Q); //.div(AMM_RESERVE_PRECISION);
21
+ const p = numerator.mul(numericConstants_1.MARK_PRICE_PRECISION).div(denomenator);
22
+ const cost = quoteScale
23
23
  .div(x.add(d))
24
24
  .sub(quoteScale
25
25
  .mul(p)
@@ -38,8 +38,8 @@ exports.calculateAdjustKCost = calculateAdjustKCost;
38
38
  * @returns cost : Precision QUOTE_ASSET_PRECISION
39
39
  */
40
40
  function calculateRepegCost(amm, newPeg) {
41
- var dqar = amm.quoteAssetReserve.sub(amm.terminalQuoteAssetReserve);
42
- var cost = dqar
41
+ const dqar = amm.quoteAssetReserve.sub(amm.terminalQuoteAssetReserve);
42
+ const cost = dqar
43
43
  .mul(newPeg.sub(amm.pegMultiplier))
44
44
  .div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
45
45
  .div(numericConstants_1.PEG_PRECISION);
@@ -47,32 +47,32 @@ function calculateRepegCost(amm, newPeg) {
47
47
  }
48
48
  exports.calculateRepegCost = calculateRepegCost;
49
49
  function calculateBudgetedKBN(x, y, budget, Q, d) {
50
- (0, assert_1.assert)(Q.gt(new anchor_1.BN(0)));
51
- var C = budget.mul(new anchor_1.BN(-1));
52
- var dSign = new anchor_1.BN(1);
50
+ assert_1.assert(Q.gt(new anchor_1.BN(0)));
51
+ const C = budget.mul(new anchor_1.BN(-1));
52
+ let dSign = new anchor_1.BN(1);
53
53
  if (d.lt(new anchor_1.BN(0))) {
54
54
  dSign = new anchor_1.BN(-1);
55
55
  }
56
- var pegged_y_d_d = y
56
+ const pegged_y_d_d = y
57
57
  .mul(d)
58
58
  .mul(d)
59
59
  .mul(Q)
60
60
  .div(numericConstants_1.AMM_RESERVE_PRECISION)
61
61
  .div(numericConstants_1.AMM_RESERVE_PRECISION)
62
62
  .div(numericConstants_1.PEG_PRECISION);
63
- var numer1 = pegged_y_d_d;
64
- var numer2 = C.mul(d)
63
+ const numer1 = pegged_y_d_d;
64
+ const numer2 = C.mul(d)
65
65
  .div(numericConstants_1.QUOTE_PRECISION)
66
66
  .mul(x.add(d))
67
67
  .div(numericConstants_1.AMM_RESERVE_PRECISION)
68
68
  .mul(dSign);
69
- var denom1 = C.mul(x)
69
+ const denom1 = C.mul(x)
70
70
  .mul(x.add(d))
71
71
  .div(numericConstants_1.AMM_RESERVE_PRECISION)
72
72
  .div(numericConstants_1.QUOTE_PRECISION);
73
- var denom2 = pegged_y_d_d;
74
- var numerator = numer1.sub(numer2).div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
75
- var denominator = denom1.add(denom2).div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
73
+ const denom2 = pegged_y_d_d;
74
+ const numerator = numer1.sub(numer2).div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
75
+ const denominator = denom1.add(denom2).div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
76
76
  return [numerator, denominator];
77
77
  }
78
78
  exports.calculateBudgetedKBN = calculateBudgetedKBN;
@@ -90,11 +90,11 @@ function calculateBudgetedK(amm, cost) {
90
90
  // = x/d**2 + 1 / d + mark/C
91
91
  // todo: assumes k = x * y
92
92
  // otherwise use: (y(1-p) + (kp^2/(x*p+d)) - k/(x+d)) * Q = C solve for p
93
- var x = amm.baseAssetReserve;
94
- var y = amm.quoteAssetReserve;
95
- var d = amm.netBaseAssetAmount;
96
- var Q = amm.pegMultiplier;
97
- var _a = calculateBudgetedKBN(x, y, cost, Q, d), numerator = _a[0], denominator = _a[1];
93
+ const x = amm.baseAssetReserve;
94
+ const y = amm.quoteAssetReserve;
95
+ const d = amm.netBaseAssetAmount;
96
+ const Q = amm.pegMultiplier;
97
+ const [numerator, denominator] = calculateBudgetedKBN(x, y, cost, Q, d);
98
98
  return [numerator, denominator];
99
99
  }
100
100
  exports.calculateBudgetedK = calculateBudgetedK;
@@ -104,25 +104,25 @@ function calculateBudgetedPeg(amm, cost, targetPrice) {
104
104
  // p = (d(y*d*Q - C(x+d))) / (C*x(x+d) + y*y*d*Q)
105
105
  // todo: assumes k = x * y
106
106
  // otherwise use: (y(1-p) + (kp^2/(x*p+d)) - k/(x+d)) * Q = C solve for p
107
- var targetPeg = targetPrice
107
+ const targetPeg = targetPrice
108
108
  .mul(amm.baseAssetReserve)
109
109
  .div(amm.quoteAssetReserve)
110
110
  .div(numericConstants_1.PRICE_DIV_PEG);
111
- var k = amm.sqrtK.mul(amm.sqrtK);
112
- var x = amm.baseAssetReserve;
113
- var y = amm.quoteAssetReserve;
114
- var d = amm.netBaseAssetAmount;
115
- var Q = amm.pegMultiplier;
116
- var C = cost.mul(new anchor_1.BN(-1));
117
- var deltaQuoteAssetReserves = y.sub(k.div(x.add(d)));
118
- var pegChangeDirection = targetPeg.sub(Q);
119
- var useTargetPeg = (deltaQuoteAssetReserves.lt(numericConstants_1.ZERO) && pegChangeDirection.gt(numericConstants_1.ZERO)) ||
111
+ const k = amm.sqrtK.mul(amm.sqrtK);
112
+ const x = amm.baseAssetReserve;
113
+ const y = amm.quoteAssetReserve;
114
+ const d = amm.netBaseAssetAmount;
115
+ const Q = amm.pegMultiplier;
116
+ const C = cost.mul(new anchor_1.BN(-1));
117
+ const deltaQuoteAssetReserves = y.sub(k.div(x.add(d)));
118
+ const pegChangeDirection = targetPeg.sub(Q);
119
+ const useTargetPeg = (deltaQuoteAssetReserves.lt(numericConstants_1.ZERO) && pegChangeDirection.gt(numericConstants_1.ZERO)) ||
120
120
  (deltaQuoteAssetReserves.gt(numericConstants_1.ZERO) && pegChangeDirection.lt(numericConstants_1.ZERO));
121
121
  if (deltaQuoteAssetReserves.eq(numericConstants_1.ZERO) || useTargetPeg) {
122
122
  return targetPeg;
123
123
  }
124
- var deltaPegMultiplier = C.mul(numericConstants_1.MARK_PRICE_PRECISION).div(deltaQuoteAssetReserves.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO));
125
- var newPeg = Q.sub(deltaPegMultiplier.mul(numericConstants_1.PEG_PRECISION).div(numericConstants_1.MARK_PRICE_PRECISION));
124
+ const deltaPegMultiplier = C.mul(numericConstants_1.MARK_PRICE_PRECISION).div(deltaQuoteAssetReserves.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO));
125
+ const newPeg = Q.sub(deltaPegMultiplier.mul(numericConstants_1.PEG_PRECISION).div(numericConstants_1.MARK_PRICE_PRECISION));
126
126
  return newPeg;
127
127
  }
128
128
  exports.calculateBudgetedPeg = calculateBudgetedPeg;
@@ -19,6 +19,7 @@ import {
19
19
  calculateSizeDiscountAssetWeight,
20
20
  calculateSizePremiumLiabilityWeight,
21
21
  } from './margin';
22
+ import { OraclePriceData } from '../oracles/types';
22
23
 
23
24
  export function getBalance(
24
25
  tokenAmount: BN,
@@ -54,6 +55,31 @@ export function getTokenAmount(
54
55
  return balanceAmount.mul(cumulativeInterest).div(precisionDecrease);
55
56
  }
56
57
 
58
+ export function getSignedTokenAmount(
59
+ tokenAmount: BN,
60
+ balanceType: SpotBalanceType
61
+ ): BN {
62
+ if (isVariant(balanceType, 'deposit')) {
63
+ return tokenAmount;
64
+ } else {
65
+ return tokenAmount.abs().neg();
66
+ }
67
+ }
68
+
69
+ export function getTokenValue(
70
+ tokenAmount: BN,
71
+ spotDecimals: number,
72
+ oraclePriceData: OraclePriceData
73
+ ): BN {
74
+ if (tokenAmount.eq(ZERO)) {
75
+ return ZERO;
76
+ }
77
+
78
+ const precisionDecrease = TEN.pow(new BN(10 + spotDecimals - 6));
79
+
80
+ return tokenAmount.mul(oraclePriceData.price).div(precisionDecrease);
81
+ }
82
+
57
83
  export function calculateAssetWeight(
58
84
  balanceAmount: BN,
59
85
  spotMarket: SpotMarketAccount,
@@ -1,6 +1,47 @@
1
- import { SpotPosition } from '../types';
1
+ import { SpotMarketAccount, SpotPosition } from '../types';
2
2
  import { ZERO } from '../constants/numericConstants';
3
+ import { BN } from '@project-serum/anchor';
4
+ import {
5
+ getSignedTokenAmount,
6
+ getTokenAmount,
7
+ getTokenValue,
8
+ } from './spotBalance';
9
+ import { OraclePriceData } from '../oracles/types';
3
10
 
4
11
  export function isSpotPositionAvailable(position: SpotPosition): boolean {
5
12
  return position.balance.eq(ZERO) && position.openOrders === 0;
6
13
  }
14
+
15
+ export function getWorstCaseTokenAmounts(
16
+ spotPosition: SpotPosition,
17
+ spotMarketAccount: SpotMarketAccount,
18
+ oraclePriceData: OraclePriceData
19
+ ): [BN, BN] {
20
+ const tokenAmount = getSignedTokenAmount(
21
+ getTokenAmount(
22
+ spotPosition.balance,
23
+ spotMarketAccount,
24
+ spotPosition.balanceType
25
+ ),
26
+ spotPosition.balanceType
27
+ );
28
+
29
+ const tokenAmountAllBidsFill = tokenAmount.add(spotPosition.openBids);
30
+ const tokenAmountAllAsksFill = tokenAmount.add(spotPosition.openAsks);
31
+
32
+ if (tokenAmountAllAsksFill.abs().gt(tokenAmountAllBidsFill.abs())) {
33
+ const worstCaseQuoteTokenAmount = getTokenValue(
34
+ spotPosition.openBids.neg(),
35
+ spotMarketAccount.decimals,
36
+ oraclePriceData
37
+ );
38
+ return [tokenAmountAllBidsFill, worstCaseQuoteTokenAmount];
39
+ } else {
40
+ const worstCaseQuoteTokenAmount = getTokenValue(
41
+ spotPosition.openAsks.neg(),
42
+ spotMarketAccount.decimals,
43
+ oraclePriceData
44
+ );
45
+ return [tokenAmountAllAsksFill, worstCaseQuoteTokenAmount];
46
+ }
47
+ }
package/src/math/trade.js CHANGED
@@ -1,15 +1,15 @@
1
1
  "use strict";
2
- exports.__esModule = true;
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.calculateTargetPriceTrade = exports.calculateTradeAcquiredAmounts = exports.calculateTradeSlippage = void 0;
4
- var types_1 = require("../types");
5
- var anchor_1 = require("@project-serum/anchor");
6
- var assert_1 = require("../assert/assert");
7
- var numericConstants_1 = require("../constants/numericConstants");
8
- var market_1 = require("./market");
9
- var amm_1 = require("./amm");
10
- var utils_1 = require("./utils");
11
- var types_2 = require("../types");
12
- var MAXPCT = new anchor_1.BN(1000); //percentage units are [0,1000] => [0,1]
4
+ const types_1 = require("../types");
5
+ const anchor_1 = require("@project-serum/anchor");
6
+ const assert_1 = require("../assert/assert");
7
+ const numericConstants_1 = require("../constants/numericConstants");
8
+ const market_1 = require("./market");
9
+ const amm_1 = require("./amm");
10
+ const utils_1 = require("./utils");
11
+ const types_2 = require("../types");
12
+ const MAXPCT = new anchor_1.BN(1000); //percentage units are [0,1000] => [0,1]
13
13
  /**
14
14
  * Calculates avg/max slippage (price impact) for candidate trade
15
15
  * @param direction
@@ -27,55 +27,53 @@ var MAXPCT = new anchor_1.BN(1000); //percentage units are [0,1000] => [0,1]
27
27
  *
28
28
  * 'newPrice' => the price of the asset after the trade : Precision MARK_PRICE_PRECISION
29
29
  */
30
- function calculateTradeSlippage(direction, amount, market, inputAssetType, oraclePriceData, useSpread) {
31
- if (inputAssetType === void 0) { inputAssetType = 'quote'; }
32
- if (useSpread === void 0) { useSpread = true; }
33
- var oldPrice;
30
+ function calculateTradeSlippage(direction, amount, market, inputAssetType = 'quote', oraclePriceData, useSpread = true) {
31
+ let oldPrice;
34
32
  if (useSpread && market.amm.baseSpread > 0) {
35
- if ((0, types_2.isVariant)(direction, 'long')) {
36
- oldPrice = (0, market_1.calculateAskPrice)(market, oraclePriceData);
33
+ if (types_2.isVariant(direction, 'long')) {
34
+ oldPrice = market_1.calculateAskPrice(market, oraclePriceData);
37
35
  }
38
36
  else {
39
- oldPrice = (0, market_1.calculateBidPrice)(market, oraclePriceData);
37
+ oldPrice = market_1.calculateBidPrice(market, oraclePriceData);
40
38
  }
41
39
  }
42
40
  else {
43
- oldPrice = (0, market_1.calculateMarkPrice)(market, oraclePriceData);
41
+ oldPrice = market_1.calculateMarkPrice(market, oraclePriceData);
44
42
  }
45
43
  if (amount.eq(numericConstants_1.ZERO)) {
46
44
  return [numericConstants_1.ZERO, numericConstants_1.ZERO, oldPrice, oldPrice];
47
45
  }
48
- var _a = calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType, oraclePriceData, useSpread), acquiredBaseReserve = _a[0], acquiredQuoteReserve = _a[1], acquiredQuoteAssetAmount = _a[2];
49
- var entryPrice = acquiredQuoteAssetAmount
46
+ const [acquiredBaseReserve, acquiredQuoteReserve, acquiredQuoteAssetAmount] = calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType, oraclePriceData, useSpread);
47
+ const entryPrice = acquiredQuoteAssetAmount
50
48
  .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
51
49
  .mul(numericConstants_1.MARK_PRICE_PRECISION)
52
50
  .div(acquiredBaseReserve.abs());
53
- var amm;
51
+ let amm;
54
52
  if (useSpread && market.amm.baseSpread > 0) {
55
- var _b = (0, amm_1.calculateUpdatedAMMSpreadReserves)(market.amm, direction, oraclePriceData), baseAssetReserve = _b.baseAssetReserve, quoteAssetReserve = _b.quoteAssetReserve, sqrtK = _b.sqrtK, newPeg = _b.newPeg;
53
+ const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, direction, oraclePriceData);
56
54
  amm = {
57
- baseAssetReserve: baseAssetReserve,
58
- quoteAssetReserve: quoteAssetReserve,
55
+ baseAssetReserve,
56
+ quoteAssetReserve,
59
57
  sqrtK: sqrtK,
60
- pegMultiplier: newPeg
58
+ pegMultiplier: newPeg,
61
59
  };
62
60
  }
63
61
  else {
64
62
  amm = market.amm;
65
63
  }
66
- var newPrice = (0, amm_1.calculatePrice)(amm.baseAssetReserve.sub(acquiredBaseReserve), amm.quoteAssetReserve.sub(acquiredQuoteReserve), amm.pegMultiplier);
64
+ const newPrice = amm_1.calculatePrice(amm.baseAssetReserve.sub(acquiredBaseReserve), amm.quoteAssetReserve.sub(acquiredQuoteReserve), amm.pegMultiplier);
67
65
  if (direction == types_1.PositionDirection.SHORT) {
68
- (0, assert_1.assert)(newPrice.lte(oldPrice));
66
+ assert_1.assert(newPrice.lte(oldPrice));
69
67
  }
70
68
  else {
71
- (0, assert_1.assert)(oldPrice.lte(newPrice));
69
+ assert_1.assert(oldPrice.lte(newPrice));
72
70
  }
73
- var pctMaxSlippage = newPrice
71
+ const pctMaxSlippage = newPrice
74
72
  .sub(oldPrice)
75
73
  .mul(numericConstants_1.MARK_PRICE_PRECISION)
76
74
  .div(oldPrice)
77
75
  .abs();
78
- var pctAvgSlippage = entryPrice
76
+ const pctAvgSlippage = entryPrice
79
77
  .sub(oldPrice)
80
78
  .mul(numericConstants_1.MARK_PRICE_PRECISION)
81
79
  .div(oldPrice)
@@ -94,31 +92,29 @@ exports.calculateTradeSlippage = calculateTradeSlippage;
94
92
  * | 'acquiredBase' => positive/negative change in user's base : BN AMM_RESERVE_PRECISION
95
93
  * | 'acquiredQuote' => positive/negative change in user's quote : BN TODO-PRECISION
96
94
  */
97
- function calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType, oraclePriceData, useSpread) {
98
- if (inputAssetType === void 0) { inputAssetType = 'quote'; }
99
- if (useSpread === void 0) { useSpread = true; }
95
+ function calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType = 'quote', oraclePriceData, useSpread = true) {
100
96
  if (amount.eq(numericConstants_1.ZERO)) {
101
97
  return [numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO];
102
98
  }
103
- var swapDirection = (0, amm_1.getSwapDirection)(inputAssetType, direction);
104
- var amm;
99
+ const swapDirection = amm_1.getSwapDirection(inputAssetType, direction);
100
+ let amm;
105
101
  if (useSpread && market.amm.baseSpread > 0) {
106
- var _a = (0, amm_1.calculateUpdatedAMMSpreadReserves)(market.amm, direction, oraclePriceData), baseAssetReserve = _a.baseAssetReserve, quoteAssetReserve = _a.quoteAssetReserve, sqrtK = _a.sqrtK, newPeg = _a.newPeg;
102
+ const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, direction, oraclePriceData);
107
103
  amm = {
108
- baseAssetReserve: baseAssetReserve,
109
- quoteAssetReserve: quoteAssetReserve,
104
+ baseAssetReserve,
105
+ quoteAssetReserve,
110
106
  sqrtK: sqrtK,
111
- pegMultiplier: newPeg
107
+ pegMultiplier: newPeg,
112
108
  };
113
109
  }
114
110
  else {
115
111
  amm = market.amm;
116
112
  }
117
- var _b = (0, amm_1.calculateAmmReservesAfterSwap)(amm, inputAssetType, amount, swapDirection), newQuoteAssetReserve = _b[0], newBaseAssetReserve = _b[1];
118
- var acquiredBase = amm.baseAssetReserve.sub(newBaseAssetReserve);
119
- var acquiredQuote = amm.quoteAssetReserve.sub(newQuoteAssetReserve);
120
- var acquiredQuoteAssetAmount = (0, amm_1.calculateQuoteAssetAmountSwapped)(acquiredQuote.abs(), amm.pegMultiplier, swapDirection);
121
- return [acquiredBase, acquiredQuote, acquiredQuoteAssetAmount];
113
+ const [newQuoteAssetReserve, newBaseAssetReserve] = amm_1.calculateAmmReservesAfterSwap(amm, inputAssetType, amount, swapDirection);
114
+ const acquiredBase = amm.baseAssetReserve.sub(newBaseAssetReserve);
115
+ const acquiredQuote = amm.quoteAssetReserve.sub(newQuoteAssetReserve);
116
+ const acquiredQuoteAssetamount = amm_1.calculateQuoteAssetAmountSwapped(acquiredQuote.abs(), amm.pegMultiplier, swapDirection);
117
+ return [acquiredBase, acquiredQuote, acquiredQuoteAssetamount];
122
118
  }
123
119
  exports.calculateTradeAcquiredAmounts = calculateTradeAcquiredAmounts;
124
120
  /**
@@ -138,36 +134,33 @@ exports.calculateTradeAcquiredAmounts = calculateTradeAcquiredAmounts;
138
134
  * targetPrice => the target price MARK_PRICE_PRECISION
139
135
  * ]
140
136
  */
141
- function calculateTargetPriceTrade(market, targetPrice, pct, outputAssetType, oraclePriceData, useSpread) {
142
- if (pct === void 0) { pct = MAXPCT; }
143
- if (outputAssetType === void 0) { outputAssetType = 'quote'; }
144
- if (useSpread === void 0) { useSpread = true; }
145
- (0, assert_1.assert)(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
146
- (0, assert_1.assert)(targetPrice.gt(numericConstants_1.ZERO));
147
- (0, assert_1.assert)(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
148
- var markPriceBefore = (0, market_1.calculateMarkPrice)(market, oraclePriceData);
149
- var bidPriceBefore = (0, market_1.calculateBidPrice)(market, oraclePriceData);
150
- var askPriceBefore = (0, market_1.calculateAskPrice)(market, oraclePriceData);
151
- var direction;
137
+ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAssetType = 'quote', oraclePriceData, useSpread = true) {
138
+ assert_1.assert(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
139
+ assert_1.assert(targetPrice.gt(numericConstants_1.ZERO));
140
+ assert_1.assert(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
141
+ const markPriceBefore = market_1.calculateMarkPrice(market, oraclePriceData);
142
+ const bidPriceBefore = market_1.calculateBidPrice(market, oraclePriceData);
143
+ const askPriceBefore = market_1.calculateAskPrice(market, oraclePriceData);
144
+ let direction;
152
145
  if (targetPrice.gt(markPriceBefore)) {
153
- var priceGap = targetPrice.sub(markPriceBefore);
154
- var priceGapScaled = priceGap.mul(pct).div(MAXPCT);
146
+ const priceGap = targetPrice.sub(markPriceBefore);
147
+ const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
155
148
  targetPrice = markPriceBefore.add(priceGapScaled);
156
149
  direction = types_1.PositionDirection.LONG;
157
150
  }
158
151
  else {
159
- var priceGap = markPriceBefore.sub(targetPrice);
160
- var priceGapScaled = priceGap.mul(pct).div(MAXPCT);
152
+ const priceGap = markPriceBefore.sub(targetPrice);
153
+ const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
161
154
  targetPrice = markPriceBefore.sub(priceGapScaled);
162
155
  direction = types_1.PositionDirection.SHORT;
163
156
  }
164
- var tradeSize;
165
- var baseSize;
166
- var baseAssetReserveBefore;
167
- var quoteAssetReserveBefore;
168
- var peg = market.amm.pegMultiplier;
157
+ let tradeSize;
158
+ let baseSize;
159
+ let baseAssetReserveBefore;
160
+ let quoteAssetReserveBefore;
161
+ let peg = market.amm.pegMultiplier;
169
162
  if (useSpread && market.amm.baseSpread > 0) {
170
- var _a = (0, amm_1.calculateUpdatedAMMSpreadReserves)(market.amm, direction, oraclePriceData), baseAssetReserve = _a.baseAssetReserve, quoteAssetReserve = _a.quoteAssetReserve, newPeg = _a.newPeg;
163
+ const { baseAssetReserve, quoteAssetReserve, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, direction, oraclePriceData);
171
164
  baseAssetReserveBefore = baseAssetReserve;
172
165
  quoteAssetReserveBefore = quoteAssetReserve;
173
166
  peg = newPeg;
@@ -176,12 +169,12 @@ function calculateTargetPriceTrade(market, targetPrice, pct, outputAssetType, or
176
169
  baseAssetReserveBefore = market.amm.baseAssetReserve;
177
170
  quoteAssetReserveBefore = market.amm.quoteAssetReserve;
178
171
  }
179
- var invariant = market.amm.sqrtK.mul(market.amm.sqrtK);
180
- var k = invariant.mul(numericConstants_1.MARK_PRICE_PRECISION);
181
- var baseAssetReserveAfter;
182
- var quoteAssetReserveAfter;
183
- var biasModifier = new anchor_1.BN(1);
184
- var markPriceAfter;
172
+ const invariant = market.amm.sqrtK.mul(market.amm.sqrtK);
173
+ const k = invariant.mul(numericConstants_1.MARK_PRICE_PRECISION);
174
+ let baseAssetReserveAfter;
175
+ let quoteAssetReserveAfter;
176
+ const biasModifier = new anchor_1.BN(1);
177
+ let markPriceAfter;
185
178
  if (useSpread &&
186
179
  targetPrice.lt(askPriceBefore) &&
187
180
  targetPrice.gt(bidPriceBefore)) {
@@ -197,11 +190,11 @@ function calculateTargetPriceTrade(market, targetPrice, pct, outputAssetType, or
197
190
  }
198
191
  else if (markPriceBefore.gt(targetPrice)) {
199
192
  // overestimate y2
200
- baseAssetReserveAfter = (0, utils_1.squareRootBN)(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
193
+ baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
201
194
  quoteAssetReserveAfter = k
202
195
  .div(numericConstants_1.MARK_PRICE_PRECISION)
203
196
  .div(baseAssetReserveAfter);
204
- markPriceAfter = (0, amm_1.calculatePrice)(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
197
+ markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
205
198
  direction = types_1.PositionDirection.SHORT;
206
199
  tradeSize = quoteAssetReserveBefore
207
200
  .sub(quoteAssetReserveAfter)
@@ -212,11 +205,11 @@ function calculateTargetPriceTrade(market, targetPrice, pct, outputAssetType, or
212
205
  }
213
206
  else if (markPriceBefore.lt(targetPrice)) {
214
207
  // underestimate y2
215
- baseAssetReserveAfter = (0, utils_1.squareRootBN)(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
208
+ baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
216
209
  quoteAssetReserveAfter = k
217
210
  .div(numericConstants_1.MARK_PRICE_PRECISION)
218
211
  .div(baseAssetReserveAfter);
219
- markPriceAfter = (0, amm_1.calculatePrice)(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
212
+ markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
220
213
  direction = types_1.PositionDirection.LONG;
221
214
  tradeSize = quoteAssetReserveAfter
222
215
  .sub(quoteAssetReserveBefore)
@@ -231,20 +224,20 @@ function calculateTargetPriceTrade(market, targetPrice, pct, outputAssetType, or
231
224
  tradeSize = numericConstants_1.ZERO;
232
225
  return [direction, tradeSize, targetPrice, targetPrice];
233
226
  }
234
- var tp1 = targetPrice;
235
- var tp2 = markPriceAfter;
236
- var originalDiff = targetPrice.sub(markPriceBefore);
227
+ let tp1 = targetPrice;
228
+ let tp2 = markPriceAfter;
229
+ let originalDiff = targetPrice.sub(markPriceBefore);
237
230
  if (direction == types_1.PositionDirection.SHORT) {
238
231
  tp1 = markPriceAfter;
239
232
  tp2 = targetPrice;
240
233
  originalDiff = markPriceBefore.sub(targetPrice);
241
234
  }
242
- var entryPrice = tradeSize
235
+ const entryPrice = tradeSize
243
236
  .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
244
237
  .mul(numericConstants_1.MARK_PRICE_PRECISION)
245
238
  .div(baseSize.abs());
246
- (0, assert_1.assert)(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
247
- (0, assert_1.assert)(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
239
+ assert_1.assert(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
240
+ assert_1.assert(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
248
241
  tp2.toString() +
249
242
  '>=' +
250
243
  tp1.toString() +
package/src/math/utils.js CHANGED
@@ -1,16 +1,15 @@
1
1
  "use strict";
2
- exports.__esModule = true;
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.squareRootBN = void 0;
4
- var __1 = require("../");
5
- var squareRootBN = function (n, closeness) {
6
- if (closeness === void 0) { closeness = new __1.BN(1); }
4
+ const __1 = require("../");
5
+ const squareRootBN = (n, closeness = new __1.BN(1)) => {
7
6
  // Assuming the sqrt of n as n only
8
- var x = n;
7
+ let x = n;
9
8
  // The closed guess will be stored in the root
10
- var root;
9
+ let root;
11
10
  // To count the number of iterations
12
- var count = 0;
13
- var TWO = new __1.BN(2);
11
+ let count = 0;
12
+ const TWO = new __1.BN(2);
14
13
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
15
14
  while (count < Number.MAX_SAFE_INTEGER) {
16
15
  count++;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["utils.ts"],"names":[],"mappings":";;;AAAA,2BAAyB;AAElB,MAAM,YAAY,GAAG,CAAC,CAAC,EAAE,SAAS,GAAG,IAAI,MAAE,CAAC,CAAC,CAAC,EAAE,EAAE;IACxD,mCAAmC;IACnC,IAAI,CAAC,GAAG,CAAC,CAAC;IAEV,8CAA8C;IAC9C,IAAI,IAAI,CAAC;IAET,oCAAoC;IACpC,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,MAAM,GAAG,GAAG,IAAI,MAAE,CAAC,CAAC,CAAC,CAAC;IAEtB,6DAA6D;IAC7D,OAAO,KAAK,GAAG,MAAM,CAAC,gBAAgB,EAAE;QACvC,KAAK,EAAE,CAAC;QAER,0BAA0B;QAC1B,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAEhC,sBAAsB;QACtB,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,SAAS,CAAC;YAAE,MAAM;QAE5C,cAAc;QACd,CAAC,GAAG,IAAI,CAAC;KACT;IAED,OAAO,IAAI,CAAC;AACb,CAAC,CAAC;AA1BW,QAAA,YAAY,gBA0BvB"}
@@ -1,20 +1,19 @@
1
1
  "use strict";
2
- exports.__esModule = true;
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.OracleClientCache = void 0;
4
- var oracleClient_1 = require("../factory/oracleClient");
5
- var OracleClientCache = /** @class */ (function () {
6
- function OracleClientCache() {
4
+ const oracleClient_1 = require("../factory/oracleClient");
5
+ class OracleClientCache {
6
+ constructor() {
7
7
  this.cache = new Map();
8
8
  }
9
- OracleClientCache.prototype.get = function (oracleSource, connection) {
10
- var key = Object.keys(oracleSource)[0];
9
+ get(oracleSource, connection) {
10
+ const key = Object.keys(oracleSource)[0];
11
11
  if (this.cache.has(key)) {
12
12
  return this.cache.get(key);
13
13
  }
14
- var client = (0, oracleClient_1.getOracleClient)(oracleSource, connection);
14
+ const client = oracleClient_1.getOracleClient(oracleSource, connection);
15
15
  this.cache.set(key, client);
16
16
  return client;
17
- };
18
- return OracleClientCache;
19
- }());
17
+ }
18
+ }
20
19
  exports.OracleClientCache = OracleClientCache;