@drift-labs/sdk 0.1.21-master.0 → 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 (126) hide show
  1. package/lib/accounts/bulkAccountLoader.d.ts +0 -1
  2. package/lib/accounts/bulkAccountLoader.js +4 -2
  3. package/lib/accounts/bulkUserSubscription.d.ts +0 -1
  4. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +5 -2
  5. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +23 -1
  6. package/lib/accounts/pollingTokenAccountSubscriber.d.ts +0 -1
  7. package/lib/accounts/pollingUserAccountSubscriber.d.ts +3 -2
  8. package/lib/accounts/pollingUserAccountSubscriber.js +13 -0
  9. package/lib/accounts/types.d.ts +8 -3
  10. package/lib/accounts/utils.d.ts +0 -1
  11. package/lib/accounts/webSocketAccountSubscriber.d.ts +0 -1
  12. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +5 -2
  13. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +25 -0
  14. package/lib/accounts/webSocketUserAccountSubscriber.d.ts +3 -2
  15. package/lib/accounts/webSocketUserAccountSubscriber.js +11 -0
  16. package/lib/addresses.d.ts +4 -1
  17. package/lib/addresses.js +28 -1
  18. package/lib/admin.d.ts +10 -4
  19. package/lib/admin.js +48 -3
  20. package/lib/assert/assert.d.ts +0 -1
  21. package/lib/clearingHouse.d.ts +27 -2
  22. package/lib/clearingHouse.js +307 -7
  23. package/lib/clearingHouseUser.d.ts +15 -17
  24. package/lib/clearingHouseUser.js +105 -84
  25. package/lib/config.d.ts +0 -1
  26. package/lib/constants/markets.d.ts +0 -1
  27. package/lib/constants/markets.js +8 -0
  28. package/lib/constants/numericConstants.d.ts +1 -1
  29. package/lib/constants/numericConstants.js +2 -1
  30. package/lib/examples/makeTradeExample.d.ts +0 -1
  31. package/lib/factory/clearingHouse.d.ts +0 -1
  32. package/lib/factory/clearingHouseUser.d.ts +0 -1
  33. package/lib/idl/clearing_house.json +1066 -39
  34. package/lib/index.d.ts +3 -1
  35. package/lib/index.js +3 -0
  36. package/lib/math/amm.d.ts +1 -1
  37. package/lib/math/amm.js +31 -8
  38. package/lib/math/conversion.d.ts +0 -1
  39. package/lib/math/funding.d.ts +0 -1
  40. package/lib/math/insuranceFund.d.ts +0 -1
  41. package/lib/math/market.d.ts +2 -2
  42. package/lib/math/market.js +11 -1
  43. package/lib/math/orders.d.ts +3 -0
  44. package/lib/math/orders.js +32 -0
  45. package/lib/math/position.d.ts +4 -2
  46. package/lib/math/position.js +18 -4
  47. package/lib/math/trade.d.ts +0 -1
  48. package/lib/math/utils.d.ts +0 -1
  49. package/lib/mockUSDCFaucet.d.ts +0 -1
  50. package/lib/orderParams.d.ts +7 -0
  51. package/lib/orderParams.js +108 -0
  52. package/lib/orders.d.ts +6 -0
  53. package/lib/orders.js +136 -0
  54. package/lib/pythClient.d.ts +0 -1
  55. package/lib/token/index.d.ts +0 -1
  56. package/lib/tx/defaultTxSender.d.ts +0 -1
  57. package/lib/tx/types.d.ts +0 -1
  58. package/lib/tx/utils.d.ts +0 -1
  59. package/lib/types.d.ts +145 -2
  60. package/lib/types.js +36 -1
  61. package/lib/util/computeUnits.d.ts +0 -1
  62. package/lib/util/tps.d.ts +0 -1
  63. package/lib/wallet.d.ts +0 -1
  64. package/package.json +1 -1
  65. package/src/accounts/bulkAccountLoader.ts +3 -3
  66. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +33 -0
  67. package/src/accounts/pollingUserAccountSubscriber.ts +30 -2
  68. package/src/accounts/types.ts +11 -2
  69. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +47 -0
  70. package/src/accounts/webSocketUserAccountSubscriber.ts +29 -2
  71. package/src/addresses.ts +37 -0
  72. package/src/admin.ts +84 -6
  73. package/src/clearingHouse.ts +430 -5
  74. package/src/clearingHouseUser.ts +164 -102
  75. package/src/constants/markets.ts +8 -0
  76. package/src/constants/numericConstants.ts +1 -0
  77. package/src/idl/clearing_house.json +1066 -39
  78. package/src/index.ts +3 -0
  79. package/src/math/amm.ts +47 -14
  80. package/src/math/market.ts +28 -2
  81. package/src/math/orders.ts +44 -0
  82. package/src/math/position.ts +23 -3
  83. package/src/orderParams.ts +151 -0
  84. package/src/orders.ts +236 -0
  85. package/src/types.ts +129 -1
  86. package/tsconfig.json +0 -1
  87. package/lib/accounts/bulkAccountLoader.d.ts.map +0 -1
  88. package/lib/accounts/bulkUserSubscription.d.ts.map +0 -1
  89. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts.map +0 -1
  90. package/lib/accounts/pollingTokenAccountSubscriber.d.ts.map +0 -1
  91. package/lib/accounts/pollingUserAccountSubscriber.d.ts.map +0 -1
  92. package/lib/accounts/types.d.ts.map +0 -1
  93. package/lib/accounts/utils.d.ts.map +0 -1
  94. package/lib/accounts/webSocketAccountSubscriber.d.ts.map +0 -1
  95. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts.map +0 -1
  96. package/lib/accounts/webSocketUserAccountSubscriber.d.ts.map +0 -1
  97. package/lib/addresses.d.ts.map +0 -1
  98. package/lib/admin.d.ts.map +0 -1
  99. package/lib/assert/assert.d.ts.map +0 -1
  100. package/lib/clearingHouse.d.ts.map +0 -1
  101. package/lib/clearingHouseUser.d.ts.map +0 -1
  102. package/lib/config.d.ts.map +0 -1
  103. package/lib/constants/markets.d.ts.map +0 -1
  104. package/lib/constants/numericConstants.d.ts.map +0 -1
  105. package/lib/examples/makeTradeExample.d.ts.map +0 -1
  106. package/lib/factory/clearingHouse.d.ts.map +0 -1
  107. package/lib/factory/clearingHouseUser.d.ts.map +0 -1
  108. package/lib/index.d.ts.map +0 -1
  109. package/lib/math/amm.d.ts.map +0 -1
  110. package/lib/math/conversion.d.ts.map +0 -1
  111. package/lib/math/funding.d.ts.map +0 -1
  112. package/lib/math/insuranceFund.d.ts.map +0 -1
  113. package/lib/math/market.d.ts.map +0 -1
  114. package/lib/math/position.d.ts.map +0 -1
  115. package/lib/math/trade.d.ts.map +0 -1
  116. package/lib/math/utils.d.ts.map +0 -1
  117. package/lib/mockUSDCFaucet.d.ts.map +0 -1
  118. package/lib/pythClient.d.ts.map +0 -1
  119. package/lib/token/index.d.ts.map +0 -1
  120. package/lib/tx/defaultTxSender.d.ts.map +0 -1
  121. package/lib/tx/types.d.ts.map +0 -1
  122. package/lib/tx/utils.d.ts.map +0 -1
  123. package/lib/types.d.ts.map +0 -1
  124. package/lib/util/computeUnits.d.ts.map +0 -1
  125. package/lib/util/tps.d.ts.map +0 -1
  126. package/lib/wallet.d.ts.map +0 -1
