@drift-labs/sdk 0.1.18-orders.0 → 0.1.18-orders.4

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 (93) hide show
  1. package/README.md +2 -1
  2. package/lib/accounts/bulkAccountLoader.d.ts +31 -0
  3. package/lib/accounts/bulkAccountLoader.js +175 -0
  4. package/lib/accounts/bulkUserSubscription.d.ts +7 -0
  5. package/lib/accounts/bulkUserSubscription.js +28 -0
  6. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +49 -0
  7. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +228 -0
  8. package/lib/accounts/pollingTokenAccountSubscriber.d.ts +25 -0
  9. package/lib/accounts/pollingTokenAccountSubscriber.js +79 -0
  10. package/lib/accounts/pollingUserAccountSubscriber.d.ts +32 -0
  11. package/lib/accounts/pollingUserAccountSubscriber.js +133 -0
  12. package/lib/accounts/types.d.ts +34 -25
  13. package/lib/accounts/utils.d.ts +1 -0
  14. package/lib/accounts/utils.js +7 -0
  15. package/lib/accounts/webSocketAccountSubscriber.d.ts +6 -2
  16. package/lib/accounts/webSocketAccountSubscriber.js +43 -12
  17. package/lib/accounts/{defaultClearingHouseAccountSubscriber.d.ts → webSocketClearingHouseAccountSubscriber.d.ts} +6 -4
  18. package/lib/accounts/{defaultClearingHouseAccountSubscriber.js → webSocketClearingHouseAccountSubscriber.js} +5 -4
  19. package/lib/accounts/{defaultUserAccountSubscriber.d.ts → webSocketUserAccountSubscriber.d.ts} +3 -1
  20. package/lib/accounts/{defaultUserAccountSubscriber.js → webSocketUserAccountSubscriber.js} +10 -7
  21. package/lib/addresses.d.ts +2 -2
  22. package/lib/addresses.js +4 -4
  23. package/lib/admin.d.ts +3 -0
  24. package/lib/admin.js +61 -13
  25. package/lib/clearingHouse.d.ts +20 -4
  26. package/lib/clearingHouse.js +90 -10
  27. package/lib/clearingHouseUser.d.ts +12 -4
  28. package/lib/clearingHouseUser.js +35 -25
  29. package/lib/config.js +1 -1
  30. package/lib/constants/markets.d.ts +2 -1
  31. package/lib/constants/markets.js +35 -14
  32. package/lib/constants/numericConstants.d.ts +3 -1
  33. package/lib/constants/numericConstants.js +15 -17
  34. package/lib/examples/makeTradeExample.js +1 -1
  35. package/lib/factory/clearingHouse.d.ts +25 -0
  36. package/lib/factory/clearingHouse.js +64 -0
  37. package/lib/factory/clearingHouseUser.d.ts +19 -0
  38. package/lib/factory/clearingHouseUser.js +34 -0
  39. package/lib/idl/clearing_house.json +366 -17
  40. package/lib/index.d.ts +9 -3
  41. package/lib/index.js +10 -3
  42. package/lib/math/conversion.d.ts +1 -1
  43. package/lib/math/funding.js +4 -1
  44. package/lib/math/insuranceFund.d.ts +2 -1
  45. package/lib/math/insuranceFund.js +3 -6
  46. package/lib/math/position.d.ts +2 -1
  47. package/lib/math/position.js +2 -5
  48. package/lib/math/utils.d.ts +2 -1
  49. package/lib/math/utils.js +3 -3
  50. package/lib/mockUSDCFaucet.d.ts +2 -1
  51. package/lib/orderParams.d.ts +3 -3
  52. package/lib/orderParams.js +28 -8
  53. package/lib/orders.d.ts +2 -1
  54. package/lib/token/index.d.ts +3 -0
  55. package/lib/token/index.js +38 -0
  56. package/lib/types.d.ts +20 -8
  57. package/lib/types.js +2 -2
  58. package/package.json +11 -3
  59. package/src/accounts/bulkAccountLoader.ts +215 -0
  60. package/src/accounts/bulkUserSubscription.ts +28 -0
  61. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +326 -0
  62. package/src/accounts/pollingTokenAccountSubscriber.ts +99 -0
  63. package/src/accounts/pollingUserAccountSubscriber.ts +186 -0
  64. package/src/accounts/types.ts +40 -30
  65. package/src/accounts/utils.ts +3 -0
  66. package/src/accounts/webSocketAccountSubscriber.ts +67 -17
  67. package/src/accounts/{defaultClearingHouseAccountSubscriber.ts → webSocketClearingHouseAccountSubscriber.ts} +9 -6
  68. package/src/accounts/{defaultUserAccountSubscriber.ts → webSocketUserAccountSubscriber.ts} +10 -5
  69. package/src/addresses.ts +6 -4
  70. package/src/admin.ts +73 -20
  71. package/src/clearingHouse.ts +125 -25
  72. package/src/clearingHouseUser.ts +28 -8
  73. package/src/config.ts +1 -1
  74. package/src/constants/markets.ts +25 -1
  75. package/src/constants/numericConstants.ts +2 -1
  76. package/src/examples/makeTradeExample.ts +4 -1
  77. package/src/factory/clearingHouse.ts +125 -0
  78. package/src/factory/clearingHouseUser.ts +73 -0
  79. package/src/idl/clearing_house.json +366 -17
  80. package/src/index.ts +9 -3
  81. package/src/math/conversion.ts +1 -1
  82. package/src/math/funding.ts +5 -1
  83. package/src/math/insuranceFund.ts +1 -1
  84. package/src/math/position.ts +1 -1
  85. package/src/math/utils.ts +1 -1
  86. package/src/mockUSDCFaucet.ts +1 -1
  87. package/src/orderParams.ts +30 -7
  88. package/src/orders.ts +1 -1
  89. package/src/token/index.ts +37 -0
  90. package/src/types.ts +17 -6
  91. package/lib/accounts/defaultHistoryAccountSubscriber.d.ts +0 -28
  92. package/lib/accounts/defaultHistoryAccountSubscriber.js +0 -110
  93. package/src/accounts/defaultHistoryAccountSubscriber.ts +0 -176
