@drift-labs/sdk 0.2.0-master.4 → 0.2.0-master.41

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 (247) hide show
  1. package/README.md +27 -27
  2. package/lib/accounts/bulkAccountLoader.d.ts +2 -0
  3. package/lib/accounts/bulkAccountLoader.js +36 -29
  4. package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
  5. package/lib/accounts/bulkUserStatsSubscription.js +21 -0
  6. package/lib/accounts/bulkUserSubscription.d.ts +2 -2
  7. package/lib/accounts/bulkUserSubscription.js +0 -1
  8. package/lib/accounts/fetch.d.ts +2 -1
  9. package/lib/accounts/fetch.js +9 -1
  10. package/lib/accounts/{pollingClearingHouseAccountSubscriber.d.ts → pollingDriftClientAccountSubscriber.d.ts} +20 -25
  11. package/lib/accounts/{pollingClearingHouseAccountSubscriber.js → pollingDriftClientAccountSubscriber.js} +45 -49
  12. package/lib/accounts/{pollingOracleSubscriber.d.ts → pollingOracleAccountSubscriber.d.ts} +2 -2
  13. package/lib/accounts/{pollingOracleSubscriber.js → pollingOracleAccountSubscriber.js} +3 -3
  14. package/lib/accounts/pollingUserAccountSubscriber.d.ts +1 -1
  15. package/lib/accounts/pollingUserAccountSubscriber.js +5 -11
  16. package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
  17. package/lib/accounts/pollingUserStatsAccountSubscriber.js +107 -0
  18. package/lib/accounts/types.d.ts +26 -15
  19. package/lib/accounts/webSocketDriftClientAccountSubscriber.d.ts +49 -0
  20. package/lib/accounts/{webSocketClearingHouseAccountSubscriber.js → webSocketDriftClientAccountSubscriber.js} +47 -45
  21. package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
  22. package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
  23. package/lib/addresses/marketAddresses.d.ts +1 -3
  24. package/lib/addresses/marketAddresses.js +1 -1
  25. package/lib/addresses/pda.d.ts +15 -9
  26. package/lib/addresses/pda.js +73 -35
  27. package/lib/adminClient.d.ts +65 -0
  28. package/lib/adminClient.js +637 -0
  29. package/lib/config.d.ts +9 -9
  30. package/lib/config.js +25 -21
  31. package/lib/constants/numericConstants.d.ts +30 -12
  32. package/lib/constants/numericConstants.js +41 -21
  33. package/lib/constants/perpMarkets.d.ts +18 -0
  34. package/lib/constants/{markets.js → perpMarkets.js} +7 -7
  35. package/lib/constants/spotMarkets.d.ts +19 -0
  36. package/lib/constants/spotMarkets.js +53 -0
  37. package/lib/dlob/DLOB.d.ts +82 -0
  38. package/lib/dlob/DLOB.js +694 -0
  39. package/lib/dlob/DLOBNode.d.ts +54 -0
  40. package/lib/dlob/DLOBNode.js +77 -0
  41. package/lib/dlob/NodeList.d.ts +27 -0
  42. package/lib/dlob/NodeList.js +144 -0
  43. package/lib/driftClient.d.ts +234 -0
  44. package/lib/driftClient.js +2108 -0
  45. package/lib/{clearingHouseConfig.d.ts → driftClientConfig.d.ts} +9 -9
  46. package/lib/{clearingHouseConfig.js → driftClientConfig.js} +0 -0
  47. package/lib/events/eventList.js +3 -0
  48. package/lib/events/eventSubscriber.d.ts +5 -2
  49. package/lib/events/eventSubscriber.js +25 -11
  50. package/lib/events/fetchLogs.d.ts +13 -2
  51. package/lib/events/fetchLogs.js +40 -12
  52. package/lib/events/pollingLogProvider.d.ts +2 -1
  53. package/lib/events/pollingLogProvider.js +7 -3
  54. package/lib/events/sort.js +8 -11
  55. package/lib/events/types.d.ts +11 -3
  56. package/lib/events/types.js +8 -0
  57. package/lib/events/webSocketLogProvider.js +1 -1
  58. package/lib/examples/makeTradeExample.js +30 -18
  59. package/lib/factory/bigNum.d.ts +8 -4
  60. package/lib/factory/bigNum.js +109 -19
  61. package/lib/idl/drift.json +8386 -0
  62. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  63. package/lib/index.d.ts +30 -13
  64. package/lib/index.js +30 -13
  65. package/lib/math/amm.d.ts +9 -6
  66. package/lib/math/amm.js +91 -38
  67. package/lib/math/conversion.js +1 -1
  68. package/lib/math/exchangeStatus.d.ts +4 -0
  69. package/lib/math/exchangeStatus.js +18 -0
  70. package/lib/math/funding.d.ts +6 -6
  71. package/lib/math/funding.js +23 -21
  72. package/lib/math/insurance.d.ts +4 -0
  73. package/lib/math/insurance.js +27 -0
  74. package/lib/math/margin.d.ts +11 -0
  75. package/lib/math/margin.js +82 -0
  76. package/lib/math/market.d.ts +14 -9
  77. package/lib/math/market.js +70 -10
  78. package/lib/math/oracles.d.ts +4 -0
  79. package/lib/math/oracles.js +36 -8
  80. package/lib/math/orders.d.ts +16 -6
  81. package/lib/math/orders.js +97 -17
  82. package/lib/math/position.d.ts +27 -13
  83. package/lib/math/position.js +92 -36
  84. package/lib/math/repeg.js +17 -8
  85. package/lib/math/spotBalance.d.ts +22 -0
  86. package/lib/math/spotBalance.js +192 -0
  87. package/lib/math/spotMarket.d.ts +4 -0
  88. package/lib/math/spotMarket.js +8 -0
  89. package/lib/math/spotPosition.d.ts +6 -0
  90. package/lib/math/spotPosition.js +23 -0
  91. package/lib/math/trade.d.ts +10 -10
  92. package/lib/math/trade.js +27 -31
  93. package/lib/oracles/pythClient.js +1 -1
  94. package/lib/oracles/quoteAssetOracleClient.js +1 -1
  95. package/lib/oracles/switchboardClient.js +1 -1
  96. package/lib/orderParams.d.ts +4 -4
  97. package/lib/orderParams.js +12 -4
  98. package/lib/serum/serumFulfillmentConfigMap.d.ts +10 -0
  99. package/lib/serum/serumFulfillmentConfigMap.js +17 -0
  100. package/lib/serum/serumSubscriber.d.ts +27 -0
  101. package/lib/serum/serumSubscriber.js +56 -0
  102. package/lib/serum/types.d.ts +11 -0
  103. package/lib/{clearingHouseUserConfig.js → serum/types.js} +0 -0
  104. package/lib/slot/SlotSubscriber.d.ts +7 -0
  105. package/lib/slot/SlotSubscriber.js +3 -0
  106. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  107. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  108. package/lib/tx/retryTxSender.d.ts +1 -1
  109. package/lib/tx/retryTxSender.js +13 -4
  110. package/lib/tx/types.d.ts +1 -1
  111. package/lib/tx/utils.js +1 -1
  112. package/lib/types.d.ts +688 -216
  113. package/lib/types.js +153 -24
  114. package/lib/user.d.ts +228 -0
  115. package/lib/user.js +959 -0
  116. package/lib/userConfig.d.ts +14 -0
  117. package/lib/userConfig.js +2 -0
  118. package/lib/userMap/userMap.d.ts +41 -0
  119. package/lib/userMap/userMap.js +85 -0
  120. package/lib/userMap/userStatsMap.d.ts +19 -0
  121. package/lib/userMap/userStatsMap.js +68 -0
  122. package/lib/userName.d.ts +1 -0
  123. package/lib/userName.js +3 -2
  124. package/lib/userStats.d.ts +18 -0
  125. package/lib/userStats.js +49 -0
  126. package/lib/userStatsConfig.d.ts +14 -0
  127. package/lib/userStatsConfig.js +2 -0
  128. package/lib/util/computeUnits.js +1 -1
  129. package/lib/util/getTokenAddress.d.ts +2 -0
  130. package/lib/util/getTokenAddress.js +9 -0
  131. package/package.json +11 -4
  132. package/src/accounts/bulkAccountLoader.ts +44 -34
  133. package/src/accounts/bulkUserStatsSubscription.ts +33 -0
  134. package/src/accounts/bulkUserSubscription.ts +2 -3
  135. package/src/accounts/fetch.ts +27 -2
  136. package/src/accounts/{pollingClearingHouseAccountSubscriber.ts → pollingDriftClientAccountSubscriber.ts} +65 -75
  137. package/src/accounts/{pollingOracleSubscriber.ts → pollingOracleAccountSubscriber.ts} +2 -2
  138. package/src/accounts/pollingUserAccountSubscriber.ts +5 -12
  139. package/src/accounts/pollingUserStatsAccountSubscriber.ts +166 -0
  140. package/src/accounts/types.ts +35 -15
  141. package/src/accounts/{webSocketClearingHouseAccountSubscriber.ts → webSocketDriftClientAccountSubscriber.ts} +78 -73
  142. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
  143. package/src/addresses/marketAddresses.ts +3 -4
  144. package/src/addresses/pda.ts +105 -33
  145. package/src/adminClient.ts +1207 -0
  146. package/src/assert/assert.js +9 -0
  147. package/src/config.ts +37 -31
  148. package/src/constants/numericConstants.ts +58 -24
  149. package/src/constants/{markets.ts → perpMarkets.ts} +10 -10
  150. package/src/constants/spotMarkets.ts +73 -0
  151. package/src/dlob/DLOB.ts +1120 -0
  152. package/src/dlob/DLOBNode.ts +155 -0
  153. package/src/dlob/NodeList.ts +195 -0
  154. package/src/driftClient.ts +3594 -0
  155. package/src/{clearingHouseConfig.ts → driftClientConfig.ts} +9 -8
  156. package/src/events/eventList.js +77 -0
  157. package/src/events/eventList.ts +3 -0
  158. package/src/events/eventSubscriber.ts +36 -14
  159. package/src/events/fetchLogs.ts +55 -13
  160. package/src/events/pollingLogProvider.ts +11 -3
  161. package/src/events/sort.ts +11 -15
  162. package/src/events/types.ts +27 -2
  163. package/src/events/webSocketLogProvider.ts +1 -1
  164. package/src/examples/makeTradeExample.js +157 -0
  165. package/src/examples/makeTradeExample.ts +44 -28
  166. package/src/factory/bigNum.ts +150 -22
  167. package/src/idl/drift.json +8386 -0
  168. package/src/idl/pyth.json +98 -2
  169. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  170. package/src/index.ts +30 -13
  171. package/src/math/amm.ts +161 -48
  172. package/src/math/conversion.ts +2 -2
  173. package/src/math/exchangeStatus.ts +31 -0
  174. package/src/math/funding.ts +41 -31
  175. package/src/math/insurance.ts +35 -0
  176. package/src/math/margin.ts +133 -0
  177. package/src/math/market.ts +143 -14
  178. package/src/math/oracles.ts +63 -9
  179. package/src/math/orders.ts +168 -26
  180. package/src/math/position.ts +136 -58
  181. package/src/math/repeg.ts +19 -9
  182. package/src/math/spotBalance.ts +319 -0
  183. package/src/math/spotMarket.ts +9 -0
  184. package/src/math/spotPosition.ts +47 -0
  185. package/src/math/trade.ts +33 -37
  186. package/src/oracles/pythClient.ts +2 -2
  187. package/src/oracles/quoteAssetOracleClient.ts +2 -2
  188. package/src/oracles/switchboardClient.ts +2 -2
  189. package/src/orderParams.ts +16 -8
  190. package/src/serum/serumFulfillmentConfigMap.ts +26 -0
  191. package/src/serum/serumSubscriber.ts +99 -0
  192. package/src/serum/types.ts +13 -0
  193. package/src/slot/SlotSubscriber.ts +11 -1
  194. package/src/token/index.js +38 -0
  195. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  196. package/src/tx/retryTxSender.ts +16 -5
  197. package/src/tx/types.js +2 -0
  198. package/src/tx/types.ts +2 -1
  199. package/src/tx/utils.js +17 -0
  200. package/src/tx/utils.ts +1 -1
  201. package/src/types.ts +650 -189
  202. package/src/user.ts +1599 -0
  203. package/src/{clearingHouseUserConfig.ts → userConfig.ts} +5 -5
  204. package/src/userMap/userMap.ts +124 -0
  205. package/src/userMap/userStatsMap.ts +108 -0
  206. package/src/userName.ts +2 -1
  207. package/src/userStats.ts +75 -0
  208. package/src/userStatsConfig.ts +18 -0
  209. package/src/util/computeUnits.js +21 -11
  210. package/src/util/computeUnits.ts +1 -1
  211. package/src/util/getTokenAddress.js +9 -0
  212. package/src/util/getTokenAddress.ts +18 -0
  213. package/src/util/promiseTimeout.js +14 -0
  214. package/src/util/tps.js +27 -0
  215. package/tests/bn/test.ts +46 -11
  216. package/tests/dlob/helpers.ts +620 -0
  217. package/tests/dlob/test.ts +4586 -0
  218. package/yarn-error.log +3160 -0
  219. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +0 -49
  220. package/lib/admin.d.ts +0 -44
  221. package/lib/admin.js +0 -433
  222. package/lib/clearingHouse.d.ts +0 -133
  223. package/lib/clearingHouse.js +0 -931
  224. package/lib/clearingHouseUser.d.ts +0 -187
  225. package/lib/clearingHouseUser.js +0 -643
  226. package/lib/clearingHouseUserConfig.d.ts +0 -14
  227. package/lib/constants/banks.d.ts +0 -16
  228. package/lib/constants/banks.js +0 -34
  229. package/lib/constants/markets.d.ts +0 -19
  230. package/lib/idl/clearing_house.json +0 -3998
  231. package/lib/math/bankBalance.d.ts +0 -9
  232. package/lib/math/bankBalance.js +0 -75
  233. package/lib/math/state.d.ts +0 -8
  234. package/lib/math/state.js +0 -15
  235. package/lib/orders.d.ts +0 -8
  236. package/lib/orders.js +0 -134
  237. package/src/admin.ts +0 -722
  238. package/src/clearingHouse.ts +0 -1451
  239. package/src/clearingHouseUser.ts +0 -989
  240. package/src/constants/banks.ts +0 -43
  241. package/src/idl/clearing_house.json +0 -3998
  242. package/src/math/bankBalance.ts +0 -112
  243. package/src/math/state.ts +0 -14
  244. package/src/math/utils.js +0 -27
  245. package/src/math/utils.js.map +0 -1
  246. package/src/orders.ts +0 -244
  247. package/src/util/computeUnits.js.map +0 -1
