@drift-labs/sdk 0.2.0-master.2 → 0.2.0-master.22

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 (149) hide show
  1. package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
  2. package/lib/accounts/bulkUserStatsSubscription.js +21 -0
  3. package/lib/accounts/bulkUserSubscription.js +0 -1
  4. package/lib/accounts/fetch.d.ts +2 -1
  5. package/lib/accounts/fetch.js +9 -1
  6. package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
  7. package/lib/accounts/pollingUserStatsAccountSubscriber.js +113 -0
  8. package/lib/accounts/types.d.ts +14 -1
  9. package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
  10. package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
  11. package/lib/addresses/pda.d.ts +1 -0
  12. package/lib/addresses/pda.js +8 -1
  13. package/lib/admin.d.ts +9 -5
  14. package/lib/admin.js +52 -11
  15. package/lib/clearingHouse.d.ts +52 -23
  16. package/lib/clearingHouse.js +736 -200
  17. package/lib/clearingHouseConfig.d.ts +1 -0
  18. package/lib/clearingHouseUser.d.ts +24 -16
  19. package/lib/clearingHouseUser.js +223 -101
  20. package/lib/clearingHouseUserStats.d.ts +18 -0
  21. package/lib/clearingHouseUserStats.js +49 -0
  22. package/lib/clearingHouseUserStatsConfig.d.ts +14 -0
  23. package/lib/clearingHouseUserStatsConfig.js +2 -0
  24. package/lib/config.js +1 -1
  25. package/lib/constants/banks.d.ts +2 -2
  26. package/lib/constants/banks.js +12 -4
  27. package/lib/constants/numericConstants.d.ts +5 -0
  28. package/lib/constants/numericConstants.js +8 -3
  29. package/lib/events/eventList.js +3 -0
  30. package/lib/events/types.d.ts +3 -1
  31. package/lib/events/types.js +2 -0
  32. package/lib/factory/bigNum.d.ts +1 -0
  33. package/lib/factory/bigNum.js +34 -10
  34. package/lib/idl/clearing_house.json +1603 -377
  35. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  36. package/lib/index.d.ts +9 -3
  37. package/lib/index.js +13 -3
  38. package/lib/math/amm.d.ts +1 -0
  39. package/lib/math/amm.js +22 -38
  40. package/lib/math/auction.js +4 -1
  41. package/lib/math/bankBalance.d.ts +7 -1
  42. package/lib/math/bankBalance.js +77 -2
  43. package/lib/math/margin.d.ts +11 -0
  44. package/lib/math/margin.js +72 -0
  45. package/lib/math/market.d.ts +4 -1
  46. package/lib/math/market.js +35 -1
  47. package/lib/math/oracles.d.ts +3 -0
  48. package/lib/math/oracles.js +25 -5
  49. package/lib/math/orders.d.ts +6 -2
  50. package/lib/math/orders.js +62 -12
  51. package/lib/math/position.d.ts +8 -0
  52. package/lib/math/position.js +45 -12
  53. package/lib/math/trade.d.ts +1 -1
  54. package/lib/math/trade.js +7 -10
  55. package/lib/orderParams.d.ts +14 -5
  56. package/lib/orderParams.js +8 -96
  57. package/lib/slot/SlotSubscriber.d.ts +7 -0
  58. package/lib/slot/SlotSubscriber.js +3 -0
  59. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  60. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  61. package/lib/tx/retryTxSender.js +9 -2
  62. package/lib/tx/utils.js +1 -1
  63. package/lib/types.d.ts +236 -26
  64. package/lib/types.js +64 -1
  65. package/lib/util/computeUnits.js +1 -1
  66. package/lib/util/getTokenAddress.d.ts +2 -0
  67. package/lib/util/getTokenAddress.js +9 -0
  68. package/package.json +3 -3
  69. package/src/accounts/bulkUserStatsSubscription.ts +33 -0
  70. package/src/accounts/bulkUserSubscription.ts +0 -1
  71. package/src/accounts/fetch.ts +27 -2
  72. package/src/accounts/pollingUserStatsAccountSubscriber.ts +172 -0
  73. package/src/accounts/types.ts +18 -0
  74. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
  75. package/src/addresses/marketAddresses.js +26 -0
  76. package/src/addresses/pda.ts +13 -0
  77. package/src/admin.ts +82 -15
  78. package/src/assert/assert.js +9 -0
  79. package/src/clearingHouse.ts +1232 -323
  80. package/src/clearingHouseConfig.ts +1 -0
  81. package/src/clearingHouseUser.ts +343 -155
  82. package/src/clearingHouseUserStats.ts +75 -0
  83. package/src/clearingHouseUserStatsConfig.ts +18 -0
  84. package/src/config.ts +1 -1
  85. package/src/constants/banks.js +42 -0
  86. package/src/constants/banks.ts +14 -4
  87. package/src/constants/markets.js +42 -0
  88. package/src/constants/numericConstants.js +41 -0
  89. package/src/constants/numericConstants.ts +14 -2
  90. package/src/events/eventList.js +77 -0
  91. package/src/events/eventList.ts +3 -0
  92. package/src/events/eventSubscriber.js +139 -0
  93. package/src/events/sort.js +44 -0
  94. package/src/events/txEventCache.js +71 -0
  95. package/src/events/types.ts +6 -0
  96. package/src/examples/makeTradeExample.js +80 -0
  97. package/src/factory/bigNum.js +390 -0
  98. package/src/factory/bigNum.ts +42 -13
  99. package/src/factory/oracleClient.js +20 -0
  100. package/src/idl/clearing_house.json +1603 -377
  101. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  102. package/src/index.ts +9 -3
  103. package/src/math/amm.ts +54 -55
  104. package/src/math/auction.js +42 -0
  105. package/src/math/auction.ts +5 -1
  106. package/src/math/bankBalance.ts +148 -2
  107. package/src/math/conversion.js +11 -0
  108. package/src/math/funding.js +248 -0
  109. package/src/math/margin.ts +124 -0
  110. package/src/math/market.ts +66 -1
  111. package/src/math/oracles.js +26 -0
  112. package/src/math/oracles.ts +42 -5
  113. package/src/math/orders.ts +129 -13
  114. package/src/math/position.ts +64 -9
  115. package/src/math/repeg.js +128 -0
  116. package/src/math/state.js +15 -0
  117. package/src/math/trade.js +253 -0
  118. package/src/math/trade.ts +23 -25
  119. package/src/math/utils.js +0 -1
  120. package/src/oracles/oracleClientCache.js +19 -0
  121. package/src/oracles/pythClient.js +46 -0
  122. package/src/oracles/quoteAssetOracleClient.js +32 -0
  123. package/src/oracles/switchboardClient.js +69 -0
  124. package/src/oracles/types.js +2 -0
  125. package/src/orderParams.js +20 -0
  126. package/src/orderParams.ts +20 -141
  127. package/src/slot/SlotSubscriber.js +39 -0
  128. package/src/slot/SlotSubscriber.ts +11 -1
  129. package/src/token/index.js +38 -0
  130. package/src/tokenFaucet.js +189 -0
  131. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  132. package/src/tx/retryTxSender.ts +11 -3
  133. package/src/tx/types.js +2 -0
  134. package/src/tx/utils.js +17 -0
  135. package/src/tx/utils.ts +1 -1
  136. package/src/types.ts +239 -27
  137. package/src/userName.js +20 -0
  138. package/src/util/computeUnits.js +21 -11
  139. package/src/util/computeUnits.ts +1 -1
  140. package/src/util/getTokenAddress.js +9 -0
  141. package/src/util/getTokenAddress.ts +18 -0
  142. package/src/util/promiseTimeout.js +14 -0
  143. package/src/util/tps.js +27 -0
  144. package/src/wallet.js +35 -0
  145. package/tests/bn/test.ts +10 -0
  146. package/lib/orders.d.ts +0 -8
  147. package/lib/orders.js +0 -142
  148. package/src/orders.ts +0 -251
  149. package/src/util/computeUnits.js.map +0 -1
