@drift-labs/sdk 0.1.18 → 0.1.20

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 (101) hide show
  1. package/lib/accounts/bulkAccountLoader.d.ts +32 -0
  2. package/lib/accounts/bulkAccountLoader.d.ts.map +1 -0
  3. package/lib/accounts/bulkAccountLoader.js +166 -0
  4. package/lib/accounts/bulkUserSubscription.d.ts +8 -0
  5. package/lib/accounts/bulkUserSubscription.d.ts.map +1 -0
  6. package/lib/accounts/bulkUserSubscription.js +28 -0
  7. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +46 -0
  8. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts.map +1 -0
  9. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +206 -0
  10. package/lib/accounts/pollingTokenAccountSubscriber.d.ts +26 -0
  11. package/lib/accounts/pollingTokenAccountSubscriber.d.ts.map +1 -0
  12. package/lib/accounts/pollingTokenAccountSubscriber.js +79 -0
  13. package/lib/accounts/pollingUserAccountSubscriber.d.ts +31 -0
  14. package/lib/accounts/pollingUserAccountSubscriber.d.ts.map +1 -0
  15. package/lib/accounts/pollingUserAccountSubscriber.js +123 -0
  16. package/lib/accounts/types.d.ts +30 -0
  17. package/lib/accounts/types.d.ts.map +1 -1
  18. package/lib/accounts/utils.d.ts +2 -0
  19. package/lib/accounts/utils.d.ts.map +1 -0
  20. package/lib/accounts/utils.js +7 -0
  21. package/lib/accounts/webSocketAccountSubscriber.d.ts +6 -2
  22. package/lib/accounts/webSocketAccountSubscriber.d.ts.map +1 -1
  23. package/lib/accounts/webSocketAccountSubscriber.js +43 -12
  24. package/lib/accounts/{defaultClearingHouseAccountSubscriber.d.ts → webSocketClearingHouseAccountSubscriber.d.ts} +4 -2
  25. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts.map +1 -0
  26. package/lib/accounts/{defaultClearingHouseAccountSubscriber.js → webSocketClearingHouseAccountSubscriber.js} +4 -3
  27. package/lib/accounts/{defaultUserAccountSubscriber.d.ts → webSocketUserAccountSubscriber.d.ts} +4 -2
  28. package/lib/accounts/webSocketUserAccountSubscriber.d.ts.map +1 -0
  29. package/lib/accounts/{defaultUserAccountSubscriber.js → webSocketUserAccountSubscriber.js} +4 -3
  30. package/lib/admin.d.ts +1 -0
  31. package/lib/admin.d.ts.map +1 -1
  32. package/lib/admin.js +20 -11
  33. package/lib/clearingHouse.d.ts +12 -2
  34. package/lib/clearingHouse.d.ts.map +1 -1
  35. package/lib/clearingHouse.js +19 -8
  36. package/lib/clearingHouseUser.d.ts +11 -3
  37. package/lib/clearingHouseUser.d.ts.map +1 -1
  38. package/lib/clearingHouseUser.js +33 -23
  39. package/lib/constants/markets.d.ts +2 -1
  40. package/lib/constants/markets.d.ts.map +1 -1
  41. package/lib/constants/markets.js +20 -15
  42. package/lib/constants/numericConstants.d.ts +3 -1
  43. package/lib/constants/numericConstants.d.ts.map +1 -1
  44. package/lib/constants/numericConstants.js +15 -17
  45. package/lib/examples/makeTradeExample.js +1 -1
  46. package/lib/factory/clearingHouse.d.ts +26 -0
  47. package/lib/factory/clearingHouse.d.ts.map +1 -0
  48. package/lib/factory/clearingHouse.js +64 -0
  49. package/lib/factory/clearingHouseUser.d.ts +20 -0
  50. package/lib/factory/clearingHouseUser.d.ts.map +1 -0
  51. package/lib/factory/clearingHouseUser.js +34 -0
  52. package/lib/index.d.ts +8 -2
  53. package/lib/index.d.ts.map +1 -1
  54. package/lib/index.js +9 -2
  55. package/lib/math/conversion.d.ts +1 -1
  56. package/lib/math/conversion.d.ts.map +1 -1
  57. package/lib/math/insuranceFund.d.ts +2 -1
  58. package/lib/math/insuranceFund.d.ts.map +1 -1
  59. package/lib/math/insuranceFund.js +3 -6
  60. package/lib/math/position.d.ts +2 -1
  61. package/lib/math/position.d.ts.map +1 -1
  62. package/lib/math/position.js +2 -5
  63. package/lib/math/utils.d.ts +2 -1
  64. package/lib/math/utils.d.ts.map +1 -1
  65. package/lib/math/utils.js +3 -3
  66. package/lib/mockUSDCFaucet.d.ts +2 -1
  67. package/lib/mockUSDCFaucet.d.ts.map +1 -1
  68. package/lib/token/index.d.ts +4 -0
  69. package/lib/token/index.d.ts.map +1 -0
  70. package/lib/token/index.js +38 -0
  71. package/lib/types.d.ts +3 -1
  72. package/lib/types.d.ts.map +1 -1
  73. package/package.json +11 -3
  74. package/src/accounts/bulkAccountLoader.ts +207 -0
  75. package/src/accounts/bulkUserSubscription.ts +28 -0
  76. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +293 -0
  77. package/src/accounts/pollingTokenAccountSubscriber.ts +99 -0
  78. package/src/accounts/pollingUserAccountSubscriber.ts +166 -0
  79. package/src/accounts/types.ts +38 -0
  80. package/src/accounts/utils.ts +3 -0
  81. package/src/accounts/webSocketAccountSubscriber.ts +67 -17
  82. package/src/accounts/{defaultClearingHouseAccountSubscriber.ts → webSocketClearingHouseAccountSubscriber.ts} +4 -1
  83. package/src/accounts/{defaultUserAccountSubscriber.ts → webSocketUserAccountSubscriber.ts} +4 -1
  84. package/src/admin.ts +27 -18
  85. package/src/clearingHouse.ts +25 -17
  86. package/src/clearingHouseUser.ts +26 -6
  87. package/src/constants/markets.ts +9 -1
  88. package/src/constants/numericConstants.ts +2 -1
  89. package/src/examples/makeTradeExample.ts +4 -1
  90. package/src/factory/clearingHouse.ts +125 -0
  91. package/src/factory/clearingHouseUser.ts +73 -0
  92. package/src/index.ts +8 -2
  93. package/src/math/conversion.ts +1 -1
  94. package/src/math/insuranceFund.ts +1 -1
  95. package/src/math/position.ts +1 -1
  96. package/src/math/utils.ts +1 -1
  97. package/src/mockUSDCFaucet.ts +1 -1
  98. package/src/token/index.ts +37 -0
  99. package/src/types.ts +2 -1
  100. package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts.map +0 -1
  101. package/lib/accounts/defaultUserAccountSubscriber.d.ts.map +0 -1
