@drift-labs/sdk 0.2.0-master.4 → 0.2.0-master.41
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.
- package/README.md +27 -27
- package/lib/accounts/bulkAccountLoader.d.ts +2 -0
- package/lib/accounts/bulkAccountLoader.js +36 -29
- package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
- package/lib/accounts/bulkUserStatsSubscription.js +21 -0
- package/lib/accounts/bulkUserSubscription.d.ts +2 -2
- package/lib/accounts/bulkUserSubscription.js +0 -1
- package/lib/accounts/fetch.d.ts +2 -1
- package/lib/accounts/fetch.js +9 -1
- package/lib/accounts/{pollingClearingHouseAccountSubscriber.d.ts → pollingDriftClientAccountSubscriber.d.ts} +20 -25
- package/lib/accounts/{pollingClearingHouseAccountSubscriber.js → pollingDriftClientAccountSubscriber.js} +45 -49
- package/lib/accounts/{pollingOracleSubscriber.d.ts → pollingOracleAccountSubscriber.d.ts} +2 -2
- package/lib/accounts/{pollingOracleSubscriber.js → pollingOracleAccountSubscriber.js} +3 -3
- package/lib/accounts/pollingUserAccountSubscriber.d.ts +1 -1
- package/lib/accounts/pollingUserAccountSubscriber.js +5 -11
- package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
- package/lib/accounts/pollingUserStatsAccountSubscriber.js +107 -0
- package/lib/accounts/types.d.ts +26 -15
- package/lib/accounts/webSocketDriftClientAccountSubscriber.d.ts +49 -0
- package/lib/accounts/{webSocketClearingHouseAccountSubscriber.js → webSocketDriftClientAccountSubscriber.js} +47 -45
- package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
- package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
- package/lib/addresses/marketAddresses.d.ts +1 -3
- package/lib/addresses/marketAddresses.js +1 -1
- package/lib/addresses/pda.d.ts +15 -9
- package/lib/addresses/pda.js +73 -35
- package/lib/adminClient.d.ts +65 -0
- package/lib/adminClient.js +637 -0
- package/lib/config.d.ts +9 -9
- package/lib/config.js +25 -21
- package/lib/constants/numericConstants.d.ts +30 -12
- package/lib/constants/numericConstants.js +41 -21
- package/lib/constants/perpMarkets.d.ts +18 -0
- package/lib/constants/{markets.js → perpMarkets.js} +7 -7
- package/lib/constants/spotMarkets.d.ts +19 -0
- package/lib/constants/spotMarkets.js +53 -0
- package/lib/dlob/DLOB.d.ts +82 -0
- package/lib/dlob/DLOB.js +694 -0
- package/lib/dlob/DLOBNode.d.ts +54 -0
- package/lib/dlob/DLOBNode.js +77 -0
- package/lib/dlob/NodeList.d.ts +27 -0
- package/lib/dlob/NodeList.js +144 -0
- package/lib/driftClient.d.ts +234 -0
- package/lib/driftClient.js +2108 -0
- package/lib/{clearingHouseConfig.d.ts → driftClientConfig.d.ts} +9 -9
- package/lib/{clearingHouseConfig.js → driftClientConfig.js} +0 -0
- package/lib/events/eventList.js +3 -0
- package/lib/events/eventSubscriber.d.ts +5 -2
- package/lib/events/eventSubscriber.js +25 -11
- package/lib/events/fetchLogs.d.ts +13 -2
- package/lib/events/fetchLogs.js +40 -12
- package/lib/events/pollingLogProvider.d.ts +2 -1
- package/lib/events/pollingLogProvider.js +7 -3
- package/lib/events/sort.js +8 -11
- package/lib/events/types.d.ts +11 -3
- package/lib/events/types.js +8 -0
- package/lib/events/webSocketLogProvider.js +1 -1
- package/lib/examples/makeTradeExample.js +30 -18
- package/lib/factory/bigNum.d.ts +8 -4
- package/lib/factory/bigNum.js +109 -19
- package/lib/idl/drift.json +8386 -0
- package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
- package/lib/index.d.ts +30 -13
- package/lib/index.js +30 -13
- package/lib/math/amm.d.ts +9 -6
- package/lib/math/amm.js +91 -38
- package/lib/math/conversion.js +1 -1
- package/lib/math/exchangeStatus.d.ts +4 -0
- package/lib/math/exchangeStatus.js +18 -0
- package/lib/math/funding.d.ts +6 -6
- package/lib/math/funding.js +23 -21
- package/lib/math/insurance.d.ts +4 -0
- package/lib/math/insurance.js +27 -0
- package/lib/math/margin.d.ts +11 -0
- package/lib/math/margin.js +82 -0
- package/lib/math/market.d.ts +14 -9
- package/lib/math/market.js +70 -10
- package/lib/math/oracles.d.ts +4 -0
- package/lib/math/oracles.js +36 -8
- package/lib/math/orders.d.ts +16 -6
- package/lib/math/orders.js +97 -17
- package/lib/math/position.d.ts +27 -13
- package/lib/math/position.js +92 -36
- package/lib/math/repeg.js +17 -8
- package/lib/math/spotBalance.d.ts +22 -0
- package/lib/math/spotBalance.js +192 -0
- package/lib/math/spotMarket.d.ts +4 -0
- package/lib/math/spotMarket.js +8 -0
- package/lib/math/spotPosition.d.ts +6 -0
- package/lib/math/spotPosition.js +23 -0
- package/lib/math/trade.d.ts +10 -10
- package/lib/math/trade.js +27 -31
- package/lib/oracles/pythClient.js +1 -1
- package/lib/oracles/quoteAssetOracleClient.js +1 -1
- package/lib/oracles/switchboardClient.js +1 -1
- package/lib/orderParams.d.ts +4 -4
- package/lib/orderParams.js +12 -4
- package/lib/serum/serumFulfillmentConfigMap.d.ts +10 -0
- package/lib/serum/serumFulfillmentConfigMap.js +17 -0
- package/lib/serum/serumSubscriber.d.ts +27 -0
- package/lib/serum/serumSubscriber.js +56 -0
- package/lib/serum/types.d.ts +11 -0
- package/lib/{clearingHouseUserConfig.js → serum/types.js} +0 -0
- package/lib/slot/SlotSubscriber.d.ts +7 -0
- package/lib/slot/SlotSubscriber.js +3 -0
- package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
- package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
- package/lib/tx/retryTxSender.d.ts +1 -1
- package/lib/tx/retryTxSender.js +13 -4
- package/lib/tx/types.d.ts +1 -1
- package/lib/tx/utils.js +1 -1
- package/lib/types.d.ts +688 -216
- package/lib/types.js +153 -24
- package/lib/user.d.ts +228 -0
- package/lib/user.js +959 -0
- package/lib/userConfig.d.ts +14 -0
- package/lib/userConfig.js +2 -0
- package/lib/userMap/userMap.d.ts +41 -0
- package/lib/userMap/userMap.js +85 -0
- package/lib/userMap/userStatsMap.d.ts +19 -0
- package/lib/userMap/userStatsMap.js +68 -0
- package/lib/userName.d.ts +1 -0
- package/lib/userName.js +3 -2
- package/lib/userStats.d.ts +18 -0
- package/lib/userStats.js +49 -0
- package/lib/userStatsConfig.d.ts +14 -0
- package/lib/userStatsConfig.js +2 -0
- package/lib/util/computeUnits.js +1 -1
- package/lib/util/getTokenAddress.d.ts +2 -0
- package/lib/util/getTokenAddress.js +9 -0
- package/package.json +11 -4
- package/src/accounts/bulkAccountLoader.ts +44 -34
- package/src/accounts/bulkUserStatsSubscription.ts +33 -0
- package/src/accounts/bulkUserSubscription.ts +2 -3
- package/src/accounts/fetch.ts +27 -2
- package/src/accounts/{pollingClearingHouseAccountSubscriber.ts → pollingDriftClientAccountSubscriber.ts} +65 -75
- package/src/accounts/{pollingOracleSubscriber.ts → pollingOracleAccountSubscriber.ts} +2 -2
- package/src/accounts/pollingUserAccountSubscriber.ts +5 -12
- package/src/accounts/pollingUserStatsAccountSubscriber.ts +166 -0
- package/src/accounts/types.ts +35 -15
- package/src/accounts/{webSocketClearingHouseAccountSubscriber.ts → webSocketDriftClientAccountSubscriber.ts} +78 -73
- package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
- package/src/addresses/marketAddresses.ts +3 -4
- package/src/addresses/pda.ts +105 -33
- package/src/adminClient.ts +1207 -0
- package/src/assert/assert.js +9 -0
- package/src/config.ts +37 -31
- package/src/constants/numericConstants.ts +58 -24
- package/src/constants/{markets.ts → perpMarkets.ts} +10 -10
- package/src/constants/spotMarkets.ts +73 -0
- package/src/dlob/DLOB.ts +1120 -0
- package/src/dlob/DLOBNode.ts +155 -0
- package/src/dlob/NodeList.ts +195 -0
- package/src/driftClient.ts +3594 -0
- package/src/{clearingHouseConfig.ts → driftClientConfig.ts} +9 -8
- package/src/events/eventList.js +77 -0
- package/src/events/eventList.ts +3 -0
- package/src/events/eventSubscriber.ts +36 -14
- package/src/events/fetchLogs.ts +55 -13
- package/src/events/pollingLogProvider.ts +11 -3
- package/src/events/sort.ts +11 -15
- package/src/events/types.ts +27 -2
- package/src/events/webSocketLogProvider.ts +1 -1
- package/src/examples/makeTradeExample.js +157 -0
- package/src/examples/makeTradeExample.ts +44 -28
- package/src/factory/bigNum.ts +150 -22
- package/src/idl/drift.json +8386 -0
- package/src/idl/pyth.json +98 -2
- package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
- package/src/index.ts +30 -13
- package/src/math/amm.ts +161 -48
- package/src/math/conversion.ts +2 -2
- package/src/math/exchangeStatus.ts +31 -0
- package/src/math/funding.ts +41 -31
- package/src/math/insurance.ts +35 -0
- package/src/math/margin.ts +133 -0
- package/src/math/market.ts +143 -14
- package/src/math/oracles.ts +63 -9
- package/src/math/orders.ts +168 -26
- package/src/math/position.ts +136 -58
- package/src/math/repeg.ts +19 -9
- package/src/math/spotBalance.ts +319 -0
- package/src/math/spotMarket.ts +9 -0
- package/src/math/spotPosition.ts +47 -0
- package/src/math/trade.ts +33 -37
- package/src/oracles/pythClient.ts +2 -2
- package/src/oracles/quoteAssetOracleClient.ts +2 -2
- package/src/oracles/switchboardClient.ts +2 -2
- package/src/orderParams.ts +16 -8
- package/src/serum/serumFulfillmentConfigMap.ts +26 -0
- package/src/serum/serumSubscriber.ts +99 -0
- package/src/serum/types.ts +13 -0
- package/src/slot/SlotSubscriber.ts +11 -1
- package/src/token/index.js +38 -0
- package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
- package/src/tx/retryTxSender.ts +16 -5
- package/src/tx/types.js +2 -0
- package/src/tx/types.ts +2 -1
- package/src/tx/utils.js +17 -0
- package/src/tx/utils.ts +1 -1
- package/src/types.ts +650 -189
- package/src/user.ts +1599 -0
- package/src/{clearingHouseUserConfig.ts → userConfig.ts} +5 -5
- package/src/userMap/userMap.ts +124 -0
- package/src/userMap/userStatsMap.ts +108 -0
- package/src/userName.ts +2 -1
- package/src/userStats.ts +75 -0
- package/src/userStatsConfig.ts +18 -0
- package/src/util/computeUnits.js +21 -11
- package/src/util/computeUnits.ts +1 -1
- package/src/util/getTokenAddress.js +9 -0
- package/src/util/getTokenAddress.ts +18 -0
- package/src/util/promiseTimeout.js +14 -0
- package/src/util/tps.js +27 -0
- package/tests/bn/test.ts +46 -11
- package/tests/dlob/helpers.ts +620 -0
- package/tests/dlob/test.ts +4586 -0
- package/yarn-error.log +3160 -0
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +0 -49
- package/lib/admin.d.ts +0 -44
- package/lib/admin.js +0 -433
- package/lib/clearingHouse.d.ts +0 -133
- package/lib/clearingHouse.js +0 -931
- package/lib/clearingHouseUser.d.ts +0 -187
- package/lib/clearingHouseUser.js +0 -643
- package/lib/clearingHouseUserConfig.d.ts +0 -14
- package/lib/constants/banks.d.ts +0 -16
- package/lib/constants/banks.js +0 -34
- package/lib/constants/markets.d.ts +0 -19
- package/lib/idl/clearing_house.json +0 -3998
- package/lib/math/bankBalance.d.ts +0 -9
- package/lib/math/bankBalance.js +0 -75
- package/lib/math/state.d.ts +0 -8
- package/lib/math/state.js +0 -15
- package/lib/orders.d.ts +0 -8
- package/lib/orders.js +0 -134
- package/src/admin.ts +0 -722
- package/src/clearingHouse.ts +0 -1451
- package/src/clearingHouseUser.ts +0 -989
- package/src/constants/banks.ts +0 -43
- package/src/idl/clearing_house.json +0 -3998
- package/src/math/bankBalance.ts +0 -112
- package/src/math/state.ts +0 -14
- package/src/math/utils.js +0 -27
- package/src/math/utils.js.map +0 -1
- package/src/orders.ts +0 -244
- package/src/util/computeUnits.js.map +0 -1
|
@@ -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
|
-
|
|
7
|
-
|
|
8
|
-
|
|
6
|
+
calculateReservePrice,
|
|
7
|
+
DriftClient,
|
|
8
|
+
User,
|
|
9
9
|
initialize,
|
|
10
10
|
PositionDirection,
|
|
11
11
|
convertToNumber,
|
|
12
12
|
calculateTradeSlippage,
|
|
13
|
-
|
|
13
|
+
BulkAccountLoader,
|
|
14
|
+
PerpMarkets,
|
|
15
|
+
PRICE_PRECISION,
|
|
14
16
|
QUOTE_PRECISION,
|
|
15
17
|
} from '..';
|
|
16
|
-
import {
|
|
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:
|
|
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
|
|
64
|
-
|
|
67
|
+
const driftPublicKey = new PublicKey(sdkConfig.CLEARING_HOUSE_PROGRAM_ID);
|
|
68
|
+
const bulkAccountLoader = new BulkAccountLoader(
|
|
69
|
+
connection,
|
|
70
|
+
'confirmed',
|
|
71
|
+
1000
|
|
65
72
|
);
|
|
66
|
-
const
|
|
73
|
+
const driftClient = new DriftClient({
|
|
67
74
|
connection,
|
|
68
75
|
wallet: provider.wallet,
|
|
69
|
-
programID:
|
|
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
|
|
86
|
+
await driftClient.subscribe();
|
|
72
87
|
|
|
73
88
|
// Set up Clearing House user client
|
|
74
|
-
const user = new
|
|
75
|
-
|
|
76
|
-
userAccountPublicKey: await
|
|
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
|
|
104
|
+
await driftClient.initializeUserAccountAndDepositCollateral(
|
|
86
105
|
depositAmount,
|
|
87
106
|
await getTokenAddress(
|
|
88
107
|
usdcTokenAddress.toString(),
|
|
89
108
|
wallet.publicKey.toString()
|
|
90
109
|
),
|
|
91
|
-
|
|
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.
|
|
117
|
+
const solMarketInfo = sdkConfig.PERP_MARKETS.find(
|
|
99
118
|
(market) => market.baseAssetSymbol === 'SOL'
|
|
100
119
|
);
|
|
101
120
|
|
|
102
|
-
const currentMarketPrice =
|
|
103
|
-
|
|
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 =
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
|
168
|
+
await driftClient.closePosition(solMarketInfo.marketIndex);
|
|
153
169
|
};
|
|
154
170
|
|
|
155
171
|
main();
|
package/src/factory/bigNum.ts
CHANGED
|
@@ -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 =
|
|
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
|
|
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
|
|
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 =
|
|
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 =
|
|
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 =
|
|
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 =
|
|
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 =
|
|
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
|
|
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(
|
|
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
|
|
396
|
-
useTradePrecision || precisionOverride
|
|
397
|
-
|
|
398
|
-
|
|
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
|
-
|
|
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
|
|
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(
|
|
630
|
+
const rawBn = new BN(bnInput);
|
|
503
631
|
|
|
504
632
|
const rightSideLength = rightSide?.length ?? 0;
|
|
505
633
|
|