@drift-labs/sdk 0.2.0-master.3 → 0.2.0-master.30

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 (208) hide show
  1. package/README.md +13 -13
  2. package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
  3. package/lib/accounts/bulkUserStatsSubscription.js +21 -0
  4. package/lib/accounts/bulkUserSubscription.js +0 -1
  5. package/lib/accounts/fetch.d.ts +2 -1
  6. package/lib/accounts/fetch.js +9 -1
  7. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +16 -16
  8. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +31 -28
  9. package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
  10. package/lib/accounts/pollingUserStatsAccountSubscriber.js +113 -0
  11. package/lib/accounts/types.d.ts +22 -11
  12. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +17 -17
  13. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +37 -35
  14. package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
  15. package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
  16. package/lib/addresses/marketAddresses.d.ts +1 -3
  17. package/lib/addresses/pda.d.ts +10 -4
  18. package/lib/addresses/pda.js +51 -14
  19. package/lib/admin.d.ts +34 -22
  20. package/lib/admin.js +182 -73
  21. package/lib/clearingHouse.d.ts +120 -42
  22. package/lib/clearingHouse.js +1505 -254
  23. package/lib/clearingHouseConfig.d.ts +4 -4
  24. package/lib/clearingHouseUser.d.ts +50 -38
  25. package/lib/clearingHouseUser.js +410 -190
  26. package/lib/clearingHouseUserStats.d.ts +18 -0
  27. package/lib/clearingHouseUserStats.js +49 -0
  28. package/lib/clearingHouseUserStatsConfig.d.ts +14 -0
  29. package/lib/clearingHouseUserStatsConfig.js +2 -0
  30. package/lib/config.d.ts +7 -9
  31. package/lib/config.js +21 -21
  32. package/lib/constants/numericConstants.d.ts +18 -12
  33. package/lib/constants/numericConstants.js +28 -21
  34. package/lib/constants/perpMarkets.d.ts +18 -0
  35. package/lib/constants/{markets.js → perpMarkets.js} +7 -7
  36. package/lib/constants/spotMarkets.d.ts +19 -0
  37. package/lib/constants/spotMarkets.js +53 -0
  38. package/lib/dlob/DLOB.d.ts +73 -0
  39. package/lib/dlob/DLOB.js +553 -0
  40. package/lib/dlob/DLOBNode.d.ts +52 -0
  41. package/lib/dlob/DLOBNode.js +82 -0
  42. package/lib/dlob/NodeList.d.ts +26 -0
  43. package/lib/dlob/NodeList.js +138 -0
  44. package/lib/events/eventList.js +3 -0
  45. package/lib/events/eventSubscriber.d.ts +4 -2
  46. package/lib/events/eventSubscriber.js +16 -9
  47. package/lib/events/fetchLogs.d.ts +10 -1
  48. package/lib/events/fetchLogs.js +27 -7
  49. package/lib/events/pollingLogProvider.d.ts +2 -1
  50. package/lib/events/pollingLogProvider.js +6 -2
  51. package/lib/events/sort.js +8 -11
  52. package/lib/events/types.d.ts +7 -2
  53. package/lib/events/types.js +5 -0
  54. package/lib/examples/makeTradeExample.js +20 -8
  55. package/lib/factory/bigNum.d.ts +1 -0
  56. package/lib/factory/bigNum.js +34 -10
  57. package/lib/idl/clearing_house.json +4313 -1433
  58. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  59. package/lib/index.d.ts +21 -6
  60. package/lib/index.js +25 -6
  61. package/lib/math/amm.d.ts +8 -5
  62. package/lib/math/amm.js +68 -46
  63. package/lib/math/auction.js +4 -1
  64. package/lib/math/conversion.js +1 -1
  65. package/lib/math/funding.d.ts +6 -6
  66. package/lib/math/funding.js +11 -10
  67. package/lib/math/insurance.d.ts +4 -0
  68. package/lib/math/insurance.js +27 -0
  69. package/lib/math/margin.d.ts +11 -0
  70. package/lib/math/margin.js +77 -0
  71. package/lib/math/market.d.ts +14 -9
  72. package/lib/math/market.js +69 -7
  73. package/lib/math/oracles.d.ts +4 -0
  74. package/lib/math/oracles.js +36 -8
  75. package/lib/math/orders.d.ts +6 -2
  76. package/lib/math/orders.js +78 -3
  77. package/lib/math/position.d.ts +21 -13
  78. package/lib/math/position.js +76 -36
  79. package/lib/math/repeg.js +14 -5
  80. package/lib/math/spotBalance.d.ts +22 -0
  81. package/lib/math/spotBalance.js +193 -0
  82. package/lib/math/spotMarket.d.ts +4 -0
  83. package/lib/math/spotMarket.js +8 -0
  84. package/lib/math/spotPosition.d.ts +6 -0
  85. package/lib/math/spotPosition.js +23 -0
  86. package/lib/math/trade.d.ts +10 -10
  87. package/lib/math/trade.js +22 -29
  88. package/lib/oracles/pythClient.js +1 -1
  89. package/lib/oracles/quoteAssetOracleClient.js +1 -1
  90. package/lib/oracles/switchboardClient.js +1 -1
  91. package/lib/orderParams.d.ts +14 -5
  92. package/lib/orderParams.js +12 -92
  93. package/lib/serum/serumSubscriber.d.ts +23 -0
  94. package/lib/serum/serumSubscriber.js +41 -0
  95. package/lib/serum/types.d.ts +11 -0
  96. package/lib/serum/types.js +2 -0
  97. package/lib/slot/SlotSubscriber.d.ts +7 -0
  98. package/lib/slot/SlotSubscriber.js +3 -0
  99. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  100. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  101. package/lib/tx/retryTxSender.d.ts +1 -1
  102. package/lib/tx/retryTxSender.js +13 -4
  103. package/lib/tx/types.d.ts +1 -1
  104. package/lib/tx/utils.js +1 -1
  105. package/lib/types.d.ts +474 -123
  106. package/lib/types.js +99 -5
  107. package/lib/userMap/userMap.d.ts +25 -0
  108. package/lib/userMap/userMap.js +73 -0
  109. package/lib/userMap/userStatsMap.d.ts +19 -0
  110. package/lib/userMap/userStatsMap.js +68 -0
  111. package/lib/util/computeUnits.js +1 -1
  112. package/lib/util/getTokenAddress.d.ts +2 -0
  113. package/lib/util/getTokenAddress.js +9 -0
  114. package/package.json +9 -5
  115. package/src/accounts/bulkUserStatsSubscription.ts +33 -0
  116. package/src/accounts/bulkUserSubscription.ts +0 -1
  117. package/src/accounts/fetch.ts +27 -2
  118. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +46 -42
  119. package/src/accounts/pollingUserStatsAccountSubscriber.ts +172 -0
  120. package/src/accounts/types.ts +31 -11
  121. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +64 -59
  122. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
  123. package/src/addresses/marketAddresses.ts +1 -2
  124. package/src/addresses/pda.ts +88 -14
  125. package/src/admin.ts +333 -128
  126. package/src/assert/assert.js +9 -0
  127. package/src/clearingHouse.ts +2464 -458
  128. package/src/clearingHouseConfig.ts +4 -3
  129. package/src/clearingHouseUser.ts +747 -291
  130. package/src/clearingHouseUserStats.ts +75 -0
  131. package/src/clearingHouseUserStatsConfig.ts +18 -0
  132. package/src/config.ts +30 -31
  133. package/src/constants/numericConstants.ts +41 -25
  134. package/src/constants/{markets.ts → perpMarkets.ts} +10 -10
  135. package/src/constants/spotMarkets.ts +72 -0
  136. package/src/dlob/DLOB.ts +868 -0
  137. package/src/dlob/DLOBNode.ts +162 -0
  138. package/src/dlob/NodeList.ts +185 -0
  139. package/src/events/eventList.js +77 -0
  140. package/src/events/eventList.ts +3 -0
  141. package/src/events/eventSubscriber.ts +20 -12
  142. package/src/events/fetchLogs.ts +35 -8
  143. package/src/events/pollingLogProvider.ts +10 -2
  144. package/src/events/sort.ts +11 -15
  145. package/src/events/types.ts +16 -1
  146. package/src/examples/makeTradeExample.js +157 -0
  147. package/src/examples/makeTradeExample.ts +32 -14
  148. package/src/factory/bigNum.ts +42 -13
  149. package/src/idl/clearing_house.json +4313 -1433
  150. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  151. package/src/index.ts +21 -6
  152. package/src/math/amm.ts +136 -66
  153. package/src/math/auction.ts +5 -1
  154. package/src/math/conversion.ts +2 -2
  155. package/src/math/funding.ts +20 -18
  156. package/src/math/insurance.ts +35 -0
  157. package/src/math/margin.ts +127 -0
  158. package/src/math/market.ts +138 -12
  159. package/src/math/oracles.ts +63 -9
  160. package/src/math/orders.ts +138 -4
  161. package/src/math/position.ts +119 -58
  162. package/src/math/repeg.ts +16 -6
  163. package/src/math/spotBalance.ts +316 -0
  164. package/src/math/spotMarket.ts +9 -0
  165. package/src/math/spotPosition.ts +47 -0
  166. package/src/math/trade.ts +43 -49
  167. package/src/oracles/pythClient.ts +2 -2
  168. package/src/oracles/quoteAssetOracleClient.ts +2 -2
  169. package/src/oracles/switchboardClient.ts +2 -2
  170. package/src/orderParams.ts +24 -137
  171. package/src/serum/serumSubscriber.ts +80 -0
  172. package/src/serum/types.ts +13 -0
  173. package/src/slot/SlotSubscriber.ts +11 -1
  174. package/src/token/index.js +38 -0
  175. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  176. package/src/tx/retryTxSender.ts +16 -5
  177. package/src/tx/types.js +2 -0
  178. package/src/tx/types.ts +2 -1
  179. package/src/tx/utils.js +17 -0
  180. package/src/tx/utils.ts +1 -1
  181. package/src/types.ts +477 -125
  182. package/src/userMap/userMap.ts +100 -0
  183. package/src/userMap/userStatsMap.ts +110 -0
  184. package/src/util/computeUnits.js +21 -11
  185. package/src/util/computeUnits.ts +1 -1
  186. package/src/util/getTokenAddress.js +9 -0
  187. package/src/util/getTokenAddress.ts +18 -0
  188. package/src/util/promiseTimeout.js +14 -0
  189. package/src/util/tps.js +27 -0
  190. package/tests/bn/test.ts +12 -3
  191. package/tests/dlob/helpers.ts +374 -0
  192. package/tests/dlob/test.ts +2865 -0
  193. package/lib/constants/banks.d.ts +0 -16
  194. package/lib/constants/banks.js +0 -34
  195. package/lib/constants/markets.d.ts +0 -19
  196. package/lib/math/bankBalance.d.ts +0 -9
  197. package/lib/math/bankBalance.js +0 -75
  198. package/lib/math/state.d.ts +0 -8
  199. package/lib/math/state.js +0 -15
  200. package/lib/orders.d.ts +0 -8
  201. package/lib/orders.js +0 -134
  202. package/src/constants/banks.ts +0 -43
  203. package/src/math/bankBalance.ts +0 -112
  204. package/src/math/state.ts +0 -14
  205. package/src/math/utils.js +0 -27
  206. package/src/math/utils.js.map +0 -1
  207. package/src/orders.ts +0 -244
  208. package/src/util/computeUnits.js.map +0 -1
