@drift-labs/sdk 0.2.0-master.0 → 0.2.0-master.11
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/lib/admin.d.ts +8 -5
- package/lib/admin.js +43 -11
- package/lib/clearingHouse.d.ts +28 -18
- package/lib/clearingHouse.js +366 -143
- package/lib/clearingHouseUser.d.ts +2 -2
- package/lib/clearingHouseUser.js +8 -17
- package/lib/config.js +1 -1
- package/lib/constants/banks.js +9 -2
- package/lib/constants/numericConstants.d.ts +2 -0
- package/lib/constants/numericConstants.js +3 -1
- package/lib/factory/bigNum.d.ts +8 -2
- package/lib/factory/bigNum.js +14 -6
- package/lib/idl/clearing_house.json +805 -202
- package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
- package/lib/index.d.ts +3 -2
- package/lib/index.js +7 -2
- package/lib/math/amm.d.ts +6 -1
- package/lib/math/amm.js +124 -41
- package/lib/math/auction.js +4 -1
- package/lib/math/orders.d.ts +2 -2
- package/lib/math/orders.js +18 -11
- package/lib/math/position.js +3 -1
- package/lib/math/repeg.js +1 -1
- package/lib/math/trade.d.ts +1 -1
- package/lib/math/trade.js +7 -10
- package/lib/orderParams.d.ts +14 -5
- package/lib/orderParams.js +8 -96
- package/lib/orders.d.ts +1 -2
- package/lib/orders.js +6 -85
- package/lib/slot/SlotSubscriber.d.ts +7 -0
- package/lib/slot/SlotSubscriber.js +3 -0
- package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +7 -5
- package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +41 -40
- package/lib/tx/utils.js +1 -1
- package/lib/types.d.ts +137 -14
- package/lib/types.js +53 -1
- package/lib/util/computeUnits.js +1 -1
- package/package.json +3 -3
- package/src/accounts/bulkAccountLoader.js +197 -0
- package/src/accounts/bulkUserSubscription.js +33 -0
- package/src/accounts/fetch.js +29 -0
- package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
- package/src/accounts/pollingOracleSubscriber.js +93 -0
- package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
- package/src/accounts/pollingUserAccountSubscriber.js +132 -0
- package/src/accounts/types.js +10 -0
- package/src/accounts/utils.js +7 -0
- package/src/accounts/webSocketAccountSubscriber.js +93 -0
- package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
- package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
- package/src/addresses/marketAddresses.js +26 -0
- package/src/addresses/pda.js +104 -0
- package/src/admin.ts +66 -14
- package/src/assert/assert.js +9 -0
- package/src/clearingHouse.ts +558 -230
- package/src/clearingHouseUser.ts +12 -23
- package/src/config.ts +1 -1
- package/src/constants/banks.ts +9 -2
- package/src/constants/numericConstants.ts +2 -0
- package/src/events/eventList.js +77 -0
- package/src/events/eventSubscriber.js +139 -0
- package/src/events/fetchLogs.js +50 -0
- package/src/events/pollingLogProvider.js +64 -0
- package/src/events/sort.js +44 -0
- package/src/events/txEventCache.js +71 -0
- package/src/events/types.js +20 -0
- package/src/events/webSocketLogProvider.js +41 -0
- package/src/examples/makeTradeExample.js +80 -0
- package/src/factory/bigNum.js +364 -0
- package/src/factory/bigNum.ts +26 -9
- package/src/factory/oracleClient.js +20 -0
- package/src/idl/clearing_house.json +805 -202
- package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
- package/src/index.js +100 -0
- package/src/index.ts +3 -2
- package/src/math/amm.js +369 -0
- package/src/math/amm.ts +207 -52
- package/src/math/auction.js +42 -0
- package/src/math/auction.ts +5 -1
- package/src/math/bankBalance.js +75 -0
- package/src/math/conversion.js +11 -0
- package/src/math/funding.js +248 -0
- package/src/math/market.js +57 -0
- package/src/math/oracles.js +26 -0
- package/src/math/orders.js +110 -0
- package/src/math/orders.ts +17 -13
- package/src/math/position.js +140 -0
- package/src/math/position.ts +5 -1
- package/src/math/repeg.js +128 -0
- package/src/math/repeg.ts +2 -1
- package/src/math/state.js +15 -0
- package/src/math/trade.js +253 -0
- package/src/math/trade.ts +23 -25
- package/src/math/utils.js +0 -1
- package/src/mockUSDCFaucet.js +280 -0
- package/src/oracles/oracleClientCache.js +19 -0
- package/src/oracles/pythClient.js +46 -0
- package/src/oracles/quoteAssetOracleClient.js +32 -0
- package/src/oracles/switchboardClient.js +69 -0
- package/src/oracles/types.js +2 -0
- package/src/orderParams.js +20 -0
- package/src/orderParams.ts +20 -141
- package/src/orders.js +134 -0
- package/src/orders.ts +7 -131
- package/src/slot/SlotSubscriber.js +39 -0
- package/src/slot/SlotSubscriber.ts +11 -1
- package/src/token/index.js +38 -0
- package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +48 -59
- package/src/tx/retryTxSender.js +188 -0
- package/src/tx/types.js +2 -0
- package/src/tx/utils.js +17 -0
- package/src/tx/utils.ts +1 -1
- package/src/types.js +114 -0
- package/src/types.ts +132 -16
- package/src/userName.js +20 -0
- package/src/util/computeUnits.ts +1 -1
- package/src/util/promiseTimeout.js +14 -0
- package/src/util/tps.js +27 -0
- package/src/wallet.js +35 -0
- package/src/util/computeUnits.js +0 -17
- 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,364 @@
|
|
|
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
|
+
add(bn) {
|
|
14
|
+
assert_1.assert(bn.precision.eq(this.precision), 'Adding unequal precisions');
|
|
15
|
+
return BigNum.from(this.val.add(bn.val), this.precision);
|
|
16
|
+
}
|
|
17
|
+
sub(bn) {
|
|
18
|
+
assert_1.assert(bn.precision.eq(this.precision), 'Subtracting unequal precisions');
|
|
19
|
+
return BigNum.from(this.val.sub(bn.val), this.precision);
|
|
20
|
+
}
|
|
21
|
+
mul(bn) {
|
|
22
|
+
const mulVal = bn instanceof BigNum ? bn : BigNum.from(bn);
|
|
23
|
+
return BigNum.from(this.val.mul(mulVal.val), this.precision.add(mulVal.precision));
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* 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
|
|
27
|
+
* @param bn
|
|
28
|
+
* @returns
|
|
29
|
+
*/
|
|
30
|
+
scalarMul(bn) {
|
|
31
|
+
if (bn instanceof anchor_1.BN)
|
|
32
|
+
return BigNum.from(this.val.mul(bn), this.precision);
|
|
33
|
+
return BigNum.from(this.val.mul(bn.val), this.precision.add(bn.precision)).shift(bn.precision.neg());
|
|
34
|
+
}
|
|
35
|
+
div(bn) {
|
|
36
|
+
if (bn instanceof anchor_1.BN)
|
|
37
|
+
return BigNum.from(this.val.div(bn), this.precision);
|
|
38
|
+
return BigNum.from(this.val.div(bn.val), this.precision.sub(bn.precision));
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Shift precision up or down
|
|
42
|
+
* @param exponent
|
|
43
|
+
* @param skipAdjustingPrecision
|
|
44
|
+
* @returns
|
|
45
|
+
*/
|
|
46
|
+
shift(exponent, skipAdjustingPrecision = false) {
|
|
47
|
+
const shiftVal = typeof exponent === 'number' ? new anchor_1.BN(exponent) : exponent;
|
|
48
|
+
return BigNum.from(shiftVal.isNeg()
|
|
49
|
+
? this.val.div(new anchor_1.BN(10).pow(shiftVal))
|
|
50
|
+
: this.val.mul(new anchor_1.BN(10).pow(shiftVal)), skipAdjustingPrecision ? this.precision : this.precision.add(shiftVal));
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Shift to a target precision
|
|
54
|
+
* @param targetPrecision
|
|
55
|
+
* @returns
|
|
56
|
+
*/
|
|
57
|
+
shiftTo(targetPrecision) {
|
|
58
|
+
return this.shift(targetPrecision.sub(this.precision));
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Scale the number by a fraction
|
|
62
|
+
* @param numerator
|
|
63
|
+
* @param denominator
|
|
64
|
+
* @returns
|
|
65
|
+
*/
|
|
66
|
+
scale(numerator, denominator) {
|
|
67
|
+
return this.mul(BigNum.from(new anchor_1.BN(numerator))).div(new anchor_1.BN(denominator));
|
|
68
|
+
}
|
|
69
|
+
toPercentage(denominator, precision) {
|
|
70
|
+
return this.shift(precision)
|
|
71
|
+
.shift(2, true)
|
|
72
|
+
.div(denominator)
|
|
73
|
+
.toPrecision(precision);
|
|
74
|
+
}
|
|
75
|
+
gt(bn, ignorePrecision) {
|
|
76
|
+
const comparisonVal = bn instanceof BigNum ? bn : BigNum.from(bn);
|
|
77
|
+
if (!ignorePrecision && !comparisonVal.eq(numericConstants_1.ZERO)) {
|
|
78
|
+
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');
|
|
79
|
+
}
|
|
80
|
+
return this.val.gt(comparisonVal.val);
|
|
81
|
+
}
|
|
82
|
+
lt(bn, ignorePrecision) {
|
|
83
|
+
const comparisonVal = bn instanceof BigNum ? bn : BigNum.from(bn);
|
|
84
|
+
if (!ignorePrecision && !comparisonVal.val.eq(numericConstants_1.ZERO)) {
|
|
85
|
+
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');
|
|
86
|
+
}
|
|
87
|
+
return this.val.lt(comparisonVal.val);
|
|
88
|
+
}
|
|
89
|
+
gte(bn, ignorePrecision) {
|
|
90
|
+
const comparisonVal = bn instanceof BigNum ? bn : BigNum.from(bn);
|
|
91
|
+
if (!ignorePrecision && !comparisonVal.val.eq(numericConstants_1.ZERO)) {
|
|
92
|
+
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');
|
|
93
|
+
}
|
|
94
|
+
return this.val.gte(comparisonVal.val);
|
|
95
|
+
}
|
|
96
|
+
lte(bn, ignorePrecision) {
|
|
97
|
+
const comparisonVal = bn instanceof BigNum ? bn : BigNum.from(bn);
|
|
98
|
+
if (!ignorePrecision && !comparisonVal.val.eq(numericConstants_1.ZERO)) {
|
|
99
|
+
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');
|
|
100
|
+
}
|
|
101
|
+
return this.val.lte(comparisonVal.val);
|
|
102
|
+
}
|
|
103
|
+
eq(bn, ignorePrecision) {
|
|
104
|
+
const comparisonVal = bn instanceof BigNum ? bn : BigNum.from(bn);
|
|
105
|
+
if (!ignorePrecision && !comparisonVal.val.eq(numericConstants_1.ZERO)) {
|
|
106
|
+
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');
|
|
107
|
+
}
|
|
108
|
+
return this.val.eq(comparisonVal.val);
|
|
109
|
+
}
|
|
110
|
+
eqZero() {
|
|
111
|
+
return this.val.eq(numericConstants_1.ZERO);
|
|
112
|
+
}
|
|
113
|
+
gtZero() {
|
|
114
|
+
return this.val.gt(numericConstants_1.ZERO);
|
|
115
|
+
}
|
|
116
|
+
ltZero() {
|
|
117
|
+
return this.val.lt(numericConstants_1.ZERO);
|
|
118
|
+
}
|
|
119
|
+
gteZero() {
|
|
120
|
+
return this.val.gte(numericConstants_1.ZERO);
|
|
121
|
+
}
|
|
122
|
+
lteZero() {
|
|
123
|
+
return this.val.lte(numericConstants_1.ZERO);
|
|
124
|
+
}
|
|
125
|
+
abs() {
|
|
126
|
+
return new BigNum(this.val.abs(), this.precision);
|
|
127
|
+
}
|
|
128
|
+
neg() {
|
|
129
|
+
return new BigNum(this.val.neg(), this.precision);
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Pretty print the underlying value in human-readable form. Depends on precision being correct for the output string to be correct
|
|
133
|
+
* @returns
|
|
134
|
+
*/
|
|
135
|
+
print() {
|
|
136
|
+
assert_1.assert(this.precision.gte(numericConstants_1.ZERO), 'Tried to print a BN with precision lower than zero');
|
|
137
|
+
const plainString = this.toString();
|
|
138
|
+
const precisionNum = this.precision.toNumber();
|
|
139
|
+
// make a string with at least the precisionNum number of zeroes
|
|
140
|
+
let printString = [
|
|
141
|
+
...Array(this.precision.toNumber()).fill(0),
|
|
142
|
+
...plainString.split(''),
|
|
143
|
+
].join('');
|
|
144
|
+
// inject decimal
|
|
145
|
+
printString =
|
|
146
|
+
printString.substring(0, printString.length - precisionNum) +
|
|
147
|
+
BigNum.delim +
|
|
148
|
+
printString.substring(printString.length - precisionNum);
|
|
149
|
+
// remove leading zeroes
|
|
150
|
+
printString = printString.replace(/^0+/, '');
|
|
151
|
+
// add zero if leading delim
|
|
152
|
+
if (printString[0] === BigNum.delim)
|
|
153
|
+
printString = `0${printString}`;
|
|
154
|
+
// remove trailing delim
|
|
155
|
+
if (printString[printString.length - 1] === BigNum.delim)
|
|
156
|
+
printString = printString.slice(0, printString.length - 1);
|
|
157
|
+
return printString;
|
|
158
|
+
}
|
|
159
|
+
prettyPrint(useTradePrecision, precisionOverride) {
|
|
160
|
+
const [leftSide, rightSide] = this.printShort(useTradePrecision, precisionOverride).split(BigNum.delim);
|
|
161
|
+
let formattedLeftSide = leftSide;
|
|
162
|
+
const isNeg = formattedLeftSide.includes('-');
|
|
163
|
+
if (isNeg) {
|
|
164
|
+
formattedLeftSide = formattedLeftSide.replace('-', '');
|
|
165
|
+
}
|
|
166
|
+
let index = formattedLeftSide.length - 3;
|
|
167
|
+
while (index >= 1) {
|
|
168
|
+
const formattedLeftSideArray = formattedLeftSide.split('');
|
|
169
|
+
formattedLeftSideArray.splice(index, 0, BigNum.spacer);
|
|
170
|
+
formattedLeftSide = formattedLeftSideArray.join('');
|
|
171
|
+
index -= 3;
|
|
172
|
+
}
|
|
173
|
+
return `${isNeg ? '-' : ''}${formattedLeftSide}${rightSide ? `${BigNum.delim}${rightSide}` : ''}`;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Print and remove unnecessary trailing zeroes
|
|
177
|
+
* @returns
|
|
178
|
+
*/
|
|
179
|
+
printShort(useTradePrecision, precisionOverride) {
|
|
180
|
+
const printVal = precisionOverride
|
|
181
|
+
? this.toPrecision(precisionOverride)
|
|
182
|
+
: useTradePrecision
|
|
183
|
+
? this.toTradePrecision()
|
|
184
|
+
: this.print();
|
|
185
|
+
return printVal.replace(/0+$/g, '').replace(/\.$/, '').replace(/,$/, '');
|
|
186
|
+
}
|
|
187
|
+
debug() {
|
|
188
|
+
console.log(`${this.toString()} | ${this.print()} | ${this.precision.toString()}`);
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Pretty print with the specified number of decimal places
|
|
192
|
+
* @param fixedPrecision
|
|
193
|
+
* @returns
|
|
194
|
+
*/
|
|
195
|
+
toFixed(fixedPrecision) {
|
|
196
|
+
const printString = this.print();
|
|
197
|
+
const [leftSide, rightSide] = printString.split(BigNum.delim);
|
|
198
|
+
const filledRightSide = [
|
|
199
|
+
...(rightSide !== null && rightSide !== void 0 ? rightSide : '').slice(0, fixedPrecision),
|
|
200
|
+
...Array(fixedPrecision).fill('0'),
|
|
201
|
+
]
|
|
202
|
+
.slice(0, fixedPrecision)
|
|
203
|
+
.join('');
|
|
204
|
+
return `${leftSide}${BigNum.delim}${filledRightSide}`;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Pretty print to the specified number of significant figures
|
|
208
|
+
* @param fixedPrecision
|
|
209
|
+
* @returns
|
|
210
|
+
*/
|
|
211
|
+
toPrecision(fixedPrecision, trailingZeroes = false) {
|
|
212
|
+
const printString = this.print();
|
|
213
|
+
let precisionPrintString = printString.slice(0, fixedPrecision + 1);
|
|
214
|
+
if (!precisionPrintString.includes(BigNum.delim) ||
|
|
215
|
+
precisionPrintString[precisionPrintString.length - 1] === BigNum.delim) {
|
|
216
|
+
precisionPrintString = printString.slice(0, fixedPrecision);
|
|
217
|
+
}
|
|
218
|
+
const pointsOfPrecision = precisionPrintString.replace(BigNum.delim, '').length;
|
|
219
|
+
if (pointsOfPrecision < fixedPrecision) {
|
|
220
|
+
precisionPrintString = [
|
|
221
|
+
...precisionPrintString.split(''),
|
|
222
|
+
...Array(fixedPrecision - pointsOfPrecision).fill('0'),
|
|
223
|
+
].join('');
|
|
224
|
+
}
|
|
225
|
+
if (!precisionPrintString.includes(BigNum.delim)) {
|
|
226
|
+
const delimFullStringLocation = printString.indexOf(BigNum.delim);
|
|
227
|
+
let skipExponent = false;
|
|
228
|
+
if (delimFullStringLocation === -1) {
|
|
229
|
+
// no decimal, not missing any precision
|
|
230
|
+
skipExponent = true;
|
|
231
|
+
}
|
|
232
|
+
if (precisionPrintString[precisionPrintString.length - 1] === BigNum.delim) {
|
|
233
|
+
// decimal is at end of string, not missing any precision, do nothing
|
|
234
|
+
skipExponent = true;
|
|
235
|
+
}
|
|
236
|
+
if (printString.indexOf(BigNum.delim) === fixedPrecision) {
|
|
237
|
+
// decimal is at end of string, not missing any precision, do nothing
|
|
238
|
+
skipExponent = true;
|
|
239
|
+
}
|
|
240
|
+
if (!skipExponent) {
|
|
241
|
+
const exponent = delimFullStringLocation - fixedPrecision;
|
|
242
|
+
if (trailingZeroes) {
|
|
243
|
+
precisionPrintString = `${precisionPrintString}${Array(exponent)
|
|
244
|
+
.fill('0')
|
|
245
|
+
.join('')}`;
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
precisionPrintString = `${precisionPrintString}e${exponent}`;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
return precisionPrintString;
|
|
253
|
+
}
|
|
254
|
+
toTradePrecision() {
|
|
255
|
+
return this.toPrecision(6, true);
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Print dollar formatted value. Defaults to fixed decimals two unless a given precision is given.
|
|
259
|
+
* @param useTradePrecision
|
|
260
|
+
* @param precisionOverride
|
|
261
|
+
* @returns
|
|
262
|
+
*/
|
|
263
|
+
toNotional(useTradePrecision, precisionOverride) {
|
|
264
|
+
const prefix = `${this.lt(BigNum.zero()) ? `-` : ``}$`;
|
|
265
|
+
const val = useTradePrecision || precisionOverride
|
|
266
|
+
? this.prettyPrint(useTradePrecision, precisionOverride)
|
|
267
|
+
: BigNum.fromPrint(this.toFixed(2), new anchor_1.BN(2)).prettyPrint();
|
|
268
|
+
return `${prefix}${val.replace('-', '')}`;
|
|
269
|
+
}
|
|
270
|
+
toMillified(precision = 3) {
|
|
271
|
+
const stringVal = this.print();
|
|
272
|
+
const [leftSide] = stringVal.split(BigNum.delim);
|
|
273
|
+
if (!leftSide) {
|
|
274
|
+
return this.shift(new anchor_1.BN(precision)).toPrecision(precision, true);
|
|
275
|
+
}
|
|
276
|
+
if (leftSide.length <= 3) {
|
|
277
|
+
return this.shift(new anchor_1.BN(precision)).toPrecision(precision, true);
|
|
278
|
+
}
|
|
279
|
+
const unitTicks = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
|
|
280
|
+
const unitNumber = Math.floor((leftSide.length - 1) / 3);
|
|
281
|
+
const unit = unitTicks[unitNumber];
|
|
282
|
+
let leadDigits = leftSide.slice(0, precision);
|
|
283
|
+
if (leadDigits.length < precision) {
|
|
284
|
+
leadDigits = [
|
|
285
|
+
...leadDigits.split(''),
|
|
286
|
+
...Array(precision - leadDigits.length).fill('0'),
|
|
287
|
+
].join('');
|
|
288
|
+
}
|
|
289
|
+
const decimalLocation = leftSide.length - 3 * unitNumber;
|
|
290
|
+
let leadString = '';
|
|
291
|
+
if (decimalLocation >= precision) {
|
|
292
|
+
leadString = `${leadDigits}`;
|
|
293
|
+
}
|
|
294
|
+
else {
|
|
295
|
+
leadString = `${leadDigits.slice(0, decimalLocation)}${BigNum.delim}${leadDigits.slice(decimalLocation)}`;
|
|
296
|
+
}
|
|
297
|
+
return `${leadString}${unit}`;
|
|
298
|
+
}
|
|
299
|
+
toJSON() {
|
|
300
|
+
return {
|
|
301
|
+
val: this.val.toString(),
|
|
302
|
+
precision: this.precision.toString(),
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
isNeg() {
|
|
306
|
+
return this.lt(numericConstants_1.ZERO, true);
|
|
307
|
+
}
|
|
308
|
+
isPos() {
|
|
309
|
+
return !this.isNeg();
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Get the numerical value of the BigNum. This can break if the BigNum is too large.
|
|
313
|
+
* @returns
|
|
314
|
+
*/
|
|
315
|
+
toNum() {
|
|
316
|
+
return parseFloat(this.print());
|
|
317
|
+
}
|
|
318
|
+
static fromJSON(json) {
|
|
319
|
+
return BigNum.from(new anchor_1.BN(json.val), new anchor_1.BN(json.precision));
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Create a BigNum instance
|
|
323
|
+
* @param val
|
|
324
|
+
* @param precision
|
|
325
|
+
* @returns
|
|
326
|
+
*/
|
|
327
|
+
static from(val = numericConstants_1.ZERO, precision) {
|
|
328
|
+
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');
|
|
329
|
+
return new BigNum(val, precision);
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Create a BigNum instance from a printed BigNum
|
|
333
|
+
* @param val
|
|
334
|
+
* @param precisionOverride
|
|
335
|
+
* @returns
|
|
336
|
+
*/
|
|
337
|
+
static fromPrint(val, precisionShift) {
|
|
338
|
+
var _a;
|
|
339
|
+
// Handle empty number edge cases
|
|
340
|
+
if (!val)
|
|
341
|
+
return BigNum.from(numericConstants_1.ZERO, precisionShift);
|
|
342
|
+
if (!val.replace(BigNum.delim, ''))
|
|
343
|
+
return BigNum.from(numericConstants_1.ZERO, precisionShift);
|
|
344
|
+
const [leftSide, rightSide] = val.split(BigNum.delim);
|
|
345
|
+
const rawBn = new anchor_1.BN(`${leftSide !== null && leftSide !== void 0 ? leftSide : ''}${rightSide !== null && rightSide !== void 0 ? rightSide : ''}`);
|
|
346
|
+
const rightSideLength = (_a = rightSide === null || rightSide === void 0 ? void 0 : rightSide.length) !== null && _a !== void 0 ? _a : 0;
|
|
347
|
+
const totalShift = precisionShift
|
|
348
|
+
? precisionShift.sub(new anchor_1.BN(rightSideLength))
|
|
349
|
+
: numericConstants_1.ZERO;
|
|
350
|
+
return BigNum.from(rawBn, precisionShift).shift(totalShift, true);
|
|
351
|
+
}
|
|
352
|
+
static max(a, b) {
|
|
353
|
+
return a.gt(b) ? a : b;
|
|
354
|
+
}
|
|
355
|
+
static min(a, b) {
|
|
356
|
+
return a.lt(b) ? a : b;
|
|
357
|
+
}
|
|
358
|
+
static zero(precision) {
|
|
359
|
+
return BigNum.from(0, precision);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
exports.BigNum = BigNum;
|
|
363
|
+
BigNum.delim = '.';
|
|
364
|
+
BigNum.spacer = ',';
|
package/src/factory/bigNum.ts
CHANGED
|
@@ -234,8 +234,14 @@ export class BigNum {
|
|
|
234
234
|
return printString;
|
|
235
235
|
}
|
|
236
236
|
|
|
237
|
-
public prettyPrint(
|
|
238
|
-
|
|
237
|
+
public prettyPrint(
|
|
238
|
+
useTradePrecision?: boolean,
|
|
239
|
+
precisionOverride?: number
|
|
240
|
+
): string {
|
|
241
|
+
const [leftSide, rightSide] = this.printShort(
|
|
242
|
+
useTradePrecision,
|
|
243
|
+
precisionOverride
|
|
244
|
+
).split(BigNum.delim);
|
|
239
245
|
|
|
240
246
|
let formattedLeftSide = leftSide;
|
|
241
247
|
|
|
@@ -374,13 +380,24 @@ export class BigNum {
|
|
|
374
380
|
return this.toPrecision(6, true);
|
|
375
381
|
}
|
|
376
382
|
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
383
|
+
/**
|
|
384
|
+
* Print dollar formatted value. Defaults to fixed decimals two unless a given precision is given.
|
|
385
|
+
* @param useTradePrecision
|
|
386
|
+
* @param precisionOverride
|
|
387
|
+
* @returns
|
|
388
|
+
*/
|
|
389
|
+
public toNotional(
|
|
390
|
+
useTradePrecision?: boolean,
|
|
391
|
+
precisionOverride?: number
|
|
392
|
+
): string {
|
|
393
|
+
const prefix = `${this.lt(BigNum.zero()) ? `-` : ``}$`;
|
|
394
|
+
|
|
395
|
+
const val =
|
|
396
|
+
useTradePrecision || precisionOverride
|
|
397
|
+
? this.prettyPrint(useTradePrecision, precisionOverride)
|
|
398
|
+
: BigNum.fromPrint(this.toFixed(2), new BN(2)).prettyPrint();
|
|
399
|
+
|
|
400
|
+
return `${prefix}${val.replace('-', '')}`;
|
|
384
401
|
}
|
|
385
402
|
|
|
386
403
|
public toMillified(precision = 3): string {
|
|
@@ -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;
|