@drift-labs/sdk 0.1.18-orders.1 → 0.1.19-master.2

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 (112) hide show
  1. package/README.md +2 -1
  2. package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts +4 -7
  3. package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts.map +1 -0
  4. package/lib/accounts/defaultClearingHouseAccountSubscriber.js +2 -27
  5. package/lib/accounts/defaultUserAccountSubscriber.d.ts +2 -3
  6. package/lib/accounts/defaultUserAccountSubscriber.d.ts.map +1 -0
  7. package/lib/accounts/defaultUserAccountSubscriber.js +5 -14
  8. package/lib/accounts/types.d.ts +6 -32
  9. package/lib/accounts/types.d.ts.map +1 -0
  10. package/lib/accounts/webSocketAccountSubscriber.d.ts +1 -0
  11. package/lib/accounts/webSocketAccountSubscriber.d.ts.map +1 -0
  12. package/lib/addresses.d.ts +1 -4
  13. package/lib/addresses.d.ts.map +1 -0
  14. package/lib/addresses.js +1 -28
  15. package/lib/admin.d.ts +7 -10
  16. package/lib/admin.d.ts.map +1 -0
  17. package/lib/admin.js +64 -53
  18. package/lib/assert/assert.d.ts +1 -0
  19. package/lib/assert/assert.d.ts.map +1 -0
  20. package/lib/clearingHouse.d.ts +3 -22
  21. package/lib/clearingHouse.d.ts.map +1 -0
  22. package/lib/clearingHouse.js +15 -246
  23. package/lib/clearingHouseUser.d.ts +17 -10
  24. package/lib/clearingHouseUser.d.ts.map +1 -0
  25. package/lib/clearingHouseUser.js +97 -111
  26. package/lib/config.d.ts +1 -0
  27. package/lib/config.d.ts.map +1 -0
  28. package/lib/config.js +1 -1
  29. package/lib/constants/markets.d.ts +1 -0
  30. package/lib/constants/markets.d.ts.map +1 -0
  31. package/lib/constants/markets.js +16 -0
  32. package/lib/constants/numericConstants.d.ts +1 -0
  33. package/lib/constants/numericConstants.d.ts.map +1 -0
  34. package/lib/examples/makeTradeExample.d.ts +1 -0
  35. package/lib/examples/makeTradeExample.d.ts.map +1 -0
  36. package/lib/examples/makeTradeExample.js +6 -6
  37. package/lib/idl/clearing_house.json +233 -911
  38. package/lib/index.d.ts +1 -4
  39. package/lib/index.d.ts.map +1 -0
  40. package/lib/index.js +0 -4
  41. package/lib/math/amm.d.ts +1 -1
  42. package/lib/math/amm.d.ts.map +1 -0
  43. package/lib/math/amm.js +15 -38
  44. package/lib/math/conversion.d.ts +1 -0
  45. package/lib/math/conversion.d.ts.map +1 -0
  46. package/lib/math/conversion.js +1 -1
  47. package/lib/math/funding.d.ts +1 -0
  48. package/lib/math/funding.d.ts.map +1 -0
  49. package/lib/math/funding.js +5 -2
  50. package/lib/math/insuranceFund.d.ts +1 -0
  51. package/lib/math/insuranceFund.d.ts.map +1 -0
  52. package/lib/math/market.d.ts +2 -2
  53. package/lib/math/market.d.ts.map +1 -0
  54. package/lib/math/market.js +2 -12
  55. package/lib/math/position.d.ts +2 -4
  56. package/lib/math/position.d.ts.map +1 -0
  57. package/lib/math/position.js +5 -19
  58. package/lib/math/trade.d.ts +1 -0
  59. package/lib/math/trade.d.ts.map +1 -0
  60. package/lib/math/trade.js +16 -16
  61. package/lib/math/utils.d.ts +1 -0
  62. package/lib/math/utils.d.ts.map +1 -0
  63. package/lib/mockUSDCFaucet.d.ts +1 -0
  64. package/lib/mockUSDCFaucet.d.ts.map +1 -0
  65. package/lib/pythClient.d.ts +1 -0
  66. package/lib/pythClient.d.ts.map +1 -0
  67. package/lib/pythClient.js +1 -1
  68. package/lib/tx/defaultTxSender.d.ts +1 -0
  69. package/lib/tx/defaultTxSender.d.ts.map +1 -0
  70. package/lib/tx/types.d.ts +1 -0
  71. package/lib/tx/types.d.ts.map +1 -0
  72. package/lib/tx/utils.d.ts +1 -0
  73. package/lib/tx/utils.d.ts.map +1 -0
  74. package/lib/types.d.ts +9 -140
  75. package/lib/types.d.ts.map +1 -0
  76. package/lib/types.js +1 -36
  77. package/lib/util/computeUnits.d.ts +1 -0
  78. package/lib/util/computeUnits.d.ts.map +1 -0
  79. package/lib/util/tps.d.ts +1 -0
  80. package/lib/util/tps.d.ts.map +1 -0
  81. package/lib/wallet.d.ts +1 -0
  82. package/lib/wallet.d.ts.map +1 -0
  83. package/package.json +1 -1
  84. package/src/accounts/defaultClearingHouseAccountSubscriber.ts +5 -52
  85. package/src/accounts/defaultUserAccountSubscriber.ts +6 -31
  86. package/src/accounts/types.ts +5 -42
  87. package/src/addresses.ts +0 -35
  88. package/src/admin.ts +71 -86
  89. package/src/clearingHouse.ts +7 -340
  90. package/src/clearingHouseUser.ts +102 -154
  91. package/src/config.ts +1 -1
  92. package/src/constants/markets.ts +16 -0
  93. package/src/idl/clearing_house.json +233 -911
  94. package/src/index.ts +0 -4
  95. package/src/math/amm.ts +14 -47
  96. package/src/math/funding.ts +5 -1
  97. package/src/math/market.ts +2 -28
  98. package/src/math/position.ts +3 -23
  99. package/src/types.ts +8 -124
  100. package/tsconfig.json +1 -0
  101. package/lib/accounts/defaultHistoryAccountSubscriber.d.ts +0 -28
  102. package/lib/accounts/defaultHistoryAccountSubscriber.js +0 -110
  103. package/lib/math/orders.d.ts +0 -3
  104. package/lib/math/orders.js +0 -30
  105. package/lib/orderParams.d.ts +0 -7
  106. package/lib/orderParams.js +0 -88
  107. package/lib/orders.d.ts +0 -5
  108. package/lib/orders.js +0 -136
  109. package/src/accounts/defaultHistoryAccountSubscriber.ts +0 -176
  110. package/src/math/orders.ts +0 -39
  111. package/src/orderParams.ts +0 -128
  112. package/src/orders.ts +0 -230
