@drift-labs/sdk 0.1.36-master.7 → 0.2.0-master.10

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 (254) hide show
  1. package/lib/accounts/bulkAccountLoader.d.ts +6 -6
  2. package/lib/accounts/bulkAccountLoader.js +81 -95
  3. package/lib/accounts/bulkUserSubscription.js +13 -57
  4. package/lib/accounts/fetch.d.ts +4 -0
  5. package/lib/accounts/fetch.js +18 -0
  6. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +34 -38
  7. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +224 -224
  8. package/lib/accounts/pollingOracleSubscriber.d.ts +3 -3
  9. package/lib/accounts/pollingOracleSubscriber.js +37 -49
  10. package/lib/accounts/pollingTokenAccountSubscriber.d.ts +3 -3
  11. package/lib/accounts/pollingTokenAccountSubscriber.js +35 -50
  12. package/lib/accounts/pollingUserAccountSubscriber.d.ts +7 -13
  13. package/lib/accounts/pollingUserAccountSubscriber.js +71 -134
  14. package/lib/accounts/types.d.ts +34 -41
  15. package/lib/accounts/webSocketAccountSubscriber.d.ts +6 -4
  16. package/lib/accounts/webSocketAccountSubscriber.js +39 -35
  17. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +33 -28
  18. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +153 -185
  19. package/lib/accounts/webSocketUserAccountSubscriber.d.ts +5 -11
  20. package/lib/accounts/webSocketUserAccountSubscriber.js +22 -67
  21. package/lib/addresses/marketAddresses.d.ts +4 -0
  22. package/lib/addresses/marketAddresses.js +15 -0
  23. package/lib/addresses/pda.d.ts +12 -0
  24. package/lib/addresses/pda.js +83 -0
  25. package/lib/admin.d.ts +12 -18
  26. package/lib/admin.js +398 -558
  27. package/lib/clearingHouse.d.ts +83 -109
  28. package/lib/clearingHouse.js +832 -893
  29. package/lib/clearingHouseConfig.d.ts +34 -0
  30. package/lib/clearingHouseConfig.js +2 -0
  31. package/lib/clearingHouseUser.d.ts +19 -22
  32. package/lib/clearingHouseUser.js +155 -141
  33. package/lib/clearingHouseUserConfig.d.ts +14 -0
  34. package/lib/clearingHouseUserConfig.js +2 -0
  35. package/lib/config.d.ts +12 -0
  36. package/lib/config.js +35 -4
  37. package/lib/constants/banks.d.ts +16 -0
  38. package/lib/constants/banks.js +41 -0
  39. package/lib/constants/markets.d.ts +8 -3
  40. package/lib/constants/markets.js +13 -206
  41. package/lib/constants/numericConstants.d.ts +17 -0
  42. package/lib/constants/numericConstants.js +23 -6
  43. package/lib/events/eventList.d.ts +22 -0
  44. package/lib/events/eventList.js +77 -0
  45. package/lib/events/eventSubscriber.d.ts +34 -0
  46. package/lib/events/eventSubscriber.js +126 -0
  47. package/lib/events/fetchLogs.d.ts +13 -0
  48. package/lib/events/fetchLogs.js +39 -0
  49. package/lib/events/pollingLogProvider.d.ts +15 -0
  50. package/lib/events/pollingLogProvider.js +53 -0
  51. package/lib/events/sort.d.ts +2 -0
  52. package/lib/events/sort.js +44 -0
  53. package/lib/events/txEventCache.d.ts +24 -0
  54. package/lib/events/txEventCache.js +71 -0
  55. package/lib/events/types.d.ts +49 -0
  56. package/lib/events/types.js +20 -0
  57. package/lib/events/webSocketLogProvider.d.ts +12 -0
  58. package/lib/events/webSocketLogProvider.js +30 -0
  59. package/lib/examples/makeTradeExample.js +26 -27
  60. package/lib/factory/bigNum.d.ts +118 -0
  61. package/lib/factory/bigNum.js +364 -0
  62. package/lib/factory/oracleClient.d.ts +1 -2
  63. package/lib/factory/oracleClient.js +6 -2
  64. package/lib/idl/clearing_house.json +2258 -2774
  65. package/lib/index.d.ts +14 -5
  66. package/lib/index.js +18 -5
  67. package/lib/math/amm.d.ts +24 -29
  68. package/lib/math/amm.js +209 -176
  69. package/lib/math/auction.d.ts +5 -0
  70. package/lib/math/auction.js +42 -0
  71. package/lib/math/bankBalance.d.ts +9 -0
  72. package/lib/math/bankBalance.js +75 -0
  73. package/lib/math/conversion.d.ts +0 -1
  74. package/lib/math/conversion.js +1 -5
  75. package/lib/math/funding.d.ts +6 -6
  76. package/lib/math/funding.js +158 -175
  77. package/lib/math/market.d.ts +6 -6
  78. package/lib/math/market.js +10 -9
  79. package/lib/math/orders.d.ts +6 -1
  80. package/lib/math/orders.js +38 -1
  81. package/lib/math/position.d.ts +7 -5
  82. package/lib/math/position.js +29 -27
  83. package/lib/math/repeg.d.ts +22 -0
  84. package/lib/math/repeg.js +128 -0
  85. package/lib/math/trade.d.ts +5 -4
  86. package/lib/math/trade.js +29 -24
  87. package/lib/mockUSDCFaucet.js +87 -116
  88. package/lib/oracles/oracleClientCache.d.ts +8 -0
  89. package/lib/oracles/oracleClientCache.js +19 -0
  90. package/lib/oracles/pythClient.d.ts +3 -5
  91. package/lib/oracles/pythClient.js +12 -31
  92. package/lib/oracles/quoteAssetOracleClient.d.ts +9 -0
  93. package/lib/oracles/quoteAssetOracleClient.js +21 -0
  94. package/lib/oracles/switchboardClient.d.ts +3 -5
  95. package/lib/oracles/switchboardClient.js +29 -50
  96. package/lib/oracles/types.d.ts +6 -1
  97. package/lib/orderParams.d.ts +14 -5
  98. package/lib/orderParams.js +8 -96
  99. package/lib/orders.d.ts +6 -7
  100. package/lib/orders.js +11 -89
  101. package/lib/slot/SlotSubscriber.d.ts +19 -0
  102. package/lib/slot/SlotSubscriber.js +26 -0
  103. package/lib/tx/retryTxSender.d.ts +2 -2
  104. package/lib/tx/retryTxSender.js +108 -123
  105. package/lib/tx/types.d.ts +5 -1
  106. package/lib/tx/utils.d.ts +1 -1
  107. package/lib/tx/utils.js +11 -2
  108. package/lib/types.d.ts +180 -110
  109. package/lib/types.js +54 -1
  110. package/lib/userName.d.ts +4 -0
  111. package/lib/userName.js +20 -0
  112. package/lib/util/computeUnits.js +10 -21
  113. package/lib/util/tps.js +11 -22
  114. package/lib/wallet.js +7 -20
  115. package/package.json +11 -4
  116. package/src/accounts/bulkAccountLoader.js +197 -0
  117. package/src/accounts/bulkAccountLoader.ts +21 -15
  118. package/src/accounts/bulkUserSubscription.js +33 -0
  119. package/src/accounts/bulkUserSubscription.ts +1 -45
  120. package/src/accounts/fetch.js +29 -0
  121. package/src/accounts/fetch.ts +33 -0
  122. package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
  123. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +249 -214
  124. package/src/accounts/pollingOracleSubscriber.js +93 -0
  125. package/src/accounts/pollingOracleSubscriber.ts +16 -8
  126. package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
  127. package/src/accounts/pollingTokenAccountSubscriber.ts +11 -8
  128. package/src/accounts/pollingUserAccountSubscriber.js +132 -0
  129. package/src/accounts/pollingUserAccountSubscriber.ts +21 -86
  130. package/src/accounts/types.js +10 -0
  131. package/src/accounts/types.ts +41 -70
  132. package/src/accounts/utils.js +7 -0
  133. package/src/accounts/webSocketAccountSubscriber.js +93 -0
  134. package/src/accounts/webSocketAccountSubscriber.ts +33 -16
  135. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
  136. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +190 -240
  137. package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
  138. package/src/accounts/webSocketUserAccountSubscriber.ts +11 -71
  139. package/src/addresses/marketAddresses.js +26 -0
  140. package/src/addresses/marketAddresses.ts +18 -0
  141. package/{lib/addresses.js → src/addresses/pda.js} +45 -34
  142. package/src/addresses/pda.ts +118 -0
  143. package/src/admin.ts +247 -336
  144. package/src/assert/assert.js +9 -0
  145. package/src/clearingHouse.ts +1023 -1026
  146. package/src/clearingHouseConfig.ts +37 -0
  147. package/src/clearingHouseUser.ts +275 -185
  148. package/src/clearingHouseUserConfig.ts +18 -0
  149. package/src/config.ts +54 -1
  150. package/src/constants/banks.ts +50 -0
  151. package/src/constants/markets.ts +16 -207
  152. package/src/constants/numericConstants.ts +34 -5
  153. package/src/events/eventList.js +77 -0
  154. package/src/events/eventList.ts +94 -0
  155. package/src/events/eventSubscriber.js +139 -0
  156. package/src/events/eventSubscriber.ts +194 -0
  157. package/src/events/fetchLogs.js +50 -0
  158. package/src/events/fetchLogs.ts +80 -0
  159. package/src/events/pollingLogProvider.js +64 -0
  160. package/src/events/pollingLogProvider.ts +79 -0
  161. package/src/events/sort.js +44 -0
  162. package/src/events/sort.ts +65 -0
  163. package/src/events/txEventCache.js +71 -0
  164. package/src/events/txEventCache.ts +74 -0
  165. package/src/events/types.js +20 -0
  166. package/src/events/types.ts +98 -0
  167. package/src/events/webSocketLogProvider.js +41 -0
  168. package/src/events/webSocketLogProvider.ts +38 -0
  169. package/src/examples/makeTradeExample.js +80 -0
  170. package/src/examples/makeTradeExample.ts +20 -11
  171. package/src/factory/bigNum.js +364 -0
  172. package/src/factory/bigNum.ts +524 -0
  173. package/src/factory/oracleClient.js +20 -0
  174. package/src/factory/oracleClient.ts +7 -4
  175. package/src/idl/clearing_house.json +2258 -2774
  176. package/src/index.js +69 -0
  177. package/src/index.ts +14 -5
  178. package/src/math/amm.js +369 -0
  179. package/src/math/amm.ts +382 -243
  180. package/src/math/auction.js +42 -0
  181. package/src/math/auction.ts +43 -0
  182. package/src/math/bankBalance.js +75 -0
  183. package/src/math/bankBalance.ts +112 -0
  184. package/src/math/conversion.js +11 -0
  185. package/src/math/conversion.ts +1 -11
  186. package/src/math/funding.js +248 -0
  187. package/src/math/funding.ts +12 -9
  188. package/src/math/market.js +57 -0
  189. package/src/math/market.ts +37 -30
  190. package/src/math/oracles.js +26 -0
  191. package/src/math/orders.js +110 -0
  192. package/src/math/orders.ts +43 -1
  193. package/src/math/position.js +140 -0
  194. package/src/math/position.ts +52 -35
  195. package/src/math/repeg.js +128 -0
  196. package/src/math/repeg.ts +176 -0
  197. package/src/math/state.js +15 -0
  198. package/src/math/trade.js +253 -0
  199. package/src/math/trade.ts +55 -47
  200. package/src/math/utils.js +26 -0
  201. package/src/math/utils.js.map +1 -0
  202. package/src/mockUSDCFaucet.js +171 -0
  203. package/src/oracles/oracleClientCache.js +19 -0
  204. package/src/oracles/oracleClientCache.ts +20 -0
  205. package/src/oracles/pythClient.js +46 -0
  206. package/src/oracles/pythClient.ts +4 -11
  207. package/src/oracles/quoteAssetOracleClient.js +32 -0
  208. package/src/oracles/quoteAssetOracleClient.ts +25 -0
  209. package/src/oracles/switchboardClient.js +69 -0
  210. package/src/oracles/switchboardClient.ts +11 -24
  211. package/src/oracles/types.js +2 -0
  212. package/src/oracles/types.ts +7 -1
  213. package/src/orderParams.js +20 -0
  214. package/src/orderParams.ts +20 -141
  215. package/src/orders.js +134 -0
  216. package/src/orders.ts +25 -134
  217. package/src/slot/SlotSubscriber.js +39 -0
  218. package/src/slot/SlotSubscriber.ts +42 -0
  219. package/src/token/index.js +38 -0
  220. package/src/tx/retryTxSender.js +188 -0
  221. package/src/tx/retryTxSender.ts +6 -4
  222. package/src/tx/types.js +2 -0
  223. package/src/tx/types.ts +6 -1
  224. package/src/tx/utils.js +17 -0
  225. package/src/tx/utils.ts +22 -3
  226. package/src/types.js +114 -0
  227. package/src/types.ts +176 -124
  228. package/src/userName.js +20 -0
  229. package/src/userName.ts +20 -0
  230. package/src/util/promiseTimeout.js +14 -0
  231. package/src/util/tps.js +27 -0
  232. package/src/wallet.js +35 -0
  233. package/tests/bn/test.ts +255 -0
  234. package/tsconfig.json +12 -12
  235. package/lib/addresses.d.ts +0 -10
  236. package/lib/constants/accounts.d.ts +0 -15
  237. package/lib/constants/accounts.js +0 -18
  238. package/lib/factory/clearingHouse.d.ts +0 -35
  239. package/lib/factory/clearingHouse.js +0 -81
  240. package/lib/factory/clearingHouseUser.d.ts +0 -19
  241. package/lib/factory/clearingHouseUser.js +0 -34
  242. package/lib/math/insuranceFund.d.ts +0 -15
  243. package/lib/math/insuranceFund.js +0 -33
  244. package/lib/settlement.d.ts +0 -4
  245. package/lib/settlement.js +0 -10
  246. package/lib/tx/defaultTxSender.d.ts +0 -8
  247. package/lib/tx/defaultTxSender.js +0 -12
  248. package/src/addresses.ts +0 -82
  249. package/src/constants/accounts.ts +0 -26
  250. package/src/factory/clearingHouse.ts +0 -173
  251. package/src/factory/clearingHouseUser.ts +0 -73
  252. package/src/math/insuranceFund.ts +0 -29
  253. package/src/settlement.ts +0 -9
  254. package/src/tx/defaultTxSender.ts +0 -24
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getAuctionPrice = exports.isAuctionComplete = void 0;
4
+ const types_1 = require("../types");
5
+ const _1 = require("../.");
6
+ function isAuctionComplete(order, slot) {
7
+ if (order.auctionDuration === 0) {
8
+ return true;
9
+ }
10
+ return new _1.BN(slot).sub(order.slot).gt(new _1.BN(order.auctionDuration));
11
+ }
12
+ exports.isAuctionComplete = isAuctionComplete;
13
+ function getAuctionPrice(order, slot) {
14
+ const slotsElapsed = new _1.BN(slot).sub(order.slot);
15
+ const deltaDenominator = new _1.BN(order.auctionDuration);
16
+ const deltaNumerator = _1.BN.min(slotsElapsed, deltaDenominator);
17
+ if (deltaDenominator.eq(_1.ZERO)) {
18
+ return order.auctionEndPrice;
19
+ }
20
+ let priceDelta;
21
+ if (types_1.isVariant(order.direction, 'long')) {
22
+ priceDelta = order.auctionEndPrice
23
+ .sub(order.auctionStartPrice)
24
+ .mul(deltaNumerator)
25
+ .div(deltaDenominator);
26
+ }
27
+ else {
28
+ priceDelta = order.auctionStartPrice
29
+ .sub(order.auctionEndPrice)
30
+ .mul(deltaNumerator)
31
+ .div(deltaDenominator);
32
+ }
33
+ let price;
34
+ if (types_1.isVariant(order.direction, 'long')) {
35
+ price = order.auctionStartPrice.add(priceDelta);
36
+ }
37
+ else {
38
+ price = order.auctionStartPrice.sub(priceDelta);
39
+ }
40
+ return price;
41
+ }
42
+ exports.getAuctionPrice = getAuctionPrice;
@@ -0,0 +1,43 @@
1
+ import { isVariant, Order } from '../types';
2
+ import { BN, ZERO } from '../.';
3
+
4
+ export function isAuctionComplete(order: Order, slot: number): boolean {
5
+ if (order.auctionDuration === 0) {
6
+ return true;
7
+ }
8
+
9
+ return new BN(slot).sub(order.slot).gt(new BN(order.auctionDuration));
10
+ }
11
+
12
+ export function getAuctionPrice(order: Order, slot: number): BN {
13
+ const slotsElapsed = new BN(slot).sub(order.slot);
14
+
15
+ const deltaDenominator = new BN(order.auctionDuration);
16
+ const deltaNumerator = BN.min(slotsElapsed, deltaDenominator);
17
+
18
+ if (deltaDenominator.eq(ZERO)) {
19
+ return order.auctionEndPrice;
20
+ }
21
+
22
+ let priceDelta;
23
+ if (isVariant(order.direction, 'long')) {
24
+ priceDelta = order.auctionEndPrice
25
+ .sub(order.auctionStartPrice)
26
+ .mul(deltaNumerator)
27
+ .div(deltaDenominator);
28
+ } else {
29
+ priceDelta = order.auctionStartPrice
30
+ .sub(order.auctionEndPrice)
31
+ .mul(deltaNumerator)
32
+ .div(deltaDenominator);
33
+ }
34
+
35
+ let price;
36
+ if (isVariant(order.direction, 'long')) {
37
+ price = order.auctionStartPrice.add(priceDelta);
38
+ } else {
39
+ price = order.auctionStartPrice.sub(priceDelta);
40
+ }
41
+
42
+ return price;
43
+ }
@@ -0,0 +1,75 @@
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 = 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) && 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 = 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;
@@ -0,0 +1,112 @@
1
+ import { BankAccount, BankBalanceType, isVariant } from '../types';
2
+ import { BN } from '@project-serum/anchor';
3
+ import {
4
+ BANK_UTILIZATION_PRECISION,
5
+ ONE,
6
+ TEN,
7
+ ZERO,
8
+ BANK_INTEREST_PRECISION,
9
+ ONE_YEAR,
10
+ } from '../constants/numericConstants';
11
+
12
+ export function getBalance(
13
+ tokenAmount: BN,
14
+ bank: BankAccount,
15
+ balanceType: BankBalanceType
16
+ ): BN {
17
+ const precisionIncrease = TEN.pow(new BN(16 - bank.decimals));
18
+
19
+ const cumulativeInterest = isVariant(balanceType, 'deposit')
20
+ ? bank.cumulativeDepositInterest
21
+ : bank.cumulativeBorrowInterest;
22
+
23
+ let balance = tokenAmount.mul(precisionIncrease).div(cumulativeInterest);
24
+
25
+ if (!balance.eq(ZERO) && isVariant(balanceType, 'borrow')) {
26
+ balance = balance.add(ONE);
27
+ }
28
+
29
+ return balance;
30
+ }
31
+
32
+ export function getTokenAmount(
33
+ balanceAmount: BN,
34
+ bank: BankAccount,
35
+ balanceType: BankBalanceType
36
+ ): BN {
37
+ const precisionDecrease = TEN.pow(new BN(16 - bank.decimals));
38
+
39
+ const cumulativeInterest = isVariant(balanceType, 'deposit')
40
+ ? bank.cumulativeDepositInterest
41
+ : bank.cumulativeBorrowInterest;
42
+
43
+ return balanceAmount.mul(cumulativeInterest).div(precisionDecrease);
44
+ }
45
+
46
+ export function calculateInterestAccumulated(
47
+ bank: BankAccount,
48
+ now: BN
49
+ ): { borrowInterest: BN; depositInterest: BN } {
50
+ const token_deposit_amount = getTokenAmount(
51
+ bank.depositBalance,
52
+ bank,
53
+ BankBalanceType.DEPOSIT
54
+ );
55
+ const token_borrow_amount = getTokenAmount(
56
+ bank.borrowBalance,
57
+ bank,
58
+ BankBalanceType.BORROW
59
+ );
60
+
61
+ let utilization: BN;
62
+ if (token_borrow_amount.eq(ZERO) && token_deposit_amount.eq(ZERO)) {
63
+ utilization = ZERO;
64
+ } else if (token_deposit_amount.eq(ZERO)) {
65
+ utilization = BANK_UTILIZATION_PRECISION;
66
+ } else {
67
+ utilization = token_borrow_amount
68
+ .mul(BANK_UTILIZATION_PRECISION)
69
+ .div(token_deposit_amount);
70
+ }
71
+
72
+ let interest_rate: BN;
73
+ if (utilization.gt(bank.optimalUtilization)) {
74
+ const surplusUtilization = utilization.sub(bank.optimalUtilization);
75
+ const borrowRateSlope = bank.maxBorrowRate
76
+ .sub(bank.optimalBorrowRate)
77
+ .mul(BANK_UTILIZATION_PRECISION)
78
+ .div(BANK_UTILIZATION_PRECISION.sub(bank.optimalUtilization));
79
+
80
+ interest_rate = bank.optimalBorrowRate.add(
81
+ surplusUtilization.mul(borrowRateSlope).div(BANK_UTILIZATION_PRECISION)
82
+ );
83
+ } else {
84
+ const borrowRateSlope = bank.optimalBorrowRate
85
+ .mul(BANK_UTILIZATION_PRECISION)
86
+ .div(BANK_UTILIZATION_PRECISION.sub(bank.optimalUtilization));
87
+
88
+ interest_rate = utilization
89
+ .mul(borrowRateSlope)
90
+ .div(BANK_UTILIZATION_PRECISION);
91
+ }
92
+
93
+ const timeSinceLastUpdate = now.sub(bank.lastUpdated);
94
+
95
+ const modifiedBorrowRate = interest_rate.mul(timeSinceLastUpdate);
96
+
97
+ const modifiedDepositRate = modifiedBorrowRate
98
+ .mul(utilization)
99
+ .div(BANK_UTILIZATION_PRECISION);
100
+
101
+ const borrowInterest = bank.cumulativeBorrowInterest
102
+ .mul(modifiedBorrowRate)
103
+ .div(ONE_YEAR)
104
+ .div(BANK_INTEREST_PRECISION)
105
+ .add(ONE);
106
+ const depositInterest = bank.cumulativeDepositInterest
107
+ .mul(modifiedDepositRate)
108
+ .div(ONE_YEAR)
109
+ .div(BANK_INTEREST_PRECISION);
110
+
111
+ return { borrowInterest, depositInterest };
112
+ }
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.convertToNumber = void 0;
4
+ const numericConstants_1 = require("../constants/numericConstants");
5
+ const convertToNumber = (bigNumber, precision = numericConstants_1.MARK_PRICE_PRECISION) => {
6
+ if (!bigNumber)
7
+ return 0;
8
+ return (bigNumber.div(precision).toNumber() +
9
+ bigNumber.mod(precision).toNumber() / precision.toNumber());
10
+ };
11
+ exports.convertToNumber = convertToNumber;
@@ -1,8 +1,5 @@
1
1
  import { BN } from '../';
