@drift-labs/sdk 0.2.0-master.3 → 0.2.0-master.31
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 +13 -13
- package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
- package/lib/accounts/bulkUserStatsSubscription.js +21 -0
- 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 +16 -16
- package/lib/accounts/pollingClearingHouseAccountSubscriber.js +31 -28
- package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
- package/lib/accounts/pollingUserStatsAccountSubscriber.js +113 -0
- package/lib/accounts/types.d.ts +22 -11
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +17 -17
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +37 -35
- 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/pda.d.ts +10 -4
- package/lib/addresses/pda.js +51 -14
- package/lib/admin.d.ts +42 -26
- package/lib/admin.js +228 -81
- package/lib/clearingHouse.d.ts +130 -49
- package/lib/clearingHouse.js +1256 -367
- package/lib/clearingHouseConfig.d.ts +4 -4
- package/lib/clearingHouseUser.d.ts +51 -39
- package/lib/clearingHouseUser.js +408 -191
- package/lib/clearingHouseUserStats.d.ts +18 -0
- package/lib/clearingHouseUserStats.js +49 -0
- package/lib/clearingHouseUserStatsConfig.d.ts +14 -0
- package/lib/clearingHouseUserStatsConfig.js +2 -0
- package/lib/config.d.ts +7 -9
- package/lib/config.js +21 -21
- package/lib/constants/numericConstants.d.ts +25 -12
- package/lib/constants/numericConstants.js +35 -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 +74 -0
- package/lib/dlob/DLOB.js +595 -0
- package/lib/dlob/DLOBNode.d.ts +54 -0
- package/lib/dlob/DLOBNode.js +85 -0
- package/lib/dlob/NodeList.d.ts +26 -0
- package/lib/dlob/NodeList.js +139 -0
- package/lib/events/eventList.js +3 -0
- package/lib/events/eventSubscriber.d.ts +4 -2
- package/lib/events/eventSubscriber.js +16 -9
- package/lib/events/fetchLogs.d.ts +10 -1
- package/lib/events/fetchLogs.js +27 -7
- package/lib/events/pollingLogProvider.d.ts +2 -1
- package/lib/events/pollingLogProvider.js +6 -2
- package/lib/events/sort.js +8 -11
- package/lib/events/types.d.ts +8 -2
- package/lib/events/types.js +6 -0
- package/lib/examples/makeTradeExample.js +20 -8
- package/lib/factory/bigNum.d.ts +2 -0
- package/lib/factory/bigNum.js +48 -10
- package/lib/idl/clearing_house.json +4889 -1529
- package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
- package/lib/index.d.ts +21 -6
- package/lib/index.js +25 -6
- package/lib/math/amm.d.ts +9 -6
- package/lib/math/amm.js +91 -66
- package/lib/math/auction.js +4 -1
- package/lib/math/conversion.js +1 -1
- package/lib/math/funding.d.ts +6 -6
- package/lib/math/funding.js +11 -10
- 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 +77 -0
- package/lib/math/market.d.ts +14 -9
- package/lib/math/market.js +72 -10
- package/lib/math/oracles.d.ts +4 -0
- package/lib/math/oracles.js +36 -8
- package/lib/math/orders.d.ts +6 -2
- package/lib/math/orders.js +78 -3
- package/lib/math/position.d.ts +21 -13
- package/lib/math/position.js +76 -36
- package/lib/math/repeg.js +14 -5
- 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 +32 -39
- 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 +14 -5
- package/lib/orderParams.js +12 -92
- package/lib/serum/serumSubscriber.d.ts +23 -0
- package/lib/serum/serumSubscriber.js +41 -0
- package/lib/serum/types.d.ts +11 -0
- package/lib/serum/types.js +2 -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 +566 -138
- package/lib/types.js +129 -5
- package/lib/userMap/userMap.d.ts +25 -0
- package/lib/userMap/userMap.js +73 -0
- package/lib/userMap/userStatsMap.d.ts +19 -0
- package/lib/userMap/userStatsMap.js +68 -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 +12 -6
- package/src/accounts/bulkUserStatsSubscription.ts +33 -0
- package/src/accounts/bulkUserSubscription.ts +0 -1
- package/src/accounts/fetch.ts +27 -2
- package/src/accounts/pollingClearingHouseAccountSubscriber.ts +46 -42
- package/src/accounts/pollingUserStatsAccountSubscriber.ts +172 -0
- package/src/accounts/types.ts +31 -11
- package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +64 -59
- package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
- package/src/addresses/marketAddresses.ts +1 -2
- package/src/addresses/pda.ts +88 -14
- package/src/admin.ts +452 -147
- package/src/assert/assert.js +9 -0
- package/src/clearingHouse.ts +2066 -467
- package/src/clearingHouseConfig.ts +4 -3
- package/src/clearingHouseUser.ts +747 -294
- package/src/clearingHouseUserStats.ts +75 -0
- package/src/clearingHouseUserStatsConfig.ts +18 -0
- package/src/config.ts +30 -31
- package/src/constants/numericConstants.ts +48 -25
- package/src/constants/{markets.ts → perpMarkets.ts} +10 -10
- package/src/constants/spotMarkets.ts +73 -0
- package/src/dlob/DLOB.ts +953 -0
- package/src/dlob/DLOBNode.ts +167 -0
- package/src/dlob/NodeList.ts +189 -0
- package/src/events/eventList.js +77 -0
- package/src/events/eventList.ts +3 -0
- package/src/events/eventSubscriber.ts +20 -12
- package/src/events/fetchLogs.ts +35 -8
- package/src/events/pollingLogProvider.ts +10 -2
- package/src/events/sort.ts +11 -15
- package/src/events/types.ts +19 -1
- package/src/examples/makeTradeExample.js +157 -0
- package/src/examples/makeTradeExample.ts +32 -14
- package/src/factory/bigNum.ts +65 -13
- package/src/idl/clearing_house.json +4889 -1529
- package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
- package/src/index.ts +21 -6
- package/src/math/amm.ts +171 -88
- package/src/math/auction.ts +5 -1
- package/src/math/conversion.ts +2 -2
- package/src/math/funding.ts +20 -18
- package/src/math/insurance.ts +35 -0
- package/src/math/margin.ts +127 -0
- package/src/math/market.ts +145 -14
- package/src/math/oracles.ts +63 -9
- package/src/math/orders.ts +138 -4
- package/src/math/position.ts +119 -58
- package/src/math/repeg.ts +16 -6
- 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 +53 -59
- 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 +24 -137
- package/src/serum/serumSubscriber.ts +80 -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 +533 -140
- package/src/userMap/userMap.ts +100 -0
- package/src/userMap/userStatsMap.ts +110 -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 +24 -10
- package/tests/dlob/helpers.ts +397 -0
- package/tests/dlob/test.ts +3688 -0
- 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/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/constants/banks.ts +0 -43
- 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
package/src/events/types.ts
CHANGED
|
@@ -4,7 +4,13 @@ import {
|
|
|
4
4
|
FundingPaymentRecord,
|
|
5
5
|
FundingRateRecord,
|
|
6
6
|
LiquidationRecord,
|
|
7
|
+
NewUserRecord,
|
|
8
|
+
OrderActionRecord,
|
|
7
9
|
OrderRecord,
|
|
10
|
+
SettlePnlRecord,
|
|
11
|
+
LPRecord,
|
|
12
|
+
InsuranceFundRecord,
|
|
13
|
+
SpotInterestRecord,
|
|
8
14
|
} from '../index';
|
|
9
15
|
|
|
10
16
|
export type EventSubscriptionOptions = {
|
|
@@ -26,7 +32,13 @@ export const DefaultEventSubscriptionOptions: EventSubscriptionOptions = {
|
|
|
26
32
|
'FundingPaymentRecord',
|
|
27
33
|
'LiquidationRecord',
|
|
28
34
|
'OrderRecord',
|
|
35
|
+
'OrderActionRecord',
|
|
29
36
|
'FundingRateRecord',
|
|
37
|
+
'NewUserRecord',
|
|
38
|
+
'SettlePnlRecord',
|
|
39
|
+
'LPRecord',
|
|
40
|
+
'InsuranceFundRecord',
|
|
41
|
+
'SpotInterestRecord',
|
|
30
42
|
],
|
|
31
43
|
maxEventsPerType: 4096,
|
|
32
44
|
orderBy: 'blockchain',
|
|
@@ -59,6 +71,12 @@ export type EventMap = {
|
|
|
59
71
|
LiquidationRecord: Event<LiquidationRecord>;
|
|
60
72
|
FundingRateRecord: Event<FundingRateRecord>;
|
|
61
73
|
OrderRecord: Event<OrderRecord>;
|
|
74
|
+
OrderActionRecord: Event<OrderActionRecord>;
|
|
75
|
+
SettlePnlRecord: Event<SettlePnlRecord>;
|
|
76
|
+
NewUserRecord: Event<NewUserRecord>;
|
|
77
|
+
LPRecord: Event<LPRecord>;
|
|
78
|
+
InsuranceFundRecord: Event<InsuranceFundRecord>;
|
|
79
|
+
SpotInterestRecord: Event<SpotInterestRecord>;
|
|
62
80
|
};
|
|
63
81
|
|
|
64
82
|
export type EventType = keyof EventMap;
|
|
@@ -80,7 +98,7 @@ export type logProviderCallback = (
|
|
|
80
98
|
|
|
81
99
|
export interface LogProvider {
|
|
82
100
|
isSubscribed(): boolean;
|
|
83
|
-
subscribe(callback: logProviderCallback): boolean;
|
|
101
|
+
subscribe(callback: logProviderCallback, skipHistory?: boolean): boolean;
|
|
84
102
|
unsubscribe(): Promise<boolean>;
|
|
85
103
|
}
|
|
86
104
|
|
|
@@ -0,0 +1,157 @@
|
|
|
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.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.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();
|
|
@@ -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
|
-
|
|
6
|
+
calculateReservePrice,
|
|
7
7
|
ClearingHouse,
|
|
8
8
|
ClearingHouseUser,
|
|
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
|
|
@@ -63,10 +67,23 @@ const main = async () => {
|
|
|
63
67
|
const clearingHousePublicKey = new PublicKey(
|
|
64
68
|
sdkConfig.CLEARING_HOUSE_PROGRAM_ID
|
|
65
69
|
);
|
|
70
|
+
const bulkAccountLoader = new BulkAccountLoader(
|
|
71
|
+
connection,
|
|
72
|
+
'confirmed',
|
|
73
|
+
1000
|
|
74
|
+
);
|
|
66
75
|
const clearingHouse = new ClearingHouse({
|
|
67
76
|
connection,
|
|
68
77
|
wallet: provider.wallet,
|
|
69
78
|
programID: clearingHousePublicKey,
|
|
79
|
+
perpMarketIndexes: PerpMarkets[cluster].map((market) => market.marketIndex),
|
|
80
|
+
spotMarketIndexes: SpotMarkets[cluster].map(
|
|
81
|
+
(spotMarket) => spotMarket.marketIndex
|
|
82
|
+
),
|
|
83
|
+
accountSubscription: {
|
|
84
|
+
type: 'polling',
|
|
85
|
+
accountLoader: bulkAccountLoader,
|
|
86
|
+
},
|
|
70
87
|
});
|
|
71
88
|
await clearingHouse.subscribe();
|
|
72
89
|
|
|
@@ -74,6 +91,10 @@ const main = async () => {
|
|
|
74
91
|
const user = new ClearingHouseUser({
|
|
75
92
|
clearingHouse,
|
|
76
93
|
userAccountPublicKey: await clearingHouse.getUserAccountPublicKey(),
|
|
94
|
+
accountSubscription: {
|
|
95
|
+
type: 'polling',
|
|
96
|
+
accountLoader: bulkAccountLoader,
|
|
97
|
+
},
|
|
77
98
|
});
|
|
78
99
|
|
|
79
100
|
//// Check if clearing house account exists for the current wallet
|
|
@@ -88,31 +109,28 @@ const main = async () => {
|
|
|
88
109
|
usdcTokenAddress.toString(),
|
|
89
110
|
wallet.publicKey.toString()
|
|
90
111
|
),
|
|
91
|
-
|
|
112
|
+
SpotMarkets['devnet'][0].marketIndex
|
|
92
113
|
);
|
|
93
114
|
}
|
|
94
115
|
|
|
95
116
|
await user.subscribe();
|
|
96
117
|
|
|
97
118
|
// Get current price
|
|
98
|
-
const solMarketInfo = sdkConfig.
|
|
119
|
+
const solMarketInfo = sdkConfig.PERP_MARKETS.find(
|
|
99
120
|
(market) => market.baseAssetSymbol === 'SOL'
|
|
100
121
|
);
|
|
101
122
|
|
|
102
|
-
const currentMarketPrice =
|
|
103
|
-
clearingHouse.
|
|
123
|
+
const currentMarketPrice = calculateReservePrice(
|
|
124
|
+
clearingHouse.getPerpMarketAccount(solMarketInfo.marketIndex),
|
|
104
125
|
undefined
|
|
105
126
|
);
|
|
106
127
|
|
|
107
|
-
const formattedPrice = convertToNumber(
|
|
108
|
-
currentMarketPrice,
|
|
109
|
-
MARK_PRICE_PRECISION
|
|
110
|
-
);
|
|
128
|
+
const formattedPrice = convertToNumber(currentMarketPrice, PRICE_PRECISION);
|
|
111
129
|
|
|
112
130
|
console.log(`Current Market Price is $${formattedPrice}`);
|
|
113
131
|
|
|
114
132
|
// Estimate the slippage for a $5000 LONG trade
|
|
115
|
-
const solMarketAccount = clearingHouse.
|
|
133
|
+
const solMarketAccount = clearingHouse.getPerpMarketAccount(
|
|
116
134
|
solMarketInfo.marketIndex
|
|
117
135
|
);
|
|
118
136
|
|
|
@@ -125,7 +143,7 @@ const main = async () => {
|
|
|
125
143
|
'quote',
|
|
126
144
|
undefined
|
|
127
145
|
)[0],
|
|
128
|
-
|
|
146
|
+
PRICE_PRECISION
|
|
129
147
|
);
|
|
130
148
|
|
|
131
149
|
console.log(
|
package/src/factory/bigNum.ts
CHANGED
|
@@ -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 =
|
|
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
|
|
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
|
|
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 =
|
|
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 =
|
|
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 =
|
|
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 =
|
|
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 =
|
|
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
|
|
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);
|
|
@@ -281,6 +290,8 @@ export class BigNum {
|
|
|
281
290
|
? this.toTradePrecision()
|
|
282
291
|
: this.print();
|
|
283
292
|
|
|
293
|
+
if (!printVal.includes(BigNum.delim)) return printVal;
|
|
294
|
+
|
|
284
295
|
return printVal.replace(/0+$/g, '').replace(/\.$/, '').replace(/,$/, '');
|
|
285
296
|
}
|
|
286
297
|
|
|
@@ -310,6 +321,10 @@ export class BigNum {
|
|
|
310
321
|
return `${leftSide}${BigNum.delim}${filledRightSide}`;
|
|
311
322
|
}
|
|
312
323
|
|
|
324
|
+
private getZeroes(count: number) {
|
|
325
|
+
return new Array(count).fill('0').join('');
|
|
326
|
+
}
|
|
327
|
+
|
|
313
328
|
/**
|
|
314
329
|
* Pretty print to the specified number of significant figures
|
|
315
330
|
* @param fixedPrecision
|
|
@@ -320,6 +335,19 @@ export class BigNum {
|
|
|
320
335
|
|
|
321
336
|
let precisionPrintString = printString.slice(0, fixedPrecision + 1);
|
|
322
337
|
|
|
338
|
+
const thisString = this.toString();
|
|
339
|
+
|
|
340
|
+
if (
|
|
341
|
+
!printString.includes(BigNum.delim) &&
|
|
342
|
+
thisString.length < fixedPrecision
|
|
343
|
+
) {
|
|
344
|
+
const precisionMismatch = fixedPrecision - thisString.length;
|
|
345
|
+
return BigNum.from(
|
|
346
|
+
thisString + this.getZeroes(precisionMismatch),
|
|
347
|
+
precisionMismatch
|
|
348
|
+
).toPrecision(fixedPrecision, trailingZeroes);
|
|
349
|
+
}
|
|
350
|
+
|
|
323
351
|
if (
|
|
324
352
|
!precisionPrintString.includes(BigNum.delim) ||
|
|
325
353
|
precisionPrintString[precisionPrintString.length - 1] === BigNum.delim
|
|
@@ -392,10 +420,30 @@ export class BigNum {
|
|
|
392
420
|
): string {
|
|
393
421
|
const prefix = `${this.lt(BigNum.zero()) ? `-` : ``}$`;
|
|
394
422
|
|
|
395
|
-
const
|
|
396
|
-
useTradePrecision || precisionOverride
|
|
397
|
-
|
|
398
|
-
|
|
423
|
+
const usingCustomPrecision =
|
|
424
|
+
true && (useTradePrecision || precisionOverride);
|
|
425
|
+
|
|
426
|
+
let val = usingCustomPrecision
|
|
427
|
+
? this.prettyPrint(useTradePrecision, precisionOverride)
|
|
428
|
+
: BigNum.fromPrint(this.toFixed(2), new BN(2)).prettyPrint();
|
|
429
|
+
|
|
430
|
+
// Append two trailing zeroes if not using custom precision
|
|
431
|
+
if (!usingCustomPrecision) {
|
|
432
|
+
const [_, rightSide] = val.split(BigNum.delim);
|
|
433
|
+
|
|
434
|
+
const trailingLength = rightSide?.length ?? 0;
|
|
435
|
+
|
|
436
|
+
if (trailingLength < 2) {
|
|
437
|
+
const numHasDecimals = this.print().includes(BigNum.delim);
|
|
438
|
+
|
|
439
|
+
// Handle case where pretty print won't include the decimal point
|
|
440
|
+
if (trailingLength === 0 && numHasDecimals) {
|
|
441
|
+
val = `${val}.00`;
|
|
442
|
+
} else {
|
|
443
|
+
val = `${val}${new Array(2 - trailingLength).fill('0').join('')}`;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|
|
399
447
|
|
|
400
448
|
return `${prefix}${val.replace('-', '')}`;
|
|
401
449
|
}
|
|
@@ -409,6 +457,10 @@ export class BigNum {
|
|
|
409
457
|
return this.shift(new BN(precision)).toPrecision(precision, true);
|
|
410
458
|
}
|
|
411
459
|
|
|
460
|
+
if (leftSide.length <= precision) {
|
|
461
|
+
return this.toPrecision(precision);
|
|
462
|
+
}
|
|
463
|
+
|
|
412
464
|
if (leftSide.length <= 3) {
|
|
413
465
|
return this.shift(new BN(precision)).toPrecision(precision, true);
|
|
414
466
|
}
|