@drift-labs/sdk 2.12.0 → 2.13.0-beta.0

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.
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const anchor_1 = require("@project-serum/anchor");
4
+ const __1 = require("..");
5
+ const web3_js_1 = require("@solana/web3.js");
6
+ const __2 = require("..");
7
+ const env = 'mainnet-beta';
8
+ const main = async () => {
9
+ // Initialize Drift SDK
10
+ const sdkConfig = __2.initialize({ env });
11
+ // Set up the Wallet and Provider
12
+ const privateKey = process.env.BOT_PRIVATE_KEY; // stored as an array string
13
+ const keypair = web3_js_1.Keypair.fromSecretKey(Uint8Array.from(JSON.parse(privateKey)));
14
+ const wallet = new __1.Wallet(keypair);
15
+ // Set up the Connection
16
+ const rpcAddress = process.env.RPC_ADDRESS; // can use: https://api.devnet.solana.com for devnet; https://api.mainnet-beta.solana.com for mainnet;
17
+ const connection = new web3_js_1.Connection(rpcAddress);
18
+ // Set up the Provider
19
+ const provider = new anchor_1.AnchorProvider(connection, wallet, anchor_1.AnchorProvider.defaultOptions());
20
+ // Set up the Drift Clearing House
21
+ const driftPublicKey = new web3_js_1.PublicKey(sdkConfig.DRIFT_PROGRAM_ID);
22
+ const bulkAccountLoader = new __2.BulkAccountLoader(connection, 'confirmed', 1000);
23
+ const driftClient = new __2.DriftClient({
24
+ connection,
25
+ wallet: provider.wallet,
26
+ programID: driftPublicKey,
27
+ ...__2.getMarketsAndOraclesForSubscription(env),
28
+ accountSubscription: {
29
+ type: 'polling',
30
+ accountLoader: bulkAccountLoader,
31
+ },
32
+ });
33
+ console.log('Subscribing drift client...');
34
+ await driftClient.subscribe();
35
+ console.log('Loading user map...');
36
+ const userMap = new __1.UserMap(driftClient, {
37
+ type: 'polling',
38
+ accountLoader: bulkAccountLoader,
39
+ });
40
+ // fetches all users and subscribes for updates
41
+ await userMap.fetchAllUsers();
42
+ console.log('Loading dlob from user map...');
43
+ const dlob = new __1.DLOB();
44
+ await dlob.initFromUserMap(userMap);
45
+ console.log('number of orders', dlob.getDLOBOrders().length);
46
+ dlob.clear();
47
+ console.log('Unsubscribing users...');
48
+ for (const user of userMap.values()) {
49
+ await user.unsubscribe();
50
+ }
51
+ console.log('Unsubscribing drift client...');
52
+ await driftClient.unsubscribe();
53
+ };
54
+ main();
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.12.0",
2
+ "version": "2.13.0-beta.0",
3
3
  "name": "drift",
4
4
  "instructions": [
5
5
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/sdk",
3
- "version": "2.12.0",
3
+ "version": "2.13.0-beta.0",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "author": "crispheaney",
@@ -0,0 +1,82 @@
1
+ import { AnchorProvider } from '@project-serum/anchor';
2
+ import { DLOB, UserMap, Wallet } from '..';
3
+ import { Connection, Keypair, PublicKey } from '@solana/web3.js';
4
+ import {
5
+ DriftClient,
6
+ initialize,
7
+ BulkAccountLoader,
8
+ getMarketsAndOraclesForSubscription,
9
+ } from '..';
10
+
11
+ const env = 'mainnet-beta';
12
+
13
+ const main = async () => {
14
+ // Initialize Drift SDK
15
+ const sdkConfig = initialize({ env });
16
+
17
+ // Set up the Wallet and Provider
18
+ const privateKey = process.env.BOT_PRIVATE_KEY; // stored as an array string
19
+ const keypair = Keypair.fromSecretKey(
20
+ Uint8Array.from(JSON.parse(privateKey))
21
+ );
22
+ const wallet = new Wallet(keypair);
23
+
24
+ // Set up the Connection
25
+ const rpcAddress = process.env.RPC_ADDRESS; // can use: https://api.devnet.solana.com for devnet; https://api.mainnet-beta.solana.com for mainnet;
26
+ const connection = new Connection(rpcAddress);
27
+
28
+ // Set up the Provider
29
+ const provider = new AnchorProvider(
30
+ connection,
31
+ wallet,
32
+ AnchorProvider.defaultOptions()
33
+ );
34
+
35
+ // Set up the Drift Clearing House
36
+ const driftPublicKey = new PublicKey(sdkConfig.DRIFT_PROGRAM_ID);
37
+ const bulkAccountLoader = new BulkAccountLoader(
38
+ connection,
39
+ 'confirmed',
40
+ 1000
41
+ );
42
+ const driftClient = new DriftClient({
43
+ connection,
44
+ wallet: provider.wallet,
45
+ programID: driftPublicKey,
46
+ ...getMarketsAndOraclesForSubscription(env),
47
+ accountSubscription: {
48
+ type: 'polling',
49
+ accountLoader: bulkAccountLoader,
50
+ },
51
+ });
52
+
53
+ console.log('Subscribing drift client...');
54
+ await driftClient.subscribe();
55
+
56
+ console.log('Loading user map...');
57
+ const userMap = new UserMap(driftClient, {
58
+ type: 'polling',
59
+ accountLoader: bulkAccountLoader,
60
+ });
61
+
62
+ // fetches all users and subscribes for updates
63
+ await userMap.fetchAllUsers();
64
+
65
+ console.log('Loading dlob from user map...');
66
+ const dlob = new DLOB();
67
+ await dlob.initFromUserMap(userMap);
68
+
69
+ console.log('number of orders', dlob.getDLOBOrders().length);
70
+
71
+ dlob.clear();
72
+
73
+ console.log('Unsubscribing users...');
74
+ for (const user of userMap.values()) {
75
+ await user.unsubscribe();
76
+ }
77
+
78
+ console.log('Unsubscribing drift client...');
79
+ await driftClient.unsubscribe();
80
+ };
81
+
82
+ main();
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.12.0",
2
+ "version": "2.13.0-beta.0",
3
3
  "name": "drift",
4
4
  "instructions": [
5
5
  {
@@ -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.DRIFT_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();