@drift-labs/sdk 0.2.0-temp.1 → 2.0.0

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 (274) hide show
  1. package/README.md +27 -29
  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 +10 -10
  30. package/lib/config.js +26 -22
  31. package/lib/constants/numericConstants.d.ts +29 -12
  32. package/lib/constants/numericConstants.js +40 -21
  33. package/lib/constants/perpMarkets.d.ts +18 -0
  34. package/lib/constants/{markets.js → perpMarkets.js} +20 -9
  35. package/lib/constants/spotMarkets.d.ts +19 -0
  36. package/lib/constants/spotMarkets.js +63 -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 +45 -14
  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 +8392 -0
  62. package/lib/index.d.ts +29 -12
  63. package/lib/index.js +29 -12
  64. package/lib/math/amm.d.ts +9 -6
  65. package/lib/math/amm.js +91 -38
  66. package/lib/math/conversion.js +1 -1
  67. package/lib/math/exchangeStatus.d.ts +4 -0
  68. package/lib/math/exchangeStatus.js +18 -0
  69. package/lib/math/funding.d.ts +6 -6
  70. package/lib/math/funding.js +23 -21
  71. package/lib/math/insurance.d.ts +4 -0
  72. package/lib/math/insurance.js +27 -0
  73. package/lib/math/margin.d.ts +11 -0
  74. package/lib/math/margin.js +82 -0
  75. package/lib/math/market.d.ts +14 -9
  76. package/lib/math/market.js +70 -10
  77. package/lib/math/oracles.d.ts +4 -0
  78. package/lib/math/oracles.js +36 -8
  79. package/lib/math/orders.d.ts +16 -6
  80. package/lib/math/orders.js +97 -17
  81. package/lib/math/position.d.ts +27 -13
  82. package/lib/math/position.js +91 -37
  83. package/lib/math/repeg.js +17 -8
  84. package/lib/math/spotBalance.d.ts +22 -0
  85. package/lib/math/spotBalance.js +192 -0
  86. package/lib/math/spotMarket.d.ts +4 -0
  87. package/lib/math/spotMarket.js +8 -0
  88. package/lib/math/spotPosition.d.ts +6 -0
  89. package/lib/math/spotPosition.js +23 -0
  90. package/lib/math/trade.d.ts +10 -10
  91. package/lib/math/trade.js +27 -31
  92. package/lib/oracles/pythClient.js +1 -1
  93. package/lib/oracles/quoteAssetOracleClient.js +1 -1
  94. package/lib/oracles/switchboardClient.js +1 -1
  95. package/lib/orderParams.d.ts +4 -4
  96. package/lib/orderParams.js +12 -4
  97. package/lib/serum/serumFulfillmentConfigMap.d.ts +10 -0
  98. package/lib/serum/serumFulfillmentConfigMap.js +17 -0
  99. package/lib/serum/serumSubscriber.d.ts +27 -0
  100. package/lib/serum/serumSubscriber.js +56 -0
  101. package/lib/serum/types.d.ts +11 -0
  102. package/{src/oracles → lib/serum}/types.js +0 -0
  103. package/lib/tokenFaucet.d.ts +1 -0
  104. package/lib/tokenFaucet.js +23 -12
  105. package/lib/tx/retryTxSender.d.ts +1 -1
  106. package/lib/tx/retryTxSender.js +13 -4
  107. package/lib/tx/types.d.ts +1 -1
  108. package/lib/types.d.ts +631 -222
  109. package/lib/types.js +137 -24
  110. package/lib/user.d.ts +228 -0
  111. package/lib/user.js +959 -0
  112. package/lib/userConfig.d.ts +14 -0
  113. package/lib/{clearingHouseUserConfig.js → userConfig.js} +0 -0
  114. package/lib/userMap/userMap.d.ts +41 -0
  115. package/lib/userMap/userMap.js +85 -0
  116. package/lib/userMap/userStatsMap.d.ts +19 -0
  117. package/lib/userMap/userStatsMap.js +68 -0
  118. package/lib/userName.d.ts +1 -0
  119. package/lib/userName.js +3 -2
  120. package/lib/userStats.d.ts +18 -0
  121. package/lib/userStats.js +49 -0
  122. package/lib/userStatsConfig.d.ts +14 -0
  123. package/{src/clearingHouseConfig.js → lib/userStatsConfig.js} +0 -0
  124. package/lib/util/getTokenAddress.d.ts +2 -0
  125. package/lib/util/getTokenAddress.js +9 -0
  126. package/package.json +12 -5
  127. package/src/accounts/bulkAccountLoader.ts +44 -34
  128. package/src/accounts/bulkUserStatsSubscription.ts +33 -0
  129. package/src/accounts/bulkUserSubscription.ts +2 -3
  130. package/src/accounts/fetch.ts +27 -2
  131. package/src/accounts/{pollingClearingHouseAccountSubscriber.ts → pollingDriftClientAccountSubscriber.ts} +65 -75
  132. package/src/accounts/{pollingOracleSubscriber.ts → pollingOracleAccountSubscriber.ts} +2 -2
  133. package/src/accounts/pollingUserAccountSubscriber.ts +5 -12
  134. package/src/accounts/pollingUserStatsAccountSubscriber.ts +166 -0
  135. package/src/accounts/types.ts +35 -15
  136. package/src/accounts/{webSocketClearingHouseAccountSubscriber.ts → webSocketDriftClientAccountSubscriber.ts} +78 -73
  137. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
  138. package/src/addresses/marketAddresses.ts +3 -4
  139. package/src/addresses/pda.ts +105 -33
  140. package/src/adminClient.ts +1207 -0
  141. package/src/config.ts +41 -34
  142. package/src/constants/numericConstants.ts +59 -26
  143. package/src/constants/{markets.ts → perpMarkets.ts} +22 -11
  144. package/src/constants/spotMarkets.ts +83 -0
  145. package/src/dlob/DLOB.ts +1120 -0
  146. package/src/dlob/DLOBNode.ts +155 -0
  147. package/src/dlob/NodeList.ts +195 -0
  148. package/src/driftClient.ts +3594 -0
  149. package/src/{clearingHouseConfig.ts → driftClientConfig.ts} +9 -8
  150. package/src/events/eventList.ts +3 -0
  151. package/src/events/eventSubscriber.ts +36 -14
  152. package/src/events/fetchLogs.ts +60 -15
  153. package/src/events/pollingLogProvider.ts +11 -3
  154. package/src/events/sort.ts +11 -15
  155. package/src/events/types.ts +27 -2
  156. package/src/events/webSocketLogProvider.ts +1 -1
  157. package/src/examples/makeTradeExample.js +152 -75
  158. package/src/examples/makeTradeExample.ts +44 -28
  159. package/src/factory/bigNum.ts +150 -22
  160. package/src/idl/drift.json +8392 -0
  161. package/src/idl/pyth.json +98 -2
  162. package/src/index.ts +29 -12
  163. package/src/math/amm.ts +161 -48
  164. package/src/math/conversion.ts +2 -2
  165. package/src/math/exchangeStatus.ts +31 -0
  166. package/src/math/funding.ts +41 -31
  167. package/src/math/insurance.ts +35 -0
  168. package/src/math/margin.ts +133 -0
  169. package/src/math/market.ts +143 -14
  170. package/src/math/oracles.ts +63 -9
  171. package/src/math/orders.ts +168 -26
  172. package/src/math/position.ts +133 -59
  173. package/src/math/repeg.ts +19 -9
  174. package/src/math/spotBalance.ts +319 -0
  175. package/src/math/spotMarket.ts +9 -0
  176. package/src/math/spotPosition.ts +47 -0
  177. package/src/math/trade.ts +33 -37
  178. package/src/oracles/pythClient.ts +2 -2
  179. package/src/oracles/quoteAssetOracleClient.ts +2 -2
  180. package/src/oracles/switchboardClient.ts +2 -2
  181. package/src/orderParams.ts +16 -8
  182. package/src/serum/serumFulfillmentConfigMap.ts +26 -0
  183. package/src/serum/serumSubscriber.ts +99 -0
  184. package/src/serum/types.ts +13 -0
  185. package/src/tokenFaucet.ts +38 -15
  186. package/src/tx/retryTxSender.ts +16 -5
  187. package/src/tx/types.ts +2 -1
  188. package/src/types.ts +594 -195
  189. package/src/user.ts +1599 -0
  190. package/src/{clearingHouseUserConfig.ts → userConfig.ts} +5 -5
  191. package/src/userMap/userMap.ts +124 -0
  192. package/src/userMap/userStatsMap.ts +108 -0
  193. package/src/userName.ts +2 -1
  194. package/src/userStats.ts +75 -0
  195. package/src/userStatsConfig.ts +18 -0
  196. package/src/util/getTokenAddress.ts +18 -0
  197. package/tests/bn/test.ts +46 -11
  198. package/tests/dlob/helpers.ts +619 -0
  199. package/tests/dlob/test.ts +4586 -0
  200. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +0 -49
  201. package/lib/admin.d.ts +0 -44
  202. package/lib/admin.js +0 -438
  203. package/lib/clearingHouse.d.ts +0 -146
  204. package/lib/clearingHouse.js +0 -1154
  205. package/lib/clearingHouseUser.d.ts +0 -187
  206. package/lib/clearingHouseUser.js +0 -634
  207. package/lib/clearingHouseUserConfig.d.ts +0 -14
  208. package/lib/constants/banks.d.ts +0 -16
  209. package/lib/constants/banks.js +0 -41
  210. package/lib/constants/markets.d.ts +0 -19
  211. package/lib/idl/clearing_house.json +0 -4464
  212. package/lib/math/bankBalance.d.ts +0 -9
  213. package/lib/math/bankBalance.js +0 -75
  214. package/lib/math/state.d.ts +0 -8
  215. package/lib/math/state.js +0 -15
  216. package/lib/orders.d.ts +0 -8
  217. package/lib/orders.js +0 -134
  218. package/src/accounts/bulkAccountLoader.js +0 -197
  219. package/src/accounts/bulkUserSubscription.js +0 -33
  220. package/src/accounts/pollingClearingHouseAccountSubscriber.js +0 -311
  221. package/src/accounts/pollingOracleSubscriber.js +0 -93
  222. package/src/accounts/pollingTokenAccountSubscriber.js +0 -90
  223. package/src/accounts/pollingUserAccountSubscriber.js +0 -132
  224. package/src/accounts/types.js +0 -10
  225. package/src/accounts/utils.js +0 -7
  226. package/src/accounts/webSocketAccountSubscriber.js +0 -93
  227. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +0 -233
  228. package/src/accounts/webSocketUserAccountSubscriber.js +0 -62
  229. package/src/addresses/marketAddresses.js +0 -26
  230. package/src/admin.js +0 -517
  231. package/src/admin.ts +0 -730
  232. package/src/clearingHouse.ts +0 -1828
  233. package/src/clearingHouseUser.ts +0 -978
  234. package/src/clearingHouseUserConfig.js +0 -2
  235. package/src/config.js +0 -67
  236. package/src/constants/banks.js +0 -42
  237. package/src/constants/banks.ts +0 -50
  238. package/src/constants/markets.js +0 -42
  239. package/src/constants/numericConstants.js +0 -41
  240. package/src/events/eventSubscriber.js +0 -139
  241. package/src/events/fetchLogs.js +0 -50
  242. package/src/events/pollingLogProvider.js +0 -64
  243. package/src/events/sort.js +0 -44
  244. package/src/events/txEventCache.js +0 -71
  245. package/src/events/types.js +0 -20
  246. package/src/events/webSocketLogProvider.js +0 -41
  247. package/src/factory/bigNum.js +0 -390
  248. package/src/factory/oracleClient.js +0 -20
  249. package/src/idl/clearing_house.json +0 -4464
  250. package/src/index.js +0 -69
  251. package/src/math/amm.js +0 -369
  252. package/src/math/auction.js +0 -42
  253. package/src/math/bankBalance.ts +0 -112
  254. package/src/math/conversion.js +0 -11
  255. package/src/math/funding.js +0 -248
  256. package/src/math/oracles.js +0 -26
  257. package/src/math/repeg.js +0 -128
  258. package/src/math/state.js +0 -15
  259. package/src/math/state.ts +0 -14
  260. package/src/math/trade.js +0 -253
  261. package/src/math/utils.js +0 -26
  262. package/src/math/utils.js.map +0 -1
  263. package/src/mockUSDCFaucet.js +0 -280
  264. package/src/oracles/oracleClientCache.js +0 -19
  265. package/src/oracles/pythClient.js +0 -46
  266. package/src/oracles/quoteAssetOracleClient.js +0 -32
  267. package/src/oracles/switchboardClient.js +0 -69
  268. package/src/orderParams.js +0 -20
  269. package/src/orders.ts +0 -245
  270. package/src/slot/SlotSubscriber.js +0 -39
  271. package/src/tokenFaucet.js +0 -189
  272. package/src/types.js +0 -125
  273. package/src/userName.js +0 -20
  274. package/src/wallet.js +0 -35
