@drift-labs/sdk 2.96.0-beta.1 → 2.96.0-beta.10

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.
Files changed (82) hide show
  1. package/VERSION +1 -1
  2. package/lib/accounts/types.d.ts +0 -8
  3. package/lib/accounts/webSocketAccountSubscriber.d.ts +1 -1
  4. package/lib/accounts/webSocketDriftClientAccountSubscriber.d.ts +3 -3
  5. package/lib/accounts/webSocketProgramAccountSubscriber.d.ts +1 -1
  6. package/lib/constants/perpMarkets.js +10 -0
  7. package/lib/constants/spotMarkets.js +2 -1
  8. package/lib/driftClient.d.ts +42 -2
  9. package/lib/driftClient.js +139 -42
  10. package/lib/driftClientConfig.d.ts +0 -6
  11. package/lib/events/eventSubscriber.d.ts +7 -0
  12. package/lib/events/eventSubscriber.js +69 -31
  13. package/lib/events/eventsServerLogProvider.d.ts +21 -0
  14. package/lib/events/eventsServerLogProvider.js +121 -0
  15. package/lib/events/pollingLogProvider.js +1 -1
  16. package/lib/events/types.d.ts +12 -5
  17. package/lib/events/types.js +5 -1
  18. package/lib/events/webSocketLogProvider.js +2 -2
  19. package/lib/idl/drift.json +104 -0
  20. package/lib/math/margin.d.ts +16 -1
  21. package/lib/math/margin.js +67 -1
  22. package/lib/orderParams.js +8 -8
  23. package/lib/orderSubscriber/OrderSubscriber.d.ts +1 -2
  24. package/lib/orderSubscriber/OrderSubscriber.js +4 -19
  25. package/lib/orderSubscriber/types.d.ts +0 -9
  26. package/lib/types.d.ts +10 -1
  27. package/lib/user.d.ts +4 -1
  28. package/lib/user.js +13 -13
  29. package/lib/userConfig.d.ts +1 -6
  30. package/lib/userMap/userMap.js +0 -14
  31. package/lib/userMap/userMapConfig.d.ts +0 -7
  32. package/lib/userStatsConfig.d.ts +0 -6
  33. package/package.json +2 -4
  34. package/src/accounts/types.ts +0 -9
  35. package/src/accounts/webSocketAccountSubscriber.ts +1 -1
  36. package/src/accounts/webSocketDriftClientAccountSubscriber.ts +3 -3
  37. package/src/accounts/webSocketProgramAccountSubscriber.ts +1 -1
  38. package/src/constants/perpMarkets.ts +10 -0
  39. package/src/constants/spotMarkets.ts +3 -1
  40. package/src/driftClient.ts +309 -39
  41. package/src/driftClientConfig.ts +0 -7
  42. package/src/events/eventSubscriber.ts +132 -54
  43. package/src/events/eventsServerLogProvider.ts +152 -0
  44. package/src/events/pollingLogProvider.ts +1 -1
  45. package/src/events/types.ts +29 -6
  46. package/src/events/webSocketLogProvider.ts +4 -4
  47. package/src/idl/drift.json +104 -0
  48. package/src/math/margin.ts +137 -1
  49. package/src/orderParams.ts +20 -12
  50. package/src/orderSubscriber/OrderSubscriber.ts +1 -15
  51. package/src/orderSubscriber/types.ts +0 -10
  52. package/src/types.ts +16 -1
  53. package/src/user.ts +35 -13
  54. package/src/userConfig.ts +1 -7
  55. package/src/userMap/userMap.ts +1 -17
  56. package/src/userMap/userMapConfig.ts +0 -8
  57. package/src/userStatsConfig.ts +0 -7
  58. package/tests/ci/idl.ts +12 -3
  59. package/lib/accounts/grpcAccountSubscriber.d.ts +0 -16
  60. package/lib/accounts/grpcAccountSubscriber.js +0 -155
  61. package/lib/accounts/grpcDriftClientAccountSubscriber.d.ts +0 -13
  62. package/lib/accounts/grpcDriftClientAccountSubscriber.js +0 -96
  63. package/lib/accounts/grpcInsuranceFundStakeAccountSubscriber.d.ts +0 -10
  64. package/lib/accounts/grpcInsuranceFundStakeAccountSubscriber.js +0 -30
  65. package/lib/accounts/grpcProgramAccountSubscriber.d.ts +0 -19
  66. package/lib/accounts/grpcProgramAccountSubscriber.js +0 -161
  67. package/lib/accounts/grpcUserAccountSubscriber.d.ts +0 -10
  68. package/lib/accounts/grpcUserAccountSubscriber.js +0 -28
  69. package/lib/accounts/grpcUserStatsAccountSubscriber.d.ts +0 -10
  70. package/lib/accounts/grpcUserStatsAccountSubscriber.js +0 -28
  71. package/lib/orderSubscriber/grpcSubscription.d.ts +0 -25
  72. package/lib/orderSubscriber/grpcSubscription.js +0 -68
  73. package/lib/userMap/grpcSubscription.d.ts +0 -26
  74. package/lib/userMap/grpcSubscription.js +0 -42
  75. package/src/accounts/grpcAccountSubscriber.ts +0 -158
  76. package/src/accounts/grpcDriftClientAccountSubscriber.ts +0 -196
  77. package/src/accounts/grpcInsuranceFundStakeAccountSubscriber.ts +0 -62
  78. package/src/accounts/grpcProgramAccountSubscriber.ts +0 -181
  79. package/src/accounts/grpcUserAccountSubscriber.ts +0 -48
  80. package/src/accounts/grpcUserStatsAccountSubscriber.ts +0 -51
  81. package/src/orderSubscriber/grpcSubscription.ts +0 -126
  82. package/src/userMap/grpcSubscription.ts +0 -83