2
- import {
3
- MARK_PRICE_PRECISION,
4
- PEG_PRECISION,
5
- } from '../constants/numericConstants';
2
+ import { MARK_PRICE_PRECISION } from '../constants/numericConstants';
6
3
 
7
4
  export const convertToNumber = (
8
5
  bigNumber: BN,
@@ -14,10 +11,3 @@ export const convertToNumber = (
14
11
  bigNumber.mod(precision).toNumber() / precision.toNumber()
15
12
  );
16
13
  };
17
-
18
- export const convertBaseAssetAmountToNumber = (baseAssetAmount: BN) => {
19
- return convertToNumber(
20
- baseAssetAmount,
21
- MARK_PRICE_PRECISION.mul(PEG_PRECISION)
22
- );
23
- };
@@ -0,0 +1,248 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.calculateFundingPool = exports.calculateLongShortFundingRateAndLiveTwaps = exports.calculateLongShortFundingRate = exports.calculateEstimatedFundingRate = exports.calculateAllEstimatedFundingRate = void 0;
13
+ const anchor_1 = require("@project-serum/anchor");
14
+ const numericConstants_1 = require("../constants/numericConstants");
15
+ const market_1 = require("./market");
16
+ /**
17
+ *
18
+ * @param market
19
+ * @param oraclePriceData
20
+ * @param periodAdjustment
21
+ * @returns Estimated funding rate. : Precision //TODO-PRECISION
22
+ */
23
+ function calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ // periodAdjustment
26
+ // 1: hourly
27
+ // 24: daily
28
+ // 24 * 365.25: annualized
29
+ const secondsInHour = new anchor_1.BN(3600);
30
+ const hoursInDay = new anchor_1.BN(24);
31
+ const ONE = new anchor_1.BN(1);
32
+ if (!market.initialized) {
33
+ return [numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO];
34
+ }
35
+ const payFreq = new anchor_1.BN(market.amm.fundingPeriod);
36
+ // todo: sufficiently differs from blockchain timestamp?
37
+ const now = new anchor_1.BN((Date.now() / 1000).toFixed(0));
38
+ const timeSinceLastUpdate = now.sub(market.amm.lastFundingRateTs);
39
+ // calculate real-time mark twap
40
+ const lastMarkTwapWithMantissa = market.amm.lastMarkPriceTwap;
41
+ const lastMarkPriceTwapTs = market.amm.lastMarkPriceTwapTs;
42
+ const timeSinceLastMarkChange = now.sub(lastMarkPriceTwapTs);
43
+ const markTwapTimeSinceLastUpdate = anchor_1.BN.max(secondsInHour, anchor_1.BN.max(numericConstants_1.ZERO, secondsInHour.sub(timeSinceLastMarkChange)));
44
+ const baseAssetPriceWithMantissa = market_1.calculateMarkPrice(market, oraclePriceData);
45
+ const markTwapWithMantissa = markTwapTimeSinceLastUpdate
46
+ .mul(lastMarkTwapWithMantissa)
47
+ .add(timeSinceLastMarkChange.mul(baseAssetPriceWithMantissa))
48
+ .div(timeSinceLastMarkChange.add(markTwapTimeSinceLastUpdate));
49
+ // calculate real-time (predicted) oracle twap
50
+ // note: oracle twap depends on `when the chord is struck` (market is trade)
51
+ const lastOracleTwapWithMantissa = market.amm.lastOraclePriceTwap;
52
+ const lastOraclePriceTwapTs = market.amm.lastOraclePriceTwapTs;
53
+ const oracleInvalidDuration = anchor_1.BN.max(numericConstants_1.ZERO, lastMarkPriceTwapTs.sub(lastOraclePriceTwapTs));
54
+ const timeSinceLastOracleTwapUpdate = now.sub(lastOraclePriceTwapTs);
55
+ const oracleTwapTimeSinceLastUpdate = anchor_1.BN.max(ONE, anchor_1.BN.min(secondsInHour, anchor_1.BN.max(ONE, secondsInHour.sub(timeSinceLastOracleTwapUpdate))));
56
+ let oracleTwapWithMantissa = lastOracleTwapWithMantissa;
57
+ // if passing live oracle data, improve predicted calc estimate
58
+ if (oraclePriceData) {
59
+ const oraclePrice = oraclePriceData.price;
60
+ const oracleLiveVsTwap = oraclePrice
61
+ .sub(lastOracleTwapWithMantissa)
62
+ .abs()
63
+ .mul(numericConstants_1.MARK_PRICE_PRECISION)
64
+ .mul(new anchor_1.BN(100))
65
+ .div(lastOracleTwapWithMantissa);
66
+ // verify pyth live input is within 10% of last twap for live update
67
+ if (oracleLiveVsTwap.lte(numericConstants_1.MARK_PRICE_PRECISION.mul(new anchor_1.BN(10)))) {
68
+ oracleTwapWithMantissa = oracleTwapTimeSinceLastUpdate
69
+ .mul(lastOracleTwapWithMantissa)
70
+ .add(timeSinceLastMarkChange.mul(oraclePrice))
71
+ .div(timeSinceLastMarkChange.add(oracleTwapTimeSinceLastUpdate));
72
+ }
73
+ }
74
+ const shrunkLastOracleTwapwithMantissa = oracleTwapTimeSinceLastUpdate
75
+ .mul(lastOracleTwapWithMantissa)
76
+ .add(oracleInvalidDuration.mul(lastMarkTwapWithMantissa))
77
+ .div(oracleTwapTimeSinceLastUpdate.add(oracleInvalidDuration));
78
+ const twapSpread = lastMarkTwapWithMantissa.sub(shrunkLastOracleTwapwithMantissa);
79
+ const twapSpreadPct = twapSpread
80
+ .mul(numericConstants_1.MARK_PRICE_PRECISION)
81
+ .mul(new anchor_1.BN(100))
82
+ .div(shrunkLastOracleTwapwithMantissa);
83
+ const lowerboundEst = twapSpreadPct
84
+ .mul(payFreq)
85
+ .mul(anchor_1.BN.min(secondsInHour, timeSinceLastUpdate))
86
+ .mul(periodAdjustment)
87
+ .div(secondsInHour)
88
+ .div(secondsInHour)
89
+ .div(hoursInDay);
90
+ const interpEst = twapSpreadPct.mul(periodAdjustment).div(hoursInDay);
91
+ const interpRateQuote = twapSpreadPct
92
+ .mul(periodAdjustment)
93
+ .div(hoursInDay)
94
+ .div(numericConstants_1.MARK_PRICE_PRECISION.div(numericConstants_1.QUOTE_PRECISION));
95
+ let feePoolSize = calculateFundingPool(market);
96
+ if (interpRateQuote.lt(new anchor_1.BN(0))) {
97
+ feePoolSize = feePoolSize.mul(new anchor_1.BN(-1));
98
+ }
99
+ let cappedAltEst;
100
+ let largerSide;
101
+ let smallerSide;
102
+ if (market.baseAssetAmountLong.gt(market.baseAssetAmountShort.abs())) {
103
+ largerSide = market.baseAssetAmountLong.abs();
104
+ smallerSide = market.baseAssetAmountShort.abs();
105
+ if (twapSpread.gt(new anchor_1.BN(0))) {
106
+ return [
107
+ markTwapWithMantissa,
108
+ oracleTwapWithMantissa,
109
+ lowerboundEst,
110
+ interpEst,
111
+ interpEst,
112
+ ];
113
+ }
114
+ }
115
+ else if (market.baseAssetAmountLong.lt(market.baseAssetAmountShort.abs())) {
116
+ largerSide = market.baseAssetAmountShort.abs();
117
+ smallerSide = market.baseAssetAmountLong.abs();
118
+ if (twapSpread.lt(new anchor_1.BN(0))) {
119
+ return [
120
+ markTwapWithMantissa,
121
+ oracleTwapWithMantissa,
122
+ lowerboundEst,
123
+ interpEst,
124
+ interpEst,
125
+ ];
126
+ }
127
+ }
128
+ else {
129
+ return [
130
+ markTwapWithMantissa,
131
+ oracleTwapWithMantissa,
132
+ lowerboundEst,
133
+ interpEst,
134
+ interpEst,
135
+ ];
136
+ }
137
+ if (largerSide.gt(numericConstants_1.ZERO)) {
138
+ // funding smaller flow
139
+ cappedAltEst = smallerSide.mul(twapSpread).div(hoursInDay);
140
+ const feePoolTopOff = feePoolSize
141
+ .mul(numericConstants_1.MARK_PRICE_PRECISION.div(numericConstants_1.QUOTE_PRECISION))
142
+ .mul(numericConstants_1.AMM_RESERVE_PRECISION);
143
+ cappedAltEst = cappedAltEst.add(feePoolTopOff).div(largerSide);
144
+ cappedAltEst = cappedAltEst
145
+ .mul(numericConstants_1.MARK_PRICE_PRECISION)
146
+ .mul(new anchor_1.BN(100))
147
+ .div(oracleTwapWithMantissa)
148
+ .mul(periodAdjustment);
149
+ if (cappedAltEst.abs().gte(interpEst.abs())) {
150
+ cappedAltEst = interpEst;
151
+ }
152
+ }
153
+ else {
154
+ cappedAltEst = interpEst;
155
+ }
156
+ return [
157
+ markTwapWithMantissa,
158
+ oracleTwapWithMantissa,
159
+ lowerboundEst,
160
+ cappedAltEst,
161
+ interpEst,
162
+ ];
163
+ });
164
+ }
165
+ exports.calculateAllEstimatedFundingRate = calculateAllEstimatedFundingRate;
166
+ /**
167
+ *
168
+ * @param market
169
+ * @param oraclePriceData
170
+ * @param periodAdjustment
171
+ * @param estimationMethod
172
+ * @returns Estimated funding rate. : Precision //TODO-PRECISION
173
+ */
174
+ function calculateEstimatedFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1), estimationMethod) {
175
+ return __awaiter(this, void 0, void 0, function* () {
176
+ const [_1, _2, lowerboundEst, cappedAltEst, interpEst] = yield calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment);
177
+ if (estimationMethod == 'lowerbound') {
178
+ //assuming remaining funding period has no gap
179
+ return lowerboundEst;
180
+ }
181
+ else if (estimationMethod == 'capped') {
182
+ return cappedAltEst;
183
+ }
184
+ else {
185
+ return interpEst;
186
+ }
187
+ });
188
+ }
189
+ exports.calculateEstimatedFundingRate = calculateEstimatedFundingRate;
190
+ /**
191
+ *
192
+ * @param market
193
+ * @param oraclePriceData
194
+ * @param periodAdjustment
195
+ * @returns Estimated funding rate. : Precision //TODO-PRECISION
196
+ */
197
+ function calculateLongShortFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
198
+ return __awaiter(this, void 0, void 0, function* () {
199
+ const [_1, _2, _, cappedAltEst, interpEst] = yield calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment);
200
+ if (market.baseAssetAmountLong.gt(market.baseAssetAmountShort)) {
201
+ return [cappedAltEst, interpEst];
202
+ }
203
+ else if (market.baseAssetAmountLong.lt(market.baseAssetAmountShort)) {
204
+ return [interpEst, cappedAltEst];
205
+ }
206
+ else {
207
+ return [interpEst, interpEst];
208
+ }
209
+ });
210
+ }
211
+ exports.calculateLongShortFundingRate = calculateLongShortFundingRate;
212
+ /**
213
+ *
214
+ * @param market
215
+ * @param oraclePriceData
216
+ * @param periodAdjustment
217
+ * @returns Estimated funding rate. : Precision //TODO-PRECISION
218
+ */
219
+ function calculateLongShortFundingRateAndLiveTwaps(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
220
+ return __awaiter(this, void 0, void 0, function* () {
221
+ const [markTwapLive, oracleTwapLive, _2, cappedAltEst, interpEst] = yield calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment);
222
+ if (market.baseAssetAmountLong.gt(market.baseAssetAmountShort.abs())) {
223
+ return [markTwapLive, oracleTwapLive, cappedAltEst, interpEst];
224
+ }
225
+ else if (market.baseAssetAmountLong.lt(market.baseAssetAmountShort.abs())) {
226
+ return [markTwapLive, oracleTwapLive, interpEst, cappedAltEst];
227
+ }
228
+ else {
229
+ return [markTwapLive, oracleTwapLive, interpEst, interpEst];
230
+ }
231
+ });
232
+ }
233
+ exports.calculateLongShortFundingRateAndLiveTwaps = calculateLongShortFundingRateAndLiveTwaps;
234
+ /**
235
+ *
236
+ * @param market
237
+ * @returns Estimated fee pool size
238
+ */
239
+ function calculateFundingPool(market) {
240
+ // todo
241
+ const totalFeeLB = market.amm.totalExchangeFee.div(new anchor_1.BN(2));
242
+ const feePool = anchor_1.BN.max(numericConstants_1.ZERO, market.amm.totalFeeMinusDistributions
243
+ .sub(totalFeeLB)
244
+ .mul(new anchor_1.BN(1))
245
+ .div(new anchor_1.BN(3)));
246
+ return feePool;
247
+ }
248
+ exports.calculateFundingPool = calculateFundingPool;
@@ -5,7 +5,7 @@ import {
5
5
  QUOTE_PRECISION,
6
6
  ZERO,
7
7
  } from '../constants/numericConstants';
