@drift-labs/sdk 2.8.0-beta.2 → 2.8.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.
@@ -1,5 +1,4 @@
1
1
  /// <reference types="node" />
2
- /// <reference types="node" />
3
2
  import { SpotMarketAccount, PerpMarketAccount, OracleSource, StateAccount, UserAccount, UserStatsAccount } from '../types';
4
3
  import StrictEventEmitter from 'strict-event-emitter-types';
5
4
  import { EventEmitter } from 'events';
@@ -194,6 +194,8 @@ export declare class DriftClient {
194
194
  addSerumRemainingAccounts(marketIndex: number, remainingAccounts: AccountMeta[], fulfillmentConfig: SerumV3FulfillmentConfigAccount): void;
195
195
  triggerOrder(userAccountPublicKey: PublicKey, user: UserAccount, order: Order): Promise<TransactionSignature>;
196
196
  getTriggerOrderIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, order: Order): Promise<TransactionInstruction>;
197
+ forceCancelOrders(userAccountPublicKey: PublicKey, user: UserAccount): Promise<TransactionSignature>;
198
+ getForceCancelOrdersIx(userAccountPublicKey: PublicKey, userAccount: UserAccount): Promise<TransactionInstruction>;
197
199
  placeAndTakePerpOrder(orderParams: OptionalOrderParams, makerInfo?: MakerInfo, referrerInfo?: ReferrerInfo): Promise<TransactionSignature>;
198
200
  getPlaceAndTakePerpOrderIx(orderParams: OptionalOrderParams, makerInfo?: MakerInfo, referrerInfo?: ReferrerInfo): Promise<TransactionInstruction>;
199
201
  placeAndMakePerpOrder(orderParams: OptionalOrderParams, takerInfo: TakerInfo, referrerInfo?: ReferrerInfo): Promise<TransactionSignature>;
@@ -1484,6 +1484,26 @@ class DriftClient {
1484
1484
  remainingAccounts,
1485
1485
  });
1486
1486
  }
1487
+ async forceCancelOrders(userAccountPublicKey, user) {
1488
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getForceCancelOrdersIx(userAccountPublicKey, user)), [], this.opts);
1489
+ return txSig;
1490
+ }
1491
+ async getForceCancelOrdersIx(userAccountPublicKey, userAccount) {
1492
+ const fillerPublicKey = await this.getUserAccountPublicKey();
1493
+ const remainingAccounts = this.getRemainingAccounts({
1494
+ userAccounts: [userAccount],
1495
+ writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
1496
+ });
1497
+ return await this.program.instruction.forceCancelOrders({
1498
+ accounts: {
1499
+ state: await this.getStatePublicKey(),
1500
+ filler: fillerPublicKey,
1501
+ user: userAccountPublicKey,
1502
+ authority: this.wallet.publicKey,
1503
+ },
1504
+ remainingAccounts,
1505
+ });
1506
+ }
1487
1507
  async placeAndTakePerpOrder(orderParams, makerInfo, referrerInfo) {
1488
1508
  const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getPlaceAndTakePerpOrderIx(orderParams, makerInfo, referrerInfo)), [], this.opts);
1489
1509
  this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.8.0-beta.2",
2
+ "version": "2.8.0",
3
3
  "name": "drift",
4
4
  "instructions": [
5
5
  {
@@ -946,6 +946,32 @@
946
946
  }
947
947
  ]
948
948
  },
949
+ {
950
+ "name": "forceCancelOrders",
951
+ "accounts": [
952
+ {
953
+ "name": "state",
954
+ "isMut": false,
955
+ "isSigner": false
956
+ },
957
+ {
958
+ "name": "authority",
959
+ "isMut": false,
960
+ "isSigner": true
961
+ },
962
+ {
963
+ "name": "filler",
964
+ "isMut": true,
965
+ "isSigner": false
966
+ },
967
+ {
968
+ "name": "user",
969
+ "isMut": true,
970
+ "isSigner": false
971
+ }
972
+ ],
973
+ "args": []
974
+ },
949
975
  {
950
976
  "name": "settlePnl",
951
977
  "accounts": [
@@ -31,6 +31,7 @@ class UserStatsMap {
31
31
  await (0, __1.bulkPollingUserStatsSubscribe)(userStatArray, this.accountSubscription.accountLoader);
32
32
  }
33
33
  for (const userStat of userStatArray) {
34
+ await userStat.subscribe();
34
35
  this.userStatsMap.set(userStat.getAccount().authority.toString(), userStat);
35
36
  }
36
37
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/sdk",
3
- "version": "2.8.0-beta.2",
3
+ "version": "2.8.0",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "author": "crispheaney",
@@ -2470,6 +2470,40 @@ export class DriftClient {
2470
2470
  });
2471
2471
  }
