@drift-labs/sdk 0.1.18-orders.1 → 0.1.18-orders.5

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 (94) 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 +136 -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 +8 -3
  41. package/lib/index.js +9 -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 +3 -2
  54. package/lib/orders.js +8 -8
  55. package/lib/token/index.d.ts +3 -0
  56. package/lib/token/index.js +38 -0
  57. package/lib/types.d.ts +20 -8
  58. package/lib/types.js +2 -2
  59. package/package.json +11 -3
  60. package/src/accounts/bulkAccountLoader.ts +215 -0
  61. package/src/accounts/bulkUserSubscription.ts +28 -0
  62. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +326 -0
  63. package/src/accounts/pollingTokenAccountSubscriber.ts +99 -0
  64. package/src/accounts/pollingUserAccountSubscriber.ts +194 -0
  65. package/src/accounts/types.ts +40 -30
  66. package/src/accounts/utils.ts +3 -0
  67. package/src/accounts/webSocketAccountSubscriber.ts +67 -17
  68. package/src/accounts/{defaultClearingHouseAccountSubscriber.ts → webSocketClearingHouseAccountSubscriber.ts} +9 -6
  69. package/src/accounts/{defaultUserAccountSubscriber.ts → webSocketUserAccountSubscriber.ts} +10 -5
  70. package/src/addresses.ts +6 -4
  71. package/src/admin.ts +73 -20
  72. package/src/clearingHouse.ts +125 -25
  73. package/src/clearingHouseUser.ts +28 -8
  74. package/src/config.ts +1 -1
  75. package/src/constants/markets.ts +25 -1
  76. package/src/constants/numericConstants.ts +2 -1
  77. package/src/examples/makeTradeExample.ts +4 -1
  78. package/src/factory/clearingHouse.ts +125 -0
  79. package/src/factory/clearingHouseUser.ts +73 -0
  80. package/src/idl/clearing_house.json +366 -17
  81. package/src/index.ts +8 -3
  82. package/src/math/conversion.ts +1 -1
  83. package/src/math/funding.ts +5 -1
  84. package/src/math/insuranceFund.ts +1 -1
  85. package/src/math/position.ts +1 -1
  86. package/src/math/utils.ts +1 -1
  87. package/src/mockUSDCFaucet.ts +1 -1
  88. package/src/orderParams.ts +30 -7
  89. package/src/orders.ts +13 -7
  90. package/src/token/index.ts +37 -0
  91. package/src/types.ts +17 -6
  92. package/lib/accounts/defaultHistoryAccountSubscriber.d.ts +0 -28
  93. package/lib/accounts/defaultHistoryAccountSubscriber.js +0 -110
  94. package/src/accounts/defaultHistoryAccountSubscriber.ts +0 -176
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.PollingUserAccountSubscriber = void 0;
13
+ const types_1 = require("./types");
14
+ const events_1 = require("events");
15
+ const addresses_1 = require("../addresses");
16
+ const utils_1 = require("./utils");
17
+ class PollingUserAccountSubscriber {
18
+ constructor(program, authority, accountLoader) {
19
+ this.accountsToPoll = new Map();
20
+ this.type = 'polling';
21
+ this.isSubscribed = false;
22
+ this.program = program;
23
+ this.authority = authority;
24
+ this.accountLoader = accountLoader;
25
+ this.eventEmitter = new events_1.EventEmitter();
26
+ }
27
+ subscribe() {
28
+ return __awaiter(this, void 0, void 0, function* () {
29
+ if (this.isSubscribed) {
30
+ return true;
31
+ }
32
+ yield this.addToAccountLoader();
33
+ yield this.fetchIfUnloaded();
34
+ this.eventEmitter.emit('update');
35
+ this.isSubscribed = true;
36
+ return true;
37
+ });
38
+ }
39
+ addToAccountLoader() {
40
+ return __awaiter(this, void 0, void 0, function* () {
41
+ if (this.accountsToPoll.size > 0) {
42
+ return;
43
+ }
44
+ const userPublicKey = yield addresses_1.getUserAccountPublicKey(this.program.programId, this.authority);
45
+ const userAccount = (yield this.program.account.user.fetch(userPublicKey));
46
+ this.accountsToPoll.set(userPublicKey.toString(), {
47
+ key: 'user',
48
+ publicKey: userPublicKey,
49
+ eventType: 'userAccountData',
50
+ });
51
+ this.accountsToPoll.set(userAccount.positions.toString(), {
52
+ key: 'userPositions',
53
+ publicKey: userAccount.positions,
54
+ eventType: 'userPositionsData',
55
+ });
56
+ const userOrdersPublicKey = yield addresses_1.getUserOrdersAccountPublicKey(this.program.programId, userPublicKey);
57
+ const userOrdersExist = (yield this.program.provider.connection.getParsedAccountInfo(userOrdersPublicKey)).value !== null;
58
+ if (userOrdersExist) {
59
+ this.accountsToPoll.set(userOrdersPublicKey.toString(), {
60
+ key: 'userOrders',
61
+ publicKey: userOrdersPublicKey,
62
+ eventType: 'userOrdersData',
63
+ });
64
+ }
65
+ for (const [_, accountToPoll] of this.accountsToPoll) {
66
+ accountToPoll.callbackId = this.accountLoader.addAccount(accountToPoll.publicKey, (buffer) => {
67
+ const account = this.program.account[accountToPoll.key].coder.accounts.decode(utils_1.capitalize(accountToPoll.key), buffer);
68
+ this[accountToPoll.key] = account;
69
+ // @ts-ignore
70
+ this.eventEmitter.emit(accountToPoll.eventType, account);
71
+ this.eventEmitter.emit('update');
72
+ });
73
+ }
74
+ this.errorCallbackId = this.accountLoader.addErrorCallbacks((error) => {
75
+ this.eventEmitter.emit('error', error);
76
+ });
77
+ });
78
+ }
79
+ fetchIfUnloaded() {
80
+ return __awaiter(this, void 0, void 0, function* () {
81
+ let shouldFetch = false;
82
+ for (const [_, accountToPoll] of this.accountsToPoll) {
83
+ if (this[accountToPoll.key] === undefined) {
84
+ shouldFetch = true;
85
+ break;
86
+ }
87
+ }
88
+ if (shouldFetch) {
89
+ yield this.fetch();
90
+ }
91
+ });
92
+ }
93
+ fetch() {
94
+ return __awaiter(this, void 0, void 0, function* () {
95
+ yield this.accountLoader.load();
96
+ for (const [_, accountToPoll] of this.accountsToPoll) {
97
+ const buffer = this.accountLoader.getAccountData(accountToPoll.publicKey);
98
+ if (buffer) {
99
+ this[accountToPoll.key] = this.program.account[accountToPoll.key].coder.accounts.decode(utils_1.capitalize(accountToPoll.key), buffer);
100
+ }
101
+ }
102
+ });
103
+ }
104
+ unsubscribe() {
105
+ return __awaiter(this, void 0, void 0, function* () {
106
+ if (!this.isSubscribed) {
107
+ return;
108
+ }
109
+ for (const [_, accountToPoll] of this.accountsToPoll) {
110
+ this.accountLoader.removeAccount(accountToPoll.publicKey, accountToPoll.callbackId);
111
+ }
112
+ this.accountLoader.removeErrorCallbacks(this.errorCallbackId);
113
+ this.errorCallbackId = undefined;
114
+ this.accountsToPoll.clear();
115
+ this.isSubscribed = false;
116
+ });
117
+ }
118
+ assertIsSubscribed() {
119
+ if (!this.isSubscribed) {
120
+ throw new types_1.NotSubscribedError('You must call `subscribe` before using this function');
121
+ }
122
+ }
123
+ getUserAccount() {
124
+ this.assertIsSubscribed();
125
+ return this.user;
126
+ }
127
+ getUserPositionsAccount() {
128
+ this.assertIsSubscribed();
129
+ return this.userPositions;
130
+ }
131
+ getUserOrdersAccount() {
132
+ this.assertIsSubscribed();
133
+ return this.userOrders;
134
+ }
135
+ }
136
+ exports.PollingUserAccountSubscriber = PollingUserAccountSubscriber;
@@ -1,12 +1,15 @@
1
1
  /// <reference types="node" />