package/lib/index.d.ts CHANGED
@@ -22,6 +22,9 @@ export * from './math/market';
22
22
  export * from './math/position';
23
23
  export * from './math/amm';
24
24
  export * from './math/trade';
25
+ export * from './math/orders';
26
+ export * from './orders';
27
+ export * from './orderParams';
25
28
  export * from './wallet';
26
29
  export * from './types';
27
30
  export * from './math/utils';
@@ -30,4 +33,3 @@ export * from './constants/numericConstants';
30
33
  export * from './util/computeUnits';
31
34
  export * from './util/tps';
32
35
  export { BN, PublicKey };
33
- //# sourceMappingURL=index.d.ts.map
package/lib/index.js CHANGED
@@ -37,6 +37,9 @@ __exportStar(require("./math/market"), exports);
37
37
  __exportStar(require("./math/position"), exports);
38
38
  __exportStar(require("./math/amm"), exports);
39
39
  __exportStar(require("./math/trade"), exports);
40
+ __exportStar(require("./math/orders"), exports);
41
+ __exportStar(require("./orders"), exports);
42
+ __exportStar(require("./orderParams"), exports);
40
43
  __exportStar(require("./wallet"), exports);
41
44
  __exportStar(require("./types"), exports);
42
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");
@@ -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,6 +102,7 @@ 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
107
  const currentValue = position_1.calculateBaseAssetValue(market, netUserPosition);