package/VERSION CHANGED
@@ -1 +1 @@
1
- 2.96.0-beta.1
1
+ 2.96.0-beta.10
@@ -6,8 +6,6 @@ import { EventEmitter } from 'events';
6
6
  import { Context, PublicKey } from '@solana/web3.js';
7
7
  import { Account } from '@solana/spl-token';
8
8
  import { OracleInfo, OraclePriceData } from '..';
9
- import { CommitmentLevel } from '@triton-one/yellowstone-grpc';
10
- import { ChannelOptions } from '@grpc/grpc-js';
11
9
  export interface AccountSubscriber<T> {
12
10
  dataAndSlot?: DataAndSlot<T>;
13
11
  subscribe(onChange: (data: T) => void): Promise<void>;
@@ -142,9 +140,3 @@ export interface UserStatsAccountSubscriber {
142
140
  unsubscribe(): Promise<void>;
143
141
  getUserStatsAccountAndSlot(): DataAndSlot<UserStatsAccount>;
144
142
  }
145
- export type GrpcConfigs = {
146
- endpoint: string;
147
- token: string;
148
- commitmentLevel?: CommitmentLevel;
149
- channelOptions?: ChannelOptions;
150
- };
@@ -20,7 +20,7 @@ export declare class WebSocketAccountSubscriber<T> implements AccountSubscriber<
20
20
  constructor(accountName: string, program: Program, accountPublicKey: PublicKey, decodeBuffer?: (buffer: Buffer) => T, resubOpts?: ResubOpts, commitment?: Commitment);
21
21
  subscribe(onChange: (data: T) => void): Promise<void>;
22
22
  setData(data: T, slot?: number): void;
23
- protected setTimeout(): void;
23
+ private setTimeout;
24
24
  fetch(): Promise<void>;
25
25
  handleRpcResponse(context: Context, accountInfo?: AccountInfo<Buffer>): void;
26
26
  decodeBuffer(buffer: Buffer): T;
@@ -30,9 +30,9 @@ export declare class WebSocketDriftClientAccountSubscriber implements DriftClien
30
30
  initialPerpMarketAccountData: Map<number, PerpMarketAccount>;
31
31
  initialSpotMarketAccountData: Map<number, SpotMarketAccount>;
32
32
  initialOraclePriceData: Map<string, OraclePriceData>;
33
- protected isSubscribing: boolean;
34
- protected subscriptionPromise: Promise<boolean>;
35
- protected subscriptionPromiseResolver: (val: boolean) => void;
33
+ private isSubscribing;
34
+ private subscriptionPromise;
35
+ private subscriptionPromiseResolver;
36
36
  constructor(program: Program, perpMarketIndexes: number[], spotMarketIndexes: number[], oracleInfos: OracleInfo[], shouldFindAllMarketsAndOracles: boolean, resubOpts?: ResubOpts, commitment?: Commitment);
37
37
  subscribe(): Promise<boolean>;
38
38
  setInitialData(): Promise<void>;
@@ -27,7 +27,7 @@ export declare class WebSocketProgramAccountSubscriber<T> implements ProgramAcco
27
27
  commitment?: Commitment;
28
28
  }, resubOpts?: ResubOpts);
29
29
  subscribe(onChange: (accountId: PublicKey, data: T, context: Context, buffer: Buffer) => void): Promise<void>;
30
- protected setTimeout(): void;
30
+ private setTimeout;
31
31
  handleRpcResponse(context: Context, keyedAccountInfo: KeyedAccountInfo): void;
32
32
  unsubscribe(onResub?: boolean): Promise<void>;
33
33
  }
@@ -778,6 +778,16 @@ exports.MainnetPerpMarkets = [
778
778
  oracleSource: __1.OracleSource.PYTH_PULL,
779
779
  pythFeedId: '0x8963217838ab4cf5cadc172203c1f0b763fbaa45f346d8ee50ba994bbcac3026',
780
780
  },
781
+ {
782
+ fullName: 'LANDO-F1-SGP-WIN-BET',
783
+ category: ['Prediction', 'Sports'],
784
+ symbol: 'LANDO-F1-SGP-WIN-BET',
785
+ baseAssetSymbol: 'LANDO-F1-SGP-WIN',
786
+ marketIndex: 43,
787
+ oracle: new web3_js_1.PublicKey('DpJz7rjTJLxxnuqrqZTUjMWtnaMFAEfZUv5ATdb9HTh1'),
788
+ launchTs: 1726646453000,
789
+ oracleSource: __1.OracleSource.Prelaunch,
790
+ },
781
791
  ];