@@ -1,13 +1,17 @@
1
- import { AccountSubscriber } from './types';
1
+ import { AccountData, AccountSubscriber } from './types';
2
2
  import { Program } from '@project-serum/anchor';
3
- import { PublicKey } from '@solana/web3.js';
3
+ import { AccountInfo, Context, PublicKey } from '@solana/web3.js';
4
+ import { capitalize } from './utils';
5
+ import * as Buffer from 'buffer';
4
6
 
5
7
  export class WebSocketAccountSubscriber<T> implements AccountSubscriber<T> {
6
8
  data?: T;
9
+ accountData?: AccountData;
7
10
  accountName: string;
8
11
  program: Program;
9
12
  accountPublicKey: PublicKey;
10
13
  onChange: (data: T) => void;
14
+ listenerId?: number;
11
15
 
12
16
  public constructor(
13
17
  accountName: string,
@@ -20,32 +24,78 @@ export class WebSocketAccountSubscriber<T> implements AccountSubscriber<T> {
20
24
  }
21
25
 
22
26
  async subscribe(onChange: (data: T) => void): Promise<void> {
27
+ if (this.listenerId) {
28
+ return;
29
+ }
30
+
23
31
  this.onChange = onChange;
24
32
  await this.fetch();
25
33
 
26
- this.program.account[this.accountName]
27
- .subscribe(this.accountPublicKey, this.program.provider.opts.commitment)
28
- .on('change', async (data: T) => {
29
- this.data = data;
30
- this.onChange(data);
31
- });
34
+ this.listenerId = this.program.provider.connection.onAccountChange(
35
+ this.accountPublicKey,
36
+ (accountInfo, context) => {
37
+ this.handleRpcResponse(context, accountInfo);
38
+ },
39
+ this.program.provider.opts.commitment
40
+ );
32
41
  }
33
42
 
34
43
  async fetch(): Promise<void> {
35
- const newData = (await this.program.account[this.accountName].fetch(
36
- this.accountPublicKey
37
- )) as T;
44
+ const rpcResponse =
45
+ await this.program.provider.connection.getAccountInfoAndContext(
46
+ this.accountPublicKey,
47
+ this.program.provider.opts.commitment
48
+ );
49
+ this.handleRpcResponse(rpcResponse.context, rpcResponse?.value);
50
+ }
51
+
52
+ handleRpcResponse(context: Context, accountInfo?: AccountInfo<Buffer>): void {
53
+ const newSlot = context.slot;
54
+ let newBuffer: Buffer | undefined = undefined;
55
+ if (accountInfo) {
56
+ newBuffer = accountInfo.data;
57
+ }
38
58
 
39
- // if data has changed trigger update
40
- if (JSON.stringify(newData) !== JSON.stringify(this.data)) {
41
- this.data = newData;
59
+ if (!this.accountData) {
60
+ this.accountData = {
61
+ buffer: newBuffer,
62
+ slot: newSlot,
63
+ };
64
+ if (newBuffer) {
65
+ this.data = this.program.account[
66
+ this.accountName
67
+ ].coder.accounts.decode(capitalize(this.accountName), newBuffer);
68
+ this.onChange(this.data);
69
+ }
70
+ return;
71
+ }
72
+
73
+ if (newSlot <= this.accountData.slot) {
74
+ return;
75
+ }
76
+
77
+ const oldBuffer = this.accountData.buffer;
78
+ if (newBuffer && (!oldBuffer || !newBuffer.equals(oldBuffer))) {
79
+ this.accountData = {
80
+ buffer: newBuffer,
81
+ slot: newSlot,
82
+ };
83
+ this.data = this.program.account[this.accountName].coder.accounts.decode(
84
+ capitalize(this.accountName),
85
+ newBuffer
86
+ );
42
87
  this.onChange(this.data);
43
88
  }
44
89
  }
45
90
 
46
91
  unsubscribe(): Promise<void> {
47
- return this.program.account[this.accountName].unsubscribe(
48
- this.accountPublicKey
49
- );
92
+ if (this.listenerId) {
93
+ const promise =
94
+ this.program.provider.connection.removeAccountChangeListener(
95
+ this.listenerId
96
+ );
97
+ this.listenerId = undefined;
98
+ return promise;
99
+ }
50
100
  }
51
101
  }
@@ -19,8 +19,9 @@ import StrictEventEmitter from 'strict-event-emitter-types';
19
19
  import { EventEmitter } from 'events';
20
20
  import { getClearingHouseStateAccountPublicKey } from '../addresses';
21
21
  import { WebSocketAccountSubscriber } from './webSocketAccountSubscriber';
22
+ import { ClearingHouseConfigType } from '../factory/clearingHouse';
22
23
 
23
- export class DefaultClearingHouseAccountSubscriber
24
+ export class WebSocketClearingHouseAccountSubscriber
24
25
  implements ClearingHouseAccountSubscriber
25
26
  {
26
27
  isSubscribed: boolean;
@@ -37,6 +38,8 @@ export class DefaultClearingHouseAccountSubscriber
37
38
 
38
39
  optionalExtraSubscriptions: ClearingHouseAccountTypes[] = [];
39
40
 
41
+ type: ClearingHouseConfigType = 'websocket';
42
+
40
43
  private isSubscribing = false;
41
44
  private subscriptionPromise: Promise<boolean>;
42
45
  private subscriptionPromiseResolver: (val: boolean) => void;
@@ -11,8 +11,9 @@ import { PublicKey } from '@solana/web3.js';
11
11
  import { getUserAccountPublicKey } from '../addresses';
12
12
  import { WebSocketAccountSubscriber } from './webSocketAccountSubscriber';
13
13
  import { UserAccount, UserPositionsAccount } from '../types';
14
+ import { ClearingHouseConfigType } from '../factory/clearingHouse';
14
15
 
15
- export class DefaultUserAccountSubscriber implements UserAccountSubscriber {
16
+ export class WebSocketUserAccountSubscriber implements UserAccountSubscriber {
16
17
  isSubscribed: boolean;
17
18
  program: Program;
18
19
  eventEmitter: StrictEventEmitter<EventEmitter, UserAccountEvents>;
@@ -21,6 +22,8 @@ export class DefaultUserAccountSubscriber implements UserAccountSubscriber {
21
22
  userDataAccountSubscriber: AccountSubscriber<UserAccount>;
22
23
  userPositionsAccountSubscriber: AccountSubscriber<UserPositionsAccount>;
23
24
 
25
+ type: ClearingHouseConfigType = 'websocket';
26
+
24
27
  public constructor(program: Program, authority: PublicKey) {
25
28
  this.isSubscribed = false;
26
29
  this.program = program;
package/src/admin.ts CHANGED
@@ -6,17 +6,18 @@ import {
6
6
  TransactionSignature,
7
7
  } from '@solana/web3.js';
8
8
  import { FeeStructure, IWallet, OracleGuardRails, OracleSource } from './types';
9
- import { BN, Idl, Program, Provider } from '@project-serum/anchor';
9
+ import { BN, Provider } from '@project-serum/anchor';
10
10
  import * as anchor from '@project-serum/anchor';
11
11
  import { getClearingHouseStateAccountPublicKeyAndNonce } from './addresses';
12
12
  import { TOKEN_PROGRAM_ID } from '@solana/spl-token';
13
13
  import { ClearingHouse } from './clearingHouse';
14
14
  import { PEG_PRECISION } from './constants/numericConstants';
15
- import clearingHouseIDL from './idl/clearing_house.json';
16
- import { DefaultClearingHouseAccountSubscriber } from './accounts/defaultClearingHouseAccountSubscriber';
17
- import { DefaultTxSender } from './tx/defaultTxSender';
18
15
  import { calculateTargetPriceTrade } from './math/trade';
19
16
  import { calculateAmmReservesAfterSwap, getSwapDirection } from './math/amm';
17
+ import {
18
+ getAdmin,
19
+ getWebSocketClearingHouseConfig,
20
+ } from './factory/clearingHouse';
20
21
 
21
22
  export class Admin extends ClearingHouse {
22
23
  public static from(
@@ -25,24 +26,13 @@ export class Admin extends ClearingHouse {
25
26
  clearingHouseProgramId: PublicKey,
26
27
  opts: ConfirmOptions = Provider.defaultOptions()
27
28
  ): Admin {
28
- const provider = new Provider(connection, wallet, opts);
29
- const program = new Program(
30
- clearingHouseIDL as Idl,
31
- clearingHouseProgramId,
32
- provider
33
- );
34
- const accountSubscriber = new DefaultClearingHouseAccountSubscriber(
35
- program
36
- );
37
- const txSender = new DefaultTxSender(provider);
38
- return new Admin(
29
+ const config = getWebSocketClearingHouseConfig(
39
30
  connection,
40
31
  wallet,
41
- program,
42
- accountSubscriber,
43
- txSender,
32
+ clearingHouseProgramId,
44
33
  opts
45
34
  );
35
+ return getAdmin(config);
46
36
  }
47
37
 
48
38
  public async initialize(
@@ -338,6 +328,25 @@ export class Admin extends ClearingHouse {
338
328
  });
339
329
  }
340
330
 
331
+ public async resetAmmOracleTwap(
332
+ marketIndex: BN
333
+ ): Promise<TransactionSignature> {
334
+ const state = this.getStateAccount();
335
+ const markets = this.getMarketsAccount();
336
+ const marketData = markets.markets[marketIndex.toNumber()];
337
+ const ammData = marketData.amm;
338
+
339
+ return await this.program.rpc.resetAmmOracleTwap(marketIndex, {
340
+ accounts: {
341
+ state: await this.getStatePublicKey(),
342
+ admin: this.wallet.publicKey,
343
+ oracle: ammData.oracle,
344
+ markets: state.markets,
345
+ curveHistory: state.extendedCurveHistory,
346
+ },
347
+ });
348
+ }
349
+
341
350
  public async withdrawFromInsuranceVault(
342
351
  amount: BN,
343
352
  recipient: PublicKey
@@ -44,16 +44,19 @@ import {
44
44
  ClearingHouseAccountEvents,
45
45
  ClearingHouseAccountTypes,
46
46
  } from './accounts/types';
47
- import { DefaultClearingHouseAccountSubscriber } from './accounts/defaultClearingHouseAccountSubscriber';
48
47
  import { TxSender } from './tx/types';
49
48
  import { DefaultTxSender } from './tx/defaultTxSender';
50
49
  import { wrapInTx } from './tx/utils';
50
+ import {
51
+ getClearingHouse,
52
+ getWebSocketClearingHouseConfig,
53
+ } from './factory/clearingHouse';
51
54
 
52
55
  /**
53
56
  * # ClearingHouse
54
57
  * 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.
55
58
  *
56
- * The default way to construct a ClearingHouse instance is using the {@link from} method. This will create an instance using the static {@link DefaultClearingHouseAccountSubscriber}, which will use a websocket for each state account subscription.
59
+ * The default way to construct a ClearingHouse instance is using the {@link from} method. This will create an instance using the static {@link WebSocketClearingHouseAccountSubscriber}, which will use a websocket for each state account subscription.
57
60
  * Alternatively, if you want to implement your own method of subscribing to the state accounts on the blockchain, you can implement a {@link ClearingHouseAccountSubscriber} and use it in the {@link ClearingHouse.constructor}
58
61
  */
59
62
  export class ClearingHouse {
@@ -64,33 +67,38 @@ export class ClearingHouse {
64
67
  opts?: ConfirmOptions;
65
68
  accountSubscriber: ClearingHouseAccountSubscriber;
66
69
  eventEmitter: StrictEventEmitter<EventEmitter, ClearingHouseAccountEvents>;
67
- isSubscribed = false;
70
+ _isSubscribed = false;
68
71
  txSender: TxSender;
69
72
 
73
+ public get isSubscribed() {
74
+ return this._isSubscribed && this.accountSubscriber.isSubscribed;
75
+ }
76
+
77
+ public set isSubscribed(val: boolean) {
78
+ this._isSubscribed = val;
79
+ }
80
+
81
+ /**
82
+ * @deprecated You should use the getClearingHouse factory method instead
83
+ * @param connection
84
+ * @param wallet
85
+ * @param clearingHouseProgramId
86
+ * @param opts
87
+ * @returns
88
+ */
70
89
  public static from(
71
90
  connection: Connection,
72
91
  wallet: IWallet,
73
92
  clearingHouseProgramId: PublicKey,
74
93
  opts: ConfirmOptions = Provider.defaultOptions()
75
94
  ): ClearingHouse {
76
- const provider = new Provider(connection, wallet, opts);
77
- const program = new Program(
78
- clearingHouseIDL as Idl,
79
- clearingHouseProgramId,
80
- provider
81
- );
82
- const accountSubscriber = new DefaultClearingHouseAccountSubscriber(
83
- program
84
- );
85
- const txSender = new DefaultTxSender(provider);
86
- return new ClearingHouse(
95
+ const config = getWebSocketClearingHouseConfig(
87
96
  connection,
88
97
  wallet,
89
- program,
90
- accountSubscriber,
91
- txSender,
98
+ clearingHouseProgramId,
92
99
  opts
93
100
  );
101
+ return getClearingHouse(config);
94
102
  }
95
103
 
96
104
  public constructor(
@@ -1,5 +1,4 @@
1
1
  import { PublicKey } from '@solana/web3.js';
2
- import BN from 'bn.js';
3
2
  import { EventEmitter } from 'events';
4
3
  import StrictEventEmitter from 'strict-event-emitter-types';
5
4
  import { ClearingHouse } from './clearingHouse';
@@ -18,7 +17,6 @@ import {
18
17
  PRICE_TO_QUOTE_PRECISION,
19
18
  } from './constants/numericConstants';
20
19
  import { UserAccountSubscriber, UserAccountEvents } from './accounts/types';
21
- import { DefaultUserAccountSubscriber } from './accounts/defaultUserAccountSubscriber';
22
20
  import {
23
21
  calculateMarkPrice,
24
22
  calculateBaseAssetValue,
@@ -26,26 +24,48 @@ import {
26
24
  calculatePositionPNL,
27
25
  PositionDirection,
28
26
  calculateTradeSlippage,
27
+ BN,
29
28
  } from '.';
30
29
  import { getUserAccountPublicKey } from './addresses';
30
+ import {
31
+ getClearingHouseUser,
32
+ getWebSocketClearingHouseUserConfig,
33
+ } from './factory/clearingHouseUser';
31
34
 
32
35
  export class ClearingHouseUser {
33
36
  clearingHouse: ClearingHouse;
34
37
  authority: PublicKey;
35
38
  accountSubscriber: UserAccountSubscriber;
36
39
  userAccountPublicKey?: PublicKey;
37
- isSubscribed = false;
40
+ _isSubscribed = false;
38
41
  eventEmitter: StrictEventEmitter<EventEmitter, UserAccountEvents>;
39
42
 
43
+ public get isSubscribed() {
44
+ return this._isSubscribed && this.accountSubscriber.isSubscribed;
45
+ }
46
+
47
+ public set isSubscribed(val: boolean) {
48
+ this._isSubscribed = val;
49
+ }
50
+
51
+ /**
52
+ * @deprecated You should use getClearingHouseUser factory method instead
53
+ * @param clearingHouse
54
+ * @param authority
55
+ * @returns
56
+ */
40
57
  public static from(
41
58
  clearingHouse: ClearingHouse,
42
59
  authority: PublicKey
43
60
  ): ClearingHouseUser {
44
- const accountSubscriber = new DefaultUserAccountSubscriber(
45
- clearingHouse.program,
61
+ if (clearingHouse.accountSubscriber.type !== 'websocket')
62
+ throw 'This method only works for clearing houses with a websocket account listener. Try using the getClearingHouseUser factory method to initialize a ClearingHouseUser instead';
63
+
64
+ const config = getWebSocketClearingHouseUserConfig(
65
+ clearingHouse,
46
66
  authority
47
67
  );
48
- return new ClearingHouseUser(clearingHouse, authority, accountSubscriber);
68
+ return getClearingHouseUser(config);
49
69
  }
50
70
 
51
71
  public constructor(
@@ -1,4 +1,4 @@
1
- import BN from 'bn.js';
1
+ import { BN } from '../';
2
2
 
3
3
  type Market = {
4
4
  symbol: string;
@@ -98,6 +98,14 @@ export const Markets: Market[] = [
98
98
  mainnetPythOracle: 'HqFyq1wh1xKvL7KDqqT7NJeSPdAqsDqnmBisUC2XdXAX',
99
99
  launchTs: 1643686767000,
100
100
  },
101
+ {
102
+ symbol: 'FTT-PERP',
103
+ baseAssetSymbol: 'FTT',
104
+ marketIndex: new BN(11),
105
+ devnetPythOracle: '6vivTRs5ZPeeXbjo7dfburfaYDWoXjBtdtuYgQRuGfu',
106
+ mainnetPythOracle: '8JPJJkmDScpcNmBRKGZuPuG2GYAveQgP3t5gFuMymwvF',
107
+ launchTs: 1644382122000,
108
+ },
101
109
  // {
102
110
  // symbol: 'mSOL-PERP',
103
111
  // baseAssetSymbol: 'mSOL',
@@ -1,4 +1,4 @@
1
- import BN from 'bn.js';
1
+ import { BN } from '../';
2
2
 
3
3
  export const ZERO = new BN(0);
4
4
  export const ONE = new BN(1);
@@ -15,6 +15,7 @@ export const FUNDING_PAYMENT_PRECISION = new BN(10000);
15
15
  export const PEG_PRECISION = new BN(1000);
16
16
 
17
17
  export const AMM_RESERVE_PRECISION = new BN(10 ** 13);
18
+ export const BASE_PRECISION = AMM_RESERVE_PRECISION;
18
19
  export const AMM_TO_QUOTE_PRECISION_RATIO =
19
20
  AMM_RESERVE_PRECISION.div(QUOTE_PRECISION); // 10^7
20
21
  export const PRICE_TO_QUOTE_PRECISION =
@@ -95,7 +95,10 @@ const main = async () => {
95
95
  clearingHouse.getMarket(solMarketInfo.marketIndex)
96
96
  );
97
97
 
98
- const formattedPrice = convertToNumber(currentMarketPrice, QUOTE_PRECISION);
98
+ const formattedPrice = convertToNumber(
99
+ currentMarketPrice,
100
+ MARK_PRICE_PRECISION
101
+ );
99
102
 
100
103
  console.log(`Current Market Price is $${formattedPrice}`);
101
104
 
@@ -0,0 +1,125 @@
1
+ import { ConfirmOptions, Connection, PublicKey } from '@solana/web3.js';
2
+ import { IWallet } from '../types';
3
+ import { BulkAccountLoader } from '../accounts/bulkAccountLoader';
4
+ import { TxSender } from '../tx/types';
5
+ import { Idl, Program, Provider } from '@project-serum/anchor';
6
+ import { ClearingHouse } from '../clearingHouse';
7
+ import clearingHouseIDL from '../idl/clearing_house.json';
8
+ import { WebSocketClearingHouseAccountSubscriber } from '../accounts/webSocketClearingHouseAccountSubscriber';
9
+ import { DefaultTxSender } from '../tx/defaultTxSender';
10
+ import { ClearingHouseAccountSubscriber } from '../accounts/types';
11
+ import { PollingClearingHouseAccountSubscriber } from '../accounts/pollingClearingHouseAccountSubscriber';
12
+ import { Admin } from '../admin';
13
+
14
+ export type ClearingHouseConfigType = 'websocket' | 'polling' | 'custom';
15
+
16
+ type BaseClearingHouseConfig = {
17
+ type: ClearingHouseConfigType;
18
+ connection: Connection;
19
+ wallet: IWallet;
20
+ programID: PublicKey;
21
+ opts?: ConfirmOptions;
22
+ txSender?: TxSender;
23
+ };
24
+
25
+ type WebSocketClearingHouseConfiguration = BaseClearingHouseConfig;
26
+
27
+ type PollingClearingHouseConfiguration = BaseClearingHouseConfig & {
28
+ accountLoader: BulkAccountLoader;
29
+ };
30
+
31
+ type ClearingHouseConfig =
32
+ | PollingClearingHouseConfiguration
33
+ | WebSocketClearingHouseConfiguration;
34
+
35
+ export function getWebSocketClearingHouseConfig(
36
+ connection: Connection,
37
+ wallet: IWallet,
38
+ programID: PublicKey,
39
+ opts: ConfirmOptions = Provider.defaultOptions(),
40
+ txSender?: TxSender
41
+ ): WebSocketClearingHouseConfiguration {
42
+ return {
43
+ type: 'websocket',
44
+ connection,
45
+ wallet,
46
+ programID,
47
+ opts,
48
+ txSender,
49
+ };
50
+ }
51
+
52
+ export function getPollingClearingHouseConfig(
53
+ connection: Connection,
54
+ wallet: IWallet,
55
+ programID: PublicKey,
56
+ accountLoader: BulkAccountLoader,
57
+ opts: ConfirmOptions = Provider.defaultOptions(),
58
+ txSender?: TxSender
59
+ ): PollingClearingHouseConfiguration {
60
+ return {
61
+ type: 'polling',
62
+ connection,
63
+ wallet,
64
+ programID,
65
+ accountLoader,
66
+ opts,
67
+ txSender,
68
+ };
69
+ }
70
+
71
+ export function getClearingHouse(config: ClearingHouseConfig): ClearingHouse {
72
+ const provider = new Provider(config.connection, config.wallet, config.opts);
73
+ const program = new Program(
74
+ clearingHouseIDL as Idl,
75
+ config.programID,
76
+ provider
77
+ );
78
+ let accountSubscriber: ClearingHouseAccountSubscriber;
79
+ if (config.type === 'websocket') {
80
+ accountSubscriber = new WebSocketClearingHouseAccountSubscriber(program);
81
+ } else if (config.type === 'polling') {
82
+ accountSubscriber = new PollingClearingHouseAccountSubscriber(
83
+ program,
84
+ (config as PollingClearingHouseConfiguration).accountLoader
85
+ );
86
+ }
87
+
88
+ const txSender = config.txSender || new DefaultTxSender(provider);
89
+ return new ClearingHouse(
90
+ config.connection,
91
+ config.wallet,
92
+ program,
93
+ accountSubscriber,
94
+ txSender,
95
+ config.opts
96
+ );
97
+ }
98
+
99
+ export function getAdmin(config: ClearingHouseConfig): Admin {
100
+ const provider = new Provider(config.connection, config.wallet, config.opts);
101
+ const program = new Program(
102
+ clearingHouseIDL as Idl,
103
+ config.programID,
104
+ provider
105
+ );
106
+ let accountSubscriber: ClearingHouseAccountSubscriber;
107
+ if (config.type === 'websocket') {
108
+ accountSubscriber = new WebSocketClearingHouseAccountSubscriber(program);
109
+ } else if (config.type === 'polling') {
110
+ accountSubscriber = new PollingClearingHouseAccountSubscriber(
111
+ program,
112
+ (config as PollingClearingHouseConfiguration).accountLoader
113
+ );
114
+ }
115
+
116
+ const txSender = config.txSender || new DefaultTxSender(provider);
117
+ return new Admin(
118
+ config.connection,
119
+ config.wallet,
120
+ program,
121
+ accountSubscriber,
122
+ txSender,
123
+ config.opts
124
+ );
125
+ }
@@ -0,0 +1,73 @@
1
+ import { PublicKey } from '@solana/web3.js';
2
+ import { ClearingHouse } from '../clearingHouse';
3
+ import { BulkAccountLoader } from '../accounts/bulkAccountLoader';
4
+ import { ClearingHouseUser } from '../clearingHouseUser';
5
+ import { UserAccountSubscriber } from '../accounts/types';
6
+ import { WebSocketUserAccountSubscriber } from '../accounts/webSocketUserAccountSubscriber';
7
+ import { PollingUserAccountSubscriber } from '../accounts/pollingUserAccountSubscriber';
8
+
9
+ export type ClearingHouseUserConfigType = 'websocket' | 'polling' | 'custom';
10
+
11
+ type BaseClearingHouseUserConfig = {
12
+ type: ClearingHouseUserConfigType;
13
+ clearingHouse: ClearingHouse;
14
+ authority: PublicKey;
15
+ };
16
+
17
+ type WebSocketClearingHouseUserConfig = BaseClearingHouseUserConfig;
18
+
19
+ type PollingClearingHouseUserConfig = BaseClearingHouseUserConfig & {
20
+ accountLoader: BulkAccountLoader;
21
+ };
22
+
23
+ type ClearingHouseUserConfig =
24
+ | PollingClearingHouseUserConfig
25
+ | WebSocketClearingHouseUserConfig;
26
+
27
+ export function getWebSocketClearingHouseUserConfig(
28
+ clearingHouse: ClearingHouse,
29
+ authority: PublicKey
30
+ ): WebSocketClearingHouseUserConfig {
31
+ return {
32
+ type: 'websocket',
33
+ clearingHouse,
34
+ authority,
35
+ };
36
+ }
37
+
38
+ export function getPollingClearingHouseUserConfig(
39
+ clearingHouse: ClearingHouse,
40
+ authority: PublicKey,
41
+ accountLoader: BulkAccountLoader
42
+ ): PollingClearingHouseUserConfig {
43
+ return {
44
+ type: 'polling',
45
+ clearingHouse,
46
+ authority,
47
+ accountLoader,
48
+ };
49
+ }
50
+
51
+ export function getClearingHouseUser(
52
+ config: ClearingHouseUserConfig
53
+ ): ClearingHouseUser {
54
+ let accountSubscriber: UserAccountSubscriber;
55
+ if (config.type === 'websocket') {
56
+ accountSubscriber = new WebSocketUserAccountSubscriber(
57
+ config.clearingHouse.program,
58
+ config.authority
59
+ );
60
+ } else if (config.type === 'polling') {
61
+ accountSubscriber = new PollingUserAccountSubscriber(
62
+ config.clearingHouse.program,
63
+ config.authority,
64
+ (config as PollingClearingHouseUserConfig).accountLoader
65
+ );
66
+ }
67
+
68
+ return new ClearingHouseUser(
69
+ config.clearingHouse,
70
+ config.authority,
71
+ accountSubscriber
72
+ );
73
+ }
package/src/index.ts CHANGED
@@ -1,15 +1,21 @@
1
1
  import { BN } from '@project-serum/anchor';
2
+ import { PublicKey } from '@solana/web3.js';
2
3
 
3
4
  export * from './mockUSDCFaucet';
4
5
  export * from './pythClient';
5
6
  export * from './types';
6
7
  export * from './constants/markets';
7
- export * from './accounts/defaultClearingHouseAccountSubscriber';
8
+ export * from './accounts/webSocketClearingHouseAccountSubscriber';
9
+ export * from './accounts/bulkAccountLoader';
10
+ export * from './accounts/pollingClearingHouseAccountSubscriber';
11
+ export * from './accounts/pollingTokenAccountSubscriber';
8
12
  export * from './accounts/types';
9
13
  export * from './addresses';
10
14
  export * from './admin';
11
15
  export * from './clearingHouseUser';
12
16
  export * from './clearingHouse';
17
+ export * from './factory/clearingHouse';
18
+ export * from './factory/clearingHouseUser';
13
19
  export * from './math/conversion';
14
20
  export * from './math/funding';
15
21
  export * from './math/insuranceFund';
@@ -25,4 +31,4 @@ export * from './constants/numericConstants';
25
31
  export * from './util/computeUnits';
26
32
  export * from './util/tps';
27
33
 
28
- export { BN };
34
+ export { BN, PublicKey };
@@ -1,4 +1,4 @@
1
- import BN from 'bn.js';
1
+ import { BN } from '../';
2
2
  import {
3
3
  MARK_PRICE_PRECISION,
4
4
  PEG_PRECISION,
@@ -1,5 +1,5 @@
1
1
  import { MarketsAccount, StateAccount } from '../types';
2
- import BN from 'bn.js';
2
+ import { BN } from '../';
3
3
  import { Connection } from '@solana/web3.js';
4
4
 
5
5
  /**
@@ -1,4 +1,4 @@
1
- import BN from 'bn.js';
1
+ import { BN } from '../';
2
2
  import {
3
3
  AMM_RESERVE_PRECISION,
4
4
  AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO,
package/src/math/utils.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { BN } from 'bn.js';
1
+ import { BN } from '../';
2
2
 
3
3
  export const squareRootBN = (n, closeness = new BN(1)) => {
4
4
  // Assuming the sqrt of n as n only