109
108
  const marketNewK = Object.assign({}, market);
@@ -134,6 +133,7 @@ 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
138
  const currentValue = position_1.calculateBaseAssetValue(market, netUserPosition);
139
139
  netUserPosition.quoteAssetAmount = currentValue;
@@ -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
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
@@ -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
@@ -13,4 +13,3 @@ import { Connection } from '@solana/web3.js';
13
13
  * @returns Precision : QUOTE_ASSET_PRECISION
14
14
  */
15
15
  export declare function calculateInsuranceFundSize(connection: Connection, state: StateAccount, marketsAccount: MarketsAccount): Promise<BN>;
16
- //# sourceMappingURL=insuranceFund.d.ts.map
@@ -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
@@ -12,3 +12,13 @@ function calculateMarkPrice(market) {
12
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,6 +1,6 @@
1
1
  /// <reference types="bn.js" />
2
2
  import { BN } from '../';
3
- import { Market, UserPosition } from '../types';
3
+ import { Market, PositionDirection, UserPosition } from '../types';
4
4
  /**
5
5
  * calculateBaseAssetValue
6
6
  * = market value of closing entire position
@@ -31,4 +31,6 @@ export declare function calculatePositionFundingPNL(market: Market, marketPositi
31
31
  * @returns Precision: MARK_PRICE_PRECISION (10^10)
32
32
  */
33
33
  export declare function calculateEntryPrice(userPosition: UserPosition): BN;
34
- //# 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,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculateEntryPrice = exports.calculatePositionFundingPNL = exports.calculatePositionPNL = exports.calculateBaseAssetValue = void 0;
3
+ exports.isEmptyPosition = exports.positionCurrentDirection = exports.findDirectionToClose = exports.calculateEntryPrice = exports.calculatePositionFundingPNL = exports.calculatePositionPNL = exports.calculateBaseAssetValue = void 0;
4
4
  const __1 = require("../");
5
5
  const numericConstants_1 = require("../constants/numericConstants");
6
6
  const types_1 = require("../types");
@@ -16,9 +16,7 @@ function calculateBaseAssetValue(market, userPosition) {
16
16
  if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
17
17
  return numericConstants_1.ZERO;
18
18
  }
19
- const directionToClose = userPosition.baseAssetAmount.gt(numericConstants_1.ZERO)
20
- ? types_1.PositionDirection.SHORT
21
- : types_1.PositionDirection.LONG;
19
+ const directionToClose = findDirectionToClose(userPosition);
22
20
  const [newQuoteAssetReserve, _] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'base', userPosition.baseAssetAmount.abs(), amm_1.getSwapDirection('base', directionToClose));