782
792
  exports.PerpMarkets = {
783
793
  devnet: exports.DevnetPerpMarkets,
@@ -94,7 +94,7 @@ exports.MainnetSpotMarkets = [
94
94
  precision: new __1.BN(10).pow(numericConstants_1.EIGHT),
95
95
  precisionExp: numericConstants_1.EIGHT,
96
96
  serumMarket: new web3_js_1.PublicKey('3BAKsQd3RuhZKES2DGysMhjBdwjZYKYmxRqnSMtZ4KSN'),
97
- pythFeedId: '0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43',
97
+ pythFeedId: '0xc9d8b075a5c69303365ae23633d4e085199bf5c520a3b90fed1322a0342ffc33',
98
98
  },
99
99
  {
100
100
  symbol: 'wETH',
@@ -280,6 +280,7 @@ exports.MainnetSpotMarkets = [
280
280
  precision: new __1.BN(10).pow(numericConstants_1.SIX),
281
281
  precisionExp: numericConstants_1.SIX,
282
282
  launchTs: 1719415157000,
283
+ pythFeedId: '0xc811abc82b4bad1f9bd711a2773ccaa935b03ecef974236942cec5e0eb845a3a',
283
284
  },
284
285
  {
285
286
  symbol: 'POPCAT',
@@ -3,7 +3,7 @@
3
3
  /// <reference types="node" />
4
4
  import { AnchorProvider, BN, Program, ProgramAccount } from '@coral-xyz/anchor';
5
5
  import { Idl as Idl30, Program as Program30 } from '@coral-xyz/anchor-30';
6
- import { StateAccount, IWallet, PositionDirection, UserAccount, PerpMarketAccount, OrderParams, Order, SpotMarketAccount, SpotPosition, MakerInfo, TakerInfo, OptionalOrderParams, ReferrerInfo, MarketType, TxParams, SerumV3FulfillmentConfigAccount, ReferrerNameAccount, OrderTriggerCondition, PerpMarketExtendedInfo, UserStatsAccount, PhoenixV1FulfillmentConfigAccount, ModifyOrderPolicy, SwapReduceOnly, SettlePnlMode, SignedTxData, MappedRecord, OpenbookV2FulfillmentConfigAccount } from './types';
6
+ import { StateAccount, IWallet, PositionDirection, UserAccount, PerpMarketAccount, OrderParams, Order, SpotMarketAccount, SpotPosition, MakerInfo, TakerInfo, OptionalOrderParams, ReferrerInfo, MarketType, TxParams, SerumV3FulfillmentConfigAccount, ReferrerNameAccount, OrderTriggerCondition, PerpMarketExtendedInfo, UserStatsAccount, PhoenixV1FulfillmentConfigAccount, ModifyOrderPolicy, SwapReduceOnly, SettlePnlMode, SignedTxData, MappedRecord, OpenbookV2FulfillmentConfigAccount, SwiftOrderParamsMessage } from './types';
7
7
  import * as anchor from '@coral-xyz/anchor';
8
8
  import { Connection, PublicKey, TransactionSignature, ConfirmOptions, Transaction, TransactionInstruction, AccountMeta, Signer, AddressLookupTableAccount, TransactionVersion, VersionedTransaction, BlockhashWithExpiryBlockHeight } from '@solana/web3.js';
9
9
  import { TokenFaucet } from './tokenFaucet';
@@ -239,6 +239,7 @@ export declare class DriftClient {
239
239
  */
240
240
  getAssociatedTokenAccount(marketIndex: number, useNative?: boolean, tokenProgram?: anchor.web3.PublicKey): Promise<PublicKey>;
241
241
  createAssociatedTokenAccountIdempotentInstruction(account: PublicKey, payer: PublicKey, owner: PublicKey, mint: PublicKey, tokenProgram?: anchor.web3.PublicKey): TransactionInstruction;
242
+ getDepositTxnIx(amount: BN, marketIndex: number, associatedTokenAccount: PublicKey, subAccountId?: number, reduceOnly?: boolean): Promise<TransactionInstruction[]>;
242
243
  createDepositTxn(amount: BN, marketIndex: number, associatedTokenAccount: PublicKey, subAccountId?: number, reduceOnly?: boolean, txParams?: TxParams): Promise<VersionedTransaction | Transaction>;
243
244
  /**
244
245
  * Deposit funds into the given spot market
@@ -261,6 +262,10 @@ export declare class DriftClient {
261
262
  getTokenProgramForSpotMarket(spotMarketAccount: SpotMarketAccount): PublicKey;
262
263
  addTokenMintToRemainingAccounts(spotMarketAccount: SpotMarketAccount, remainingAccounts: AccountMeta[]): void;
263
264
  getAssociatedTokenAccountCreationIx(tokenMintAddress: PublicKey, associatedTokenAddress: PublicKey, tokenProgram: PublicKey): anchor.web3.TransactionInstruction;
265
+ createInitializeUserAccountAndDepositCollateralIxs(amount: BN, userTokenAccount: PublicKey, marketIndex?: number, subAccountId?: number, name?: string, fromSubAccountId?: number, referrerInfo?: ReferrerInfo, donateAmount?: BN, customMaxMarginRatio?: number): Promise<{
266
+ ixs: TransactionInstruction[];
267
+ userAccountPublicKey: PublicKey;
268
+ }>;
264
269
  createInitializeUserAccountAndDepositCollateral(amount: BN, userTokenAccount: PublicKey, marketIndex?: number, subAccountId?: number, name?: string, fromSubAccountId?: number, referrerInfo?: ReferrerInfo, donateAmount?: BN, txParams?: TxParams, customMaxMarginRatio?: number): Promise<[Transaction | VersionedTransaction, PublicKey]>;
265
270
  /**
266
271
  * Creates the User account for a user, and deposits some initial collateral
@@ -340,7 +345,10 @@ export declare class DriftClient {
340
345
  signedSettlePnlTx?: Transaction;
341
346
  }>;
342
347
  placePerpOrder(orderParams: OptionalOrderParams, txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
343
- getPlacePerpOrderIx(orderParams: OptionalOrderParams, subAccountId?: number): Promise<TransactionInstruction>;
348
+ getPlacePerpOrderIx(orderParams: OptionalOrderParams, subAccountId?: number, depositToTradeArgs?: {
349
+ isMakingNewAccount: boolean;
350
+ depositMarketIndex: number;
351
+ }): Promise<TransactionInstruction>;
344
352
  updateAMMs(marketIndexes: number[], txParams?: TxParams): Promise<TransactionSignature>;
345
353
  getUpdateAMMsIx(marketIndexes: number[]): Promise<TransactionInstruction>;
346
354
  settleExpiredMarket(marketIndex: number, txParams?: TxParams): Promise<TransactionSignature>;
@@ -497,6 +505,38 @@ export declare class DriftClient {
497
505
  getPlaceAndTakePerpOrderIx(orderParams: OptionalOrderParams, makerInfo?: MakerInfo | MakerInfo[], referrerInfo?: ReferrerInfo, subAccountId?: number): Promise<TransactionInstruction>;
498
506
  placeAndMakePerpOrder(orderParams: OptionalOrderParams, takerInfo: TakerInfo, referrerInfo?: ReferrerInfo, txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
499
507
  getPlaceAndMakePerpOrderIx(orderParams: OptionalOrderParams, takerInfo: TakerInfo, referrerInfo?: ReferrerInfo, subAccountId?: number): Promise<TransactionInstruction>;
508
+ signTakerOrderParams(orderParamsMessage: SwiftOrderParamsMessage): Promise<Buffer>;
509
+ getEncodedSwiftOrderParamsMessage(orderParamsMessage: SwiftOrderParamsMessage): Buffer;
510
+ decodeSwiftTakerOrderParamsMessage(encodedMessage: Buffer): SwiftOrderParamsMessage;
511
+ signMessage(message: Uint8Array): Promise<Buffer>;
512
+ assembleSwiftServerMessage(message: Buffer, signature: Buffer, takerPubkey: PublicKey, marketIndex: number, marketType: MarketType, slot: number | BN): {
513
+ message: string;
514
+ signature: string;
515
+ taker_pubkey: string;
516
+ market_index: number;
517
+ market_type: 'perp' | 'spot';
518
+ slot: BN;
519
+ };
520
+ placeSwiftTakerOrder(takerOrderParamsMessage: Buffer, takerSignature: Buffer, marketIndex: number, takerInfo: {
521
+ taker: PublicKey;
522
+ takerStats: PublicKey;
523
+ takerUserAccount: UserAccount;
524
+ }, txParams?: TxParams): Promise<TransactionSignature>;
525
+ getPlaceSwiftTakerPerpOrderIx(takerOrderParamsMessage: Buffer, takerSignature: Buffer, marketIndex: number, takerInfo: {
526
+ taker: PublicKey;
527
+ takerStats: PublicKey;
528
+ takerUserAccount: UserAccount;
529
+ }): Promise<TransactionInstruction[]>;
530
+ placeAndMakeSwiftPerpOrder(encodedTakerOrderParamsMessage: Buffer, takerSignature: Buffer, takerExpectedOrderId: number, takerInfo: {
531
+ taker: PublicKey;
532
+ takerStats: PublicKey;
533
+ takerUserAccount: UserAccount;
534
+ }, orderParams: OptionalOrderParams, referrerInfo?: ReferrerInfo, txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
535
+ getPlaceAndMakeSwiftPerpOrderIxs(encodedTakerOrderParamsMessage: Buffer, takerSignature: Buffer, takerExpectedOrderId: number, takerInfo: {
536
+ taker: PublicKey;
537
+ takerStats: PublicKey;
538
+ takerUserAccount: UserAccount;
539
+ }, orderParams: OptionalOrderParams, referrerInfo?: ReferrerInfo, subAccountId?: number): Promise<TransactionInstruction[]>;
500
540
  preparePlaceAndTakeSpotOrder(orderParams: OptionalOrderParams, fulfillmentConfig?: SerumV3FulfillmentConfigAccount, makerInfo?: MakerInfo, referrerInfo?: ReferrerInfo, txParams?: TxParams, subAccountId?: number): Promise<{
501
541
  placeAndTakeSpotOrderTx: anchor.web3.Transaction | anchor.web3.VersionedTransaction;
502
542
  }>;
@@ -68,7 +68,7 @@ const utils_2 = require("./tx/utils");
68
68
  const pyth_solana_receiver_json_1 = __importDefault(require("./idl/pyth_solana_receiver.json"));
69
69
  const on_demand_1 = require("@switchboard-xyz/on-demand");
70
70
  const switchboard_on_demand_30_json_1 = __importDefault(require("./idl/switchboard_on_demand_30.json"));
71
- const grpcDriftClientAccountSubscriber_1 = require("./accounts/grpcDriftClientAccountSubscriber");
71
+ const ed = __importStar(require("@noble/ed25519"));
72
72
  /**
73
73
  * # DriftClient
74
74
  * This class is the main way to interact with Drift Protocol. It allows you to subscribe to the various accounts where the Market's state is stored, as well as: opening positions, liquidating, settling funding, depositing & withdrawing, and more.
@@ -81,7 +81,7 @@ class DriftClient {
81
81
  this._isSubscribed = val;
82
82
  }
83
83
  constructor(config) {
84
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19;
84
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6;
85
85
  this.users = new Map();
86
86
  this._isSubscribed = false;
87
87
  this.perpMarketLastSlotCache = new Map();
@@ -110,6 +110,7 @@ class DriftClient {
110
110
  this.txHandler =
111
111
  (_m = config === null || config === void 0 ? void 0 : config.txHandler) !== null && _m !== void 0 ? _m : new txHandler_1.TxHandler({
112
112
  connection: this.connection,
113
+ // @ts-ignore
113
114
  wallet: this.provider.wallet,
114
115
  confirmationOptions: this.opts,
115
116
  opts: {
@@ -144,32 +145,18 @@ class DriftClient {
144
145
  accountLoader: config.accountSubscription.accountLoader,
145
146
  };
146
147
  }
147
- else if (((_q = config.accountSubscription) === null || _q === void 0 ? void 0 : _q.type) === 'grpc') {
148
- this.userAccountSubscriptionConfig = {
149
- type: 'grpc',
150
- resubTimeoutMs: (_r = config.accountSubscription) === null || _r === void 0 ? void 0 : _r.resubTimeoutMs,
151
- logResubMessages: (_s = config.accountSubscription) === null || _s === void 0 ? void 0 : _s.logResubMessages,
152
- configs: (_t = config.accountSubscription) === null || _t === void 0 ? void 0 : _t.configs,
153
- };
154
- this.userStatsAccountSubscriptionConfig = {
155
- type: 'grpc',
156
- resubTimeoutMs: (_u = config.accountSubscription) === null || _u === void 0 ? void 0 : _u.resubTimeoutMs,
157
- logResubMessages: (_v = config.accountSubscription) === null || _v === void 0 ? void 0 : _v.logResubMessages,
158
- configs: (_w = config.accountSubscription) === null || _w === void 0 ? void 0 : _w.configs,
159
- };
160
- }
161
148
  else {
162
149
  this.userAccountSubscriptionConfig = {
163
150
  type: 'websocket',
164
- resubTimeoutMs: (_x = config.accountSubscription) === null || _x === void 0 ? void 0 : _x.resubTimeoutMs,
165
- logResubMessages: (_y = config.accountSubscription) === null || _y === void 0 ? void 0 : _y.logResubMessages,
166
- commitment: (_z = config.accountSubscription) === null || _z === void 0 ? void 0 : _z.commitment,
151
+ resubTimeoutMs: (_q = config.accountSubscription) === null || _q === void 0 ? void 0 : _q.resubTimeoutMs,
152
+ logResubMessages: (_r = config.accountSubscription) === null || _r === void 0 ? void 0 : _r.logResubMessages,
153
+ commitment: (_s = config.accountSubscription) === null || _s === void 0 ? void 0 : _s.commitment,
167
154
  };
168
155
  this.userStatsAccountSubscriptionConfig = {
169
156
  type: 'websocket',
170
- resubTimeoutMs: (_0 = config.accountSubscription) === null || _0 === void 0 ? void 0 : _0.resubTimeoutMs,
171
- logResubMessages: (_1 = config.accountSubscription) === null || _1 === void 0 ? void 0 : _1.logResubMessages,
172
- commitment: (_2 = config.accountSubscription) === null || _2 === void 0 ? void 0 : _2.commitment,
157
+ resubTimeoutMs: (_t = config.accountSubscription) === null || _t === void 0 ? void 0 : _t.resubTimeoutMs,
158
+ logResubMessages: (_u = config.accountSubscription) === null || _u === void 0 ? void 0 : _u.logResubMessages,
159
+ commitment: (_v = config.accountSubscription) === null || _v === void 0 ? void 0 : _v.commitment,
173
160
  };
174
161
  }
175
162
  if (config.userStats) {
@@ -186,20 +173,14 @@ class DriftClient {
186
173
  const noMarketsAndOraclesSpecified = config.perpMarketIndexes === undefined &&
187
174
  config.spotMarketIndexes === undefined &&
188
175
  config.oracleInfos === undefined;
189
- if (((_3 = config.accountSubscription) === null || _3 === void 0 ? void 0 : _3.type) === 'polling') {
190
- this.accountSubscriber = new pollingDriftClientAccountSubscriber_1.PollingDriftClientAccountSubscriber(this.program, config.accountSubscription.accountLoader, (_4 = config.perpMarketIndexes) !== null && _4 !== void 0 ? _4 : [], (_5 = config.spotMarketIndexes) !== null && _5 !== void 0 ? _5 : [], (_6 = config.oracleInfos) !== null && _6 !== void 0 ? _6 : [], noMarketsAndOraclesSpecified);
191
- }
192
- else if (((_7 = config.accountSubscription) === null || _7 === void 0 ? void 0 : _7.type) === 'grpc') {
193
- this.accountSubscriber = new grpcDriftClientAccountSubscriber_1.gprcDriftClientAccountSubscriber(config.accountSubscription.configs, this.program, (_8 = config.perpMarketIndexes) !== null && _8 !== void 0 ? _8 : [], (_9 = config.spotMarketIndexes) !== null && _9 !== void 0 ? _9 : [], (_10 = config.oracleInfos) !== null && _10 !== void 0 ? _10 : [], noMarketsAndOraclesSpecified, {
194
- resubTimeoutMs: (_11 = config.accountSubscription) === null || _11 === void 0 ? void 0 : _11.resubTimeoutMs,
195
- logResubMessages: (_12 = config.accountSubscription) === null || _12 === void 0 ? void 0 : _12.logResubMessages,
196
- });
176
+ if (((_w = config.accountSubscription) === null || _w === void 0 ? void 0 : _w.type) === 'polling') {
177
+ this.accountSubscriber = new pollingDriftClientAccountSubscriber_1.PollingDriftClientAccountSubscriber(this.program, config.accountSubscription.accountLoader, (_x = config.perpMarketIndexes) !== null && _x !== void 0 ? _x : [], (_y = config.spotMarketIndexes) !== null && _y !== void 0 ? _y : [], (_z = config.oracleInfos) !== null && _z !== void 0 ? _z : [], noMarketsAndOraclesSpecified);
197
178
  }
198
179
  else {
199
- this.accountSubscriber = new webSocketDriftClientAccountSubscriber_1.WebSocketDriftClientAccountSubscriber(this.program, (_13 = config.perpMarketIndexes) !== null && _13 !== void 0 ? _13 : [], (_14 = config.spotMarketIndexes) !== null && _14 !== void 0 ? _14 : [], (_15 = config.oracleInfos) !== null && _15 !== void 0 ? _15 : [], noMarketsAndOraclesSpecified, {
200
- resubTimeoutMs: (_16 = config.accountSubscription) === null || _16 === void 0 ? void 0 : _16.resubTimeoutMs,
201
- logResubMessages: (_17 = config.accountSubscription) === null || _17 === void 0 ? void 0 : _17.logResubMessages,
202
- }, (_18 = config.accountSubscription) === null || _18 === void 0 ? void 0 : _18.commitment);
180
+ this.accountSubscriber = new webSocketDriftClientAccountSubscriber_1.WebSocketDriftClientAccountSubscriber(this.program, (_0 = config.perpMarketIndexes) !== null && _0 !== void 0 ? _0 : [], (_1 = config.spotMarketIndexes) !== null && _1 !== void 0 ? _1 : [], (_2 = config.oracleInfos) !== null && _2 !== void 0 ? _2 : [], noMarketsAndOraclesSpecified, {
181
+ resubTimeoutMs: (_3 = config.accountSubscription) === null || _3 === void 0 ? void 0 : _3.resubTimeoutMs,
182
+ logResubMessages: (_4 = config.accountSubscription) === null || _4 === void 0 ? void 0 : _4.logResubMessages,
183
+ }, (_5 = config.accountSubscription) === null || _5 === void 0 ? void 0 : _5.commitment);
203
184
  }
204
185
  this.eventEmitter = this.accountSubscriber.eventEmitter;
205
186
  this.metricsEventEmitter = new events_1.EventEmitter();
@@ -207,7 +188,7 @@ class DriftClient {
207
188
  this.enableMetricsEvents = true;
208
189
  }
209
190
  this.txSender =
210
- (_19 = config.txSender) !== null && _19 !== void 0 ? _19 : new retryTxSender_1.RetryTxSender({
191
+ (_6 = config.txSender) !== null && _6 !== void 0 ? _6 : new retryTxSender_1.RetryTxSender({
211
192
  connection: this.connection,
212
193
  wallet: this.wallet,
213
194
  opts: this.opts,
@@ -1139,7 +1120,7 @@ class DriftClient {
1139
1120
  data: Buffer.from([0x1]),
1140
1121
  });
1141
1122
  }
1142
- async createDepositTxn(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly = false, txParams) {
1123
+ async getDepositTxnIx(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly = false) {
1143
1124
  const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1144
1125
  const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
1145
1126
  const signerAuthority = this.wallet.publicKey;
@@ -1156,6 +1137,10 @@ class DriftClient {
1156
1137
  if (createWSOLTokenAccount) {
1157
1138
  instructions.push((0, spl_token_1.createCloseAccountInstruction)(associatedTokenAccount, signerAuthority, signerAuthority, []));
1158
1139
  }
1140
+ return instructions;
1141
+ }
1142
+ async createDepositTxn(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly = false, txParams) {
1143
+ const instructions = await this.getDepositTxnIx(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly);
1159
1144
  txParams = { ...(txParams !== null && txParams !== void 0 ? txParams : this.txParams), computeUnits: 600000 };
1160
1145
  const tx = await this.buildTransaction(instructions, txParams);
1161
1146
  return tx;
@@ -1263,7 +1248,7 @@ class DriftClient {
1263
1248
  getAssociatedTokenAccountCreationIx(tokenMintAddress, associatedTokenAddress, tokenProgram) {
1264
1249
  return (0, spl_token_1.createAssociatedTokenAccountInstruction)(this.wallet.publicKey, associatedTokenAddress, this.wallet.publicKey, tokenMintAddress, tokenProgram);
1265
1250
  }
1266
- async createInitializeUserAccountAndDepositCollateral(amount, userTokenAccount, marketIndex = 0, subAccountId = 0, name, fromSubAccountId, referrerInfo, donateAmount, txParams, customMaxMarginRatio) {
1251
+ async createInitializeUserAccountAndDepositCollateralIxs(amount, userTokenAccount, marketIndex = 0, subAccountId = 0, name, fromSubAccountId, referrerInfo, donateAmount, customMaxMarginRatio) {
1267
1252
  const ixs = [];
1268
1253
  const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(subAccountId, name, referrerInfo);
1269
1254
  const spotMarket = this.getSpotMarketAccount(marketIndex);
@@ -1309,6 +1294,13 @@ class DriftClient {
1309
1294
  if (createWSOLTokenAccount) {
1310
1295
  ixs.push((0, spl_token_1.createCloseAccountInstruction)(wsolTokenAccount, authority, authority, []));
1311
1296
  }
1297
+ return {
1298
+ ixs,
1299
+ userAccountPublicKey,
1300
+ };
1301
+ }
1302
+ async createInitializeUserAccountAndDepositCollateral(amount, userTokenAccount, marketIndex = 0, subAccountId = 0, name, fromSubAccountId, referrerInfo, donateAmount, txParams, customMaxMarginRatio) {
1303
+ const { ixs, userAccountPublicKey } = await this.createInitializeUserAccountAndDepositCollateralIxs(amount, userTokenAccount, marketIndex, subAccountId, name, fromSubAccountId, referrerInfo, donateAmount, customMaxMarginRatio);
1312
1304
  const tx = await this.buildTransaction(ixs, txParams);
1313
1305
  return [tx, userAccountPublicKey];
1314
1306
  }
@@ -1684,13 +1676,21 @@ class DriftClient {
1684
1676
  this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
1685
1677
  return txSig;
1686
1678
  }
1687
- async getPlacePerpOrderIx(orderParams, subAccountId) {
1679
+ async getPlacePerpOrderIx(orderParams, subAccountId, depositToTradeArgs) {
1688
1680
  orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.PERP });
1689
- const user = await this.getUserAccountPublicKey(subAccountId);
1681
+ const isDepositToTradeTx = depositToTradeArgs !== undefined;
1682
+ const user = isDepositToTradeTx
1683
+ ? (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.authority, subAccountId)
1684
+ : await this.getUserAccountPublicKey(subAccountId);
1690
1685
  const remainingAccounts = this.getRemainingAccounts({
1691
- userAccounts: [this.getUserAccount(subAccountId)],
1692
- useMarketLastSlotCache: true,
1686
+ userAccounts: (depositToTradeArgs === null || depositToTradeArgs === void 0 ? void 0 : depositToTradeArgs.isMakingNewAccount)
1687
+ ? []
1688
+ : [this.getUserAccount(subAccountId)],
1689
+ useMarketLastSlotCache: false,
1693
1690
  readablePerpMarketIndex: orderParams.marketIndex,
1691
+ readableSpotMarketIndexes: isDepositToTradeTx
1692
+ ? [depositToTradeArgs === null || depositToTradeArgs === void 0 ? void 0 : depositToTradeArgs.depositMarketIndex]
1693
+ : undefined,
1694
1694
  });
1695
1695
  return await this.program.instruction.placePerpOrder(orderParams, {
1696
1696
  accounts: {
@@ -2802,7 +2802,9 @@ class DriftClient {
2802
2802
  if (!txsToSign) {
2803
2803
  return null;
2804
2804
  }
2805
- const signedTxs = (await this.txHandler.getSignedTransactionMap(txsToSign, this.provider.wallet)).signedTxMap;
2805
+ const signedTxs = (await this.txHandler.getSignedTransactionMap(txsToSign,
2806
+ // @ts-ignore
2807
+ this.provider.wallet)).signedTxMap;
2806
2808
  const { txSig, slot } = await this.sendTransaction(signedTxs.placeAndTakeTx, [], this.opts, true);
2807
2809
  this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
2808
2810
  return {
@@ -2909,6 +2911,101 @@ class DriftClient {
2909
2911
  remainingAccounts,
2910
2912
  });
2911
2913
  }
2914
+ async signTakerOrderParams(orderParamsMessage) {
2915
+ const takerOrderParamsMessage = Uint8Array.from(this.getEncodedSwiftOrderParamsMessage(orderParamsMessage));
2916
+ return await this.signMessage(takerOrderParamsMessage);
2917
+ }
2918
+ getEncodedSwiftOrderParamsMessage(orderParamsMessage) {
2919
+ return this.program.coder.types.encode('SwiftOrderParamsMessage', orderParamsMessage);
2920
+ }
2921
+ decodeSwiftTakerOrderParamsMessage(encodedMessage) {
2922
+ return this.program.coder.types.decode('SwiftOrderParamsMessage', encodedMessage);
2923
+ }
2924
+ async signMessage(message) {
2925
+ return Buffer.from(await ed.sign(message, this.wallet.payer.secretKey.slice(0, 32)));
2926
+ }
2927
+ assembleSwiftServerMessage(message, signature, takerPubkey, marketIndex, marketType, slot) {
2928
+ return {
2929
+ message: message.toString('base64'),
2930
+ signature: signature.toString('base64'),
2931
+ taker_pubkey: takerPubkey.toBase58(),
2932
+ market_index: marketIndex,
2933
+ market_type: (0, types_1.isVariant)(marketType, 'perp') ? 'perp' : 'spot',
2934
+ slot: typeof slot === 'number' ? new anchor_1.BN(slot) : slot,
2935
+ };
2936
+ }
2937
+ async placeSwiftTakerOrder(takerOrderParamsMessage, takerSignature, marketIndex, takerInfo, txParams) {
2938
+ const ixs = await this.getPlaceSwiftTakerPerpOrderIx(takerOrderParamsMessage, takerSignature, marketIndex, takerInfo);
2939
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(ixs, txParams), [], this.opts);
2940
+ return txSig;
2941
+ }
2942
+ async getPlaceSwiftTakerPerpOrderIx(takerOrderParamsMessage, takerSignature, marketIndex, takerInfo) {
2943
+ const remainingAccounts = this.getRemainingAccounts({
2944
+ userAccounts: [takerInfo.takerUserAccount],
2945
+ useMarketLastSlotCache: true,
2946
+ readablePerpMarketIndex: marketIndex,
2947
+ });
2948
+ const signatureIx = web3_js_1.Ed25519Program.createInstructionWithPublicKey({
2949
+ publicKey: takerInfo.takerUserAccount.authority.toBytes(),
2950
+ signature: Uint8Array.from(takerSignature),
2951
+ message: Uint8Array.from(takerOrderParamsMessage),
2952
+ });
2953
+ const placeTakerSwiftPerpOrderIx = await this.program.instruction.placeSwiftTakerOrder(takerOrderParamsMessage, takerSignature, {
2954
+ accounts: {
2955
+ state: await this.getStatePublicKey(),
2956
+ user: takerInfo.taker,
2957
+ userStats: takerInfo.takerStats,
2958
+ authority: this.wallet.publicKey,
2959
+ ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
2960
+ },
2961
+ remainingAccounts,
2962
+ });
2963
+ return [signatureIx, placeTakerSwiftPerpOrderIx];
2964
+ }
2965
+ async placeAndMakeSwiftPerpOrder(encodedTakerOrderParamsMessage, takerSignature, takerExpectedOrderId, takerInfo, orderParams, referrerInfo, txParams, subAccountId) {
2966
+ const ixs = await this.getPlaceAndMakeSwiftPerpOrderIxs(encodedTakerOrderParamsMessage, takerSignature, takerExpectedOrderId, takerInfo, orderParams, referrerInfo, subAccountId);
2967
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(ixs, txParams), [], this.opts);
2968
+ this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
2969
+ return txSig;
2970
+ }
2971
+ async getPlaceAndMakeSwiftPerpOrderIxs(encodedTakerOrderParamsMessage, takerSignature, takerExpectedOrderId, takerInfo, orderParams, referrerInfo, subAccountId) {
2972
+ const [signatureIx, placeTakerSwiftPerpOrderIx] = await this.getPlaceSwiftTakerPerpOrderIx(encodedTakerOrderParamsMessage, takerSignature, orderParams.marketIndex, takerInfo);
2973
+ orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.PERP });
2974
+ const userStatsPublicKey = this.getUserStatsAccountPublicKey();
2975
+ const user = await this.getUserAccountPublicKey(subAccountId);
2976
+ const remainingAccounts = this.getRemainingAccounts({
2977
+ userAccounts: [
2978
+ this.getUserAccount(subAccountId),
2979
+ takerInfo.takerUserAccount,
2980
+ ],
2981
+ useMarketLastSlotCache: true,
2982
+ writablePerpMarketIndexes: [orderParams.marketIndex],
2983
+ });
2984
+ if (referrerInfo) {
2985
+ remainingAccounts.push({
2986
+ pubkey: referrerInfo.referrer,
2987
+ isWritable: true,
2988
+ isSigner: false,
2989
+ });
2990
+ remainingAccounts.push({
2991
+ pubkey: referrerInfo.referrerStats,
2992
+ isWritable: true,
2993
+ isSigner: false,
2994
+ });
2995
+ }
2996
+ const placeAndMakeIx = await this.program.instruction.placeAndMakePerpOrder(orderParams, takerExpectedOrderId, {
2997
+ accounts: {
2998
+ state: await this.getStatePublicKey(),
2999
+ user,
3000
+ userStats: userStatsPublicKey,
3001
+ taker: takerInfo.taker,
3002
+ takerStats: takerInfo.takerStats,
3003
+ authority: this.wallet.publicKey,
3004
+ },
3005
+ remainingAccounts,
3006
+ });
3007
+ return [signatureIx, placeTakerSwiftPerpOrderIx, placeAndMakeIx];
3008
+ }
2912
3009
  async preparePlaceAndTakeSpotOrder(orderParams, fulfillmentConfig, makerInfo, referrerInfo, txParams, subAccountId) {
2913
3010
  const tx = await this.buildTransaction(await this.getPlaceAndTakeSpotOrderIx(orderParams, fulfillmentConfig, makerInfo, referrerInfo, subAccountId), txParams);
2914
3011
  return {
@@ -5,7 +5,6 @@ import { BulkAccountLoader } from './accounts/bulkAccountLoader';
5
5
  import { DriftEnv } from './config';
6
6
  import { TxSender } from './tx/types';
7
7
  import { TxHandler, TxHandlerConfig } from './tx/txHandler';
8
- import { GrpcConfigs } from './accounts/types';
9
8
  export type DriftClientConfig = {
10
9
  connection: Connection;
11
10
  wallet: IWallet;
@@ -39,9 +38,4 @@ export type DriftClientSubscriptionConfig = {
39
38
  } | {
40
39
  type: 'polling';
41
40
  accountLoader: BulkAccountLoader;
42
- } | {
43
- type: 'grpc';
44
- configs: GrpcConfigs;
45
- resubTimeoutMs?: number;
46
- logResubMessages?: boolean;
47
41
  };
@@ -15,12 +15,19 @@ export declare class EventSubscriber {
15
15
  private awaitTxPromises;
16
16
  private awaitTxResolver;
17
17
  private logProvider;
18
+ private currentProviderType;
18
19
  eventEmitter: StrictEventEmitter<EventEmitter, EventSubscriberEvents>;
19
20
  private lastSeenSlot;
20
21
  private lastSeenBlockTime;
21
22
  lastSeenTxSig: string;
22
23
  constructor(connection: Connection, program: Program, options?: EventSubscriptionOptions);
24
+ private initializeLogProvider;
23
25
  private populateInitialEventListMap;
26
+ /**
27
+ * Implements fallback logic for reconnecting to LogProvider. Currently terminates at polling,
28
+ * could be improved to try the original type again after some cooldown.
29
+ */
30
+ private updateFallbackProviderType;
24
31
  subscribe(): Promise<boolean>;
25
32
  private handleTxLogs;
26
33
  fetchPreviousTx(fetchMax?: boolean): Promise<void>;