@@ -0,0 +1,80 @@
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.getTokenAddress = void 0;
13
+ const anchor_1 = require("@project-serum/anchor");
14
+ const __1 = require("..");
15
+ const spl_token_1 = require("@solana/spl-token");
16
+ const web3_js_1 = require("@solana/web3.js");
17
+ const __2 = require("..");
18
+ const banks_1 = require("../constants/banks");
19
+ const getTokenAddress = (mintAddress, userPubKey) => {
20
+ return spl_token_1.Token.getAssociatedTokenAddress(new web3_js_1.PublicKey(`ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL`), spl_token_1.TOKEN_PROGRAM_ID, new web3_js_1.PublicKey(mintAddress), new web3_js_1.PublicKey(userPubKey));
21
+ };
22
+ exports.getTokenAddress = getTokenAddress;
23
+ const main = () => __awaiter(void 0, void 0, void 0, function* () {
24
+ // Initialize Drift SDK
25
+ const sdkConfig = __2.initialize({ env: 'devnet' });
26
+ // Set up the Wallet and Provider
27
+ const privateKey = process.env.BOT_PRIVATE_KEY; // stored as an array string
28
+ const keypair = web3_js_1.Keypair.fromSecretKey(Uint8Array.from(JSON.parse(privateKey)));
29
+ const wallet = new __1.Wallet(keypair);
30
+ // Set up the Connection
31
+ const rpcAddress = process.env.RPC_ADDRESS; // can use: https://api.devnet.solana.com for devnet; https://api.mainnet-beta.solana.com for mainnet;
32
+ const connection = new web3_js_1.Connection(rpcAddress);
33
+ // Set up the Provider
34
+ const provider = new anchor_1.AnchorProvider(connection, wallet, anchor_1.AnchorProvider.defaultOptions());
35
+ // Check SOL Balance
36
+ const lamportsBalance = yield connection.getBalance(wallet.publicKey);
37
+ console.log('SOL balance:', lamportsBalance / Math.pow(10, 9));
38
+ // Misc. other things to set up
39
+ const usdcTokenAddress = yield exports.getTokenAddress(sdkConfig.USDC_MINT_ADDRESS, wallet.publicKey.toString());
40
+ // Set up the Drift Clearing House
41
+ const clearingHousePublicKey = new web3_js_1.PublicKey(sdkConfig.CLEARING_HOUSE_PROGRAM_ID);
42
+ const clearingHouse = new __2.ClearingHouse({
43
+ connection,
44
+ wallet: provider.wallet,
45
+ programID: clearingHousePublicKey,
46
+ });
47
+ yield clearingHouse.subscribe();
48
+ // Set up Clearing House user client
49
+ const user = new __2.ClearingHouseUser({
50
+ clearingHouse,
51
+ userAccountPublicKey: yield clearingHouse.getUserAccountPublicKey(),
52
+ });
53
+ //// Check if clearing house account exists for the current wallet
54
+ const userAccountExists = yield user.exists();
55
+ if (!userAccountExists) {
56
+ //// Create a Clearing House account by Depositing some USDC ($10,000 in this case)
57
+ const depositAmount = new anchor_1.BN(10000).mul(__2.QUOTE_PRECISION);
58
+ yield clearingHouse.initializeUserAccountAndDepositCollateral(depositAmount, yield exports.getTokenAddress(usdcTokenAddress.toString(), wallet.publicKey.toString()), banks_1.Banks['devnet'][0].bankIndex);
59
+ }
60
+ yield user.subscribe();
61
+ // Get current price
62
+ const solMarketInfo = sdkConfig.MARKETS.find((market) => market.baseAssetSymbol === 'SOL');
63
+ const currentMarketPrice = __2.calculateMarkPrice(clearingHouse.getMarketAccount(solMarketInfo.marketIndex), undefined);
64
+ const formattedPrice = __2.convertToNumber(currentMarketPrice, __2.MARK_PRICE_PRECISION);
65
+ console.log(`Current Market Price is $${formattedPrice}`);
66
+ // Estimate the slippage for a $5000 LONG trade
67
+ const solMarketAccount = clearingHouse.getMarketAccount(solMarketInfo.marketIndex);
68
+ const longAmount = new anchor_1.BN(5000).mul(__2.QUOTE_PRECISION);
69
+ const slippage = __2.convertToNumber(__2.calculateTradeSlippage(__2.PositionDirection.LONG, longAmount, solMarketAccount, 'quote', undefined)[0], __2.MARK_PRICE_PRECISION);
70
+ console.log(`Slippage for a $5000 LONG on the SOL market would be $${slippage}`);
71
+ // Make a $5000 LONG trade
72
+ yield clearingHouse.openPosition(__2.PositionDirection.LONG, longAmount, solMarketInfo.marketIndex);
73
+ console.log(`LONGED $5000 SOL`);
74
+ // Reduce the position by $2000
75
+ const reduceAmount = new anchor_1.BN(2000).mul(__2.QUOTE_PRECISION);
76
+ yield clearingHouse.openPosition(__2.PositionDirection.SHORT, reduceAmount, solMarketInfo.marketIndex);
77
+ // Close the rest of the position
78
+ yield clearingHouse.closePosition(solMarketInfo.marketIndex);
79
+ });
80
+ main();
@@ -0,0 +1,390 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BigNum = void 0;
4
+ const anchor_1 = require("@project-serum/anchor");
5
+ const assert_1 = require("../assert/assert");
6
+ const numericConstants_1 = require("./../constants/numericConstants");
7
+ class BigNum {
8
+ constructor(val, precisionVal = new anchor_1.BN(0)) {
9
+ this.toString = (base, length) => this.val.toString(base, length);
10
+ this.val = new anchor_1.BN(val);
11
+ this.precision = new anchor_1.BN(precisionVal);
12
+ }
13
+ bigNumFromParam(bn) {
14
+ return anchor_1.BN.isBN(bn) ? BigNum.from(bn) : bn;
15
+ }
16
+ add(bn) {
17
+ assert_1.assert(bn.precision.eq(this.precision), 'Adding unequal precisions');
18
+ return BigNum.from(this.val.add(bn.val), this.precision);
19
+ }
20
+ sub(bn) {
21
+ assert_1.assert(bn.precision.eq(this.precision), 'Subtracting unequal precisions');
22
+ return BigNum.from(this.val.sub(bn.val), this.precision);
23
+ }
24
+ mul(bn) {
25
+ const mulVal = this.bigNumFromParam(bn);
26
+ return BigNum.from(this.val.mul(mulVal.val), this.precision.add(mulVal.precision));
27
+ }
28
+ /**
29
+ * Multiplies by another big number then scales the result down by the big number's precision so that we're in the same precision space
30
+ * @param bn
31
+ * @returns
32
+ */
33
+ scalarMul(bn) {
34
+ if (anchor_1.BN.isBN(bn))
35
+ return BigNum.from(this.val.mul(bn), this.precision);
36
+ return BigNum.from(this.val.mul(bn.val), this.precision.add(bn.precision)).shift(bn.precision.neg());
37
+ }
38
+ div(bn) {
39
+ if (anchor_1.BN.isBN(bn))
40
+ return BigNum.from(this.val.div(bn), this.precision);
41
+ return BigNum.from(this.val.div(bn.val), this.precision.sub(bn.precision));
42
+ }
43
+ /**
44
+ * Shift precision up or down
45
+ * @param exponent
46
+ * @param skipAdjustingPrecision
47
+ * @returns
48
+ */
49
+ shift(exponent, skipAdjustingPrecision = false) {
50
+ const shiftVal = typeof exponent === 'number' ? new anchor_1.BN(exponent) : exponent;
51
+ return BigNum.from(shiftVal.isNeg()
52
+ ? this.val.div(new anchor_1.BN(10).pow(shiftVal))
53
+ : this.val.mul(new anchor_1.BN(10).pow(shiftVal)), skipAdjustingPrecision ? this.precision : this.precision.add(shiftVal));
54
+ }
55
+ /**
56
+ * Shift to a target precision
57
+ * @param targetPrecision
58
+ * @returns
59
+ */
60
+ shiftTo(targetPrecision) {
61
+ return this.shift(targetPrecision.sub(this.precision));
62
+ }
63
+ /**
64
+ * Scale the number by a fraction
65
+ * @param numerator
66
+ * @param denominator
67
+ * @returns
68
+ */
69
+ scale(numerator, denominator) {
70
+ return this.mul(BigNum.from(new anchor_1.BN(numerator))).div(new anchor_1.BN(denominator));
71
+ }
72
+ toPercentage(denominator, precision) {
73
+ return this.shift(precision)
74
+ .shift(2, true)
75
+ .div(denominator)
76
+ .toPrecision(precision);
77
+ }
78
+ gt(bn, ignorePrecision) {
79
+ const comparisonVal = this.bigNumFromParam(bn);
80
+ if (!ignorePrecision && !comparisonVal.eq(numericConstants_1.ZERO)) {
81
+ assert_1.assert(comparisonVal.precision.eq(this.precision), 'Trying to compare numbers with different precision. Yo can opt to ignore precision using the ignorePrecision parameter');
82
+ }
83
+ return this.val.gt(comparisonVal.val);
84
+ }
85
+ lt(bn, ignorePrecision) {
86
+ const comparisonVal = this.bigNumFromParam(bn);
87
+ if (!ignorePrecision && !comparisonVal.val.eq(numericConstants_1.ZERO)) {
88
+ assert_1.assert(comparisonVal.precision.eq(this.precision), 'Trying to compare numbers with different precision. Yo can opt to ignore precision using the ignorePrecision parameter');
89
+ }
90
+ return this.val.lt(comparisonVal.val);
91
+ }
92
+ gte(bn, ignorePrecision) {
93
+ const comparisonVal = this.bigNumFromParam(bn);
94
+ if (!ignorePrecision && !comparisonVal.val.eq(numericConstants_1.ZERO)) {
95
+ assert_1.assert(comparisonVal.precision.eq(this.precision), 'Trying to compare numbers with different precision. Yo can opt to ignore precision using the ignorePrecision parameter');
96
+ }
97
+ return this.val.gte(comparisonVal.val);
98
+ }
99
+ lte(bn, ignorePrecision) {
100
+ const comparisonVal = this.bigNumFromParam(bn);
101
+ if (!ignorePrecision && !comparisonVal.val.eq(numericConstants_1.ZERO)) {
102
+ assert_1.assert(comparisonVal.precision.eq(this.precision), 'Trying to compare numbers with different precision. Yo can opt to ignore precision using the ignorePrecision parameter');
103
+ }
104
+ return this.val.lte(comparisonVal.val);
105
+ }
106
+ eq(bn, ignorePrecision) {
107
+ const comparisonVal = this.bigNumFromParam(bn);
108
+ if (!ignorePrecision && !comparisonVal.val.eq(numericConstants_1.ZERO)) {
109
+ assert_1.assert(comparisonVal.precision.eq(this.precision), 'Trying to compare numbers with different precision. Yo can opt to ignore precision using the ignorePrecision parameter');
110
+ }
111
+ return this.val.eq(comparisonVal.val);
112
+ }
113
+ eqZero() {
114
+ return this.val.eq(numericConstants_1.ZERO);
115
+ }
116
+ gtZero() {
117
+ return this.val.gt(numericConstants_1.ZERO);
118
+ }
119
+ ltZero() {
120
+ return this.val.lt(numericConstants_1.ZERO);
121
+ }
122
+ gteZero() {
123
+ return this.val.gte(numericConstants_1.ZERO);
124
+ }
125
+ lteZero() {
126
+ return this.val.lte(numericConstants_1.ZERO);
127
+ }
128
+ abs() {
129
+ return new BigNum(this.val.abs(), this.precision);
130
+ }
131
+ neg() {
132
+ return new BigNum(this.val.neg(), this.precision);
133
+ }
134
+ /**
135
+ * Pretty print the underlying value in human-readable form. Depends on precision being correct for the output string to be correct
136
+ * @returns
137
+ */
138
+ print() {
139
+ assert_1.assert(this.precision.gte(numericConstants_1.ZERO), 'Tried to print a BN with precision lower than zero');
140
+ const plainString = this.toString();
141
+ const precisionNum = this.precision.toNumber();
142
+ // make a string with at least the precisionNum number of zeroes
143
+ let printString = [
144
+ ...Array(this.precision.toNumber()).fill(0),
145
+ ...plainString.split(''),
146
+ ].join('');
147
+ // inject decimal
148
+ printString =
149
+ printString.substring(0, printString.length - precisionNum) +
150
+ BigNum.delim +
151
+ printString.substring(printString.length - precisionNum);
152
+ // remove leading zeroes
153
+ printString = printString.replace(/^0+/, '');
154
+ // add zero if leading delim
155
+ if (this.isNeg()) {
156
+ if (printString[1] === BigNum.delim)
157
+ printString = printString.replace('-.', '-0.');
158
+ }
159
+ else {
160
+ if (printString[0] === BigNum.delim)
161
+ printString = `0${printString}`;
162
+ }
163
+ // remove trailing delim
164
+ if (printString[printString.length - 1] === BigNum.delim)
165
+ printString = printString.slice(0, printString.length - 1);
166
+ return printString;
167
+ }
168
+ prettyPrint(useTradePrecision, precisionOverride) {
169
+ const [leftSide, rightSide] = this.printShort(useTradePrecision, precisionOverride).split(BigNum.delim);
170
+ let formattedLeftSide = leftSide;
171
+ const isNeg = formattedLeftSide.includes('-');
172
+ if (isNeg) {
173
+ formattedLeftSide = formattedLeftSide.replace('-', '');
174
+ }
175
+ let index = formattedLeftSide.length - 3;
176
+ while (index >= 1) {
177
+ const formattedLeftSideArray = formattedLeftSide.split('');
178
+ formattedLeftSideArray.splice(index, 0, BigNum.spacer);
179
+ formattedLeftSide = formattedLeftSideArray.join('');
180
+ index -= 3;
181
+ }
182
+ return `${isNeg ? '-' : ''}${formattedLeftSide}${rightSide ? `${BigNum.delim}${rightSide}` : ''}`;
183
+ }
184
+ /**
185
+ * Print and remove unnecessary trailing zeroes
186
+ * @returns
187
+ */
188
+ printShort(useTradePrecision, precisionOverride) {
189
+ const printVal = precisionOverride
190
+ ? this.toPrecision(precisionOverride)
191
+ : useTradePrecision
192
+ ? this.toTradePrecision()
193
+ : this.print();
194
+ return printVal.replace(/0+$/g, '').replace(/\.$/, '').replace(/,$/, '');
195
+ }
196
+ debug() {
197
+ console.log(`${this.toString()} | ${this.print()} | ${this.precision.toString()}`);
198
+ }
199
+ /**
200
+ * Pretty print with the specified number of decimal places
201
+ * @param fixedPrecision
202
+ * @returns
203
+ */
204
+ toFixed(fixedPrecision) {
205
+ const printString = this.print();
206
+ const [leftSide, rightSide] = printString.split(BigNum.delim);
207
+ const filledRightSide = [
208
+ ...(rightSide !== null && rightSide !== void 0 ? rightSide : '').slice(0, fixedPrecision),
209
+ ...Array(fixedPrecision).fill('0'),
210
+ ]
211
+ .slice(0, fixedPrecision)
212
+ .join('');
213
+ return `${leftSide}${BigNum.delim}${filledRightSide}`;
214
+ }
215
+ /**
216
+ * Pretty print to the specified number of significant figures
217
+ * @param fixedPrecision
218
+ * @returns
219
+ */
220
+ toPrecision(fixedPrecision, trailingZeroes = false) {
221
+ const printString = this.print();
222
+ let precisionPrintString = printString.slice(0, fixedPrecision + 1);
223
+ if (!precisionPrintString.includes(BigNum.delim) ||
224
+ precisionPrintString[precisionPrintString.length - 1] === BigNum.delim) {
225
+ precisionPrintString = printString.slice(0, fixedPrecision);
226
+ }
227
+ const pointsOfPrecision = precisionPrintString.replace(BigNum.delim, '').length;
228
+ if (pointsOfPrecision < fixedPrecision) {
229
+ precisionPrintString = [
230
+ ...precisionPrintString.split(''),
231
+ ...Array(fixedPrecision - pointsOfPrecision).fill('0'),
232
+ ].join('');
233
+ }
234
+ if (!precisionPrintString.includes(BigNum.delim)) {
235
+ const delimFullStringLocation = printString.indexOf(BigNum.delim);
236
+ let skipExponent = false;
237
+ if (delimFullStringLocation === -1) {
238
+ // no decimal, not missing any precision
239
+ skipExponent = true;
240
+ }
241
+ if (precisionPrintString[precisionPrintString.length - 1] === BigNum.delim) {
242
+ // decimal is at end of string, not missing any precision, do nothing
243
+ skipExponent = true;
244
+ }
245
+ if (printString.indexOf(BigNum.delim) === fixedPrecision) {
246
+ // decimal is at end of string, not missing any precision, do nothing
247
+ skipExponent = true;
248
+ }
249
+ if (!skipExponent) {
250
+ const exponent = delimFullStringLocation - fixedPrecision;
251
+ if (trailingZeroes) {
252
+ precisionPrintString = `${precisionPrintString}${Array(exponent)
253
+ .fill('0')
254
+ .join('')}`;
255
+ }
256
+ else {
257
+ precisionPrintString = `${precisionPrintString}e${exponent}`;
258
+ }
259
+ }
260
+ }
261
+ return precisionPrintString;
262
+ }
263
+ toTradePrecision() {
264
+ return this.toPrecision(6, true);
265
+ }
266
+ /**
267
+ * Print dollar formatted value. Defaults to fixed decimals two unless a given precision is given.
268
+ * @param useTradePrecision
269
+ * @param precisionOverride
270
+ * @returns
271
+ */
272
+ toNotional(useTradePrecision, precisionOverride) {
273
+ var _a;
274
+ const prefix = `${this.lt(BigNum.zero()) ? `-` : ``}$`;
275
+ const usingCustomPrecision = true && (useTradePrecision || precisionOverride);
276
+ let val = usingCustomPrecision
277
+ ? this.prettyPrint(useTradePrecision, precisionOverride)
278
+ : BigNum.fromPrint(this.toFixed(2), new anchor_1.BN(2)).prettyPrint();
279
+ // Append two trailing zeroes if not using custom precision
280
+ if (!usingCustomPrecision) {
281
+ const [_, rightSide] = val.split(BigNum.delim);
282
+ const trailingLength = (_a = rightSide === null || rightSide === void 0 ? void 0 : rightSide.length) !== null && _a !== void 0 ? _a : 0;
283
+ if (trailingLength < 2) {
284
+ const numHasDecimals = this.print().includes(BigNum.delim);
285
+ // Handle case where pretty print won't include the decimal point
286
+ if (trailingLength === 0 && numHasDecimals) {
287
+ val = `${val}.00`;
288
+ }
289
+ else {
290
+ val = `${val}${new Array(2 - trailingLength).fill('0').join('')}`;
291
+ }
292
+ }
293
+ }
294
+ return `${prefix}${val.replace('-', '')}`;
295
+ }
296
+ toMillified(precision = 3) {
297
+ const stringVal = this.print();
298
+ const [leftSide] = stringVal.split(BigNum.delim);
299
+ if (!leftSide) {
300
+ return this.shift(new anchor_1.BN(precision)).toPrecision(precision, true);
301
+ }
302
+ if (leftSide.length <= 3) {
303
+ return this.shift(new anchor_1.BN(precision)).toPrecision(precision, true);
304
+ }
305
+ const unitTicks = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
306
+ const unitNumber = Math.floor((leftSide.length - 1) / 3);
307
+ const unit = unitTicks[unitNumber];
308
+ let leadDigits = leftSide.slice(0, precision);
309
+ if (leadDigits.length < precision) {
310
+ leadDigits = [
311
+ ...leadDigits.split(''),
312
+ ...Array(precision - leadDigits.length).fill('0'),
313
+ ].join('');
314
+ }
315
+ const decimalLocation = leftSide.length - 3 * unitNumber;
316
+ let leadString = '';
317
+ if (decimalLocation >= precision) {
318
+ leadString = `${leadDigits}`;
319
+ }
320
+ else {
321
+ leadString = `${leadDigits.slice(0, decimalLocation)}${BigNum.delim}${leadDigits.slice(decimalLocation)}`;
322
+ }
323
+ return `${leadString}${unit}`;
324
+ }
325
+ toJSON() {
326
+ return {
327
+ val: this.val.toString(),
328
+ precision: this.precision.toString(),
329
+ };
330
+ }
331
+ isNeg() {
332
+ return this.lt(numericConstants_1.ZERO, true);
333
+ }
334
+ isPos() {
335
+ return !this.isNeg();
336
+ }
337
+ /**
338
+ * Get the numerical value of the BigNum. This can break if the BigNum is too large.
339
+ * @returns
340
+ */
341
+ toNum() {
342
+ return parseFloat(this.print());
343
+ }
344
+ static fromJSON(json) {
345
+ return BigNum.from(new anchor_1.BN(json.val), new anchor_1.BN(json.precision));
346
+ }
347
+ /**
348
+ * Create a BigNum instance
349
+ * @param val
350
+ * @param precision
351
+ * @returns
352
+ */
353
+ static from(val = numericConstants_1.ZERO, precision) {
354
+ assert_1.assert(new anchor_1.BN(precision).lt(new anchor_1.BN(100)), 'Tried to create a bignum with precision higher than 10^100');
355
+ return new BigNum(val, precision);
356
+ }
357
+ /**
358
+ * Create a BigNum instance from a printed BigNum
359
+ * @param val
360
+ * @param precisionOverride
361
+ * @returns
362
+ */
363
+ static fromPrint(val, precisionShift) {
364
+ var _a;
365
+ // Handle empty number edge cases
366
+ if (!val)
367
+ return BigNum.from(numericConstants_1.ZERO, precisionShift);
368
+ if (!val.replace(BigNum.delim, ''))
369
+ return BigNum.from(numericConstants_1.ZERO, precisionShift);
370
+ const [leftSide, rightSide] = val.split(BigNum.delim);
371
+ const rawBn = new anchor_1.BN(`${leftSide !== null && leftSide !== void 0 ? leftSide : ''}${rightSide !== null && rightSide !== void 0 ? rightSide : ''}`);
372
+ const rightSideLength = (_a = rightSide === null || rightSide === void 0 ? void 0 : rightSide.length) !== null && _a !== void 0 ? _a : 0;
373
+ const totalShift = precisionShift
374
+ ? precisionShift.sub(new anchor_1.BN(rightSideLength))
375
+ : numericConstants_1.ZERO;
376
+ return BigNum.from(rawBn, precisionShift).shift(totalShift, true);
377
+ }
378
+ static max(a, b) {
379
+ return a.gt(b) ? a : b;
380
+ }
381
+ static min(a, b) {
382
+ return a.lt(b) ? a : b;
383
+ }
384
+ static zero(precision) {
385
+ return BigNum.from(0, precision);
386
+ }
387
+ }
388
+ exports.BigNum = BigNum;
389
+ BigNum.delim = '.';
390
+ BigNum.spacer = ',';
@@ -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
  }
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getOracleClient = void 0;
4
+ const types_1 = require("../types");
5
+ const pythClient_1 = require("../oracles/pythClient");
6
+ const switchboardClient_1 = require("../oracles/switchboardClient");
7
+ const quoteAssetOracleClient_1 = require("../oracles/quoteAssetOracleClient");
8
+ function getOracleClient(oracleSource, connection) {
9
+ if (types_1.isVariant(oracleSource, 'pyth')) {
10
+ return new pythClient_1.PythClient(connection);
11
+ }
12
+ if (types_1.isVariant(oracleSource, 'switchboard')) {
13
+ return new switchboardClient_1.SwitchboardClient(connection);
14
+ }
15
+ if (types_1.isVariant(oracleSource, 'quoteAsset')) {
16
+ return new quoteAssetOracleClient_1.QuoteAssetOracleClient();
17
+ }
18
+ throw new Error(`Unknown oracle source ${oracleSource}`);
19
+ }
20
+ exports.getOracleClient = getOracleClient;