@@ -63,9 +63,6 @@ class ClearingHouseUser {
63
63
  getUserPositionsAccount() {
64
64
  return this.accountSubscriber.getUserPositionsAccount();
65
65
  }
66
- getUserOrdersAccount() {
67
- return this.accountSubscriber.getUserOrdersAccount();
68
- }
69
66
  /**
70
67
  * Gets the user's current position for a given market. If the user has no position returns undefined
71
68
  * @param marketIndex
@@ -80,34 +77,17 @@ class ClearingHouseUser {
80
77
  lastCumulativeFundingRate: numericConstants_1.ZERO,
81
78
  marketIndex,
82
79
  quoteAssetAmount: numericConstants_1.ZERO,
83
- openOrders: numericConstants_1.ZERO,
84
80
  };
85
81
  }
86
- /**
87
- * @param orderId
88
- * @returns Order
89
- */
90
- getOrder(orderId) {
91
- return this.getUserOrdersAccount().orders.find((order) => order.orderId.eq(orderId));
92
- }
93
82
  getUserAccountPublicKey() {
94
83
  return __awaiter(this, void 0, void 0, function* () {
95
84
  if (this.userAccountPublicKey) {
96
85
  return this.userAccountPublicKey;
97
86
  }
98
- this.userAccountPublicKey = yield addresses_1.getUserAccountPublicKey(this.clearingHouse.program.programId, this.authority);
87
+ this.userAccountPublicKey = yield (0, addresses_1.getUserAccountPublicKey)(this.clearingHouse.program.programId, this.authority);
99
88
  return this.userAccountPublicKey;
100
89
  });
101
90
  }
102
- getUserOrdersAccountPublicKey() {
103
- return __awaiter(this, void 0, void 0, function* () {
104
- if (this.userOrdersAccountPublicKey) {
105
- return this.userOrdersAccountPublicKey;
106
- }
107
- this.userOrdersAccountPublicKey = yield _1.getUserOrdersAccountPublicKey(this.clearingHouse.program.programId, this.authority);
108
- return this.userOrdersAccountPublicKey;
109
- });
110
- }
111
91
  exists() {
112
92
  return __awaiter(this, void 0, void 0, function* () {
113
93
  const userAccountPublicKey = yield this.getUserAccountPublicKey();
@@ -142,7 +122,7 @@ class ClearingHouseUser {
142
122
  .positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
143
123
  .reduce((pnl, marketPosition) => {
144
124
  const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
145
- return pnl.add(_1.calculatePositionPNL(market, marketPosition, withFunding));
125
+ return pnl.add((0, _1.calculatePositionPNL)(market, marketPosition, withFunding));
146
126
  }, numericConstants_1.ZERO);
147
127
  }
148
128
  /**
@@ -154,7 +134,7 @@ class ClearingHouseUser {
154
134
  .positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
155
135
  .reduce((pnl, marketPosition) => {
156
136
  const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
157
- return pnl.add(_1.calculatePositionFundingPNL(market, marketPosition));
137
+ return pnl.add((0, _1.calculatePositionFundingPNL)(market, marketPosition));
158
138
  }, numericConstants_1.ZERO);
159
139
  }
160
140
  /**
@@ -172,7 +152,7 @@ class ClearingHouseUser {
172
152
  getTotalPositionValue() {
173
153
  return this.getUserPositionsAccount().positions.reduce((positionValue, marketPosition) => {
174
154
  const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
175
- return positionValue.add(_1.calculateBaseAssetValue(market, marketPosition));
155
+ return positionValue.add((0, _1.calculateBaseAssetValue)(market, marketPosition));
176
156
  }, numericConstants_1.ZERO);
177
157
  }
178
158
  /**
@@ -182,7 +162,7 @@ class ClearingHouseUser {
182
162
  getPositionValue(marketIndex) {
183
163
  const userPosition = this.getUserPosition(marketIndex) || this.getEmptyPosition(marketIndex);
184
164
  const market = this.clearingHouse.getMarket(userPosition.marketIndex);
185
- return _1.calculateBaseAssetValue(market, userPosition);
165
+ return (0, _1.calculateBaseAssetValue)(market, userPosition);
186
166
  }
187
167
  getPositionSide(currentPosition) {
188
168
  if (currentPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
@@ -201,10 +181,10 @@ class ClearingHouseUser {
201
181
  */
202
182
  getPositionEstimatedExitPriceAndPnl(position, amountToClose) {
203
183
  const market = this.clearingHouse.getMarket(position.marketIndex);
204
- const entryPrice = position_1.calculateEntryPrice(position);
184
+ const entryPrice = (0, position_1.calculateEntryPrice)(position);
205
185
  if (amountToClose) {
206
186
  if (amountToClose.eq(numericConstants_1.ZERO)) {
207
- return [_1.calculateMarkPrice(market), numericConstants_1.ZERO];
187
+ return [(0, _1.calculateMarkPrice)(market), numericConstants_1.ZERO];
208
188
  }
209
189
  position = {
210
190
  baseAssetAmount: amountToClose,
@@ -213,7 +193,7 @@ class ClearingHouseUser {
213
193
  quoteAssetAmount: position.quoteAssetAmount,
214
194
  };
215
195
  }
216
- const baseAssetValue = _1.calculateBaseAssetValue(market, position);
196
+ const baseAssetValue = (0, _1.calculateBaseAssetValue)(market, position);
217
197
  if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
218
198
  return [numericConstants_1.ZERO, numericConstants_1.ZERO];
219
199
  }
@@ -320,7 +300,7 @@ class ClearingHouseUser {
320
300
 
321
301
  for 10x long, BTC down $400:
322
302
  3. (10k - 4k) / (100k - 4k) = 6k/96k => .0625 */
323
- const currentPrice = _1.calculateMarkPrice(this.clearingHouse.getMarket(targetMarket.marketIndex));
303
+ const currentPrice = (0, _1.calculateMarkPrice)(this.clearingHouse.getMarket(targetMarket.marketIndex));
324
304
  const totalCollateralUSDC = this.getTotalCollateral();
325
305
  // calculate the total position value ignoring any value from the target market of the trade
326
306
  const totalCurrentPositionValueIgnoringTargetUSDC = this.getTotalPositionValueExcludingMarket(targetMarket.marketIndex);
@@ -333,10 +313,9 @@ class ClearingHouseUser {
333
313
  baseAssetAmount: currentMarketPositionBaseSize.add(positionBaseSizeChange),
334
314
  lastCumulativeFundingRate: new bn_js_1.default(0),
335
315
  quoteAssetAmount: new bn_js_1.default(0),
336
- openOrders: new bn_js_1.default(0),
337
316
  };
338
317
  const market = this.clearingHouse.getMarket(proposedMarketPosition.marketIndex);
339
- const proposedMarketPositionValueUSDC = _1.calculateBaseAssetValue(market, proposedMarketPosition);
318
+ const proposedMarketPositionValueUSDC = (0, _1.calculateBaseAssetValue)(market, proposedMarketPosition);
340
319
  // total position value after trade
341
320
  const targetTotalPositionValueUSDC = totalCurrentPositionValueIgnoringTargetUSDC.add(proposedMarketPositionValueUSDC);
342
321
  let totalFreeCollateralUSDC = this.getTotalCollateral().sub(this.getTotalPositionValue()
@@ -394,14 +373,14 @@ class ClearingHouseUser {
394
373
  liquidationPrice(targetMarket, positionBaseSizeChange = numericConstants_1.ZERO, partial = false) {
395
374
  // solves formula for example calc below
396
375
  /* example: assume BTC price is $40k (examine 10% up/down)
397
-
398
- if 10k deposit and levered 10x short BTC => BTC up $400 means:
399
- 1. higher base_asset_value (+$4k)
400
- 2. lower collateral (-$4k)
401
- 3. (10k - 4k)/(100k + 4k) => 6k/104k => .0576
402
-
403
- for 10x long, BTC down $400:
404
- 3. (10k - 4k) / (100k - 4k) = 6k/96k => .0625 */
376
+
377
+ if 10k deposit and levered 10x short BTC => BTC up $400 means:
378
+ 1. higher base_asset_value (+$4k)
379
+ 2. lower collateral (-$4k)
380
+ 3. (10k - 4k)/(100k + 4k) => 6k/104k => .0576
381
+
382
+ for 10x long, BTC down $400:
383
+ 3. (10k - 4k) / (100k - 4k) = 6k/96k => .0625 */
405
384
  const tc = this.getTotalCollateral();
406
385
  const tpv = this.getTotalPositionValue();
407
386
  const partialLev = 16;
@@ -419,10 +398,9 @@ class ClearingHouseUser {
419
398
  baseAssetAmount: proposedBaseAssetAmount,
420
399
  lastCumulativeFundingRate: currentMarketPosition.lastCumulativeFundingRate,
421
400
  quoteAssetAmount: new bn_js_1.default(0),
422
- openOrders: new bn_js_1.default(0),
423
401
  };
424
402
  const market = this.clearingHouse.getMarket(proposedMarketPosition.marketIndex);
425
- const proposedMarketPositionValueUSDC = _1.calculateBaseAssetValue(market, proposedMarketPosition);
403
+ const proposedMarketPositionValueUSDC = (0, _1.calculateBaseAssetValue)(market, proposedMarketPosition);
426
404
  // total position value after trade
427
405
  const targetTotalPositionValueUSDC = totalCurrentPositionValueIgnoringTargetUSDC.add(proposedMarketPositionValueUSDC);
428
406
  let totalFreeCollateralUSDC = tc.sub(totalCurrentPositionValueIgnoringTargetUSDC
@@ -450,13 +428,13 @@ class ClearingHouseUser {
450
428
  }
451
429
  let currentPrice;
452
430
  if (positionBaseSizeChange.eq(numericConstants_1.ZERO)) {
453
- currentPrice = _1.calculateMarkPrice(this.clearingHouse.getMarket(targetMarket.marketIndex));
431
+ currentPrice = (0, _1.calculateMarkPrice)(this.clearingHouse.getMarket(targetMarket.marketIndex));
454
432
  }
455
433
  else {
456
434
  const direction = positionBaseSizeChange.gt(numericConstants_1.ZERO)
457
435
  ? _1.PositionDirection.LONG
458
436
  : _1.PositionDirection.SHORT;
459
- currentPrice = _1.calculateTradeSlippage(direction, positionBaseSizeChange.abs(), this.clearingHouse.getMarket(targetMarket.marketIndex), 'base')[3]; // newPrice after swap
437
+ currentPrice = (0, _1.calculateTradeSlippage)(direction, positionBaseSizeChange.abs(), this.clearingHouse.getMarket(targetMarket.marketIndex), 'base')[3]; // newPrice after swap
460
438
  }
461
439
  // if the position value after the trade is less than total collateral, there is no liq price
462
440
  if (targetTotalPositionValueUSDC.lte(totalFreeCollateralUSDC) &&
@@ -496,32 +474,42 @@ class ClearingHouseUser {
496
474
  }
497
475
  /**
498
476
  * Get the maximum trade size for a given market, taking into account the user's current leverage, positions, collateral, etc.
477
+ *
478
+ * To Calculate Max Quote Available:
479
+ *
480
+ * Case 1: SameSide
481
+ * => Remaining quote to get to maxLeverage
482
+ *
483
+ * Case 2: NOT SameSide && currentLeverage <= maxLeverage
484
+ * => Current opposite position x2 + remaining to get to maxLeverage
485
+ *
486
+ * Case 3: NOT SameSide && currentLeverage > maxLeverage && otherPositions - currentPosition > maxLeverage
487
+ * => strictly reduce current position size
488
+ *
489
+ * Case 4: NOT SameSide && currentLeverage > maxLeverage && otherPositions - currentPosition < maxLeverage
490
+ * => current position + remaining to get to maxLeverage
491
+ *
499
492
  * @param marketIndex
500
493
  * @param tradeSide
501
494
  * @param userMaxLeverageSetting - leverage : Precision TEN_THOUSAND
502
495
  * @returns tradeSizeAllowed : Precision QUOTE_PRECISION
503
496
  */
504
497
  getMaxTradeSizeUSDC(targetMarketIndex, tradeSide, userMaxLeverageSetting) {
505
- // inline function which get's the current position size on the opposite side of the target trade
506
- const getOppositePositionValueUSDC = () => {
507
- if (!currentPosition)
508
- return numericConstants_1.ZERO;
509
- const side = tradeSide === _1.PositionDirection.SHORT ? 'short' : 'long';
510
- if (side === 'long' && (currentPosition === null || currentPosition === void 0 ? void 0 : currentPosition.baseAssetAmount.isNeg())) {
511
- return this.getPositionValue(targetMarketIndex);
512
- }
513
- else if (side === 'short' &&
514
- !(currentPosition === null || currentPosition === void 0 ? void 0 : currentPosition.baseAssetAmount.isNeg())) {
515
- return this.getPositionValue(targetMarketIndex);
516
- }
517
- return numericConstants_1.ZERO;
518
- };
519
498
  const currentPosition = this.getUserPosition(targetMarketIndex) ||
520
499
  this.getEmptyPosition(targetMarketIndex);
500
+ const targetSide = tradeSide === _1.PositionDirection.SHORT ? 'short' : 'long';
501
+ const currentPositionSide = (currentPosition === null || currentPosition === void 0 ? void 0 : currentPosition.baseAssetAmount.isNeg())
502
+ ? 'short'
503
+ : 'long';
504
+ const targettingSameSide = !currentPosition
505
+ ? true
506
+ : targetSide === currentPositionSide;
507
+ // add any position we have on the opposite side of the current trade, because we can "flip" the size of this position without taking any extra leverage.
508
+ const oppositeSizeValueUSDC = targettingSameSide
509
+ ? numericConstants_1.ZERO
510
+ : this.getPositionValue(targetMarketIndex);
521
511
  // get current leverage
522
512
  const currentLeverage = this.getLeverage();
523
- // remaining leverage
524
- // let remainingLeverage = userMaxLeverageSetting;
525
513
  const remainingLeverage = bn_js_1.default.max(userMaxLeverageSetting.sub(currentLeverage), numericConstants_1.ZERO);
526
514
  // get total collateral
527
515
  const totalCollateral = this.getTotalCollateral();
@@ -529,9 +517,43 @@ class ClearingHouseUser {
529
517
  let maxPositionSize = remainingLeverage
530
518
  .mul(totalCollateral)
531
519
  .div(numericConstants_1.TEN_THOUSAND);
532
- // add any position we have on the opposite side of the current trade, because we can "flip" the size of this position without taking any extra leverage.
533
- const oppositeSizeValueUSDC = getOppositePositionValueUSDC();
534
- maxPositionSize = maxPositionSize.add(oppositeSizeValueUSDC.mul(new bn_js_1.default(2)));
520
+ if (userMaxLeverageSetting.sub(currentLeverage).gte(numericConstants_1.ZERO)) {
521
+ if (oppositeSizeValueUSDC.eq(numericConstants_1.ZERO)) {
522
+ // case 1 : Regular trade where current total position less than max, and no opposite position to account for
523
+ // do nothing
524
+ }
525
+ else {
526
+ // case 2 : trade where current total position less than max, but need to account for flipping the current position over to the other side
527
+ maxPositionSize = maxPositionSize.add(oppositeSizeValueUSDC.mul(new bn_js_1.default(2)));
528
+ }
529
+ }
530
+ else {
531
+ // current leverage is greater than max leverage - can only reduce position size
532
+ if (!targettingSameSide) {
533
+ const currentPositionQuoteSize = this.getPositionValue(targetMarketIndex);
534
+ const currentTotalQuoteSize = currentLeverage
535
+ .mul(totalCollateral)
536
+ .div(numericConstants_1.TEN_THOUSAND);
537
+ const otherPositionsTotalQuoteSize = currentTotalQuoteSize.sub(currentPositionQuoteSize);
538
+ const quoteValueOfMaxLeverage = userMaxLeverageSetting
539
+ .mul(totalCollateral)
540
+ .div(numericConstants_1.TEN_THOUSAND);
541
+ if (otherPositionsTotalQuoteSize
542
+ .sub(currentPositionQuoteSize)
543
+ .gte(quoteValueOfMaxLeverage)) {
544
+ // case 3: Can only reduce the current position because it will still be greater than max leverage
545
+ maxPositionSize = currentPositionQuoteSize;
546
+ }
547
+ else {
548
+ // case 4: Can reduce the position, and then take extra remaining quote to get to max leverage
549
+ const allowedQuoteSizeAfterClosingCurrentPosition = quoteValueOfMaxLeverage.sub(otherPositionsTotalQuoteSize);
550
+ maxPositionSize = currentPositionQuoteSize.add(allowedQuoteSizeAfterClosingCurrentPosition);
551
+ }
552
+ }
553
+ else {
554
+ // do nothing if targetting same side
555
+ }
556
+ }
535
557
  // subtract oneMillionth of maxPositionSize
536
558
  // => to avoid rounding errors when taking max leverage
537
559
  const oneMilli = maxPositionSize.div(numericConstants_1.QUOTE_PRECISION);
@@ -560,12 +582,18 @@ class ClearingHouseUser {
560
582
  .add(tradeQuoteAmount)
561
583
  .abs();
562
584
  const totalPositionAfterTradeExcludingTargetMarket = this.getTotalPositionValueExcludingMarket(targetMarketIndex);
563
- const newLeverage = currentMarketPositionAfterTrade
564
- .add(totalPositionAfterTradeExcludingTargetMarket)
565
- .abs()
566
- .mul(numericConstants_1.TEN_THOUSAND)
567
- .div(this.getTotalCollateral());
568
- return newLeverage;
585
+ const totalCollateral = this.getTotalCollateral();
586
+ if (totalCollateral.gt(numericConstants_1.ZERO)) {
587
+ const newLeverage = currentMarketPositionAfterTrade
588
+ .add(totalPositionAfterTradeExcludingTargetMarket)
589
+ .abs()
590
+ .mul(numericConstants_1.TEN_THOUSAND)
591
+ .div(totalCollateral);
592
+ return newLeverage;
593
+ }
594
+ else {
595
+ return new bn_js_1.default(0);
596
+ }
569
597
  }
570
598
  /**
571
599
  * Calculates how much fee will be taken for a given sized trade
@@ -588,51 +616,9 @@ class ClearingHouseUser {
588
616
  this.getEmptyPosition(marketToIgnore);
589
617
  let currentMarketPositionValueUSDC = numericConstants_1.ZERO;
590
618
  if (currentMarketPosition) {
591
- const market = this.clearingHouse.getMarket(currentMarketPosition.marketIndex);
592
- currentMarketPositionValueUSDC = _1.calculateBaseAssetValue(market, currentMarketPosition);
619
+ currentMarketPositionValueUSDC = this.getPositionValue(marketToIgnore);
593
620
  }
594
621
  return this.getTotalPositionValue().sub(currentMarketPositionValueUSDC);
595
622
  }
596
- canFillOrder(order) {
597
- const userAccount = this.getUserAccount();
598
- const userPositionsAccount = this.getUserPositionsAccount();
599
- const userPosition = this.getUserPosition(order.marketIndex);
600
- const market = this.clearingHouse.getMarket(order.marketIndex);
601
- if (position_1.isEmptyPosition(userPosition)) {
602
- return false;
603
- }
604
- const newState = _1.calculateNewStateAfterOrder(userAccount, userPosition, market, order);
605
- if (newState === null) {
606
- return false;
607
- }
608
- const [userAccountAfter, userPositionAfter, marketAfter] = newState;
609
- const totalPositionValue = userPositionsAccount.positions.reduce((positionValue, marketPosition) => {
610
- let market = this.clearingHouse.getMarket(marketPosition.marketIndex);
611
- if (marketPosition.marketIndex.eq(order.marketIndex)) {
612
- market = marketAfter;
613
- marketPosition = userPositionAfter;
614
- }
615
- return positionValue.add(_1.calculateBaseAssetValue(market, marketPosition));
616
- }, numericConstants_1.ZERO);
617
- if (totalPositionValue.eq(numericConstants_1.ZERO)) {
618
- return true;
619
- }
620
- const unrealizedPnL = userPositionsAccount.positions.reduce((pnl, marketPosition) => {
621
- let market = this.clearingHouse.getMarket(marketPosition.marketIndex);
622
- pnl = pnl.add(_1.calculatePositionFundingPNL(market, marketPosition).div(numericConstants_1.PRICE_TO_QUOTE_PRECISION));
623
- if (marketPosition.marketIndex.eq(order.marketIndex)) {
624
- market = marketAfter;
625
- marketPosition = userPositionAfter;
626
- }
627
- // update
628
- return pnl.add(_1.calculatePositionPNL(market, marketPosition, false));
629
- }, numericConstants_1.ZERO);
630
- const totalCollateral = userAccountAfter.collateral.add(unrealizedPnL);
631
- const marginRatioAfter = totalCollateral
632
- .mul(numericConstants_1.TEN_THOUSAND)
633
- .div(totalPositionValue);
634
- const marginRatioInitial = this.clearingHouse.getStateAccount().marginRatioInitial;
635
- return marginRatioAfter.gte(marginRatioInitial);
636
- }
637
623
  }
638
624
  exports.ClearingHouseUser = ClearingHouseUser;
package/lib/config.d.ts CHANGED
@@ -21,3 +21,4 @@ export declare const initialize: (props: {
21
21
  overrideEnv?: Partial<DriftConfig>;
22
22
  }) => DriftConfig;
23
23
  export {};
24
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,aAAK,WAAW,GAAG;IAClB,GAAG,EAAE,QAAQ,CAAC;IACd,2BAA2B,EAAE,MAAM,CAAC;IACpC,yBAAyB,EAAE,MAAM,CAAC;IAClC,iBAAiB,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,oBAAY,QAAQ,GAAG,QAAQ,GAAG,cAAc,CAAC;AAEjD,eAAO,MAAM,OAAO,EAAE;KAAG,GAAG,IAAI,QAAQ,GAAG,WAAW;CAarD,CAAC;AAIF,eAAO,MAAM,SAAS,QAAO,WAA4B,CAAC;AAE1D;;;;;;GAMG;AACH,eAAO,MAAM,UAAU,UAAW;IACjC,GAAG,EAAE,QAAQ,CAAC;IACd,WAAW,CAAC,EAAE,QAAQ,WAAW,CAAC,CAAC;CACnC,KAAG,WAQH,CAAC"}
package/lib/config.js CHANGED
@@ -5,7 +5,7 @@ exports.configs = {
5
5
  devnet: {
6
6
  ENV: 'devnet',
7
7
  PYTH_ORACLE_MAPPING_ADDRESS: 'BmA9Z6FjioHJPpjT39QazZyhDRUdZy2ezwx4GiDdE2u2',
8
- CLEARING_HOUSE_PROGRAM_ID: 'HiZ8CnfEE9LrBZTfc8hBneWrPg1Cbsn8Wdy6SPLfae9V',
8
+ CLEARING_HOUSE_PROGRAM_ID: 'AsW7LnXB9UA1uec9wi9MctYTgTz7YH9snhxd16GsFaGX',
9
9
  USDC_MINT_ADDRESS: '8zGuJQqwhZafTah7Uc7Z4tXRnguqkn5KLFAP8oV6PHe2',
10
10
  },
11
11
  'mainnet-beta': {
@@ -9,3 +9,4 @@ declare type Market = {
9
9
  };
10
10
  export declare const Markets: Market[];
11
11
  export {};
12
+ //# sourceMappingURL=markets.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markets.d.ts","sourceRoot":"","sources":["../../src/constants/markets.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,OAAO,CAAC;AAEvB,aAAK,MAAM,GAAG;IACb,MAAM,EAAE,MAAM,CAAC;IACf,eAAe,EAAE,MAAM,CAAC;IACxB,WAAW,EAAE,EAAE,CAAC;IAChB,gBAAgB,EAAE,MAAM,CAAC;IACzB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,QAAQ,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,eAAO,MAAM,OAAO,EAAE,MAAM,EAiG3B,CAAC"}
@@ -86,4 +86,20 @@ exports.Markets = [
86
86
  mainnetPythOracle: '3pyn4svBbxJ9Wnn3RVeafyLWfzie6yC5eTig2S62v9SC',
87
87
  launchTs: 1643084413000,
88
88
  },
89
+ {
90
+ symbol: 'ALGO-PERP',
91
+ baseAssetSymbol: 'ALGO',
92
+ marketIndex: new bn_js_1.default(10),
93
+ devnetPythOracle: 'c1A946dY5NHuVda77C8XXtXytyR3wK1SCP3eA9VRfC3',
94
+ mainnetPythOracle: 'HqFyq1wh1xKvL7KDqqT7NJeSPdAqsDqnmBisUC2XdXAX',
95
+ launchTs: 1643686767000,
96
+ },
97
+ // {
98
+ // symbol: 'mSOL-PERP',
99
+ // baseAssetSymbol: 'mSOL',
100
+ // marketIndex: new BN(11), //todo
101
+ // devnetPythOracle: '9a6RNx3tCu1TSs6TBSfV2XRXEPEZXQ6WB7jRojZRvyeZ',
102
+ // mainnetPythOracle: 'E4v1BBgoso9s64TQvmyownAVJbhbEPGyzA3qn4n46qj9',
103
+ // launchTs: 1643346125000,
104
+ // },
89
105
  ];
@@ -14,3 +14,4 @@ export declare const AMM_RESERVE_PRECISION: BN;
14
14
  export declare const AMM_TO_QUOTE_PRECISION_RATIO: BN;
15
15
  export declare const PRICE_TO_QUOTE_PRECISION: BN;
16
16
  export declare const AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO: BN;
17
+ //# sourceMappingURL=numericConstants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"numericConstants.d.ts","sourceRoot":"","sources":["../../src/constants/numericConstants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,OAAO,CAAC;AAEvB,eAAO,MAAM,IAAI,IAAY,CAAC;AAC9B,eAAO,MAAM,GAAG,IAAY,CAAC;AAC7B,eAAO,MAAM,YAAY,IAAgB,CAAC;AAC1C,eAAO,MAAM,MAAM,IAAkC,CAAC;AAEtD,eAAO,MAAM,YAAY,IAAY,CAAC;AACtC,eAAO,MAAM,sBAAsB,IAAc,CAAC;AAClD,eAAO,MAAM,yBAAyB,IAAc,CAAC;AAErD,eAAO,MAAM,eAAe,IAAkB,CAAC;AAC/C,eAAO,MAAM,oBAAoB,IAAmB,CAAC;AACrD,eAAO,MAAM,yBAAyB,IAAgB,CAAC;AACvD,eAAO,MAAM,aAAa,IAAe,CAAC;AAE1C,eAAO,MAAM,qBAAqB,IAAmB,CAAC;AACtD,eAAO,MAAM,4BAA4B,IACE,CAAC;AAC5C,eAAO,MAAM,wBAAwB,IACK,CAAC;AAC3C,eAAO,MAAM,sCAAsC,IACW,CAAC"}
@@ -1,2 +1,3 @@
1
1
  import { PublicKey } from '@solana/web3.js';
2
2
  export declare const getTokenAddress: (mintAddress: string, userPubKey: string) => Promise<PublicKey>;
3
+ //# sourceMappingURL=makeTradeExample.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"makeTradeExample.d.ts","sourceRoot":"","sources":["../../src/examples/makeTradeExample.ts"],"names":[],"mappings":"AAGA,OAAO,EAAuB,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAcjE,eAAO,MAAM,eAAe,gBACd,MAAM,cACP,MAAM,KAChB,QAAQ,SAAS,CAOnB,CAAC"}
@@ -21,7 +21,7 @@ const getTokenAddress = (mintAddress, userPubKey) => {
21
21
  exports.getTokenAddress = getTokenAddress;
22
22
  const main = () => __awaiter(void 0, void 0, void 0, function* () {
23
23
  // Initialize Drift SDK
24
- const sdkConfig = __2.initialize({ env: 'devnet' });
24
+ const sdkConfig = (0, __2.initialize)({ env: 'devnet' });
25
25
  // Set up the Wallet and Provider
26
26
  const privateKey = process.env.BOT_PRIVATE_KEY; // stored as an array string
27
27
  const keypair = web3_js_1.Keypair.fromSecretKey(Uint8Array.from(JSON.parse(privateKey)));
@@ -35,7 +35,7 @@ const main = () => __awaiter(void 0, void 0, void 0, function* () {
35
35
  const lamportsBalance = yield connection.getBalance(wallet.publicKey);
36
36
  console.log('SOL balance:', lamportsBalance / Math.pow(10, 9));
37
37
  // Misc. other things to set up
38
- const usdcTokenAddress = yield exports.getTokenAddress(sdkConfig.USDC_MINT_ADDRESS, wallet.publicKey.toString());
38
+ const usdcTokenAddress = yield (0, exports.getTokenAddress)(sdkConfig.USDC_MINT_ADDRESS, wallet.publicKey.toString());
39
39
  // Set up the Drift Clearing House
40
40
  const clearingHousePublicKey = new web3_js_1.PublicKey(sdkConfig.CLEARING_HOUSE_PROGRAM_ID);
41
41
  const clearingHouse = __2.ClearingHouse.from(connection, provider.wallet, clearingHousePublicKey);
@@ -47,18 +47,18 @@ const main = () => __awaiter(void 0, void 0, void 0, function* () {
47
47
  if (!userAccountExists) {
48
48
  //// Create a Clearing House account by Depositing some USDC ($10,000 in this case)
49
49
  const depositAmount = new anchor_1.BN(10000).mul(__2.QUOTE_PRECISION);
50
- yield clearingHouse.initializeUserAccountAndDepositCollateral(depositAmount, yield exports.getTokenAddress(usdcTokenAddress.toString(), wallet.publicKey.toString()));
50
+ yield clearingHouse.initializeUserAccountAndDepositCollateral(depositAmount, yield (0, exports.getTokenAddress)(usdcTokenAddress.toString(), wallet.publicKey.toString()));
51
51
  }
52
52
  yield user.subscribe();
53
53
  // Get current price
54
54
  const solMarketInfo = __2.Markets.find((market) => market.baseAssetSymbol === 'SOL');
55
- const currentMarketPrice = __2.calculateMarkPrice(clearingHouse.getMarket(solMarketInfo.marketIndex));
56
- const formattedPrice = __2.convertToNumber(currentMarketPrice, __2.QUOTE_PRECISION);
55
+ const currentMarketPrice = (0, __2.calculateMarkPrice)(clearingHouse.getMarket(solMarketInfo.marketIndex));
56
+ const formattedPrice = (0, __2.convertToNumber)(currentMarketPrice, __2.QUOTE_PRECISION);
57
57
  console.log(`Current Market Price is $${formattedPrice}`);
58
58
  // Estimate the slippage for a $5000 LONG trade
59
59
  const solMarketAccount = clearingHouse.getMarket(solMarketInfo.marketIndex);
60
60
  const longAmount = new anchor_1.BN(5000).mul(__2.QUOTE_PRECISION);
61
- const slippage = __2.convertToNumber(__2.calculateTradeSlippage(__2.PositionDirection.LONG, longAmount, solMarketAccount)[0], __2.MARK_PRICE_PRECISION);
61
+ const slippage = (0, __2.convertToNumber)((0, __2.calculateTradeSlippage)(__2.PositionDirection.LONG, longAmount, solMarketAccount)[0], __2.MARK_PRICE_PRECISION);
62
62
  console.log(`Slippage for a $5000 LONG on the SOL market would be $${slippage}`);
63
63
  // Make a $5000 LONG trade
64
64
  yield clearingHouse.openPosition(__2.PositionDirection.LONG, longAmount, solMarketInfo.marketIndex);