2472
2472
 
2473
+ public async forceCancelOrders(
2474
+ userAccountPublicKey: PublicKey,
2475
+ user: UserAccount
2476
+ ): Promise<TransactionSignature> {
2477
+ const { txSig } = await this.txSender.send(
2478
+ wrapInTx(await this.getForceCancelOrdersIx(userAccountPublicKey, user)),
2479
+ [],
2480
+ this.opts
2481
+ );
2482
+ return txSig;
2483
+ }
2484
+
2485
+ public async getForceCancelOrdersIx(
2486
+ userAccountPublicKey: PublicKey,
2487
+ userAccount: UserAccount
2488
+ ): Promise<TransactionInstruction> {
2489
+ const fillerPublicKey = await this.getUserAccountPublicKey();
2490
+
2491
+ const remainingAccounts = this.getRemainingAccounts({
2492
+ userAccounts: [userAccount],
2493
+ writableSpotMarketIndexes: [QUOTE_SPOT_MARKET_INDEX],
2494
+ });
2495
+
2496
+ return await this.program.instruction.forceCancelOrders({
2497
+ accounts: {
2498
+ state: await this.getStatePublicKey(),
2499
+ filler: fillerPublicKey,
2500
+ user: userAccountPublicKey,
2501
+ authority: this.wallet.publicKey,
2502
+ },
2503
+ remainingAccounts,
2504
+ });
2505
+ }
2506
+
2473
2507
  public async placeAndTakePerpOrder(
2474
2508
  orderParams: OptionalOrderParams,
2475
2509
  makerInfo?: MakerInfo,
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.8.0-beta.2",
2
+ "version": "2.8.0",
3
3
  "name": "drift",
4
4
  "instructions": [
5
5
  {
@@ -946,6 +946,32 @@
946
946
  }
947
947
  ]
948
948
  },