@@ -1,9 +0,0 @@
1
- /// <reference types="bn.js" />
2
- import { BankAccount, BankBalanceType } from '../types';
3
- import { BN } from '@project-serum/anchor';
4
- export declare function getBalance(tokenAmount: BN, bank: BankAccount, balanceType: BankBalanceType): BN;
5
- export declare function getTokenAmount(balanceAmount: BN, bank: BankAccount, balanceType: BankBalanceType): BN;
6
- export declare function calculateInterestAccumulated(bank: BankAccount, now: BN): {
7
- borrowInterest: BN;
8
- depositInterest: BN;
9
- };
@@ -1,75 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculateInterestAccumulated = exports.getTokenAmount = exports.getBalance = void 0;
4
- const types_1 = require("../types");
5
- const anchor_1 = require("@project-serum/anchor");
6
- const numericConstants_1 = require("../constants/numericConstants");
7
- function getBalance(tokenAmount, bank, balanceType) {
8
- const precisionIncrease = numericConstants_1.TEN.pow(new anchor_1.BN(16 - bank.decimals));
9
- const cumulativeInterest = (0, types_1.isVariant)(balanceType, 'deposit')
10
- ? bank.cumulativeDepositInterest
11
- : bank.cumulativeBorrowInterest;
12
- let balance = tokenAmount.mul(precisionIncrease).div(cumulativeInterest);
13
- if (!balance.eq(numericConstants_1.ZERO) && (0, types_1.isVariant)(balanceType, 'borrow')) {
14
- balance = balance.add(numericConstants_1.ONE);
15
- }
16
- return balance;
17
- }
18
- exports.getBalance = getBalance;
19
- function getTokenAmount(balanceAmount, bank, balanceType) {
20
- const precisionDecrease = numericConstants_1.TEN.pow(new anchor_1.BN(16 - bank.decimals));
21
- const cumulativeInterest = (0, types_1.isVariant)(balanceType, 'deposit')
22
- ? bank.cumulativeDepositInterest
23
- : bank.cumulativeBorrowInterest;
24
- return balanceAmount.mul(cumulativeInterest).div(precisionDecrease);
25
- }
26
- exports.getTokenAmount = getTokenAmount;
27
- function calculateInterestAccumulated(bank, now) {
28
- const token_deposit_amount = getTokenAmount(bank.depositBalance, bank, types_1.BankBalanceType.DEPOSIT);
29
- const token_borrow_amount = getTokenAmount(bank.borrowBalance, bank, types_1.BankBalanceType.BORROW);
30
- let utilization;
31
- if (token_borrow_amount.eq(numericConstants_1.ZERO) && token_deposit_amount.eq(numericConstants_1.ZERO)) {
32
- utilization = numericConstants_1.ZERO;
33
- }
34
- else if (token_deposit_amount.eq(numericConstants_1.ZERO)) {
35
- utilization = numericConstants_1.BANK_UTILIZATION_PRECISION;
36
- }
37
- else {
38
- utilization = token_borrow_amount
39
- .mul(numericConstants_1.BANK_UTILIZATION_PRECISION)
40
- .div(token_deposit_amount);
41
- }
42
- let interest_rate;
43
- if (utilization.gt(bank.optimalUtilization)) {
44
- const surplusUtilization = utilization.sub(bank.optimalUtilization);
45
- const borrowRateSlope = bank.maxBorrowRate
46
- .sub(bank.optimalBorrowRate)
47
- .mul(numericConstants_1.BANK_UTILIZATION_PRECISION)
48
- .div(numericConstants_1.BANK_UTILIZATION_PRECISION.sub(bank.optimalUtilization));
49
- interest_rate = bank.optimalBorrowRate.add(surplusUtilization.mul(borrowRateSlope).div(numericConstants_1.BANK_UTILIZATION_PRECISION));
50
- }
51
- else {
52
- const borrowRateSlope = bank.optimalBorrowRate
53
- .mul(numericConstants_1.BANK_UTILIZATION_PRECISION)
54
- .div(numericConstants_1.BANK_UTILIZATION_PRECISION.sub(bank.optimalUtilization));
55
- interest_rate = utilization
56
- .mul(borrowRateSlope)
57
- .div(numericConstants_1.BANK_UTILIZATION_PRECISION);
58
- }
59
- const timeSinceLastUpdate = now.sub(bank.lastUpdated);
60
- const modifiedBorrowRate = interest_rate.mul(timeSinceLastUpdate);
61
- const modifiedDepositRate = modifiedBorrowRate
62
- .mul(utilization)
63
- .div(numericConstants_1.BANK_UTILIZATION_PRECISION);
64
- const borrowInterest = bank.cumulativeBorrowInterest
65
- .mul(modifiedBorrowRate)
66
- .div(numericConstants_1.ONE_YEAR)
67
- .div(numericConstants_1.BANK_INTEREST_PRECISION)
68
- .add(numericConstants_1.ONE);
69
- const depositInterest = bank.cumulativeDepositInterest
70
- .mul(modifiedDepositRate)
71
- .div(numericConstants_1.ONE_YEAR)
72
- .div(numericConstants_1.BANK_INTEREST_PRECISION);
73
- return { borrowInterest, depositInterest };
74
- }
75
- exports.calculateInterestAccumulated = calculateInterestAccumulated;
@@ -1,8 +0,0 @@
1
- import { StateAccount } from '../types';
2
- /**
3
- * Get the clearing house percent fee charged on notional of taking trades
4
- *
5
- * @param state
6
- * @returns Precision : basis points (bps)
7
- */
8
- export declare function getExchangeFee(state: StateAccount): number;
package/lib/math/state.js DELETED
@@ -1,15 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getExchangeFee = void 0;
4
- /**
5
- * Get the clearing house percent fee charged on notional of taking trades
6
- *
7
- * @param state
8
- * @returns Precision : basis points (bps)
9
- */
10
- function getExchangeFee(state) {
11
- const exchangeFee = state.feeStructure.feeNumerator.toNumber() /
12
- state.feeStructure.feeDenominator.toNumber();
13
- return exchangeFee;
14
- }
15
- exports.getExchangeFee = getExchangeFee;
package/lib/orders.d.ts DELETED
@@ -1,8 +0,0 @@
1
- /// <reference types="bn.js" />
2
- import { MarketAccount, Order, UserAccount, UserPosition } from './types';
3
- import { BN } from '.';
4
- import { OraclePriceData } from '.';
5
- export declare function calculateNewStateAfterOrder(userAccount: UserAccount, userPosition: UserPosition, market: MarketAccount, order: Order): [UserAccount, UserPosition, MarketAccount] | null;
6
- export declare function calculateBaseAssetAmountMarketCanExecute(market: MarketAccount, order: Order, oraclePriceData?: OraclePriceData): BN;
7
- export declare function calculateAmountToTradeForLimit(market: MarketAccount, order: Order, oraclePriceData?: OraclePriceData): BN;
8
- export declare function calculateAmountToTradeForTriggerLimit(market: MarketAccount, order: Order): BN;
package/lib/orders.js DELETED
@@ -1,134 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculateAmountToTradeForTriggerLimit = exports.calculateAmountToTradeForLimit = exports.calculateBaseAssetAmountMarketCanExecute = exports.calculateNewStateAfterOrder = void 0;
4
- const types_1 = require("./types");
5
- const _1 = require(".");
6
- const market_1 = require("./math/market");
7
- const numericConstants_1 = require("./constants/numericConstants");
8
- const amm_1 = require("./math/amm");
9
- const position_1 = require("./math/position");
10
- function calculateNewStateAfterOrder(userAccount, userPosition, market, order) {
11
- if ((0, types_1.isVariant)(order.status, 'init')) {
12
- return null;
13
- }
14
- const baseAssetAmountToTrade = calculateBaseAssetAmountMarketCanExecute(market, order);
15
- if (baseAssetAmountToTrade.lt(market.amm.baseAssetAmountStepSize)) {
16
- return null;
17
- }
18
- const userAccountAfter = Object.assign({}, userAccount);
19
- const userPositionAfter = Object.assign({}, userPosition);
20
- const currentPositionDirection = (0, position_1.positionCurrentDirection)(userPosition);
21
- const increasePosition = userPosition.baseAssetAmount.eq(numericConstants_1.ZERO) ||
22
- isSameDirection(order.direction, currentPositionDirection);
23
- if (increasePosition) {
24
- const marketAfter = (0, market_1.calculateNewMarketAfterTrade)(baseAssetAmountToTrade, order.direction, market);
25
- const { quoteAssetAmountSwapped, baseAssetAmountSwapped } = calculateAmountSwapped(market, marketAfter);
26
- userPositionAfter.baseAssetAmount = userPositionAfter.baseAssetAmount.add(baseAssetAmountSwapped);
27
- userPositionAfter.quoteAssetAmount = userPositionAfter.quoteAssetAmount.add(quoteAssetAmountSwapped);
28
- return [userAccountAfter, userPositionAfter, marketAfter];
29
- }
30
- else {
31
- const reversePosition = baseAssetAmountToTrade.gt(userPosition.baseAssetAmount.abs());
32
- if (reversePosition) {
33
- const intermediateMarket = (0, market_1.calculateNewMarketAfterTrade)(userPosition.baseAssetAmount, (0, position_1.findDirectionToClose)(userPosition), market);
34
- const { quoteAssetAmountSwapped: baseAssetValue } = calculateAmountSwapped(market, intermediateMarket);
35
- let pnl;
36
- if ((0, types_1.isVariant)(currentPositionDirection, 'long')) {
37
- pnl = baseAssetValue.sub(userPosition.quoteAssetAmount);
38
- }
39
- else {
40
- pnl = userPosition.quoteAssetAmount.sub(baseAssetValue);
41
- }
42
- userAccountAfter.collateral = userAccountAfter.collateral.add(pnl);
43
- const baseAssetAmountLeft = baseAssetAmountToTrade.sub(userPosition.baseAssetAmount.abs());
44
- const marketAfter = (0, market_1.calculateNewMarketAfterTrade)(baseAssetAmountLeft, order.direction, intermediateMarket);
45
- const { quoteAssetAmountSwapped, baseAssetAmountSwapped } = calculateAmountSwapped(intermediateMarket, marketAfter);
46
- userPositionAfter.quoteAssetAmount = quoteAssetAmountSwapped;
47
- userPositionAfter.baseAssetAmount = baseAssetAmountSwapped;
48
- return [userAccountAfter, userPositionAfter, marketAfter];
49
- }
50
- else {
51
- const marketAfter = (0, market_1.calculateNewMarketAfterTrade)(baseAssetAmountToTrade, order.direction, market);
52
- const { quoteAssetAmountSwapped: baseAssetValue, baseAssetAmountSwapped, } = calculateAmountSwapped(market, marketAfter);
53
- const costBasisRealized = userPosition.quoteAssetAmount
54
- .mul(baseAssetAmountSwapped.abs())
55
- .div(userPosition.baseAssetAmount.abs());
56
- let pnl;
57
- if ((0, types_1.isVariant)(currentPositionDirection, 'long')) {
58
- pnl = baseAssetValue.sub(costBasisRealized);
59
- }
60
- else {
61
- pnl = costBasisRealized.sub(baseAssetValue);
62
- }
63
- userAccountAfter.collateral = userAccountAfter.collateral.add(pnl);
64
- userPositionAfter.baseAssetAmount = userPositionAfter.baseAssetAmount.add(baseAssetAmountSwapped);
65
- userPositionAfter.quoteAssetAmount =
66
- userPositionAfter.quoteAssetAmount.sub(costBasisRealized);
67
- return [userAccountAfter, userPositionAfter, marketAfter];
68
- }
69
- }
70
- }
71
- exports.calculateNewStateAfterOrder = calculateNewStateAfterOrder;
72
- function calculateAmountSwapped(marketBefore, marketAfter) {
73
- return {
74
- quoteAssetAmountSwapped: marketBefore.amm.quoteAssetReserve
75
- .sub(marketAfter.amm.quoteAssetReserve)
76
- .abs()
77
- .mul(marketBefore.amm.pegMultiplier)
78
- .div(numericConstants_1.PEG_PRECISION)
79
- .div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO),
80
- baseAssetAmountSwapped: marketBefore.amm.baseAssetReserve.sub(marketAfter.amm.baseAssetReserve),
81
- };
82
- }
83
- function calculateBaseAssetAmountMarketCanExecute(market, order, oraclePriceData) {
84
- if ((0, types_1.isVariant)(order.orderType, 'limit')) {
85
- return calculateAmountToTradeForLimit(market, order, oraclePriceData);
86
- }
87
- else if ((0, types_1.isVariant)(order.orderType, 'triggerLimit')) {
88
- return calculateAmountToTradeForTriggerLimit(market, order);
89
- }
90
- else if ((0, types_1.isVariant)(order.orderType, 'market')) {
91
- return numericConstants_1.ZERO;
92
- }
93
- else {
94
- return calculateAmountToTradeForTriggerMarket(market, order);
95
- }
96
- }
97
- exports.calculateBaseAssetAmountMarketCanExecute = calculateBaseAssetAmountMarketCanExecute;
98
- function calculateAmountToTradeForLimit(market, order, oraclePriceData) {
99
- let limitPrice = order.price;
100
- if (!order.oraclePriceOffset.eq(numericConstants_1.ZERO)) {
101
- if (!oraclePriceData) {
102
- throw Error('Cant calculate limit price for oracle offset oracle without OraclePriceData');
103
- }
104
- limitPrice = oraclePriceData.price.add(order.oraclePriceOffset);
105
- }
106
- const [maxAmountToTrade, direction] = (0, amm_1.calculateMaxBaseAssetAmountToTrade)(market.amm, limitPrice, order.direction);
107
- const baseAssetAmount = (0, _1.standardizeBaseAssetAmount)(maxAmountToTrade, market.amm.baseAssetAmountStepSize);
108
- // Check that directions are the same
109
- const sameDirection = isSameDirection(direction, order.direction);
110
- if (!sameDirection) {
111
- return numericConstants_1.ZERO;
112
- }
113
- return baseAssetAmount.gt(order.baseAssetAmount)
114
- ? order.baseAssetAmount
115
- : baseAssetAmount;
116
- }
117
- exports.calculateAmountToTradeForLimit = calculateAmountToTradeForLimit;
118
- function calculateAmountToTradeForTriggerLimit(market, order) {
119
- if (!order.triggered) {
120
- return numericConstants_1.ZERO;
121
- }
122
- return calculateAmountToTradeForLimit(market, order);
123
- }
124
- exports.calculateAmountToTradeForTriggerLimit = calculateAmountToTradeForTriggerLimit;
125
- function isSameDirection(firstDirection, secondDirection) {
126
- return (((0, types_1.isVariant)(firstDirection, 'long') && (0, types_1.isVariant)(secondDirection, 'long')) ||
127
- ((0, types_1.isVariant)(firstDirection, 'short') && (0, types_1.isVariant)(secondDirection, 'short')));
128
- }
129
- function calculateAmountToTradeForTriggerMarket(market, order) {
130
- if (!order.triggered) {
131
- return numericConstants_1.ZERO;
132
- }
133
- return order.baseAssetAmount;
134
- }