23
21
  switch (directionToClose) {
24
22
  case types_1.PositionDirection.SHORT:
@@ -103,3 +101,19 @@ function calculateEntryPrice(userPosition) {
103
101
  .abs();
104
102
  }
105
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
@@ -1,4 +1,3 @@
1
1
  /// <reference types="bn.js" />
2
2
  import { BN } from '../';
3
3
  export declare const squareRootBN: (n: any, closeness?: BN) => any;
4
- //# sourceMappingURL=utils.d.ts.map
@@ -34,4 +34,3 @@ export declare class MockUSDCFaucet {
34
34
  callback: (accountInfo: AccountInfo) => void;
35
35
  }): Promise<boolean>;
36
36
  }
37
- //# 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;
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getMarketOrderParams = exports.getTriggerLimitOrderParams = exports.getTriggerMarketOrderParams = exports.getLimitOrderParams = void 0;
4
+ const types_1 = require("./types");
5
+ const numericConstants_1 = require("./constants/numericConstants");
6
+ function getLimitOrderParams(marketIndex, direction, baseAssetAmount, price, reduceOnly, discountToken = false, referrer = false, userOrderId = 0) {
7
+ return {
8
+ orderType: types_1.OrderType.LIMIT,
9
+ userOrderId,
10
+ marketIndex,
11
+ direction,
12
+ quoteAssetAmount: numericConstants_1.ZERO,
13
+ baseAssetAmount,
14
+ price,
15
+ reduceOnly,
16
+ postOnly: false,
17
+ immediateOrCancel: false,
18
+ positionLimit: numericConstants_1.ZERO,
19
+ padding0: true,
20
+ padding1: numericConstants_1.ZERO,
21
+ optionalAccounts: {
22
+ discountToken,
23
+ referrer,
24
+ },
25
+ triggerCondition: types_1.OrderTriggerCondition.ABOVE,
26
+ triggerPrice: numericConstants_1.ZERO,
27
+ oraclePriceOffset: numericConstants_1.ZERO,
28
+ };
29
+ }
30
+ exports.getLimitOrderParams = getLimitOrderParams;
31
+ function getTriggerMarketOrderParams(marketIndex, direction, baseAssetAmount, triggerPrice, triggerCondition, reduceOnly, discountToken = false, referrer = false, userOrderId = 0) {
32
+ return {
33
+ orderType: types_1.OrderType.TRIGGER_MARKET,
34
+ userOrderId,
35
+ marketIndex,
36
+ direction,
37
+ quoteAssetAmount: numericConstants_1.ZERO,
38
+ baseAssetAmount,
39
+ price: numericConstants_1.ZERO,
40
+ reduceOnly,
41
+ postOnly: false,
42
+ immediateOrCancel: false,
43
+ positionLimit: numericConstants_1.ZERO,
44
+ padding0: true,
45
+ padding1: numericConstants_1.ZERO,
46
+ optionalAccounts: {
47
+ discountToken,
48
+ referrer,
49
+ },
50
+ triggerCondition,
51
+ triggerPrice,
52
+ oraclePriceOffset: numericConstants_1.ZERO,
53
+ };
54
+ }
55
+ exports.getTriggerMarketOrderParams = getTriggerMarketOrderParams;
56
+ function getTriggerLimitOrderParams(marketIndex, direction, baseAssetAmount, price, triggerPrice, triggerCondition, reduceOnly, discountToken = false, referrer = false, userOrderId = 0) {
57
+ return {
58
+ orderType: types_1.OrderType.TRIGGER_LIMIT,
59
+ userOrderId,
60
+ marketIndex,
61
+ direction,
62
+ quoteAssetAmount: numericConstants_1.ZERO,
63
+ baseAssetAmount,
64
+ price,
65
+ reduceOnly,
66
+ postOnly: false,
67
+ immediateOrCancel: false,
68
+ positionLimit: numericConstants_1.ZERO,
69
+ padding0: true,
70
+ padding1: numericConstants_1.ZERO,
71
+ optionalAccounts: {
72
+ discountToken,
73
+ referrer,
74
+ },
75
+ triggerCondition,
76
+ triggerPrice,
77
+ oraclePriceOffset: numericConstants_1.ZERO,
78
+ };
79
+ }
80
+ exports.getTriggerLimitOrderParams = getTriggerLimitOrderParams;
81
+ function getMarketOrderParams(marketIndex, direction, quoteAssetAmount, baseAssetAmount, reduceOnly, price = numericConstants_1.ZERO, discountToken = false, referrer = false) {
82
+ if (baseAssetAmount.eq(numericConstants_1.ZERO) && quoteAssetAmount.eq(numericConstants_1.ZERO)) {
83
+ throw Error('baseAssetAmount or quoteAssetAmount must be zero');
84
+ }
85
+ return {
86
+ orderType: types_1.OrderType.MARKET,
87
+ userOrderId: 0,
88
+ marketIndex,
89
+ direction,
90
+ quoteAssetAmount,
91
+ baseAssetAmount,
92
+ price,
93
+ reduceOnly,
94
+ postOnly: false,
95
+ immediateOrCancel: false,
96
+ positionLimit: numericConstants_1.ZERO,
97
+ padding0: true,
98
+ padding1: numericConstants_1.ZERO,
99
+ optionalAccounts: {
100
+ discountToken,
101
+ referrer,
102
+ },
103
+ triggerCondition: types_1.OrderTriggerCondition.ABOVE,
104
+ triggerPrice: numericConstants_1.ZERO,
105
+ oraclePriceOffset: numericConstants_1.ZERO,
106
+ };
107
+ }
108
+ exports.getMarketOrderParams = getMarketOrderParams;
@@ -0,0 +1,6 @@
1
+ /// <reference types="bn.js" />
2
+ import { Market, Order, UserAccount, UserPosition } from './types';
3
+ import { BN } from '.';
4
+ export declare function calculateNewStateAfterOrder(userAccount: UserAccount, userPosition: UserPosition, market: Market, order: Order): [UserAccount, UserPosition, Market] | null;
5
+ export declare function calculateAmountToTradeForLimit(market: Market, order: Order): BN;
6
+ export declare function calculateAmountToTradeForTriggerLimit(market: Market, order: Order): BN;
package/lib/orders.js ADDED
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.calculateAmountToTradeForTriggerLimit = exports.calculateAmountToTradeForLimit = exports.calculateNewStateAfterOrder = void 0;
4
+ const types_1 = require("./types");
5
+ const market_1 = require("./math/market");
6
+ const numericConstants_1 = require("./constants/numericConstants");
7
+ const amm_1 = require("./math/amm");
8
+ const position_1 = require("./math/position");
9
+ function calculateNewStateAfterOrder(userAccount, userPosition, market, order) {
10
+ if (types_1.isVariant(order.status, 'init')) {
11
+ return null;
12
+ }
13
+ const baseAssetAmountToTrade = calculateAmountToTrade(market, order);
14
+ if (baseAssetAmountToTrade.lt(market.amm.minimumBaseAssetTradeSize)) {
15
+ return null;
16
+ }
17
+ const userAccountAfter = Object.assign({}, userAccount);
18
+ const userPositionAfter = Object.assign({}, userPosition);
19
+ const currentPositionDirection = position_1.positionCurrentDirection(userPosition);
20
+ const increasePosition = userPosition.baseAssetAmount.eq(numericConstants_1.ZERO) ||
21
+ isSameDirection(order.direction, currentPositionDirection);
22
+ if (increasePosition) {
23
+ const marketAfter = market_1.calculateNewMarketAfterTrade(baseAssetAmountToTrade, order.direction, market);
24
+ const { quoteAssetAmountSwapped, baseAssetAmountSwapped } = calculateAmountSwapped(market, marketAfter);
25
+ userPositionAfter.baseAssetAmount = userPositionAfter.baseAssetAmount.add(baseAssetAmountSwapped);
26
+ userPositionAfter.quoteAssetAmount = userPositionAfter.quoteAssetAmount.add(quoteAssetAmountSwapped);
27
+ return [userAccountAfter, userPositionAfter, marketAfter];
28
+ }
29
+ else {
30
+ const reversePosition = baseAssetAmountToTrade.gt(userPosition.baseAssetAmount.abs());
31
+ if (reversePosition) {
32
+ const intermediateMarket = market_1.calculateNewMarketAfterTrade(userPosition.baseAssetAmount, position_1.findDirectionToClose(userPosition), market);
33
+ const { quoteAssetAmountSwapped: baseAssetValue } = calculateAmountSwapped(market, intermediateMarket);
34
+ let pnl;
35
+ if (types_1.isVariant(currentPositionDirection, 'long')) {
36
+ pnl = baseAssetValue.sub(userPosition.quoteAssetAmount);
37
+ }
38
+ else {
39
+ pnl = userPosition.quoteAssetAmount.sub(baseAssetValue);
40
+ }
41
+ userAccountAfter.collateral = userAccountAfter.collateral.add(pnl);
42
+ const baseAssetAmountLeft = baseAssetAmountToTrade.sub(userPosition.baseAssetAmount.abs());
43
+ const marketAfter = market_1.calculateNewMarketAfterTrade(baseAssetAmountLeft, order.direction, intermediateMarket);
44
+ const { quoteAssetAmountSwapped, baseAssetAmountSwapped } = calculateAmountSwapped(intermediateMarket, marketAfter);
45
+ userPositionAfter.quoteAssetAmount = quoteAssetAmountSwapped;
46
+ userPositionAfter.baseAssetAmount = baseAssetAmountSwapped;
47
+ return [userAccountAfter, userPositionAfter, marketAfter];
48
+ }
49
+ else {
50
+ const marketAfter = market_1.calculateNewMarketAfterTrade(baseAssetAmountToTrade, order.direction, market);
51
+ const { quoteAssetAmountSwapped: baseAssetValue, baseAssetAmountSwapped, } = calculateAmountSwapped(market, marketAfter);
52
+ const costBasisRealized = userPosition.quoteAssetAmount
53
+ .mul(baseAssetAmountSwapped.abs())
54
+ .div(userPosition.baseAssetAmount.abs());
55
+ let pnl;
56
+ if (types_1.isVariant(currentPositionDirection, 'long')) {
57
+ pnl = baseAssetValue.sub(costBasisRealized);
58
+ }
59
+ else {
60
+ pnl = costBasisRealized.sub(baseAssetValue);
61
+ }
62
+ userAccountAfter.collateral = userAccountAfter.collateral.add(pnl);
63
+ userPositionAfter.baseAssetAmount = userPositionAfter.baseAssetAmount.add(baseAssetAmountSwapped);
64
+ userPositionAfter.quoteAssetAmount =
65
+ userPositionAfter.quoteAssetAmount.sub(costBasisRealized);
66
+ return [userAccountAfter, userPositionAfter, marketAfter];
67
+ }
68
+ }
69
+ }
70
+ exports.calculateNewStateAfterOrder = calculateNewStateAfterOrder;
71
+ function calculateAmountSwapped(marketBefore, marketAfter) {
72
+ return {
73
+ quoteAssetAmountSwapped: marketBefore.amm.quoteAssetReserve
74
+ .sub(marketAfter.amm.quoteAssetReserve)
75
+ .abs()
76
+ .mul(marketBefore.amm.pegMultiplier)
77
+ .div(numericConstants_1.PEG_PRECISION)
78
+ .div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO),
79
+ baseAssetAmountSwapped: marketBefore.amm.baseAssetReserve.sub(marketAfter.amm.baseAssetReserve),
80
+ };
81
+ }
82
+ function calculateAmountToTrade(market, order) {
83
+ if (types_1.isVariant(order.orderType, 'limit')) {
84
+ return calculateAmountToTradeForLimit(market, order);
85
+ }
86
+ else if (types_1.isVariant(order.orderType, 'triggerLimit')) {
87
+ return calculateAmountToTradeForTriggerLimit(market, order);
88
+ }
89
+ else if (types_1.isVariant(order.orderType, 'market')) {
90
+ // should never be a market order queued
91
+ return numericConstants_1.ZERO;
92
+ }
93
+ else {
94
+ return calculateAmountToTradeForTriggerMarket(market, order);
95
+ }
96
+ }
97
+ function calculateAmountToTradeForLimit(market, order) {
98
+ const [maxAmountToTrade, direction] = amm_1.calculateMaxBaseAssetAmountToTrade(market.amm, order.price);
99
+ // Check that directions are the same
100
+ const sameDirection = isSameDirection(direction, order.direction);
101
+ if (!sameDirection) {
102
+ return numericConstants_1.ZERO;
103
+ }
104
+ return maxAmountToTrade.gt(order.baseAssetAmount)
105
+ ? order.baseAssetAmount
106
+ : maxAmountToTrade;
107
+ }
108
+ exports.calculateAmountToTradeForLimit = calculateAmountToTradeForLimit;
109
+ function calculateAmountToTradeForTriggerLimit(market, order) {
110
+ if (order.baseAssetAmountFilled.eq(numericConstants_1.ZERO)) {
111
+ const baseAssetAmount = calculateAmountToTradeForTriggerMarket(market, order);
112
+ if (baseAssetAmount.eq(numericConstants_1.ZERO)) {
113
+ return numericConstants_1.ZERO;
114
+ }
115
+ }
116
+ return calculateAmountToTradeForLimit(market, order);
117
+ }
118
+ exports.calculateAmountToTradeForTriggerLimit = calculateAmountToTradeForTriggerLimit;
119
+ function isSameDirection(firstDirection, secondDirection) {
120
+ return ((types_1.isVariant(firstDirection, 'long') && types_1.isVariant(secondDirection, 'long')) ||
121
+ (types_1.isVariant(firstDirection, 'short') && types_1.isVariant(secondDirection, 'short')));
122
+ }
123
+ function calculateAmountToTradeForTriggerMarket(market, order) {
124
+ return isTriggerConditionSatisfied(market, order)
125
+ ? order.baseAssetAmount
126
+ : numericConstants_1.ZERO;
127
+ }
128
+ function isTriggerConditionSatisfied(market, order) {
129
+ const markPrice = market_1.calculateMarkPrice(market);
130
+ if (types_1.isVariant(order.triggerCondition, 'above')) {
131
+ return markPrice.gt(order.triggerPrice);
132
+ }
133
+ else {
134
+ return markPrice.lt(order.triggerPrice);
135
+ }
136
+ }
@@ -5,4 +5,3 @@ export declare class PythClient {
5
5
  constructor(connection: Connection);
6
6
  getPriceData(pricePublicKey: PublicKey): Promise<PriceData>;
7
7
  }