949
+ {
950
+ "name": "forceCancelOrders",
951
+ "accounts": [
952
+ {
953
+ "name": "state",
954
+ "isMut": false,
955
+ "isSigner": false
956
+ },
957
+ {
958
+ "name": "authority",
959
+ "isMut": false,
960
+ "isSigner": true
961
+ },
962
+ {
963
+ "name": "filler",
964
+ "isMut": true,
965
+ "isSigner": false
966
+ },
967
+ {
968
+ "name": "user",
969
+ "isMut": true,
970
+ "isSigner": false
971
+ }
972
+ ],
973
+ "args": []
974
+ },
949
975
  {
950
976
  "name": "settlePnl",
951
977
  "accounts": [
@@ -68,6 +68,7 @@ export class UserStatsMap {
68
68
  }
69
69
 
70
70
  for (const userStat of userStatArray) {
71
+ await userStat.subscribe();
71
72
  this.userStatsMap.set(
72
73
  userStat.getAccount().authority.toString(),
73
74
  userStat
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.assert = void 0;
4
- function assert(condition, error) {
5
- if (!condition) {
6
- throw new Error(error || 'Unspecified AssertionError');
7
- }
8
- }
9
- exports.assert = assert;
@@ -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();
@@ -1,38 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseTokenAccount = void 0;
4
- const spl_token_1 = require("@solana/spl-token");
5
- const web3_js_1 = require("@solana/web3.js");
6
- function parseTokenAccount(data) {
7
- const accountInfo = spl_token_1.AccountLayout.decode(data);
8
- accountInfo.mint = new web3_js_1.PublicKey(accountInfo.mint);
9
- accountInfo.owner = new web3_js_1.PublicKey(accountInfo.owner);
10
- accountInfo.amount = spl_token_1.u64.fromBuffer(accountInfo.amount);
11
- if (accountInfo.delegateOption === 0) {
12
- accountInfo.delegate = null;
13
- // eslint-disable-next-line new-cap
14
- accountInfo.delegatedAmount = new spl_token_1.u64(0);
15
- }
16
- else {
17
- accountInfo.delegate = new web3_js_1.PublicKey(accountInfo.delegate);
18
- accountInfo.delegatedAmount = spl_token_1.u64.fromBuffer(accountInfo.delegatedAmount);
19
- }
20
- accountInfo.isInitialized = accountInfo.state !== 0;
21
- accountInfo.isFrozen = accountInfo.state === 2;
22
- if (accountInfo.isNativeOption === 1) {
23
- accountInfo.rentExemptReserve = spl_token_1.u64.fromBuffer(accountInfo.isNative);
24
- accountInfo.isNative = true;
25
- }
26
- else {
27
- accountInfo.rentExemptReserve = null;
28
- accountInfo.isNative = false;
29
- }
30
- if (accountInfo.closeAuthorityOption === 0) {
31
- accountInfo.closeAuthority = null;
32
- }
33
- else {
34
- accountInfo.closeAuthority = new web3_js_1.PublicKey(accountInfo.closeAuthority);
35
- }
36
- return accountInfo;
37
- }
38
- exports.parseTokenAccount = parseTokenAccount;
package/src/tx/types.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
package/src/tx/utils.js DELETED
@@ -1,17 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.wrapInTx = void 0;
4
- const web3_js_1 = require("@solana/web3.js");
5
- const COMPUTE_UNITS_DEFAULT = 200000;
6
- function wrapInTx(instruction, computeUnits = 600000 // TODO, requires less code change
7
- ) {
8
- const tx = new web3_js_1.Transaction();
9
- if (computeUnits != COMPUTE_UNITS_DEFAULT) {
10
- tx.add(web3_js_1.ComputeBudgetProgram.requestUnits({
11
- units: computeUnits,
12
- additionalFee: 0,
13
- }));
14
- }
15
- return tx.add(instruction);
16
- }
17
- exports.wrapInTx = wrapInTx;
@@ -1,27 +0,0 @@
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.findComputeUnitConsumption = void 0;
13
- function findComputeUnitConsumption(programId, connection, txSignature, commitment = 'confirmed') {
14
- return __awaiter(this, void 0, void 0, function* () {
15
- const tx = yield connection.getTransaction(txSignature, { commitment });
16
- const computeUnits = [];
17
- const regex = new RegExp(`Program ${programId.toString()} consumed ([0-9]{0,6}) of ([0-9]{0,7}) compute units`);
18
- tx.meta.logMessages.forEach((logMessage) => {
19
- const match = logMessage.match(regex);
20
- if (match && match[1]) {
21
- computeUnits.push(match[1]);
22
- }
23
- });
24
- return computeUnits;
25
- });
26
- }
27
- exports.findComputeUnitConsumption = findComputeUnitConsumption;
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getTokenAddress = void 0;
4
- const spl_token_1 = require("@solana/spl-token");
5
- const web3_js_1 = require("@solana/web3.js");
6
- const getTokenAddress = (mintAddress, userPubKey) => {
7
- return spl_token_1.Token.getAssociatedTokenAddress(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, new web3_js_1.PublicKey(mintAddress), new web3_js_1.PublicKey(userPubKey));
8
- };
9
- exports.getTokenAddress = getTokenAddress;
@@ -1,14 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.promiseTimeout = void 0;
4
- function promiseTimeout(promise, timeoutMs) {
5
- let timeoutId;
6
- const timeoutPromise = new Promise((resolve) => {
7
- timeoutId = setTimeout(() => resolve(null), timeoutMs);
8
- });
9
- return Promise.race([promise, timeoutPromise]).then((result) => {
10
- clearTimeout(timeoutId);
11
- return result;
12
- });
13
- }
14
- exports.promiseTimeout = promiseTimeout;
package/src/util/tps.js DELETED
@@ -1,27 +0,0 @@
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.estimateTps = void 0;
13
- function estimateTps(programId, connection, failed) {
14
- return __awaiter(this, void 0, void 0, function* () {
15
- let signatures = yield connection.getSignaturesForAddress(programId, undefined, 'finalized');
16
- if (failed) {
17
- signatures = signatures.filter((signature) => signature.err);
18
- }
19
- const numberOfSignatures = signatures.length;
20
- if (numberOfSignatures === 0) {
21
- return 0;
22
- }
23
- return (numberOfSignatures /
24
- (signatures[0].blockTime - signatures[numberOfSignatures - 1].blockTime));
25
- });
26
- }
27
- exports.estimateTps = estimateTps;