@@ -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,
7
- ClearingHouse,
8
- ClearingHouseUser,
6
+ calculateReservePrice,
7
+ DriftClient,
8
+ User,
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
@@ -60,20 +64,35 @@ const main = async () => {
60
64
  );
61
65
 
62
66
  // Set up the Drift Clearing House
63
- const clearingHousePublicKey = new PublicKey(
64
- sdkConfig.CLEARING_HOUSE_PROGRAM_ID
67
+ const driftPublicKey = new PublicKey(sdkConfig.DRIFT_PROGRAM_ID);
68
+ const bulkAccountLoader = new BulkAccountLoader(
69
+ connection,
70
+ 'confirmed',
71
+ 1000
65
72
  );
66
- const clearingHouse = new ClearingHouse({
73
+ const driftClient = new DriftClient({
67
74
  connection,
68
75
  wallet: provider.wallet,
69
- programID: clearingHousePublicKey,
76
+ programID: driftPublicKey,
77
+ perpMarketIndexes: PerpMarkets[cluster].map((market) => market.marketIndex),
78
+ spotMarketIndexes: SpotMarkets[cluster].map(
79
+ (spotMarket) => spotMarket.marketIndex
80
+ ),
81
+ accountSubscription: {
82
+ type: 'polling',
83
+ accountLoader: bulkAccountLoader,
84
+ },
70
85
  });
71
- await clearingHouse.subscribe();
86
+ await driftClient.subscribe();
72
87
 
73
88
  // Set up Clearing House user client
74
- const user = new ClearingHouseUser({
75
- clearingHouse,
76
- userAccountPublicKey: await clearingHouse.getUserAccountPublicKey(),
89
+ const user = new User({
90
+ driftClient: driftClient,
91
+ userAccountPublicKey: await driftClient.getUserAccountPublicKey(),
92
+ accountSubscription: {
93
+ type: 'polling',
94
+ accountLoader: bulkAccountLoader,
95
+ },
77
96
  });
78
97
 
79
98
  //// Check if clearing house account exists for the current wallet
@@ -82,37 +101,34 @@ const main = async () => {
82
101
  if (!userAccountExists) {
83
102
  //// Create a Clearing House account by Depositing some USDC ($10,000 in this case)
84
103
  const depositAmount = new BN(10000).mul(QUOTE_PRECISION);
85
- await clearingHouse.initializeUserAccountAndDepositCollateral(
104
+ await driftClient.initializeUserAccountAndDepositCollateral(
86
105
  depositAmount,
87
106
  await getTokenAddress(
88
107
  usdcTokenAddress.toString(),
89
108
  wallet.publicKey.toString()
90
109
  ),
91
- Banks['devnet'][0].bankIndex
110
+ SpotMarkets['devnet'][0].marketIndex
92
111
  );
93
112
  }
94
113
 
95
114
  await user.subscribe();
96
115
 
97
116
  // Get current price
98
- const solMarketInfo = sdkConfig.MARKETS.find(
117
+ const solMarketInfo = sdkConfig.PERP_MARKETS.find(
99
118
  (market) => market.baseAssetSymbol === 'SOL'
100
119
  );
101
120
 
102
- const currentMarketPrice = calculateMarkPrice(
103
- clearingHouse.getMarketAccount(solMarketInfo.marketIndex),
121
+ const currentMarketPrice = calculateReservePrice(
122
+ driftClient.getPerpMarketAccount(solMarketInfo.marketIndex),
104
123
  undefined
105
124
  );
106
125
 
107
- const formattedPrice = convertToNumber(
108
- currentMarketPrice,
109
- MARK_PRICE_PRECISION
110
- );
126
+ const formattedPrice = convertToNumber(currentMarketPrice, PRICE_PRECISION);
111
127
 
112
128
  console.log(`Current Market Price is $${formattedPrice}`);
113
129
 
114
130
  // Estimate the slippage for a $5000 LONG trade
115
- const solMarketAccount = clearingHouse.getMarketAccount(
131
+ const solMarketAccount = driftClient.getPerpMarketAccount(
116
132
  solMarketInfo.marketIndex
117
133
  );
118
134
 
@@ -125,7 +141,7 @@ const main = async () => {
125
141
  'quote',
126
142
  undefined
127
143
  )[0],
128
- MARK_PRICE_PRECISION
144
+ PRICE_PRECISION
129
145
  );
130
146
 
131
147
  console.log(
@@ -133,7 +149,7 @@ const main = async () => {
133
149
  );
134
150
 
135
151
  // Make a $5000 LONG trade
136
- await clearingHouse.openPosition(
152
+ await driftClient.openPosition(
137
153
  PositionDirection.LONG,
138
154
  longAmount,
139
155
  solMarketInfo.marketIndex
@@ -142,14 +158,14 @@ const main = async () => {
142
158
 
143
159
  // Reduce the position by $2000
144
160
  const reduceAmount = new BN(2000).mul(QUOTE_PRECISION);
145
- await clearingHouse.openPosition(
161
+ await driftClient.openPosition(
146
162
  PositionDirection.SHORT,
147
163
  reduceAmount,
148
164
  solMarketInfo.marketIndex
149
165
  );
150
166
 
151
167
  // Close the rest of the position
152
- await clearingHouse.closePosition(solMarketInfo.marketIndex);
168
+ await driftClient.closePosition(solMarketInfo.marketIndex);
153
169
  };
154
170
 
155
171
  main();
@@ -9,6 +9,11 @@ export class BigNum {
9
9
  static delim = '.';
10
10
  static spacer = ',';
11
11
 
12
+ public static setLocale(locale: string): void {
13
+ BigNum.delim = (1.1).toLocaleString(locale).slice(1, 2) || '.';
14
+ BigNum.spacer = (1000).toLocaleString(locale).slice(1, 2) || ',';
15
+ }
16
+
12
17
  constructor(
13
18
  val: BN | number | string,
14
19
  precisionVal: BN | number | string = new BN(0)
@@ -17,6 +22,10 @@ export class BigNum {
17
22
  this.precision = new BN(precisionVal);
18
23
  }
19
24
 
25
+ private bigNumFromParam(bn: BigNum | BN) {
26
+ return BN.isBN(bn) ? BigNum.from(bn) : bn;
27
+ }
28
+
20
29
  public add(bn: BigNum): BigNum {
21
30
  assert(bn.precision.eq(this.precision), 'Adding unequal precisions');
22
31
 
@@ -30,7 +39,7 @@ export class BigNum {
30
39
  }
31
40
 
32
41
  public mul(bn: BigNum | BN): BigNum {
33
- const mulVal = bn instanceof BigNum ? bn : BigNum.from(bn);
42
+ const mulVal = this.bigNumFromParam(bn);
34
43
 
35
44
  return BigNum.from(
36
45
  this.val.mul(mulVal.val),
@@ -44,7 +53,7 @@ export class BigNum {
44
53
  * @returns
45
54
  */
46
55
  public scalarMul(bn: BigNum | BN): BigNum {
47
- if (bn instanceof BN) return BigNum.from(this.val.mul(bn), this.precision);
56
+ if (BN.isBN(bn)) return BigNum.from(this.val.mul(bn), this.precision);
48
57
 
49
58
  return BigNum.from(
50
59
  this.val.mul(bn.val),
@@ -53,7 +62,8 @@ export class BigNum {
53
62
  }
54
63
 
55
64
  public div(bn: BigNum | BN): BigNum {
56
- if (bn instanceof BN) return BigNum.from(this.val.div(bn), this.precision);
65
+ if (BN.isBN(bn)) return BigNum.from(this.val.div(bn), this.precision);
66
+
57
67
  return BigNum.from(this.val.div(bn.val), this.precision.sub(bn.precision));
58
68
  }
59
69
 
@@ -101,7 +111,7 @@ export class BigNum {
101
111
  }
102
112
 
103
113
  public gt(bn: BigNum | BN, ignorePrecision?: boolean): boolean {
104
- const comparisonVal = bn instanceof BigNum ? bn : BigNum.from(bn);
114
+ const comparisonVal = this.bigNumFromParam(bn);
105
115
 
106
116
  if (!ignorePrecision && !comparisonVal.eq(ZERO)) {
107
117
  assert(
@@ -114,7 +124,7 @@ export class BigNum {
114
124
  }
115
125
 
116
126
  public lt(bn: BigNum | BN, ignorePrecision?: boolean): boolean {
117
- const comparisonVal = bn instanceof BigNum ? bn : BigNum.from(bn);
127
+ const comparisonVal = this.bigNumFromParam(bn);
118
128
 
119
129
  if (!ignorePrecision && !comparisonVal.val.eq(ZERO)) {
120
130
  assert(
@@ -127,7 +137,7 @@ export class BigNum {
127
137
  }
128
138
 
129
139
  public gte(bn: BigNum | BN, ignorePrecision?: boolean): boolean {
130
- const comparisonVal = bn instanceof BigNum ? bn : BigNum.from(bn);
140
+ const comparisonVal = this.bigNumFromParam(bn);
131
141
 
132
142
  if (!ignorePrecision && !comparisonVal.val.eq(ZERO)) {
133
143
  assert(
@@ -140,7 +150,7 @@ export class BigNum {
140
150
  }
141
151
 
142
152
  public lte(bn: BigNum | BN, ignorePrecision?: boolean): boolean {
143
- const comparisonVal = bn instanceof BigNum ? bn : BigNum.from(bn);
153
+ const comparisonVal = this.bigNumFromParam(bn);
144
154
 
145
155
  if (!ignorePrecision && !comparisonVal.val.eq(ZERO)) {
146
156
  assert(
@@ -153,7 +163,7 @@ export class BigNum {
153
163
  }
154
164
 
155
165
  public eq(bn: BigNum | BN, ignorePrecision?: boolean): boolean {
156
- const comparisonVal = bn instanceof BigNum ? bn : BigNum.from(bn);
166
+ const comparisonVal = this.bigNumFromParam(bn);
157
167
 
158
168
  if (!ignorePrecision && !comparisonVal.val.eq(ZERO)) {
159
169
  assert(
@@ -206,7 +216,8 @@ export class BigNum {
206
216
  'Tried to print a BN with precision lower than zero'
207
217
  );
208
218
 
209
- const plainString = this.toString();
219
+ const isNeg = this.isNeg();
220
+ const plainString = this.abs().toString();
210
221
  const precisionNum = this.precision.toNumber();
211
222
 
212
223
  // make a string with at least the precisionNum number of zeroes
@@ -227,6 +238,9 @@ export class BigNum {
227
238
  // add zero if leading delim
228
239
  if (printString[0] === BigNum.delim) printString = `0${printString}`;
229
240
 
241
+ // Add minus if negative
242
+ if (isNeg) printString = `-${printString}`;
243
+
230
244
  // remove trailing delim
231
245
  if (printString[printString.length - 1] === BigNum.delim)
232
246
  printString = printString.slice(0, printString.length - 1);
@@ -281,6 +295,8 @@ export class BigNum {
281
295
  ? this.toTradePrecision()
282
296
  : this.print();
283
297
 
298
+ if (!printVal.includes(BigNum.delim)) return printVal;
299
+
284
300
  return printVal.replace(/0+$/g, '').replace(/\.$/, '').replace(/,$/, '');
285
301
  }
286
302
 
@@ -295,7 +311,11 @@ export class BigNum {
295
311
  * @param fixedPrecision
296
312
  * @returns
297
313
  */
298
- public toFixed(fixedPrecision: number): string {
314
+ public toFixed(fixedPrecision: number, rounded = false): string {
315
+ if (rounded) {
316
+ return this.toRounded(fixedPrecision).toFixed(fixedPrecision);
317
+ }
318
+
299
319
  const printString = this.print();
300
320
 
301
321
  const [leftSide, rightSide] = printString.split(BigNum.delim);
@@ -310,16 +330,78 @@ export class BigNum {
310
330
  return `${leftSide}${BigNum.delim}${filledRightSide}`;
311
331
  }
312
332
 
333
+ private getZeroes(count: number) {
334
+ return new Array(Math.max(count, 0)).fill('0').join('');
335
+ }
336
+
337
+ public toRounded(roundingPrecision: number) {
338
+ const printString = this.toString();
339
+
340
+ let shouldRoundUp = false;
341
+
342
+ const roundingDigitChar = printString[roundingPrecision];
343
+
344
+ if (roundingDigitChar) {
345
+ const roundingDigitVal = Number(roundingDigitChar);
346
+ if (roundingDigitVal >= 5) shouldRoundUp = true;
347
+ }
348
+
349
+ if (shouldRoundUp) {
350
+ const valueWithRoundedPrecisionAdded = this.add(
351
+ BigNum.from(
352
+ new BN(10).pow(new BN(printString.length - roundingPrecision)),
353
+ this.precision
354
+ )
355
+ );
356
+
357
+ const roundedUpPrintString =
358
+ valueWithRoundedPrecisionAdded.toString().slice(0, roundingPrecision) +
359
+ this.getZeroes(printString.length - roundingPrecision);
360
+
361
+ return BigNum.from(roundedUpPrintString, this.precision);
362
+ } else {
363
+ const roundedDownPrintString =
364
+ printString.slice(0, roundingPrecision) +
365
+ this.getZeroes(printString.length - roundingPrecision);
366
+
367
+ return BigNum.from(roundedDownPrintString, this.precision);
368
+ }
369
+ }
370
+
313
371
  /**
314
372
  * Pretty print to the specified number of significant figures
315
373
  * @param fixedPrecision
316
374
  * @returns
317
375
  */
318
- public toPrecision(fixedPrecision: number, trailingZeroes = false): string {
376
+ public toPrecision(
377
+ fixedPrecision: number,
378
+ trailingZeroes = false,
379
+ rounded = false
380
+ ): string {
381
+ if (rounded) {
382
+ return this.toRounded(fixedPrecision).toPrecision(
383
+ fixedPrecision,
384
+ trailingZeroes
385
+ );
386
+ }
387
+
319
388
  const printString = this.print();
320
389
 
321
390
  let precisionPrintString = printString.slice(0, fixedPrecision + 1);
322
391
 
392
+ const thisString = this.toString();
393
+
394
+ if (
395
+ !printString.includes(BigNum.delim) &&
396
+ thisString.length < fixedPrecision
397
+ ) {
398
+ const precisionMismatch = fixedPrecision - thisString.length;
399
+ return BigNum.from(
400
+ thisString + this.getZeroes(precisionMismatch),
401
+ precisionMismatch
402
+ ).toPrecision(fixedPrecision, trailingZeroes);
403
+ }
404
+
323
405
  if (
324
406
  !precisionPrintString.includes(BigNum.delim) ||
325
407
  precisionPrintString[precisionPrintString.length - 1] === BigNum.delim
@@ -376,8 +458,8 @@ export class BigNum {
376
458
  return precisionPrintString;
377
459
  }
378
460
 
379
- public toTradePrecision(): string {
380
- return this.toPrecision(6, true);
461
+ public toTradePrecision(rounded = false): string {
462
+ return this.toPrecision(6, true, rounded);
381
463
  }
382
464
 
383
465
  /**
@@ -392,15 +474,39 @@ export class BigNum {
392
474
  ): string {
393
475
  const prefix = `${this.lt(BigNum.zero()) ? `-` : ``}$`;
394
476
 
395
- const val =
396
- useTradePrecision || precisionOverride
397
- ? this.prettyPrint(useTradePrecision, precisionOverride)
398
- : BigNum.fromPrint(this.toFixed(2), new BN(2)).prettyPrint();
477
+ const usingCustomPrecision =
478
+ true && (useTradePrecision || precisionOverride);
479
+
480
+ let val = usingCustomPrecision
481
+ ? this.prettyPrint(useTradePrecision, precisionOverride)
482
+ : BigNum.fromPrint(this.toFixed(2), new BN(2)).prettyPrint();
483
+
484
+ // Append two trailing zeroes if not using custom precision
485
+ if (!usingCustomPrecision) {
486
+ const [_, rightSide] = val.split(BigNum.delim);
487
+
488
+ const trailingLength = rightSide?.length ?? 0;
489
+
490
+ if (trailingLength < 2) {
491
+ const numHasDecimals = this.print().includes(BigNum.delim);
492
+
493
+ // Handle case where pretty print won't include the decimal point
494
+ if (trailingLength === 0 && numHasDecimals) {
495
+ val = `${val}.00`;
496
+ } else {
497
+ val = `${val}${new Array(2 - trailingLength).fill('0').join('')}`;
498
+ }
499
+ }
500
+ }
399
501
 
400
502
  return `${prefix}${val.replace('-', '')}`;
401
503
  }
402
504
 
403
- public toMillified(precision = 3): string {
505
+ public toMillified(precision = 3, rounded = false): string {
506
+ if (rounded) {
507
+ return this.toRounded(precision).toMillified(precision);
508
+ }
509
+
404
510
  const stringVal = this.print();
405
511
 
406
512
  const [leftSide] = stringVal.split(BigNum.delim);
@@ -409,6 +515,10 @@ export class BigNum {
409
515
  return this.shift(new BN(precision)).toPrecision(precision, true);
410
516
  }
411
517
 
518
+ if (leftSide.length <= precision) {
519
+ return this.toPrecision(precision);
520
+ }
521
+
412
522
  if (leftSide.length <= 3) {
413
523
  return this.shift(new BN(precision)).toPrecision(precision, true);
414
524
  }
@@ -461,7 +571,21 @@ export class BigNum {
461
571
  * @returns
462
572
  */
463
573
  public toNum() {
464
- return parseFloat(this.print());
574
+ let printedValue = this.print();
575
+
576
+ // Must convert any non-US delimiters and spacers to US format before using parseFloat
577
+ if (BigNum.delim !== '.' || BigNum.spacer !== ',') {
578
+ printedValue = printedValue
579
+ .split('')
580
+ .map((char) => {
581
+ if (char === BigNum.delim) return '.';
582
+ if (char === BigNum.spacer) return ',';
583
+ return char;
584
+ })
585
+ .join('');
586
+ }
587
+
588
+ return parseFloat(printedValue);
465
589
  }
466
590
 
467
591
  static fromJSON(json: { val: string; precision: string }) {
@@ -494,12 +618,16 @@ export class BigNum {
494
618
  static fromPrint(val: string, precisionShift?: BN): BigNum {
495
619
  // Handle empty number edge cases
496
620
  if (!val) return BigNum.from(ZERO, precisionShift);
497
- if (!val.replace(BigNum.delim, ''))
621
+ if (!val.replace(BigNum.delim, '')) {
498
622
  return BigNum.from(ZERO, precisionShift);
623
+ }
499
624
 
500
- const [leftSide, rightSide] = val.split(BigNum.delim);
625
+ const sides = val.split(BigNum.delim);
626
+ const rightSide = sides[1];
627
+ const leftSide = sides[0].replace(/\D/g, '');
628
+ const bnInput = `${leftSide ?? ''}${rightSide ?? ''}`;
501
629
 
502
- const rawBn = new BN(`${leftSide ?? ''}${rightSide ?? ''}`);
630
+ const rawBn = new BN(bnInput);
503
631
 
504
632
  const rightSideLength = rightSide?.length ?? 0;
505
633