2
- import { CurveHistoryAccount, DepositHistoryAccount, FundingPaymentHistoryAccount, FundingRateHistoryAccount, LiquidationHistoryAccount, MarketsAccount, OrderHistoryAccount, OrderStateAccount, StateAccount, TradeHistoryAccount, UserAccount, UserOrdersAccount, UserPositionsAccount } from '../types';
2
+ import { DepositHistoryAccount, ExtendedCurveHistoryAccount, FundingPaymentHistoryAccount, FundingRateHistoryAccount, LiquidationHistoryAccount, MarketsAccount, OrderHistoryAccount, OrderStateAccount, StateAccount, TradeHistoryAccount, UserAccount, UserOrdersAccount, UserPositionsAccount } from '../types';
3
3
  import StrictEventEmitter from 'strict-event-emitter-types';
4
4
  import { EventEmitter } from 'events';
5
+ import { PublicKey } from '@solana/web3.js';
6
+ import { AccountInfo } from '@solana/spl-token';
7
+ import { ClearingHouseConfigType, ClearingHouseUserConfigType } from '..';
5
8
  export interface AccountSubscriber<T> {
6
9
  data?: T;
7
10
  subscribe(onChange: (data: T) => void): Promise<void>;
8
11
  fetch(): Promise<void>;
9
- unsubscribe(): void;
12
+ unsubscribe(): Promise<void>;
10
13
  }
