@drift-labs/sdk 0.2.0-master.27 → 0.2.0-master.28

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 (50) hide show
  1. package/lib/accounts/types.d.ts +1 -0
  2. package/lib/clearingHouse.d.ts +1 -0
  3. package/lib/clearingHouse.js +5 -0
  4. package/lib/clearingHouseUser.js +2 -2
  5. package/lib/idl/clearing_house.json +1 -1
  6. package/lib/math/market.d.ts +2 -1
  7. package/lib/math/market.js +16 -11
  8. package/lib/math/position.d.ts +3 -3
  9. package/lib/math/position.js +23 -16
  10. package/lib/math/repeg.js +8 -0
  11. package/lib/types.d.ts +1 -1
  12. package/package.json +1 -1
  13. package/src/clearingHouse.ts +7 -0
  14. package/src/clearingHouseUser.ts +2 -2
  15. package/src/idl/clearing_house.json +1 -1
  16. package/src/math/market.ts +21 -12
  17. package/src/math/position.ts +36 -22
  18. package/src/math/repeg.ts +9 -0
  19. package/src/types.ts +1 -1
  20. package/tests/dlob/helpers.ts +1 -1
  21. package/src/addresses/marketAddresses.js +0 -26
  22. package/src/assert/assert.js +0 -9
  23. package/src/constants/banks.js +0 -42
  24. package/src/constants/markets.js +0 -42
  25. package/src/events/eventList.js +0 -77
  26. package/src/events/txEventCache.js +0 -71
  27. package/src/examples/makeTradeExample.js +0 -157
  28. package/src/factory/bigNum.js +0 -390
  29. package/src/factory/oracleClient.js +0 -20
  30. package/src/math/auction.js +0 -42
  31. package/src/math/conversion.js +0 -11
  32. package/src/math/funding.js +0 -248
  33. package/src/math/repeg.js +0 -128
  34. package/src/math/trade.js +0 -253
  35. package/src/math/utils.js +0 -26
  36. package/src/math/utils.js.map +0 -1
  37. package/src/oracles/oracleClientCache.js +0 -19
  38. package/src/oracles/pythClient.js +0 -46
  39. package/src/oracles/quoteAssetOracleClient.js +0 -32
  40. package/src/oracles/switchboardClient.js +0 -69
  41. package/src/oracles/types.js +0 -2
  42. package/src/token/index.js +0 -38
  43. package/src/tx/types.js +0 -2
  44. package/src/tx/utils.js +0 -17
  45. package/src/userName.js +0 -20
  46. package/src/util/computeUnits.js +0 -27
  47. package/src/util/getTokenAddress.js +0 -9
  48. package/src/util/promiseTimeout.js +0 -14
  49. package/src/util/tps.js +0 -27
  50. package/src/wallet.js +0 -35
@@ -1,77 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EventList = void 0;
4
- class Node {
5
- constructor(event, next, prev) {
6
- this.event = event;
7
- this.next = next;
8
- this.prev = prev;
9
- }
10
- }
11
- class EventList {
12
- constructor(eventType, maxSize, sortFn, orderDirection) {
13
- this.eventType = eventType;
14
- this.maxSize = maxSize;
15
- this.sortFn = sortFn;
16
- this.orderDirection = orderDirection;
17
- this.size = 0;
18
- }
19
- insert(event) {
20
- this.size++;
21
- const newNode = new Node(event);
22
- if (this.head === undefined) {
23
- this.head = this.tail = newNode;
24
- return;
25
- }
26
- if (this.sortFn(this.head.event, newNode.event) ===
27
- (this.orderDirection === 'asc' ? 'less than' : 'greater than')) {
28
- this.head.prev = newNode;
29
- newNode.next = this.head;
30
- this.head = newNode;
31
- }
32
- else {
33
- let currentNode = this.head;
34
- while (currentNode.next !== undefined &&
35
- this.sortFn(currentNode.next.event, newNode.event) !==
36
- (this.orderDirection === 'asc' ? 'less than' : 'greater than')) {
37
- currentNode = currentNode.next;
38
- }
39
- newNode.next = currentNode.next;
40
- if (currentNode.next !== undefined) {
41
- newNode.next.prev = newNode;
42
- }
43
- currentNode.next = newNode;
44
- newNode.prev = currentNode;
45
- }
46
- if (this.size > this.maxSize) {
47
- this.detach();
48
- }
49
- }
50
- detach() {
51
- const node = this.tail;
52
- if (node.prev !== undefined) {
53
- node.prev.next = node.next;
54
- }
55
- else {
56
- this.head = node.next;
57
- }
58
- if (node.next !== undefined) {
59
- node.next.prev = node.prev;
60
- }
61
- else {
62
- this.tail = node.prev;
63
- }
64
- this.size--;
65
- }
66
- toArray() {
67
- return Array.from(this);
68
- }
69
- *[Symbol.iterator]() {
70
- let node = this.head;
71
- while (node) {
72
- yield node.event;
73
- node = node.next;
74
- }
75
- }
76
- }
77
- exports.EventList = EventList;
@@ -1,71 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TxEventCache = void 0;
4
- class Node {
5
- constructor(key, value, next, prev) {
6
- this.key = key;
7
- this.value = value;
8
- this.next = next;
9
- this.prev = prev;
10
- }
11
- }
12
- // lru cache
13
- class TxEventCache {
14
- constructor(maxTx = 1024) {
15
- this.maxTx = maxTx;
16
- this.size = 0;
17
- this.cacheMap = {};
18
- }
19
- add(key, events) {
20
- const existingNode = this.cacheMap[key];
21
- if (existingNode) {
22
- this.detach(existingNode);
23
- this.size--;
24
- }
25
- else if (this.size === this.maxTx) {
26
- delete this.cacheMap[this.tail.key];
27
- this.detach(this.tail);
28
- this.size--;
29
- }
30
- // Write to head of LinkedList
31
- if (!this.head) {
32
- this.head = this.tail = new Node(key, events);
33
- }
34
- else {
35
- const node = new Node(key, events, this.head);
36
- this.head.prev = node;
37
- this.head = node;
38
- }
39
- // update cacheMap with LinkedList key and Node reference
40
- this.cacheMap[key] = this.head;
41
- this.size++;
42
- }
43
- has(key) {
44
- return this.cacheMap.hasOwnProperty(key);
45
- }
46
- get(key) {
47
- var _a;
48
- return (_a = this.cacheMap[key]) === null || _a === void 0 ? void 0 : _a.value;
49
- }
50
- detach(node) {
51
- if (node.prev !== undefined) {
52
- node.prev.next = node.next;
53
- }
54
- else {
55
- this.head = node.next;
56
- }
57
- if (node.next !== undefined) {
58
- node.next.prev = node.prev;
59
- }
60
- else {
61
- this.tail = node.prev;
62
- }
63
- }
64
- clear() {
65
- this.head = undefined;
66
- this.tail = undefined;
67
- this.size = 0;
68
- this.cacheMap = {};
69
- }
70
- }
71
- exports.TxEventCache = TxEventCache;
@@ -1,157 +0,0 @@
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.MARK_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.MARK_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();
@@ -1,390 +0,0 @@
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 = ',';