@@ -7,7 +7,6 @@ import {
7
7
  import {
8
8
  MarketsAccount,
9
9
  StateAccount,
10
- CurveHistoryAccount,
11
10
  DepositHistoryAccount,
12
11
  FundingPaymentHistoryAccount,
13
12
  FundingRateHistoryAccount,
@@ -21,6 +20,7 @@ import {
21
20
  OrderStateAccount,
22
21
  OrderParams,
23
22
  Order,
23
+ ExtendedCurveHistoryAccount,
24
24
  } from './types';
25
25
  import * as anchor from '@project-serum/anchor';
26
26
  import clearingHouseIDL from './idl/clearing_house.json';
@@ -51,16 +51,19 @@ import {
51
51
  ClearingHouseAccountEvents,
52
52
  ClearingHouseAccountTypes,
53
53
  } from './accounts/types';
54
- import { DefaultClearingHouseAccountSubscriber } from './accounts/defaultClearingHouseAccountSubscriber';
55
54
  import { TxSender } from './tx/types';
56
55
  import { DefaultTxSender } from './tx/defaultTxSender';
57
56
  import { wrapInTx } from './tx/utils';
57
+ import {
58
+ getClearingHouse,
59
+ getWebSocketClearingHouseConfig,
60
+ } from './factory/clearingHouse';
58
61
 
59
62
  /**
60
63
  * # ClearingHouse
61
64
  * 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.
62
65
  *
63
- * 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.
66
+ * 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.
64
67
  * 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}
65
68
  */
66
69
  export class ClearingHouse {
@@ -71,33 +74,38 @@ export class ClearingHouse {
71
74
  opts?: ConfirmOptions;
72
75
  accountSubscriber: ClearingHouseAccountSubscriber;
73
76
  eventEmitter: StrictEventEmitter<EventEmitter, ClearingHouseAccountEvents>;
74
- isSubscribed = false;
77
+ _isSubscribed = false;
75
78
  txSender: TxSender;
76
79
 
80
+ public get isSubscribed() {
81
+ return this._isSubscribed && this.accountSubscriber.isSubscribed;
82
+ }
83
+
84
+ public set isSubscribed(val: boolean) {
85
+ this._isSubscribed = val;
86
+ }
87
+
88
+ /**
89
+ * @deprecated You should use the getClearingHouse factory method instead
90
+ * @param connection
91
+ * @param wallet
92
+ * @param clearingHouseProgramId
93
+ * @param opts
94
+ * @returns
95
+ */
77
96
  public static from(
78
97
  connection: Connection,
79
98
  wallet: IWallet,
80
99
  clearingHouseProgramId: PublicKey,
81
100
  opts: ConfirmOptions = Provider.defaultOptions()
82
101
  ): ClearingHouse {
83
- const provider = new Provider(connection, wallet, opts);
84
- const program = new Program(
85
- clearingHouseIDL as Idl,
86
- clearingHouseProgramId,
87
- provider
88
- );
89
- const accountSubscriber = new DefaultClearingHouseAccountSubscriber(
90
- program
91
- );
92
- const txSender = new DefaultTxSender(provider);
93
- return new ClearingHouse(
102
+ const config = getWebSocketClearingHouseConfig(
94
103
  connection,
95
104
  wallet,
96
- program,
97
- accountSubscriber,
98
- txSender,
105
+ clearingHouseProgramId,
99
106
  opts
100
107
  );
108
+ return getClearingHouse(config);
101
109
  }
102
110
 
103
111
  public constructor(
@@ -208,7 +216,7 @@ export class ClearingHouse {
208
216
  return this.accountSubscriber.getDepositHistoryAccount();
209
217
  }
210
218
 
211
- public getCurveHistoryAccount(): CurveHistoryAccount {
219
+ public getCurveHistoryAccount(): ExtendedCurveHistoryAccount {
212
220
  return this.accountSubscriber.getCurveHistoryAccount();
213
221
  }
214
222
 
@@ -335,16 +343,16 @@ export class ClearingHouse {
335
343
  async getInitializeUserOrdersInstruction(
336
344
  userAccountPublicKey?: PublicKey
337
345
  ): Promise<TransactionInstruction> {
346
+ if (!userAccountPublicKey) {
347
+ userAccountPublicKey = await this.getUserAccountPublicKey();
348
+ }
349
+
338
350
  const [userOrdersAccountPublicKey, userOrdersAccountNonce] =
339
351
  await getUserOrdersAccountPublicKeyAndNonce(
340
352
  this.program.programId,
341
- this.wallet.publicKey
353
+ userAccountPublicKey
342
354
  );
343
355
 
344
- if (!userAccountPublicKey) {
345
- userAccountPublicKey = await this.getUserAccountPublicKey();
346
- }
347
-
348
356
  return await this.program.instruction.initializeUserOrders(
349
357
  userOrdersAccountNonce,
350
358
  {
@@ -401,11 +409,25 @@ export class ClearingHouse {
401
409
 
402
410
  this.userOrdersAccountPublicKey = await getUserOrdersAccountPublicKey(
403
411
  this.program.programId,
404
- this.wallet.publicKey
412
+ await this.getUserAccountPublicKey()
405
413
  );
406
414
  return this.userOrdersAccountPublicKey;
407
415
  }
408
416
 
417
+ userOrdersExist?: boolean;
418
+ async userOrdersAccountExists(): Promise<boolean> {
419
+ if (this.userOrdersExist) {
420
+ return this.userOrdersExist;
421
+ }
422
+ const userOrdersAccountRPCResponse =
423
+ await this.connection.getParsedAccountInfo(
424
+ await this.getUserOrdersAccountPublicKey()
425
+ );
426
+
427
+ this.userOrdersExist = userOrdersAccountRPCResponse.value !== null;
428
+ return this.userOrdersExist;
429
+ }
430
+
409
431
  public async depositCollateral(
410
432
  amount: BN,
411
433
  collateralAccountPublicKey: PublicKey,
@@ -660,6 +682,27 @@ export class ClearingHouse {
660
682
  );
661
683
  }
662
684
 
685
+ public async initializeUserOrdersThenPlaceOrder(
686
+ orderParams: OrderParams,
687
+ discountToken?: PublicKey,
688
+ referrer?: PublicKey
689
+ ): Promise<TransactionSignature> {
690
+ const instructions: anchor.web3.TransactionInstruction[] = [];
691
+ const userOrdersAccountExists = await this.userOrdersAccountExists();
692
+ if (!userOrdersAccountExists) {
693
+ instructions.push(await this.getInitializeUserOrdersInstruction());
694
+ }
695
+ instructions.push(
696
+ await this.getPlaceOrderIx(orderParams, discountToken, referrer)
697
+ );
698
+ const tx = new Transaction();
699
+ for (const instruction of instructions) {
700
+ tx.add(instruction);
701
+ }
702
+
703
+ return await this.txSender.send(tx, [], this.opts);
704
+ }
705
+
663
706
  public async placeOrder(
664
707
  orderParams: OrderParams,
665
708
  discountToken?: PublicKey,
@@ -765,6 +808,40 @@ export class ClearingHouse {
765
808
  });
766
809
  }
767
810
 
811
+ public async cancelOrderByUserId(
812
+ userOrderId: number
813
+ ): Promise<TransactionSignature> {
814
+ return await this.txSender.send(
815
+ wrapInTx(await this.getCancelOrderByUserIdIx(userOrderId)),
816
+ [],
817
+ this.opts
818
+ );
819
+ }
820
+
821
+ public async getCancelOrderByUserIdIx(
822
+ userOrderId: number
823
+ ): Promise<TransactionInstruction> {
824
+ const userAccountPublicKey = await this.getUserAccountPublicKey();
825
+ const userAccount = await this.getUserAccount();
826
+
827
+ const state = this.getStateAccount();
828
+ const orderState = this.getOrderStateAccount();
829
+ return await this.program.instruction.cancelOrderByUserId(userOrderId, {
830
+ accounts: {
831
+ state: await this.getStatePublicKey(),
832
+ user: userAccountPublicKey,
833
+ authority: this.wallet.publicKey,
834
+ markets: state.markets,
835
+ userOrders: await this.getUserOrdersAccountPublicKey(),
836
+ userPositions: userAccount.positions,
837
+ fundingPaymentHistory: state.fundingPaymentHistory,
838
+ fundingRateHistory: state.fundingRateHistory,
839
+ orderState: await this.getOrderStatePublicKey(),
840
+ orderHistory: orderState.orderHistory,
841
+ },
842
+ });
843
+ }
844
+
768
845
  public async fillOrder(
769
846
  userAccountPublicKey: PublicKey,
770
847
  userOrdersAccountPublicKey: PublicKey,
@@ -823,12 +900,34 @@ export class ClearingHouse {
823
900
  fundingRateHistory: state.fundingRateHistory,
824
901
  orderState: await this.getOrderStatePublicKey(),
825
902
  orderHistory: orderState.orderHistory,
903
+ extendedCurveHistory: state.extendedCurveHistory,
826
904
  oracle: oracle,
827
905
  },
828
906
  remainingAccounts,
829
907
  });
830
908
  }
831
909
 
910
+ public async initializeUserOrdersThenPlaceAndFillOrder(
911
+ orderParams: OrderParams,
912
+ discountToken?: PublicKey,
913
+ referrer?: PublicKey
914
+ ): Promise<TransactionSignature> {
915
+ const instructions: anchor.web3.TransactionInstruction[] = [];
916
+ const userOrdersAccountExists = await this.userOrdersAccountExists();
917
+ if (!userOrdersAccountExists) {
918
+ instructions.push(await this.getInitializeUserOrdersInstruction());
919
+ }
920
+ instructions.push(
921
+ await this.getPlaceAndFillOrderIx(orderParams, discountToken, referrer)
922
+ );
923
+ const tx = new Transaction();
924
+ for (const instruction of instructions) {
925
+ tx.add(instruction);
926
+ }
927
+
928
+ return await this.txSender.send(tx, [], this.opts);
929
+ }
930
+
832
931
  public async placeAndFillOrder(
833
932
  orderParams: OrderParams,
834
933
  discountToken?: PublicKey,
@@ -899,6 +998,7 @@ export class ClearingHouse {
899
998
  fundingRateHistory: state.fundingRateHistory,
900
999
  orderState: await this.getOrderStatePublicKey(),
901
1000
  orderHistory: orderState.orderHistory,
1001
+ extendedCurveHistory: state.extendedCurveHistory,
902
1002
  oracle: priceOracle,
903
1003
  },
904
1004
  remainingAccounts,
@@ -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';
@@ -24,7 +23,6 @@ import {
24
23
  PRICE_TO_QUOTE_PRECISION,
25
24
  } from './constants/numericConstants';
26
25
  import { UserAccountSubscriber, UserAccountEvents } from './accounts/types';
27
- import { DefaultUserAccountSubscriber } from './accounts/defaultUserAccountSubscriber';
28
26
  import {
29
27
  calculateMarkPrice,
30
28
  calculateBaseAssetValue,
@@ -34,8 +32,13 @@ import {
34
32
  getUserOrdersAccountPublicKey,
35
33
  calculateNewStateAfterOrder,
36
34
  calculateTradeSlippage,
35
+ BN,
37
36
  } from '.';
38
37
  import { getUserAccountPublicKey } from './addresses';
38
+ import {
39
+ getClearingHouseUser,
40
+ getWebSocketClearingHouseUserConfig,
41
+ } from './factory/clearingHouseUser';
39
42
 
40
43
  export class ClearingHouseUser {
41
44
  clearingHouse: ClearingHouse;
@@ -43,18 +46,35 @@ export class ClearingHouseUser {
43
46
  accountSubscriber: UserAccountSubscriber;
44
47
  userAccountPublicKey?: PublicKey;
45
48
  userOrdersAccountPublicKey?: PublicKey;
46
- isSubscribed = false;
49
+ _isSubscribed = false;
47
50
  eventEmitter: StrictEventEmitter<EventEmitter, UserAccountEvents>;
48
51
 
52
+ public get isSubscribed() {
53
+ return this._isSubscribed && this.accountSubscriber.isSubscribed;
54
+ }
55
+
56
+ public set isSubscribed(val: boolean) {
57
+ this._isSubscribed = val;
58
+ }
59
+
60
+ /**
61
+ * @deprecated You should use getClearingHouseUser factory method instead
62
+ * @param clearingHouse
63
+ * @param authority
64
+ * @returns
65
+ */
49
66
  public static from(
50
67
  clearingHouse: ClearingHouse,
51
68
  authority: PublicKey
52
69
  ): ClearingHouseUser {
53
- const accountSubscriber = new DefaultUserAccountSubscriber(
54
- clearingHouse.program,
70
+ if (clearingHouse.accountSubscriber.type !== 'websocket')
71
+ throw 'This method only works for clearing houses with a websocket account listener. Try using the getClearingHouseUser factory method to initialize a ClearingHouseUser instead';
72
+
73
+ const config = getWebSocketClearingHouseUserConfig(
74
+ clearingHouse,
55
75
  authority
56
76
  );
57
- return new ClearingHouseUser(clearingHouse, authority, accountSubscriber);
77
+ return getClearingHouseUser(config);
58
78
  }
59
79
 
60
80
  public constructor(
@@ -100,7 +120,7 @@ export class ClearingHouseUser {
100
120
  return this.accountSubscriber.getUserPositionsAccount();
101
121
  }
102
122
 
103
- public getUserOrdersAccount(): UserOrdersAccount {
123
+ public getUserOrdersAccount(): UserOrdersAccount | undefined {
104
124
  return this.accountSubscriber.getUserOrdersAccount();
105
125
  }
106
126
 
@@ -154,7 +174,7 @@ export class ClearingHouseUser {
154
174
 
155
175
  this.userOrdersAccountPublicKey = await getUserOrdersAccountPublicKey(
156
176
  this.clearingHouse.program.programId,
157
- this.authority
177
+ await this.getUserAccountPublicKey()
158
178
  );
159
179
  return this.userOrdersAccountPublicKey;
160
180
  }
package/src/config.ts CHANGED
@@ -11,7 +11,7 @@ export const configs: { [key in DriftEnv]: DriftConfig } = {
11
11
  devnet: {
12
12
  ENV: 'devnet',
13
13
  PYTH_ORACLE_MAPPING_ADDRESS: 'BmA9Z6FjioHJPpjT39QazZyhDRUdZy2ezwx4GiDdE2u2',
14
- CLEARING_HOUSE_PROGRAM_ID: 'HiZ8CnfEE9LrBZTfc8hBneWrPg1Cbsn8Wdy6SPLfae9V',
14
+ CLEARING_HOUSE_PROGRAM_ID: '3PfbDmWxR6e2rJ2brhSv7KJyUrHbSCu63d3FHqdLhxUJ',
15
15
  USDC_MINT_ADDRESS: '8zGuJQqwhZafTah7Uc7Z4tXRnguqkn5KLFAP8oV6PHe2',
16
16
  },
17
17
  'mainnet-beta': {
@@ -1,4 +1,4 @@
1
- import BN from 'bn.js';
1
+ import { BN } from '../';
2
2
 
3
3
  type Market = {
4
4
  symbol: string;
@@ -90,4 +90,28 @@ export const Markets: Market[] = [
90
90
  mainnetPythOracle: '3pyn4svBbxJ9Wnn3RVeafyLWfzie6yC5eTig2S62v9SC',
91
91
  launchTs: 1643084413000,
92
92
  },
93
+ {
94
+ symbol: 'ALGO-PERP',
95
+ baseAssetSymbol: 'ALGO',
96
+ marketIndex: new BN(10),
97
+ devnetPythOracle: 'c1A946dY5NHuVda77C8XXtXytyR3wK1SCP3eA9VRfC3',
98
+ mainnetPythOracle: 'HqFyq1wh1xKvL7KDqqT7NJeSPdAqsDqnmBisUC2XdXAX',
99
+ launchTs: 1643686767000,
100
+ },
101
+ {
102
+ symbol: 'FTT-PERP',
103
+ baseAssetSymbol: 'FTT',
104
+ marketIndex: new BN(11),
105
+ devnetPythOracle: '6vivTRs5ZPeeXbjo7dfburfaYDWoXjBtdtuYgQRuGfu',
106
+ mainnetPythOracle: '8JPJJkmDScpcNmBRKGZuPuG2GYAveQgP3t5gFuMymwvF',
107
+ launchTs: 1644382122000,
108
+ },
109
+ // {
110
+ // symbol: 'mSOL-PERP',
111
+ // baseAssetSymbol: 'mSOL',
112
+ // marketIndex: new BN(11), //todo
113
+ // devnetPythOracle: '9a6RNx3tCu1TSs6TBSfV2XRXEPEZXQ6WB7jRojZRvyeZ',
114
+ // mainnetPythOracle: 'E4v1BBgoso9s64TQvmyownAVJbhbEPGyzA3qn4n46qj9',
115
+ // launchTs: 1643346125000,
116
+ // },
93
117
  ];
@@ -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
+ }