11
14
  export declare class NotSubscribedError extends Error {
12
15
  name: string;
@@ -19,10 +22,11 @@ export interface ClearingHouseAccountEvents {
19
22
  tradeHistoryAccountUpdate: (payload: TradeHistoryAccount) => void;
20
23
  liquidationHistoryAccountUpdate: (payload: LiquidationHistoryAccount) => void;
21
24
  depositHistoryAccountUpdate: (payload: DepositHistoryAccount) => void;
22
- curveHistoryAccountUpdate: (payload: CurveHistoryAccount) => void;
25
+ curveHistoryAccountUpdate: (payload: ExtendedCurveHistoryAccount) => void;
23
26
  orderHistoryAccountUpdate: (payload: OrderHistoryAccount) => void;
24
27
  orderStateAccountUpdate: (payload: OrderStateAccount) => void;
25
28
  update: void;
29
+ error: (e: Error) => void;
26
30
  }
27
31
  export declare type ClearingHouseAccountTypes = 'tradeHistoryAccount' | 'depositHistoryAccount' | 'fundingPaymentHistoryAccount' | 'fundingRateHistoryAccount' | 'curveHistoryAccount' | 'liquidationHistoryAccount' | 'orderHistoryAccount';
28
32
  export interface ClearingHouseAccountSubscriber {
@@ -38,37 +42,18 @@ export interface ClearingHouseAccountSubscriber {
38
42
  getDepositHistoryAccount(): DepositHistoryAccount;
39
43
  getFundingPaymentHistoryAccount(): FundingPaymentHistoryAccount;
40
44
  getFundingRateHistoryAccount(): FundingRateHistoryAccount;
41
- getCurveHistoryAccount(): CurveHistoryAccount;
45
+ getCurveHistoryAccount(): ExtendedCurveHistoryAccount;
42
46
  getLiquidationHistoryAccount(): LiquidationHistoryAccount;
43
47
  getOrderStateAccount(): OrderStateAccount;
44
48
  getOrderHistoryAccount(): OrderHistoryAccount;
45
- }
46
- export interface HistoryAccountEvents {
47
- fundingPaymentHistoryAccountUpdate: (payload: FundingPaymentHistoryAccount) => void;
48
- fundingRateHistoryAccountUpdate: (payload: FundingRateHistoryAccount) => void;
49
- tradeHistoryAccountUpdate: (payload: TradeHistoryAccount) => void;
50
- liquidationHistoryAccountUpdate: (payload: LiquidationHistoryAccount) => void;
51
- depositHistoryAccountUpdate: (payload: DepositHistoryAccount) => void;
52
- curveHistoryAccountUpdate: (payload: CurveHistoryAccount) => void;
53
- update: void;
54
- }
55
- export interface HistoryAccountSubscriber {
56
- eventEmitter: StrictEventEmitter<EventEmitter, HistoryAccountEvents>;
57
- isSubscribed: boolean;
58
- subscribe(): Promise<boolean>;
59
- unsubscribe(): Promise<void>;
60
- getTradeHistoryAccount(): TradeHistoryAccount;
61
- getDepositHistoryAccount(): DepositHistoryAccount;
62
- getFundingPaymentHistoryAccount(): FundingPaymentHistoryAccount;
63
- getFundingRateHistoryAccount(): FundingRateHistoryAccount;
64
- getCurveHistoryAccount(): CurveHistoryAccount;
65
- getLiquidationHistoryAccount(): LiquidationHistoryAccount;
49
+ type: ClearingHouseConfigType;
66
50
  }
67
51
  export interface UserAccountEvents {
68
52
  userAccountData: (payload: UserAccount) => void;
69
53
  userPositionsData: (payload: UserPositionsAccount) => void;
70
54
  userOrdersData: (payload: UserOrdersAccount) => void;
71
55
  update: void;
56
+ error: (e: Error) => void;
72
57
  }
73
58
  export interface UserAccountSubscriber {
74
59
  eventEmitter: StrictEventEmitter<EventEmitter, UserAccountEvents>;
@@ -79,4 +64,28 @@ export interface UserAccountSubscriber {
79
64
  getUserAccount(): UserAccount;
80
65
  getUserPositionsAccount(): UserPositionsAccount;
81
66
  getUserOrdersAccount(): UserOrdersAccount;
67
+ type: ClearingHouseUserConfigType;
68
+ }
69
+ export interface TokenAccountEvents {
70
+ tokenAccountUpdate: (payload: AccountInfo) => void;
71
+ update: void;
72
+ error: (e: Error) => void;
73
+ }
74
+ export interface TokenAccountSubscriber {
75
+ eventEmitter: StrictEventEmitter<EventEmitter, TokenAccountEvents>;
76
+ isSubscribed: boolean;
77
+ subscribe(): Promise<boolean>;
78
+ fetch(): Promise<void>;
79
+ unsubscribe(): Promise<void>;
80
+ getTokenAccount(): AccountInfo;
82
81
  }
82
+ export declare type AccountToPoll = {
83
+ key: string;
84
+ publicKey: PublicKey;
85
+ eventType: string;
86
+ callbackId?: string;
87
+ };
88
+ export declare type AccountData = {
89
+ slot: number;
90
+ buffer: Buffer | undefined;
91
+ };
@@ -0,0 +1 @@
1
+ export declare function capitalize(value: string): string;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.capitalize = void 0;
4
+ function capitalize(value) {
5
+ return value[0].toUpperCase() + value.slice(1);
6
+ }
7
+ exports.capitalize = capitalize;
@@ -1,14 +1,18 @@
1
- import { AccountSubscriber } from './types';
1
+ /// <reference types="node" />
2
+ import { AccountData, AccountSubscriber } from './types';
2
3
  import { Program } from '@project-serum/anchor';
3
- import { PublicKey } from '@solana/web3.js';
4
+ import { AccountInfo, Context, PublicKey } from '@solana/web3.js';
4
5
  export declare class WebSocketAccountSubscriber<T> implements AccountSubscriber<T> {
5
6
  data?: T;
7
+ accountData?: AccountData;
6
8
  accountName: string;
7
9
  program: Program;
8
10
  accountPublicKey: PublicKey;
9
11
  onChange: (data: T) => void;
12
+ listenerId?: number;
10
13
  constructor(accountName: string, program: Program, accountPublicKey: PublicKey);
11
14
  subscribe(onChange: (data: T) => void): Promise<void>;
12
15
  fetch(): Promise<void>;
16
+ handleRpcResponse(context: Context, accountInfo?: AccountInfo<Buffer>): void;
13
17
  unsubscribe(): Promise<void>;
14
18
  }
@@ -10,6 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.WebSocketAccountSubscriber = void 0;
13
+ const utils_1 = require("./utils");
13
14
  class WebSocketAccountSubscriber {
14
15
  constructor(accountName, program, accountPublicKey) {
15
16
  this.accountName = accountName;
@@ -18,28 +19,58 @@ class WebSocketAccountSubscriber {
18
19
  }
19
20
  subscribe(onChange) {
20
21
  return __awaiter(this, void 0, void 0, function* () {
22
+ if (this.listenerId) {
23
+ return;
24
+ }
21
25
  this.onChange = onChange;
22
26
  yield this.fetch();
23
- this.program.account[this.accountName]
24
- .subscribe(this.accountPublicKey, this.program.provider.opts.commitment)
25
- .on('change', (data) => __awaiter(this, void 0, void 0, function* () {
26
- this.data = data;
27
- this.onChange(data);
28
- }));
27
+ this.listenerId = this.program.provider.connection.onAccountChange(this.accountPublicKey, (accountInfo, context) => {
28
+ this.handleRpcResponse(context, accountInfo);
29
+ }, this.program.provider.opts.commitment);
29
30
  });
30
31
  }
31
32
  fetch() {
32
33
  return __awaiter(this, void 0, void 0, function* () {
33
- const newData = (yield this.program.account[this.accountName].fetch(this.accountPublicKey));
34
- // if data has changed trigger update
35
- if (JSON.stringify(newData) !== JSON.stringify(this.data)) {
36
- this.data = newData;
34
+ const rpcResponse = yield this.program.provider.connection.getAccountInfoAndContext(this.accountPublicKey, this.program.provider.opts.commitment);
35
+ this.handleRpcResponse(rpcResponse.context, rpcResponse === null || rpcResponse === void 0 ? void 0 : rpcResponse.value);
36
+ });
37
+ }
38
+ handleRpcResponse(context, accountInfo) {
39
+ const newSlot = context.slot;
40
+ let newBuffer = undefined;
41
+ if (accountInfo) {
42
+ newBuffer = accountInfo.data;
43
+ }
44
+ if (!this.accountData) {
45
+ this.accountData = {
46
+ buffer: newBuffer,
47
+ slot: newSlot,
48
+ };
49
+ if (newBuffer) {
50
+ this.data = this.program.account[this.accountName].coder.accounts.decode(utils_1.capitalize(this.accountName), newBuffer);
37
51
  this.onChange(this.data);
38
52
  }
39
- });
53
+ return;
54
+ }
55
+ if (newSlot <= this.accountData.slot) {
56
+ return;
57
+ }
58
+ const oldBuffer = this.accountData.buffer;
59
+ if (newBuffer && (!oldBuffer || !newBuffer.equals(oldBuffer))) {
60
+ this.accountData = {
61
+ buffer: newBuffer,
62
+ slot: newSlot,
63
+ };
64
+ this.data = this.program.account[this.accountName].coder.accounts.decode(utils_1.capitalize(this.accountName), newBuffer);
65
+ this.onChange(this.data);
66
+ }
40
67
  }
41
68
  unsubscribe() {
42
- return this.program.account[this.accountName].unsubscribe(this.accountPublicKey);
69
+ if (this.listenerId) {
70
+ const promise = this.program.provider.connection.removeAccountChangeListener(this.listenerId);
71
+ this.listenerId = undefined;
72
+ return promise;
73
+ }
43
74
  }
44
75
  }
45
76
  exports.WebSocketAccountSubscriber = WebSocketAccountSubscriber;
@@ -1,11 +1,12 @@
1
1
  /// <reference types="node" />
2
2
  import { ClearingHouseAccountSubscriber, ClearingHouseAccountEvents, ClearingHouseAccountTypes } from './types';
3
3
  import { AccountSubscriber } from './types';
4
- import { CurveHistoryAccount, DepositHistoryAccount, FundingPaymentHistoryAccount, FundingRateHistoryAccount, LiquidationHistoryAccount, MarketsAccount, OrderHistoryAccount, OrderStateAccount, StateAccount, TradeHistoryAccount } from '../types';
4
+ import { DepositHistoryAccount, ExtendedCurveHistoryAccount, FundingPaymentHistoryAccount, FundingRateHistoryAccount, LiquidationHistoryAccount, MarketsAccount, OrderHistoryAccount, OrderStateAccount, StateAccount, TradeHistoryAccount } from '../types';
5
5
  import { Program } from '@project-serum/anchor';
6
6
  import StrictEventEmitter from 'strict-event-emitter-types';
7
7
  import { EventEmitter } from 'events';
8
- export declare class DefaultClearingHouseAccountSubscriber implements ClearingHouseAccountSubscriber {
8
+ import { ClearingHouseConfigType } from '../factory/clearingHouse';
9
+ export declare class WebSocketClearingHouseAccountSubscriber implements ClearingHouseAccountSubscriber {
9
10
  isSubscribed: boolean;
10
11
  program: Program;
11
12
  eventEmitter: StrictEventEmitter<EventEmitter, ClearingHouseAccountEvents>;
@@ -15,11 +16,12 @@ export declare class DefaultClearingHouseAccountSubscriber implements ClearingHo
15
16
  depositHistoryAccountSubscriber?: AccountSubscriber<DepositHistoryAccount>;
16
17
  fundingPaymentHistoryAccountSubscriber?: AccountSubscriber<FundingPaymentHistoryAccount>;
17
18
  fundingRateHistoryAccountSubscriber?: AccountSubscriber<FundingRateHistoryAccount>;
18
- curveHistoryAccountSubscriber?: AccountSubscriber<CurveHistoryAccount>;
19
+ curveHistoryAccountSubscriber?: AccountSubscriber<ExtendedCurveHistoryAccount>;
19
20
  liquidationHistoryAccountSubscriber?: AccountSubscriber<LiquidationHistoryAccount>;
20
21
  orderStateAccountSubscriber?: AccountSubscriber<OrderStateAccount>;
21
22
  orderHistoryAccountSubscriber?: AccountSubscriber<OrderHistoryAccount>;
22
23
  optionalExtraSubscriptions: ClearingHouseAccountTypes[];
24
+ type: ClearingHouseConfigType;
23
25
  private isSubscribing;
24
26
  private subscriptionPromise;
25
27
  private subscriptionPromiseResolver;
@@ -35,7 +37,7 @@ export declare class DefaultClearingHouseAccountSubscriber implements ClearingHo
35
37
  getDepositHistoryAccount(): DepositHistoryAccount;
36
38
  getFundingPaymentHistoryAccount(): FundingPaymentHistoryAccount;
37
39
  getFundingRateHistoryAccount(): FundingRateHistoryAccount;
38
- getCurveHistoryAccount(): CurveHistoryAccount;
40
+ getCurveHistoryAccount(): ExtendedCurveHistoryAccount;
39
41
  getLiquidationHistoryAccount(): LiquidationHistoryAccount;
40
42
  getOrderHistoryAccount(): OrderHistoryAccount;
41
43
  getOrderStateAccount(): OrderStateAccount;
@@ -9,14 +9,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.DefaultClearingHouseAccountSubscriber = void 0;
12
+ exports.WebSocketClearingHouseAccountSubscriber = void 0;
13
13
  const types_1 = require("./types");
14
14
  const events_1 = require("events");
15
15
  const addresses_1 = require("../addresses");
16
16
  const webSocketAccountSubscriber_1 = require("./webSocketAccountSubscriber");
17
- class DefaultClearingHouseAccountSubscriber {
17
+ class WebSocketClearingHouseAccountSubscriber {
18
18
  constructor(program) {
19
19
  this.optionalExtraSubscriptions = [];
20
+ this.type = 'websocket';
20
21
  this.isSubscribing = false;
21
22
  this.isSubscribed = false;
22
23
  this.program = program;
@@ -60,7 +61,7 @@ class DefaultClearingHouseAccountSubscriber {
60
61
  new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('fundingPaymentHistory', this.program, state.fundingPaymentHistory);
61
62
  this.fundingRateHistoryAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('fundingRateHistory', this.program, state.fundingRateHistory);
62
63
  this.liquidationHistoryAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('liquidationHistory', this.program, state.liquidationHistory);
63
- this.curveHistoryAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('curveHistory', this.program, state.curveHistory);
64
+ this.curveHistoryAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('extendedCurveHistory', this.program, state.extendedCurveHistory);
64
65
  this.orderHistoryAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('orderHistory', this.program, orderState.orderHistory);
65
66
  const extraSusbcribersToUse = [];
66
67
  if (optionalSubscriptions === null || optionalSubscriptions === void 0 ? void 0 : optionalSubscriptions.includes('tradeHistoryAccount'))
@@ -222,4 +223,4 @@ class DefaultClearingHouseAccountSubscriber {
222
223
  return this.orderStateAccountSubscriber.data;
223
224
  }
224
225
  }
225
- exports.DefaultClearingHouseAccountSubscriber = DefaultClearingHouseAccountSubscriber;
226
+ exports.WebSocketClearingHouseAccountSubscriber = WebSocketClearingHouseAccountSubscriber;
@@ -5,7 +5,8 @@ import StrictEventEmitter from 'strict-event-emitter-types';
5
5
  import { EventEmitter } from 'events';
6
6
  import { PublicKey } from '@solana/web3.js';
7
7
  import { UserAccount, UserOrdersAccount, UserPositionsAccount } from '../types';
8
- export declare class DefaultUserAccountSubscriber implements UserAccountSubscriber {
8
+ import { ClearingHouseConfigType } from '../factory/clearingHouse';
9
+ export declare class WebSocketUserAccountSubscriber implements UserAccountSubscriber {
9
10
  isSubscribed: boolean;
10
11
  program: Program;
11
12
  eventEmitter: StrictEventEmitter<EventEmitter, UserAccountEvents>;
@@ -13,6 +14,7 @@ export declare class DefaultUserAccountSubscriber implements UserAccountSubscrib
13
14
  userDataAccountSubscriber: AccountSubscriber<UserAccount>;
14
15
  userPositionsAccountSubscriber: AccountSubscriber<UserPositionsAccount>;
15
16
  userOrdersAccountSubscriber: AccountSubscriber<UserOrdersAccount>;
17
+ type: ClearingHouseConfigType;
16
18
  constructor(program: Program, authority: PublicKey);
17
19
  subscribe(): Promise<boolean>;
18
20
  fetch(): Promise<void>;
@@ -9,13 +9,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.DefaultUserAccountSubscriber = void 0;
12
+ exports.WebSocketUserAccountSubscriber = void 0;
13
13
  const types_1 = require("./types");
14
14
  const events_1 = require("events");
15
15
  const addresses_1 = require("../addresses");
16
16
  const webSocketAccountSubscriber_1 = require("./webSocketAccountSubscriber");
17
- class DefaultUserAccountSubscriber {
17
+ class WebSocketUserAccountSubscriber {
18
18
  constructor(program, authority) {
19
+ this.type = 'websocket';
19
20
  this.isSubscribed = false;
20
21
  this.program = program;
21
22
  this.authority = authority;
@@ -38,7 +39,7 @@ class DefaultUserAccountSubscriber {
38
39
  this.eventEmitter.emit('userPositionsData', data);
39
40
  this.eventEmitter.emit('update');
40
41
  });
41
- const userOrdersPublicKey = yield addresses_1.getUserOrdersAccountPublicKey(this.program.programId, this.authority);
42
+ const userOrdersPublicKey = yield addresses_1.getUserOrdersAccountPublicKey(this.program.programId, userPublicKey);
42
43
  this.userOrdersAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('userOrders', this.program, userOrdersPublicKey);
43
44
  yield this.userOrdersAccountSubscriber.subscribe((data) => {
44
45
  this.eventEmitter.emit('userOrdersData', data);
@@ -63,9 +64,11 @@ class DefaultUserAccountSubscriber {
63
64
  if (!this.isSubscribed) {
64
65
  return;
65
66
  }
66
- this.userDataAccountSubscriber.unsubscribe();
67
- this.userPositionsAccountSubscriber.unsubscribe();
68
- this.userOrdersAccountSubscriber.unsubscribe();
67
+ yield Promise.all([
68
+ this.userDataAccountSubscriber.unsubscribe(),
69
+ this.userPositionsAccountSubscriber.unsubscribe(),
70
+ yield this.userOrdersAccountSubscriber.unsubscribe(),
71
+ ]);
69
72
  this.isSubscribed = false;
70
73
  });
71
74
  }
@@ -86,4 +89,4 @@ class DefaultUserAccountSubscriber {
86
89
  return this.userOrdersAccountSubscriber.data;
87
90
  }
88
91
  }
89
- exports.DefaultUserAccountSubscriber = DefaultUserAccountSubscriber;
92
+ exports.WebSocketUserAccountSubscriber = WebSocketUserAccountSubscriber;
@@ -5,5 +5,5 @@ export declare function getOrderStateAccountPublicKeyAndNonce(programId: PublicK
5
5
  export declare function getClearingHouseStateAccountPublicKey(programId: PublicKey): Promise<PublicKey>;
6
6
  export declare function getUserAccountPublicKeyAndNonce(programId: PublicKey, authority: PublicKey): Promise<[PublicKey, number]>;
7
7
  export declare function getUserAccountPublicKey(programId: PublicKey, authority: PublicKey): Promise<PublicKey>;
8
- export declare function getUserOrdersAccountPublicKeyAndNonce(programId: PublicKey, authority: PublicKey): Promise<[PublicKey, number]>;
9
- export declare function getUserOrdersAccountPublicKey(programId: PublicKey, authority: PublicKey): Promise<PublicKey>;
8
+ export declare function getUserOrdersAccountPublicKeyAndNonce(programId: PublicKey, userAccount: PublicKey): Promise<[PublicKey, number]>;
9
+ export declare function getUserOrdersAccountPublicKey(programId: PublicKey, userAccount: PublicKey): Promise<PublicKey>;
package/lib/addresses.js CHANGED
@@ -66,18 +66,18 @@ function getUserAccountPublicKey(programId, authority) {
66
66
  });
67
67
  }
68
68
  exports.getUserAccountPublicKey = getUserAccountPublicKey;
69
- function getUserOrdersAccountPublicKeyAndNonce(programId, authority) {
69
+ function getUserOrdersAccountPublicKeyAndNonce(programId, userAccount) {
70
70
  return __awaiter(this, void 0, void 0, function* () {
71
71
  return anchor.web3.PublicKey.findProgramAddress([
72
72
  Buffer.from(anchor.utils.bytes.utf8.encode('user_orders')),
73
- authority.toBuffer(),
73
+ userAccount.toBuffer(),
74
74
  ], programId);
75
75
  });
76
76
  }
77
77
  exports.getUserOrdersAccountPublicKeyAndNonce = getUserOrdersAccountPublicKeyAndNonce;
78
- function getUserOrdersAccountPublicKey(programId, authority) {
78
+ function getUserOrdersAccountPublicKey(programId, userAccount) {
79
79
  return __awaiter(this, void 0, void 0, function* () {
80
- return (yield getUserOrdersAccountPublicKeyAndNonce(programId, authority))[0];
80
+ return (yield getUserOrdersAccountPublicKeyAndNonce(programId, userAccount))[0];
81
81
  });
82
82
  }
83
83
  exports.getUserOrdersAccountPublicKey = getUserOrdersAccountPublicKey;
package/lib/admin.d.ts CHANGED
@@ -14,8 +14,11 @@ export declare class Admin extends ClearingHouse {
14
14
  initializeMarket(marketIndex: BN, priceOracle: PublicKey, baseAssetReserve: BN, quoteAssetReserve: BN, periodicity: BN, pegMultiplier?: BN): Promise<TransactionSignature>;
15
15
  moveAmmPrice(baseAssetReserve: BN, quoteAssetReserve: BN, marketIndex: BN): Promise<TransactionSignature>;
16
16
  updateK(sqrtK: BN, marketIndex: BN): Promise<TransactionSignature>;
17
+ updateCurveHistory(): Promise<TransactionSignature>;
17
18
  moveAmmToPrice(marketIndex: BN, targetPrice: BN): Promise<TransactionSignature>;
18
19
  repegAmmCurve(newPeg: BN, marketIndex: BN): Promise<TransactionSignature>;
20
+ updateAmmOracleTwap(marketIndex: BN): Promise<TransactionSignature>;
21
+ resetAmmOracleTwap(marketIndex: BN): Promise<TransactionSignature>;
19
22
  withdrawFromInsuranceVault(amount: BN, recipient: PublicKey): Promise<TransactionSignature>;
20
23
  withdrawFees(marketIndex: BN, amount: BN, recipient: PublicKey): Promise<TransactionSignature>;
21
24
  withdrawFromInsuranceVaultToMarket(marketIndex: BN, amount: BN): Promise<TransactionSignature>;
package/lib/admin.js CHANGED
@@ -27,9 +27,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
27
27
  step((generator = generator.apply(thisArg, _arguments || [])).next());
28
28
  });
29
29
  };
30
- var __importDefault = (this && this.__importDefault) || function (mod) {
31
- return (mod && mod.__esModule) ? mod : { "default": mod };
32
- };
33
30
  Object.defineProperty(exports, "__esModule", { value: true });
34
31
  exports.Admin = void 0;
35
32
  const web3_js_1 = require("@solana/web3.js");
@@ -39,18 +36,13 @@ const addresses_1 = require("./addresses");
39
36
  const spl_token_1 = require("@solana/spl-token");
40
37
  const clearingHouse_1 = require("./clearingHouse");
41
38
  const numericConstants_1 = require("./constants/numericConstants");
42
- const clearing_house_json_1 = __importDefault(require("./idl/clearing_house.json"));
43
- const defaultClearingHouseAccountSubscriber_1 = require("./accounts/defaultClearingHouseAccountSubscriber");
44
- const defaultTxSender_1 = require("./tx/defaultTxSender");
45
39
  const trade_1 = require("./math/trade");
46
40
  const amm_1 = require("./math/amm");
41
+ const clearingHouse_2 = require("./factory/clearingHouse");
47
42
  class Admin extends clearingHouse_1.ClearingHouse {
48
43
  static from(connection, wallet, clearingHouseProgramId, opts = anchor_1.Provider.defaultOptions()) {
49
- const provider = new anchor_1.Provider(connection, wallet, opts);
50
- const program = new anchor_1.Program(clearing_house_json_1.default, clearingHouseProgramId, provider);
51
- const accountSubscriber = new defaultClearingHouseAccountSubscriber_1.DefaultClearingHouseAccountSubscriber(program);
52
- const txSender = new defaultTxSender_1.DefaultTxSender(provider);
53
- return new Admin(connection, wallet, program, accountSubscriber, txSender, opts);
44
+ const config = clearingHouse_2.getWebSocketClearingHouseConfig(connection, wallet, clearingHouseProgramId, opts);
45
+ return clearingHouse_2.getAdmin(config);
54
46
  }
55
47
  initialize(usdcMint, adminControlsPrices) {
56
48
  return __awaiter(this, void 0, void 0, function* () {
@@ -108,7 +100,7 @@ class Admin extends clearingHouse_1.ClearingHouse {
108
100
  yield this.program.account.tradeHistory.createInstruction(tradeHistory),
109
101
  yield this.program.account.liquidationHistory.createInstruction(liquidationHistory),
110
102
  yield this.program.account.depositHistory.createInstruction(depositHistory),
111
- yield this.program.account.curveHistory.createInstruction(curveHistory),
103
+ yield this.program.account.extendedCurveHistory.createInstruction(curveHistory),
112
104
  ],
113
105
  });
114
106
  const initializeHistoryTxSig = yield this.txSender.send(initializeHistoryTx, [
@@ -175,13 +167,35 @@ class Admin extends clearingHouse_1.ClearingHouse {
175
167
  updateK(sqrtK, marketIndex) {
176
168
  return __awaiter(this, void 0, void 0, function* () {
177
169
  const state = this.getStateAccount();
170
+ const markets = this.getMarketsAccount();
171
+ const marketData = markets.markets[marketIndex.toNumber()];
172
+ const ammData = marketData.amm;
178
173
  return yield this.program.rpc.updateK(sqrtK, marketIndex, {
179
174
  accounts: {
180
175
  state: yield this.getStatePublicKey(),
181
176
  admin: this.wallet.publicKey,
182
177
  markets: state.markets,
178
+ curveHistory: state.extendedCurveHistory,
179
+ oracle: ammData.oracle,
180
+ },
181
+ });
182
+ });
183
+ }
184
+ updateCurveHistory() {
185
+ return __awaiter(this, void 0, void 0, function* () {
186
+ const extendedCurveHistory = anchor.web3.Keypair.generate();
187
+ const state = this.getStateAccount();
188
+ return yield this.program.rpc.updateCurveHistory({
189
+ accounts: {
190
+ state: yield this.getStatePublicKey(),
191
+ admin: this.wallet.publicKey,
183
192
  curveHistory: state.curveHistory,
193
+ extendedCurveHistory: extendedCurveHistory.publicKey,
184
194
  },
195
+ instructions: [
196
+ yield this.program.account.extendedCurveHistory.createInstruction(extendedCurveHistory),
197
+ ],
198
+ signers: [extendedCurveHistory],
185
199
  });
186
200
  });
187
201
  }
@@ -212,7 +226,41 @@ class Admin extends clearingHouse_1.ClearingHouse {
212
226
  admin: this.wallet.publicKey,
213
227
  oracle: ammData.oracle,
214
228
  markets: state.markets,
215
- curveHistory: state.curveHistory,
229
+ curveHistory: state.extendedCurveHistory,
230
+ },
231
+ });
232
+ });
233
+ }
234
+ updateAmmOracleTwap(marketIndex) {
235
+ return __awaiter(this, void 0, void 0, function* () {
236
+ const state = this.getStateAccount();
237
+ const markets = this.getMarketsAccount();
238
+ const marketData = markets.markets[marketIndex.toNumber()];
239
+ const ammData = marketData.amm;
240
+ return yield this.program.rpc.updateAmmOracleTwap(marketIndex, {
241
+ accounts: {
242
+ state: yield this.getStatePublicKey(),
243
+ admin: this.wallet.publicKey,
244
+ oracle: ammData.oracle,
245
+ markets: state.markets,
246
+ curveHistory: state.extendedCurveHistory,
247
+ },
248
+ });
249
+ });
250
+ }
251
+ resetAmmOracleTwap(marketIndex) {
252
+ return __awaiter(this, void 0, void 0, function* () {
253
+ const state = this.getStateAccount();
254
+ const markets = this.getMarketsAccount();
255
+ const marketData = markets.markets[marketIndex.toNumber()];
256
+ const ammData = marketData.amm;
257
+ return yield this.program.rpc.resetAmmOracleTwap(marketIndex, {
258
+ accounts: {
259
+ state: yield this.getStatePublicKey(),
260
+ admin: this.wallet.publicKey,
261
+ oracle: ammData.oracle,
262
+ markets: state.markets,
263
+ curveHistory: state.extendedCurveHistory,
216
264
  },
217
265
  });
218
266
  });