8
- //# sourceMappingURL=pythClient.d.ts.map
@@ -1,4 +1,3 @@
1
1
  /// <reference types="node" />
2
2
  import { AccountInfo } from '@solana/spl-token';
3
3
  export declare function parseTokenAccount(data: Buffer): AccountInfo;
4
- //# sourceMappingURL=index.d.ts.map
@@ -6,4 +6,3 @@ export declare class DefaultTxSender implements TxSender {
6
6
  constructor(provider: Provider);
7
7
  send(tx: Transaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions): Promise<TransactionSignature>;
8
8
  }
9
- //# sourceMappingURL=defaultTxSender.d.ts.map
package/lib/tx/types.d.ts CHANGED
@@ -2,4 +2,3 @@ import { ConfirmOptions, Signer, Transaction, TransactionSignature } from '@sola
2
2
  export interface TxSender {
3
3
  send(tx: Transaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions): Promise<TransactionSignature>;
4
4
  }
5
- //# sourceMappingURL=types.d.ts.map
package/lib/tx/utils.d.ts CHANGED
@@ -1,3 +1,2 @@
1
1
  import { Transaction, TransactionInstruction } from '@solana/web3.js';
2
2
  export declare function wrapInTx(instruction: TransactionInstruction): Transaction;
3
- //# sourceMappingURL=utils.d.ts.map