@@ -4,7 +4,12 @@ import {
4
4
  FundingPaymentRecord,
5
5
  FundingRateRecord,
6
6
  LiquidationRecord,
7
+ NewUserRecord,
8
+ OrderActionRecord,
7
9
  OrderRecord,
10
+ SettlePnlRecord,
11
+ LPRecord,
12
+ InsuranceFundRecord,
8
13
  } from '../index';
9
14
 
10
15
  export type EventSubscriptionOptions = {
@@ -26,7 +31,12 @@ export const DefaultEventSubscriptionOptions: EventSubscriptionOptions = {
26
31
  'FundingPaymentRecord',
27
32
  'LiquidationRecord',
28
33
  'OrderRecord',
34
+ 'OrderActionRecord',
29
35
  'FundingRateRecord',
36
+ 'NewUserRecord',
37
+ 'SettlePnlRecord',
38
+ 'LPRecord',
39
+ 'InsuranceFundRecord',
30
40
  ],
31
41
  maxEventsPerType: 4096,
32
42
  orderBy: 'blockchain',
@@ -59,6 +69,11 @@ export type EventMap = {
59
69
  LiquidationRecord: Event<LiquidationRecord>;
60
70
  FundingRateRecord: Event<FundingRateRecord>;
61
71
  OrderRecord: Event<OrderRecord>;
72
+ OrderActionRecord: Event<OrderActionRecord>;
73
+ SettlePnlRecord: Event<SettlePnlRecord>;
74
+ NewUserRecord: Event<NewUserRecord>;
75
+ LPRecord: Event<LPRecord>;
76
+ InsuranceFundRecord: Event<InsuranceFundRecord>;
62
77
  };
63
78
 
64
79
  export type EventType = keyof EventMap;
@@ -80,7 +95,7 @@ export type logProviderCallback = (
80
95
 
81
96
  export interface LogProvider {
82
97
  isSubscribed(): boolean;
83
- subscribe(callback: logProviderCallback): boolean;
98
+ subscribe(callback: logProviderCallback, skipHistory?: boolean): boolean;
84
99
  unsubscribe(): Promise<boolean>;
85
100
  }
86
101
 
@@ -0,0 +1,157 @@
1
+ 'use strict';
2
+ var __awaiter =
3
+ (this && this.__awaiter) ||
4
+ function (thisArg, _arguments, P, generator) {
5
+ function adopt(value) {
6
+ return value instanceof P
7
+ ? value
8
+ : new P(function (resolve) {
9
+ resolve(value);
10
+ });
11
+ }
12
+ return new (P || (P = Promise))(function (resolve, reject) {
13
+ function fulfilled(value) {
14
+ try {
15
+ step(generator.next(value));
16
+ } catch (e) {
17
+ reject(e);
18
+ }
19
+ }
20
+ function rejected(value) {
21
+ try {
22
+ step(generator['throw'](value));
23
+ } catch (e) {
24
+ reject(e);
25
+ }
26
+ }
27
+ function step(result) {
28
+ result.done
29
+ ? resolve(result.value)
30
+ : adopt(result.value).then(fulfilled, rejected);
31
+ }
32
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
33
+ });
34
+ };
35
+ Object.defineProperty(exports, '__esModule', { value: true });
36
+ exports.getTokenAddress = void 0;
37
+ const anchor_1 = require('@project-serum/anchor');
38
+ const __1 = require('..');
39
+ const spl_token_1 = require('@solana/spl-token');
40
+ const web3_js_1 = require('@solana/web3.js');
41
+ const __2 = require('..');
42
+ const banks_1 = require('../constants/spotMarkets');
43
+ const getTokenAddress = (mintAddress, userPubKey) => {
44
+ return spl_token_1.Token.getAssociatedTokenAddress(
45
+ new web3_js_1.PublicKey(`ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL`),
46
+ spl_token_1.TOKEN_PROGRAM_ID,
47
+ new web3_js_1.PublicKey(mintAddress),
48
+ new web3_js_1.PublicKey(userPubKey)
49
+ );
50
+ };
51
+ exports.getTokenAddress = getTokenAddress;
52
+ const main = () =>
53
+ __awaiter(void 0, void 0, void 0, function* () {
54
+ // Initialize Drift SDK
55
+ const sdkConfig = __2.initialize({ env: 'devnet' });
56
+ // Set up the Wallet and Provider
57
+ const privateKey = process.env.BOT_PRIVATE_KEY; // stored as an array string
58
+ const keypair = web3_js_1.Keypair.fromSecretKey(
59
+ Uint8Array.from(JSON.parse(privateKey))
60
+ );
61
+ const wallet = new __1.Wallet(keypair);
62
+ // Set up the Connection
63
+ const rpcAddress = process.env.RPC_ADDRESS; // can use: https://api.devnet.solana.com for devnet; https://api.mainnet-beta.solana.com for mainnet;
64
+ const connection = new web3_js_1.Connection(rpcAddress);
65
+ // Set up the Provider
66
+ const provider = new anchor_1.AnchorProvider(
67
+ connection,
68
+ wallet,
69
+ anchor_1.AnchorProvider.defaultOptions()
70
+ );
71
+ // Check SOL Balance
72
+ const lamportsBalance = yield connection.getBalance(wallet.publicKey);
73
+ console.log('SOL balance:', lamportsBalance / Math.pow(10, 9));
74
+ // Misc. other things to set up
75
+ const usdcTokenAddress = yield exports.getTokenAddress(
76
+ sdkConfig.USDC_MINT_ADDRESS,
77
+ wallet.publicKey.toString()
78
+ );
79
+ // Set up the Drift Clearing House
80
+ const clearingHousePublicKey = new web3_js_1.PublicKey(
81
+ sdkConfig.CLEARING_HOUSE_PROGRAM_ID
82
+ );
83
+ const clearingHouse = new __2.ClearingHouse({
84
+ connection,
85
+ wallet: provider.wallet,
86
+ programID: clearingHousePublicKey,
87
+ });
88
+ yield clearingHouse.subscribe();
89
+ // Set up Clearing House user client
90
+ const user = new __2.ClearingHouseUser({
91
+ clearingHouse,
92
+ userAccountPublicKey: yield clearingHouse.getUserAccountPublicKey(),
93
+ });
94
+ //// Check if clearing house account exists for the current wallet
95
+ const userAccountExists = yield user.exists();
96
+ if (!userAccountExists) {
97
+ //// Create a Clearing House account by Depositing some USDC ($10,000 in this case)
98
+ const depositAmount = new anchor_1.BN(10000).mul(__2.QUOTE_PRECISION);
99
+ yield clearingHouse.initializeUserAccountAndDepositCollateral(
100
+ depositAmount,
101
+ yield exports.getTokenAddress(
102
+ usdcTokenAddress.toString(),
103
+ wallet.publicKey.toString()
104
+ ),
105
+ banks_1.SpotMarkets['devnet'][0].marketIndex
106
+ );
107
+ }
108
+ yield user.subscribe();
109
+ // Get current price
110
+ const solMarketInfo = sdkConfig.PERP_MARKETS.find(
111
+ (market) => market.baseAssetSymbol === 'SOL'
112
+ );
113
+ const currentMarketPrice = __2.calculateMarkPrice(
114
+ clearingHouse.getMarketAccount(solMarketInfo.marketIndex),
115
+ undefined
116
+ );
117
+ const formattedPrice = __2.convertToNumber(
118
+ currentMarketPrice,
119
+ __2.PRICE_PRECISION
120
+ );
121
+ console.log(`Current Market Price is $${formattedPrice}`);
122
+ // Estimate the slippage for a $5000 LONG trade
123
+ const solMarketAccount = clearingHouse.getMarketAccount(
124
+ solMarketInfo.marketIndex
125
+ );
126
+ const longAmount = new anchor_1.BN(5000).mul(__2.QUOTE_PRECISION);
127
+ const slippage = __2.convertToNumber(
128
+ __2.calculateTradeSlippage(
129
+ __2.PositionDirection.LONG,
130
+ longAmount,
131
+ solMarketAccount,
132
+ 'quote',
133
+ undefined
134
+ )[0],
135
+ __2.PRICE_PRECISION
136
+ );
137
+ console.log(
138
+ `Slippage for a $5000 LONG on the SOL market would be $${slippage}`
139
+ );
140
+ // Make a $5000 LONG trade
141
+ yield clearingHouse.openPosition(
142
+ __2.PositionDirection.LONG,
143
+ longAmount,
144
+ solMarketInfo.marketIndex
145
+ );
146
+ console.log(`LONGED $5000 SOL`);
147
+ // Reduce the position by $2000
148
+ const reduceAmount = new anchor_1.BN(2000).mul(__2.QUOTE_PRECISION);
149
+ yield clearingHouse.openPosition(
150
+ __2.PositionDirection.SHORT,
151
+ reduceAmount,
152
+ solMarketInfo.marketIndex
153
+ );
154
+ // Close the rest of the position
155
+ yield clearingHouse.closePosition(solMarketInfo.marketIndex);
156
+ });
157
+ main();
@@ -3,17 +3,19 @@ import { Wallet } from '..';
3
3
  import { Token, TOKEN_PROGRAM_ID } from '@solana/spl-token';
4
4
  import { Connection, Keypair, PublicKey } from '@solana/web3.js';
5
5
  import {
6
- calculateMarkPrice,
6
+ calculateReservePrice,
7
7
  ClearingHouse,
8
8
  ClearingHouseUser,
9
9
  initialize,
10
10
  PositionDirection,
11
11
  convertToNumber,
12
12
  calculateTradeSlippage,
13
- MARK_PRICE_PRECISION,
13
+ BulkAccountLoader,
14
+ PerpMarkets,
15
+ PRICE_PRECISION,
14
16
  QUOTE_PRECISION,
15
17
  } from '..';
16
- import { Banks } from '../constants/banks';
18
+ import { SpotMarkets } from '../constants/spotMarkets';
17
19
 
18
20
  export const getTokenAddress = (
19
21
  mintAddress: string,
@@ -27,9 +29,11 @@ export const getTokenAddress = (
27
29
  );
28
30
  };
29
31
 
32
+ const cluster = 'devnet';
33
+
30
34
  const main = async () => {
31
35
  // Initialize Drift SDK
32
- const sdkConfig = initialize({ env: 'devnet' });
36
+ const sdkConfig = initialize({ env: cluster });
33
37
 
34
38
  // Set up the Wallet and Provider
35
39
  const privateKey = process.env.BOT_PRIVATE_KEY; // stored as an array string
@@ -63,10 +67,23 @@ const main = async () => {
63
67
  const clearingHousePublicKey = new PublicKey(
64
68
  sdkConfig.CLEARING_HOUSE_PROGRAM_ID
65
69
  );
70
+ const bulkAccountLoader = new BulkAccountLoader(
71
+ connection,
72
+ 'confirmed',
73
+ 1000
74
+ );
66
75
  const clearingHouse = new ClearingHouse({
67
76
  connection,
68
77
  wallet: provider.wallet,
69
78
  programID: clearingHousePublicKey,
79
+ perpMarketIndexes: PerpMarkets[cluster].map((market) => market.marketIndex),
80
+ spotMarketIndexes: SpotMarkets[cluster].map(
81
+ (spotMarket) => spotMarket.marketIndex
82
+ ),
83
+ accountSubscription: {
84
+ type: 'polling',
85
+ accountLoader: bulkAccountLoader,
86
+ },
70
87
  });
71
88
  await clearingHouse.subscribe();
72
89
 
@@ -74,6 +91,10 @@ const main = async () => {
74
91
  const user = new ClearingHouseUser({
75
92
  clearingHouse,
76
93
  userAccountPublicKey: await clearingHouse.getUserAccountPublicKey(),
94
+ accountSubscription: {
95
+ type: 'polling',
96
+ accountLoader: bulkAccountLoader,
97
+ },
77
98
  });
78
99
 
79
100
  //// Check if clearing house account exists for the current wallet
@@ -88,31 +109,28 @@ const main = async () => {
88
109
  usdcTokenAddress.toString(),
89
110
  wallet.publicKey.toString()
90
111
  ),
91
- Banks['devnet'][0].bankIndex
112
+ SpotMarkets['devnet'][0].marketIndex
92
113
  );
93
114
  }
94
115
 
95
116
  await user.subscribe();
96
117
 
97
118
  // Get current price
98
- const solMarketInfo = sdkConfig.MARKETS.find(
119
+ const solMarketInfo = sdkConfig.PERP_MARKETS.find(
99
120
  (market) => market.baseAssetSymbol === 'SOL'
100
121
  );
101
122
 
102
- const currentMarketPrice = calculateMarkPrice(
103
- clearingHouse.getMarketAccount(solMarketInfo.marketIndex),
123
+ const currentMarketPrice = calculateReservePrice(
124
+ clearingHouse.getPerpMarketAccount(solMarketInfo.marketIndex),
104
125
  undefined
105
126
  );
106
127
 
107
- const formattedPrice = convertToNumber(
108
- currentMarketPrice,
109
- MARK_PRICE_PRECISION
110
- );
128
+ const formattedPrice = convertToNumber(currentMarketPrice, PRICE_PRECISION);
111
129
 
112
130
  console.log(`Current Market Price is $${formattedPrice}`);
113
131
 
114
132
  // Estimate the slippage for a $5000 LONG trade
115
- const solMarketAccount = clearingHouse.getMarketAccount(
133
+ const solMarketAccount = clearingHouse.getPerpMarketAccount(
116
134
  solMarketInfo.marketIndex
117
135
  );
118
136
 
@@ -125,7 +143,7 @@ const main = async () => {
125
143
  'quote',
126
144
  undefined
127
145
  )[0],
128
- MARK_PRICE_PRECISION
146
+ PRICE_PRECISION
129
147
  );
130
148
 
131
149
  console.log(
@@ -17,6 +17,10 @@ export class BigNum {
17
17
  this.precision = new BN(precisionVal);
18
18
  }
19
19
 
20
+ private bigNumFromParam(bn: BigNum | BN) {
21
+ return BN.isBN(bn) ? BigNum.from(bn) : bn;
22
+ }
23
+
20
24
  public add(bn: BigNum): BigNum {
21
25
  assert(bn.precision.eq(this.precision), 'Adding unequal precisions');
22
26
 
@@ -30,7 +34,7 @@ export class BigNum {
30
34
  }
31
35
 
32
36
  public mul(bn: BigNum | BN): BigNum {
33
- const mulVal = bn instanceof BigNum ? bn : BigNum.from(bn);
37
+ const mulVal = this.bigNumFromParam(bn);
34
38
 
35
39
  return BigNum.from(
36
40
  this.val.mul(mulVal.val),
@@ -44,7 +48,7 @@ export class BigNum {
44
48
  * @returns
45
49
  */
46
50
  public scalarMul(bn: BigNum | BN): BigNum {
47
- if (bn instanceof BN) return BigNum.from(this.val.mul(bn), this.precision);
51
+ if (BN.isBN(bn)) return BigNum.from(this.val.mul(bn), this.precision);
48
52
 
49
53
  return BigNum.from(
50
54
  this.val.mul(bn.val),
@@ -53,7 +57,8 @@ export class BigNum {
53
57
  }
54
58
 
55
59
  public div(bn: BigNum | BN): BigNum {
56
- if (bn instanceof BN) return BigNum.from(this.val.div(bn), this.precision);
60
+ if (BN.isBN(bn)) return BigNum.from(this.val.div(bn), this.precision);
61
+
57
62
  return BigNum.from(this.val.div(bn.val), this.precision.sub(bn.precision));
58
63
  }
59
64
 
@@ -101,7 +106,7 @@ export class BigNum {
101
106
  }
102
107
 
103
108
  public gt(bn: BigNum | BN, ignorePrecision?: boolean): boolean {
104
- const comparisonVal = bn instanceof BigNum ? bn : BigNum.from(bn);
109
+ const comparisonVal = this.bigNumFromParam(bn);
105
110
 
106
111
  if (!ignorePrecision && !comparisonVal.eq(ZERO)) {
107
112
  assert(
@@ -114,7 +119,7 @@ export class BigNum {
114
119
  }
115
120
 
116
121
  public lt(bn: BigNum | BN, ignorePrecision?: boolean): boolean {
117
- const comparisonVal = bn instanceof BigNum ? bn : BigNum.from(bn);
122
+ const comparisonVal = this.bigNumFromParam(bn);
118
123
 
119
124
  if (!ignorePrecision && !comparisonVal.val.eq(ZERO)) {
120
125
  assert(
@@ -127,7 +132,7 @@ export class BigNum {
127
132
  }
128
133
 
129
134
  public gte(bn: BigNum | BN, ignorePrecision?: boolean): boolean {
130
- const comparisonVal = bn instanceof BigNum ? bn : BigNum.from(bn);
135
+ const comparisonVal = this.bigNumFromParam(bn);
131
136
 
132
137
  if (!ignorePrecision && !comparisonVal.val.eq(ZERO)) {
133
138
  assert(
@@ -140,7 +145,7 @@ export class BigNum {
140
145
  }
141
146
 
142
147
  public lte(bn: BigNum | BN, ignorePrecision?: boolean): boolean {
143
- const comparisonVal = bn instanceof BigNum ? bn : BigNum.from(bn);
148
+ const comparisonVal = this.bigNumFromParam(bn);
144
149
 
145
150
  if (!ignorePrecision && !comparisonVal.val.eq(ZERO)) {
146
151
  assert(
@@ -153,7 +158,7 @@ export class BigNum {
153
158
  }
154
159
 
155
160
  public eq(bn: BigNum | BN, ignorePrecision?: boolean): boolean {
156
- const comparisonVal = bn instanceof BigNum ? bn : BigNum.from(bn);
161
+ const comparisonVal = this.bigNumFromParam(bn);
157
162
 
158
163
  if (!ignorePrecision && !comparisonVal.val.eq(ZERO)) {
159
164
  assert(
@@ -206,7 +211,8 @@ export class BigNum {
206
211
  'Tried to print a BN with precision lower than zero'
207
212
  );
208
213
 
209
- const plainString = this.toString();
214
+ const isNeg = this.isNeg();
215
+ const plainString = this.abs().toString();
210
216
  const precisionNum = this.precision.toNumber();
211
217
 
212
218
  // make a string with at least the precisionNum number of zeroes
@@ -227,6 +233,9 @@ export class BigNum {
227
233
  // add zero if leading delim
228
234
  if (printString[0] === BigNum.delim) printString = `0${printString}`;
229
235
 
236
+ // Add minus if negative
237
+ if (isNeg) printString = `-${printString}`;
238
+
230
239
  // remove trailing delim
231
240
  if (printString[printString.length - 1] === BigNum.delim)
232
241
  printString = printString.slice(0, printString.length - 1);
@@ -392,10 +401,30 @@ export class BigNum {
392
401
  ): string {
393
402
  const prefix = `${this.lt(BigNum.zero()) ? `-` : ``}$`;
394
403
 
395
- const val =
396
- useTradePrecision || precisionOverride
397
- ? this.prettyPrint(useTradePrecision, precisionOverride)
398
- : BigNum.fromPrint(this.toFixed(2), new BN(2)).prettyPrint();
404
+ const usingCustomPrecision =
405
+ true && (useTradePrecision || precisionOverride);
406
+
407
+ let val = usingCustomPrecision
408
+ ? this.prettyPrint(useTradePrecision, precisionOverride)
409
+ : BigNum.fromPrint(this.toFixed(2), new BN(2)).prettyPrint();
410
+
411
+ // Append two trailing zeroes if not using custom precision
412
+ if (!usingCustomPrecision) {
413
+ const [_, rightSide] = val.split(BigNum.delim);
414
+
415
+ const trailingLength = rightSide?.length ?? 0;
416
+
417
+ if (trailingLength < 2) {
418
+ const numHasDecimals = this.print().includes(BigNum.delim);
419
+
420
+ // Handle case where pretty print won't include the decimal point
421
+ if (trailingLength === 0 && numHasDecimals) {
422
+ val = `${val}.00`;
423
+ } else {
424
+ val = `${val}${new Array(2 - trailingLength).fill('0').join('')}`;
425
+ }
426
+ }
427
+ }
399
428
 
400
429
  return `${prefix}${val.replace('-', '')}`;
401
430
  }