8
- import { Market } from '../types';
8
+ import { MarketAccount } from '../types';
9
9
  import { calculateMarkPrice } from './market';
10
10
  import { OraclePriceData } from '../oracles/types';
11
11
 
@@ -17,7 +17,7 @@ import { OraclePriceData } from '../oracles/types';
17
17
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
18
18
  */
19
19
  export async function calculateAllEstimatedFundingRate(
20
- market: Market,
20
+ market: MarketAccount,
21
21
  oraclePriceData?: OraclePriceData,
22
22
  periodAdjustment: BN = new BN(1)
23
23
  ): Promise<[BN, BN, BN, BN, BN]> {
@@ -48,7 +48,10 @@ export async function calculateAllEstimatedFundingRate(
48
48
  secondsInHour,
49
49
  BN.max(ZERO, secondsInHour.sub(timeSinceLastMarkChange))
50
50
  );
51
- const baseAssetPriceWithMantissa = calculateMarkPrice(market);
51
+ const baseAssetPriceWithMantissa = calculateMarkPrice(
52
+ market,
53
+ oraclePriceData
54
+ );
52
55
 
53
56
  const markTwapWithMantissa = markTwapTimeSinceLastUpdate
54
57
  .mul(lastMarkTwapWithMantissa)
@@ -205,7 +208,7 @@ export async function calculateAllEstimatedFundingRate(
205
208
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
206
209
  */
207
210
  export async function calculateEstimatedFundingRate(
208
- market: Market,
211
+ market: MarketAccount,
209
212
  oraclePriceData?: OraclePriceData,
210
213
  periodAdjustment: BN = new BN(1),
211
214
  estimationMethod?: 'interpolated' | 'lowerbound' | 'capped'
@@ -235,7 +238,7 @@ export async function calculateEstimatedFundingRate(
235
238
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
236
239
  */
237
240
  export async function calculateLongShortFundingRate(
238
- market: Market,
241
+ market: MarketAccount,
239
242
  oraclePriceData?: OraclePriceData,
240
243
  periodAdjustment: BN = new BN(1)
241
244
  ): Promise<[BN, BN]> {
@@ -263,7 +266,7 @@ export async function calculateLongShortFundingRate(
263
266
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
264
267
  */
265
268
  export async function calculateLongShortFundingRateAndLiveTwaps(
266
- market: Market,
269
+ market: MarketAccount,
267
270
  oraclePriceData?: OraclePriceData,
268
271
  periodAdjustment: BN = new BN(1)
269
272
  ): Promise<[BN, BN, BN, BN]> {
@@ -288,14 +291,14 @@ export async function calculateLongShortFundingRateAndLiveTwaps(
288
291
  * @param market
289
292
  * @returns Estimated fee pool size
290
293
  */
291
- export function calculateFundingPool(market: Market): BN {
294
+ export function calculateFundingPool(market: MarketAccount): BN {
292
295
  // todo
293
- const totalFeeLB = market.amm.totalFee.div(new BN(2));
296
+ const totalFeeLB = market.amm.totalExchangeFee.div(new BN(2));
294
297
  const feePool = BN.max(
295
298
  ZERO,
296
299
  market.amm.totalFeeMinusDistributions
297
300
  .sub(totalFeeLB)
298
- .mul(new BN(2))
301
+ .mul(new BN(1))
299
302
  .div(new BN(3))
300
303
  );
301
304
  return feePool;
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.calculateOracleSpread = exports.calculateMarkOracleSpread = exports.calculateNewMarketAfterTrade = exports.calculateAskPrice = exports.calculateBidPrice = exports.calculateMarkPrice = void 0;
4
+ const types_1 = require("../types");
5
+ const amm_1 = require("./amm");
6
+ /**
7
+ * Calculates market mark price
8
+ *
9
+ * @param market
10
+ * @return markPrice : Precision MARK_PRICE_PRECISION
11
+ */
12
+ function calculateMarkPrice(market, oraclePriceData) {
13
+ const newAmm = amm_1.calculateUpdatedAMM(market.amm, oraclePriceData);
14
+ return amm_1.calculatePrice(newAmm.baseAssetReserve, newAmm.quoteAssetReserve, newAmm.pegMultiplier);
15
+ }
16
+ exports.calculateMarkPrice = calculateMarkPrice;
17
+ /**
18
+ * Calculates market bid price
19
+ *
20
+ * @param market
21
+ * @return bidPrice : Precision MARK_PRICE_PRECISION
22
+ */
23
+ function calculateBidPrice(market, oraclePriceData) {
24
+ const { baseAssetReserve, quoteAssetReserve, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, types_1.PositionDirection.SHORT, oraclePriceData);
25
+ return amm_1.calculatePrice(baseAssetReserve, quoteAssetReserve, newPeg);
26
+ }
27
+ exports.calculateBidPrice = calculateBidPrice;
28
+ /**
29
+ * Calculates market ask price
30
+ *
31
+ * @param market
32
+ * @return bidPrice : Precision MARK_PRICE_PRECISION
33
+ */
34
+ function calculateAskPrice(market, oraclePriceData) {
35
+ const { baseAssetReserve, quoteAssetReserve, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, types_1.PositionDirection.LONG, oraclePriceData);
36
+ return amm_1.calculatePrice(baseAssetReserve, quoteAssetReserve, newPeg);
37
+ }
38
+ exports.calculateAskPrice = calculateAskPrice;
39
+ function calculateNewMarketAfterTrade(baseAssetAmount, direction, market) {
40
+ const [newQuoteAssetReserve, newBaseAssetReserve] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'base', baseAssetAmount.abs(), amm_1.getSwapDirection('base', direction));
41
+ const newAmm = Object.assign({}, market.amm);
42
+ const newMarket = Object.assign({}, market);
43
+ newMarket.amm = newAmm;
44
+ newMarket.amm.quoteAssetReserve = newQuoteAssetReserve;
45
+ newMarket.amm.baseAssetReserve = newBaseAssetReserve;
46
+ return newMarket;
47
+ }
48
+ exports.calculateNewMarketAfterTrade = calculateNewMarketAfterTrade;
49
+ function calculateMarkOracleSpread(market, oraclePriceData) {
50
+ const markPrice = calculateMarkPrice(market, oraclePriceData);
51
+ return calculateOracleSpread(markPrice, oraclePriceData);
52
+ }
53
+ exports.calculateMarkOracleSpread = calculateMarkOracleSpread;
54
+ function calculateOracleSpread(price, oraclePriceData) {
55
+ return price.sub(oraclePriceData.price);
56
+ }
57
+ exports.calculateOracleSpread = calculateOracleSpread;