@drift-labs/sdk 0.2.0-master.2 → 0.2.0-master.22

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 (149) hide show
  1. package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
  2. package/lib/accounts/bulkUserStatsSubscription.js +21 -0
  3. package/lib/accounts/bulkUserSubscription.js +0 -1
  4. package/lib/accounts/fetch.d.ts +2 -1
  5. package/lib/accounts/fetch.js +9 -1
  6. package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
  7. package/lib/accounts/pollingUserStatsAccountSubscriber.js +113 -0
  8. package/lib/accounts/types.d.ts +14 -1
  9. package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
  10. package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
  11. package/lib/addresses/pda.d.ts +1 -0
  12. package/lib/addresses/pda.js +8 -1
  13. package/lib/admin.d.ts +9 -5
  14. package/lib/admin.js +52 -11
  15. package/lib/clearingHouse.d.ts +52 -23
  16. package/lib/clearingHouse.js +736 -200
  17. package/lib/clearingHouseConfig.d.ts +1 -0
  18. package/lib/clearingHouseUser.d.ts +24 -16
  19. package/lib/clearingHouseUser.js +223 -101
  20. package/lib/clearingHouseUserStats.d.ts +18 -0
  21. package/lib/clearingHouseUserStats.js +49 -0
  22. package/lib/clearingHouseUserStatsConfig.d.ts +14 -0
  23. package/lib/clearingHouseUserStatsConfig.js +2 -0
  24. package/lib/config.js +1 -1
  25. package/lib/constants/banks.d.ts +2 -2
  26. package/lib/constants/banks.js +12 -4
  27. package/lib/constants/numericConstants.d.ts +5 -0
  28. package/lib/constants/numericConstants.js +8 -3
  29. package/lib/events/eventList.js +3 -0
  30. package/lib/events/types.d.ts +3 -1
  31. package/lib/events/types.js +2 -0
  32. package/lib/factory/bigNum.d.ts +1 -0
  33. package/lib/factory/bigNum.js +34 -10
  34. package/lib/idl/clearing_house.json +1603 -377
  35. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  36. package/lib/index.d.ts +9 -3
  37. package/lib/index.js +13 -3
  38. package/lib/math/amm.d.ts +1 -0
  39. package/lib/math/amm.js +22 -38
  40. package/lib/math/auction.js +4 -1
  41. package/lib/math/bankBalance.d.ts +7 -1
  42. package/lib/math/bankBalance.js +77 -2
  43. package/lib/math/margin.d.ts +11 -0
  44. package/lib/math/margin.js +72 -0
  45. package/lib/math/market.d.ts +4 -1
  46. package/lib/math/market.js +35 -1
  47. package/lib/math/oracles.d.ts +3 -0
  48. package/lib/math/oracles.js +25 -5
  49. package/lib/math/orders.d.ts +6 -2
  50. package/lib/math/orders.js +62 -12
  51. package/lib/math/position.d.ts +8 -0
  52. package/lib/math/position.js +45 -12
  53. package/lib/math/trade.d.ts +1 -1
  54. package/lib/math/trade.js +7 -10
  55. package/lib/orderParams.d.ts +14 -5
  56. package/lib/orderParams.js +8 -96
  57. package/lib/slot/SlotSubscriber.d.ts +7 -0
  58. package/lib/slot/SlotSubscriber.js +3 -0
  59. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  60. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  61. package/lib/tx/retryTxSender.js +9 -2
  62. package/lib/tx/utils.js +1 -1
  63. package/lib/types.d.ts +236 -26
  64. package/lib/types.js +64 -1
  65. package/lib/util/computeUnits.js +1 -1
  66. package/lib/util/getTokenAddress.d.ts +2 -0
  67. package/lib/util/getTokenAddress.js +9 -0
  68. package/package.json +3 -3
  69. package/src/accounts/bulkUserStatsSubscription.ts +33 -0
  70. package/src/accounts/bulkUserSubscription.ts +0 -1
  71. package/src/accounts/fetch.ts +27 -2
  72. package/src/accounts/pollingUserStatsAccountSubscriber.ts +172 -0
  73. package/src/accounts/types.ts +18 -0
  74. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
  75. package/src/addresses/marketAddresses.js +26 -0
  76. package/src/addresses/pda.ts +13 -0
  77. package/src/admin.ts +82 -15
  78. package/src/assert/assert.js +9 -0
  79. package/src/clearingHouse.ts +1232 -323
  80. package/src/clearingHouseConfig.ts +1 -0
  81. package/src/clearingHouseUser.ts +343 -155
  82. package/src/clearingHouseUserStats.ts +75 -0
  83. package/src/clearingHouseUserStatsConfig.ts +18 -0
  84. package/src/config.ts +1 -1
  85. package/src/constants/banks.js +42 -0
  86. package/src/constants/banks.ts +14 -4
  87. package/src/constants/markets.js +42 -0
  88. package/src/constants/numericConstants.js +41 -0
  89. package/src/constants/numericConstants.ts +14 -2
  90. package/src/events/eventList.js +77 -0
  91. package/src/events/eventList.ts +3 -0
  92. package/src/events/eventSubscriber.js +139 -0
  93. package/src/events/sort.js +44 -0
  94. package/src/events/txEventCache.js +71 -0
  95. package/src/events/types.ts +6 -0
  96. package/src/examples/makeTradeExample.js +80 -0
  97. package/src/factory/bigNum.js +390 -0
  98. package/src/factory/bigNum.ts +42 -13
  99. package/src/factory/oracleClient.js +20 -0
  100. package/src/idl/clearing_house.json +1603 -377
  101. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  102. package/src/index.ts +9 -3
  103. package/src/math/amm.ts +54 -55
  104. package/src/math/auction.js +42 -0
  105. package/src/math/auction.ts +5 -1
  106. package/src/math/bankBalance.ts +148 -2
  107. package/src/math/conversion.js +11 -0
  108. package/src/math/funding.js +248 -0
  109. package/src/math/margin.ts +124 -0
  110. package/src/math/market.ts +66 -1
  111. package/src/math/oracles.js +26 -0
  112. package/src/math/oracles.ts +42 -5
  113. package/src/math/orders.ts +129 -13
  114. package/src/math/position.ts +64 -9
  115. package/src/math/repeg.js +128 -0
  116. package/src/math/state.js +15 -0
  117. package/src/math/trade.js +253 -0
  118. package/src/math/trade.ts +23 -25
  119. package/src/math/utils.js +0 -1
  120. package/src/oracles/oracleClientCache.js +19 -0
  121. package/src/oracles/pythClient.js +46 -0
  122. package/src/oracles/quoteAssetOracleClient.js +32 -0
  123. package/src/oracles/switchboardClient.js +69 -0
  124. package/src/oracles/types.js +2 -0
  125. package/src/orderParams.js +20 -0
  126. package/src/orderParams.ts +20 -141
  127. package/src/slot/SlotSubscriber.js +39 -0
  128. package/src/slot/SlotSubscriber.ts +11 -1
  129. package/src/token/index.js +38 -0
  130. package/src/tokenFaucet.js +189 -0
  131. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  132. package/src/tx/retryTxSender.ts +11 -3
  133. package/src/tx/types.js +2 -0
  134. package/src/tx/utils.js +17 -0
  135. package/src/tx/utils.ts +1 -1
  136. package/src/types.ts +239 -27
  137. package/src/userName.js +20 -0
  138. package/src/util/computeUnits.js +21 -11
  139. package/src/util/computeUnits.ts +1 -1
  140. package/src/util/getTokenAddress.js +9 -0
  141. package/src/util/getTokenAddress.ts +18 -0
  142. package/src/util/promiseTimeout.js +14 -0
  143. package/src/util/tps.js +27 -0
  144. package/src/wallet.js +35 -0
  145. package/tests/bn/test.ts +10 -0
  146. package/lib/orders.d.ts +0 -8
  147. package/lib/orders.js +0 -142
  148. package/src/orders.ts +0 -251
  149. package/src/util/computeUnits.js.map +0 -1
@@ -0,0 +1,7 @@
1
+ import { ClearingHouseUserStats } from '../clearingHouseUserStats';
2
+ import { BulkAccountLoader } from './bulkAccountLoader';
3
+ /**
4
+ * @param userStats
5
+ * @param accountLoader
6
+ */
7
+ export declare function bulkPollingUserStatsSubscribe(userStats: ClearingHouseUserStats[], accountLoader: BulkAccountLoader): Promise<void>;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.bulkPollingUserStatsSubscribe = void 0;
4
+ /**
5
+ * @param userStats
6
+ * @param accountLoader
7
+ */
8
+ async function bulkPollingUserStatsSubscribe(userStats, accountLoader) {
9
+ if (userStats.length === 0) {
10
+ await accountLoader.load();
11
+ return;
12
+ }
13
+ await Promise.all(userStats.map((userStat) => {
14
+ return userStat.accountSubscriber.addToAccountLoader();
15
+ }));
16
+ await accountLoader.load();
17
+ await Promise.all(userStats.map(async (userStat) => {
18
+ return userStat.subscribe();
19
+ }));
20
+ }
21
+ exports.bulkPollingUserStatsSubscribe = bulkPollingUserStatsSubscribe;
@@ -11,7 +11,6 @@ async function bulkPollingUserSubscribe(users, accountLoader) {
11
11
  return;
12
12
  }
13
13
  await Promise.all(users.map((user) => {
14
- // Pull the keys from the authority map so we can skip fetching them in addToAccountLoader
15
14
  return user.accountSubscriber.addToAccountLoader();
16
15
  }));
17
16
  await accountLoader.load();
@@ -1,4 +1,5 @@
1
1
  import { Connection, PublicKey } from '@solana/web3.js';
2
- import { UserAccount } from '../types';
2
+ import { UserAccount, UserStatsAccount } from '../types';
3
3
  import { Program } from '@project-serum/anchor';
4
4
  export declare function fetchUserAccounts(connection: Connection, program: Program, authority: PublicKey, limit?: number): Promise<(UserAccount | undefined)[]>;
5
+ export declare function fetchUserStatsAccount(connection: Connection, program: Program, authority: PublicKey): Promise<UserStatsAccount | undefined>;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.fetchUserAccounts = void 0;
3
+ exports.fetchUserStatsAccount = exports.fetchUserAccounts = void 0;
4
4
  const pda_1 = require("../addresses/pda");
5
5
  async function fetchUserAccounts(connection, program, authority, limit = 8) {
6
6
  const userAccountPublicKeys = new Array();
@@ -16,3 +16,11 @@ async function fetchUserAccounts(connection, program, authority, limit = 8) {
16
16
  });
17
17
  }
18
18
  exports.fetchUserAccounts = fetchUserAccounts;
19
+ async function fetchUserStatsAccount(connection, program, authority) {
20
+ const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(program.programId, authority);
21
+ const accountInfo = await connection.getAccountInfo(userStatsPublicKey, 'confirmed');
22
+ return accountInfo
23
+ ? program.account.user.coder.accounts.decode('UserStats', accountInfo.data)
24
+ : undefined;
25
+ }
26
+ exports.fetchUserStatsAccount = fetchUserStatsAccount;
@@ -0,0 +1,27 @@
1
+ /// <reference types="node" />
2
+ import { DataAndSlot, AccountToPoll, UserStatsAccountSubscriber, UserStatsAccountEvents } from './types';
3
+ import { Program } from '@project-serum/anchor';
4
+ import StrictEventEmitter from 'strict-event-emitter-types';
5
+ import { EventEmitter } from 'events';
6
+ import { PublicKey } from '@solana/web3.js';
7
+ import { UserStatsAccount } from '../types';
8
+ import { BulkAccountLoader } from './bulkAccountLoader';
9
+ export declare class PollingUserStatsAccountSubscriber implements UserStatsAccountSubscriber {
10
+ isSubscribed: boolean;
11
+ program: Program;
12
+ eventEmitter: StrictEventEmitter<EventEmitter, UserStatsAccountEvents>;
13
+ userStatsAccountPublicKey: PublicKey;
14
+ accountLoader: BulkAccountLoader;
15
+ accountsToPoll: Map<string, AccountToPoll>;
16
+ errorCallbackId?: string;
17
+ userStats?: DataAndSlot<UserStatsAccount>;
18
+ constructor(program: Program, userStatsAccountPublicKey: PublicKey, accountLoader: BulkAccountLoader);
19
+ subscribe(): Promise<boolean>;
20
+ addToAccountLoader(): Promise<void>;
21
+ fetchIfUnloaded(): Promise<void>;
22
+ fetch(): Promise<void>;
23
+ didSubscriptionSucceed(): boolean;
24
+ unsubscribe(): Promise<void>;
25
+ assertIsSubscribed(): void;
26
+ getUserStatsAccountAndSlot(): DataAndSlot<UserStatsAccount>;
27
+ }
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PollingUserStatsAccountSubscriber = void 0;
4
+ const types_1 = require("./types");
5
+ const events_1 = require("events");
6
+ const utils_1 = require("./utils");
7
+ class PollingUserStatsAccountSubscriber {
8
+ constructor(program, userStatsAccountPublicKey, accountLoader) {
9
+ this.accountsToPoll = new Map();
10
+ this.isSubscribed = false;
11
+ this.program = program;
12
+ this.accountLoader = accountLoader;
13
+ this.eventEmitter = new events_1.EventEmitter();
14
+ this.userStatsAccountPublicKey = userStatsAccountPublicKey;
15
+ }
16
+ async subscribe() {
17
+ if (this.isSubscribed) {
18
+ return true;
19
+ }
20
+ await this.addToAccountLoader();
21
+ let subscriptionSucceeded = false;
22
+ let retries = 0;
23
+ while (!subscriptionSucceeded && retries < 5) {
24
+ await this.fetchIfUnloaded();
25
+ subscriptionSucceeded = this.didSubscriptionSucceed();
26
+ retries++;
27
+ }
28
+ if (subscriptionSucceeded) {
29
+ this.eventEmitter.emit('update');
30
+ }
31
+ this.isSubscribed = subscriptionSucceeded;
32
+ return subscriptionSucceeded;
33
+ }
34
+ async addToAccountLoader() {
35
+ if (this.accountsToPoll.size > 0) {
36
+ return;
37
+ }
38
+ this.accountsToPoll.set(this.userStatsAccountPublicKey.toString(), {
39
+ key: 'userStats',
40
+ publicKey: this.userStatsAccountPublicKey,
41
+ eventType: 'userStatsAccountUpdate',
42
+ });
43
+ for (const [_, accountToPoll] of this.accountsToPoll) {
44
+ accountToPoll.callbackId = this.accountLoader.addAccount(accountToPoll.publicKey, (buffer, slot) => {
45
+ if (!buffer) {
46
+ return;
47
+ }
48
+ const account = this.program.account[accountToPoll.key].coder.accounts.decode((0, utils_1.capitalize)(accountToPoll.key), buffer);
49
+ this[accountToPoll.key] = { data: account, slot };
50
+ // @ts-ignore
51
+ this.eventEmitter.emit(accountToPoll.eventType, account);
52
+ this.eventEmitter.emit('update');
53
+ });
54
+ }
55
+ this.errorCallbackId = this.accountLoader.addErrorCallbacks((error) => {
56
+ this.eventEmitter.emit('error', error);
57
+ });
58
+ }
59
+ async fetchIfUnloaded() {
60
+ let shouldFetch = false;
61
+ for (const [_, accountToPoll] of this.accountsToPoll) {
62
+ if (this[accountToPoll.key] === undefined) {
63
+ shouldFetch = true;
64
+ break;
65
+ }
66
+ }
67
+ if (shouldFetch) {
68
+ await this.fetch();
69
+ }
70
+ }
71
+ async fetch() {
72
+ await this.accountLoader.load();
73
+ for (const [_, accountToPoll] of this.accountsToPoll) {
74
+ const { buffer, slot } = this.accountLoader.getBufferAndSlot(accountToPoll.publicKey);
75
+ if (buffer) {
76
+ const account = this.program.account[accountToPoll.key].coder.accounts.decode((0, utils_1.capitalize)(accountToPoll.key), buffer);
77
+ this[accountToPoll.key] = { data: account, slot };
78
+ }
79
+ }
80
+ }
81
+ didSubscriptionSucceed() {
82
+ let success = true;
83
+ for (const [_, accountToPoll] of this.accountsToPoll) {
84
+ if (!this[accountToPoll.key]) {
85
+ success = false;
86
+ break;
87
+ }
88
+ }
89
+ return success;
90
+ }
91
+ async unsubscribe() {
92
+ if (!this.isSubscribed) {
93
+ return;
94
+ }
95
+ for (const [_, accountToPoll] of this.accountsToPoll) {
96
+ this.accountLoader.removeAccount(accountToPoll.publicKey, accountToPoll.callbackId);
97
+ }
98
+ this.accountLoader.removeErrorCallbacks(this.errorCallbackId);
99
+ this.errorCallbackId = undefined;
100
+ this.accountsToPoll.clear();
101
+ this.isSubscribed = false;
102
+ }
103
+ assertIsSubscribed() {
104
+ if (!this.isSubscribed) {
105
+ throw new types_1.NotSubscribedError('You must call `subscribe` before using this function');
106
+ }
107
+ }
108
+ getUserStatsAccountAndSlot() {
109
+ this.assertIsSubscribed();
110
+ return this.userStats;
111
+ }
112
+ }
113
+ exports.PollingUserStatsAccountSubscriber = PollingUserStatsAccountSubscriber;
@@ -1,7 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  /// <reference types="bn.js" />
3
3
  /// <reference types="node" />
4
- import { BankAccount, MarketAccount, OracleSource, StateAccount, UserAccount } from '../types';
4
+ import { BankAccount, MarketAccount, OracleSource, StateAccount, UserAccount, UserStatsAccount } from '../types';
5
5
  import StrictEventEmitter from 'strict-event-emitter-types';
6
6
  import { EventEmitter } from 'events';
7
7
  import { PublicKey } from '@solana/web3.js';
@@ -100,3 +100,16 @@ export declare type DataAndSlot<T> = {
100
100
  data: T;
101
101
  slot: number;
102
102
  };
103
+ export interface UserStatsAccountEvents {
104
+ userStatsAccountUpdate: (payload: UserStatsAccount) => void;
105
+ update: void;
106
+ error: (e: Error) => void;
107
+ }
108
+ export interface UserStatsAccountSubscriber {
109
+ eventEmitter: StrictEventEmitter<EventEmitter, UserStatsAccountEvents>;
110
+ isSubscribed: boolean;
111
+ subscribe(): Promise<boolean>;
112
+ fetch(): Promise<void>;
113
+ unsubscribe(): Promise<void>;
114
+ getUserStatsAccountAndSlot(): DataAndSlot<UserStatsAccount>;
115
+ }
@@ -0,0 +1,20 @@
1
+ /// <reference types="node" />
2
+ import { DataAndSlot, AccountSubscriber, UserStatsAccountSubscriber, UserStatsAccountEvents } from './types';
3
+ import { Program } from '@project-serum/anchor';
4
+ import StrictEventEmitter from 'strict-event-emitter-types';
5
+ import { EventEmitter } from 'events';
6
+ import { PublicKey } from '@solana/web3.js';
7
+ import { UserStatsAccount } from '../types';
8
+ export declare class WebSocketUserStatsAccountSubscriber implements UserStatsAccountSubscriber {
9
+ isSubscribed: boolean;
10
+ program: Program;
11
+ eventEmitter: StrictEventEmitter<EventEmitter, UserStatsAccountEvents>;
12
+ userStatsAccountPublicKey: PublicKey;
13
+ userStatsAccountSubscriber: AccountSubscriber<UserStatsAccount>;
14
+ constructor(program: Program, userStatsAccountPublicKey: PublicKey);
15
+ subscribe(): Promise<boolean>;
16
+ fetch(): Promise<void>;
17
+ unsubscribe(): Promise<void>;
18
+ assertIsSubscribed(): void;
19
+ getUserStatsAccountAndSlot(): DataAndSlot<UserStatsAccount>;
20
+ }
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WebSocketUserStatsAccountSubscriber = void 0;
4
+ const types_1 = require("./types");
5
+ const events_1 = require("events");
6
+ const webSocketAccountSubscriber_1 = require("./webSocketAccountSubscriber");
7
+ class WebSocketUserStatsAccountSubscriber {
8
+ constructor(program, userStatsAccountPublicKey) {
9
+ this.isSubscribed = false;
10
+ this.program = program;
11
+ this.userStatsAccountPublicKey = userStatsAccountPublicKey;
12
+ this.eventEmitter = new events_1.EventEmitter();
13
+ }
14
+ async subscribe() {
15
+ if (this.isSubscribed) {
16
+ return true;
17
+ }
18
+ this.userStatsAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('userStats', this.program, this.userStatsAccountPublicKey);
19
+ await this.userStatsAccountSubscriber.subscribe((data) => {
20
+ this.eventEmitter.emit('userStatsAccountUpdate', data);
21
+ this.eventEmitter.emit('update');
22
+ });
23
+ this.eventEmitter.emit('update');
24
+ this.isSubscribed = true;
25
+ return true;
26
+ }
27
+ async fetch() {
28
+ await Promise.all([this.userStatsAccountSubscriber.fetch()]);
29
+ }
30
+ async unsubscribe() {
31
+ if (!this.isSubscribed) {
32
+ return;
33
+ }
34
+ await Promise.all([this.userStatsAccountSubscriber.unsubscribe()]);
35
+ this.isSubscribed = false;
36
+ }
37
+ assertIsSubscribed() {
38
+ if (!this.isSubscribed) {
39
+ throw new types_1.NotSubscribedError('You must call `subscribe` before using this function');
40
+ }
41
+ }
42
+ getUserStatsAccountAndSlot() {
43
+ this.assertIsSubscribed();
44
+ return this.userStatsAccountSubscriber.dataAndSlot;
45
+ }
46
+ }
47
+ exports.WebSocketUserStatsAccountSubscriber = WebSocketUserStatsAccountSubscriber;
@@ -6,6 +6,7 @@ export declare function getClearingHouseStateAccountPublicKey(programId: PublicK
6
6
  export declare function getUserAccountPublicKeyAndNonce(programId: PublicKey, authority: PublicKey, userId?: number): Promise<[PublicKey, number]>;
7
7
  export declare function getUserAccountPublicKey(programId: PublicKey, authority: PublicKey, userId?: number): Promise<PublicKey>;
8
8
  export declare function getUserAccountPublicKeySync(programId: PublicKey, authority: PublicKey, userId?: number): PublicKey;
9
+ export declare function getUserStatsAccountPublicKey(programId: PublicKey, authority: PublicKey): PublicKey;
9
10
  export declare function getMarketPublicKey(programId: PublicKey, marketIndex: BN): Promise<PublicKey>;
10
11
  export declare function getBankPublicKey(programId: PublicKey, bankIndex: BN): Promise<PublicKey>;
11
12
  export declare function getBankVaultPublicKey(programId: PublicKey, bankIndex: BN): Promise<PublicKey>;
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.getBankVaultAuthorityPublicKey = exports.getBankVaultPublicKey = exports.getBankPublicKey = exports.getMarketPublicKey = exports.getUserAccountPublicKeySync = exports.getUserAccountPublicKey = exports.getUserAccountPublicKeyAndNonce = exports.getClearingHouseStateAccountPublicKey = exports.getClearingHouseStateAccountPublicKeyAndNonce = void 0;
26
+ exports.getBankVaultAuthorityPublicKey = exports.getBankVaultPublicKey = exports.getBankPublicKey = exports.getMarketPublicKey = exports.getUserStatsAccountPublicKey = exports.getUserAccountPublicKeySync = exports.getUserAccountPublicKey = exports.getUserAccountPublicKeyAndNonce = exports.getClearingHouseStateAccountPublicKey = exports.getClearingHouseStateAccountPublicKeyAndNonce = void 0;
27
27
  const anchor = __importStar(require("@project-serum/anchor"));
28
28
  async function getClearingHouseStateAccountPublicKeyAndNonce(programId) {
29
29
  return anchor.web3.PublicKey.findProgramAddress([Buffer.from(anchor.utils.bytes.utf8.encode('clearing_house'))], programId);
@@ -53,6 +53,13 @@ function getUserAccountPublicKeySync(programId, authority, userId = 0) {
53
53
  ], programId)[0];
54
54
  }
55
55
  exports.getUserAccountPublicKeySync = getUserAccountPublicKeySync;
56
+ function getUserStatsAccountPublicKey(programId, authority) {
57
+ return anchor.web3.PublicKey.findProgramAddressSync([
58
+ Buffer.from(anchor.utils.bytes.utf8.encode('user_stats')),
59
+ authority.toBuffer(),
60
+ ], programId)[0];
61
+ }
62
+ exports.getUserStatsAccountPublicKey = getUserStatsAccountPublicKey;
56
63
  async function getMarketPublicKey(programId, marketIndex) {
57
64
  return (await anchor.web3.PublicKey.findProgramAddress([
58
65
  Buffer.from(anchor.utils.bytes.utf8.encode('market')),
package/lib/admin.d.ts CHANGED
@@ -5,8 +5,8 @@ import { BN } from '@project-serum/anchor';
5
5
  import { ClearingHouse } from './clearingHouse';
6
6
  export declare class Admin extends ClearingHouse {
7
7
  initialize(usdcMint: PublicKey, adminControlsPrices: boolean): Promise<[TransactionSignature]>;
8
- initializeBank(mint: PublicKey, optimalUtilization: BN, optimalRate: BN, maxRate: BN, oracle: PublicKey, oracleSource: OracleSource, initialAssetWeight: BN, maintenanceAssetWeight: BN, initialLiabilityWeight: BN, maintenanceLiabilityWeight: BN): Promise<TransactionSignature>;
9
- initializeMarket(priceOracle: PublicKey, baseAssetReserve: BN, quoteAssetReserve: BN, periodicity: BN, pegMultiplier?: BN, oracleSource?: OracleSource, marginRatioInitial?: number, marginRatioPartial?: number, marginRatioMaintenance?: number): Promise<TransactionSignature>;
8
+ initializeBank(mint: PublicKey, optimalUtilization: BN, optimalRate: BN, maxRate: BN, oracle: PublicKey, oracleSource: OracleSource, initialAssetWeight: BN, maintenanceAssetWeight: BN, initialLiabilityWeight: BN, maintenanceLiabilityWeight: BN, imfFactor?: BN, liquidationFee?: BN): Promise<TransactionSignature>;
9
+ initializeMarket(priceOracle: PublicKey, baseAssetReserve: BN, quoteAssetReserve: BN, periodicity: BN, pegMultiplier?: BN, oracleSource?: OracleSource, marginRatioInitial?: number, marginRatioMaintenance?: number, liquidationFee?: BN): Promise<TransactionSignature>;
10
10
  moveAmmPrice(baseAssetReserve: BN, quoteAssetReserve: BN, marketIndex: BN): Promise<TransactionSignature>;
11
11
  updateK(sqrtK: BN, marketIndex: BN): Promise<TransactionSignature>;
12
12
  moveAmmToPrice(marketIndex: BN, targetPrice: BN): Promise<TransactionSignature>;
@@ -14,11 +14,11 @@ export declare class Admin extends ClearingHouse {
14
14
  updateAmmOracleTwap(marketIndex: BN): Promise<TransactionSignature>;
15
15
  resetAmmOracleTwap(marketIndex: BN): Promise<TransactionSignature>;
16
16
  withdrawFromInsuranceVault(amount: BN, recipient: PublicKey): Promise<TransactionSignature>;
17
- withdrawFees(marketIndex: BN, amount: BN, recipient: PublicKey): Promise<TransactionSignature>;
17
+ withdrawFromMarketToInsuranceVault(marketIndex: BN, amount: BN, recipient: PublicKey): Promise<TransactionSignature>;
18
18
  withdrawFromInsuranceVaultToMarket(marketIndex: BN, amount: BN): Promise<TransactionSignature>;
19
19
  updateAdmin(admin: PublicKey): Promise<TransactionSignature>;
20
20
  updateCurveUpdateIntensity(marketIndex: BN, curveUpdateIntensity: number): Promise<TransactionSignature>;
21
- updateMarginRatio(marketIndex: BN, marginRatioInitial: number, marginRatioPartial: number, marginRatioMaintenance: number): Promise<TransactionSignature>;
21
+ updateMarginRatio(marketIndex: BN, marginRatioInitial: number, marginRatioMaintenance: number): Promise<TransactionSignature>;
22
22
  updateMarketBaseSpread(marketIndex: BN, baseSpread: number): Promise<TransactionSignature>;
23
23
  updateMarketMaxSpread(marketIndex: BN, maxSpread: number): Promise<TransactionSignature>;
24
24
  updatePartialLiquidationClosePercentage(numerator: BN, denominator: BN): Promise<TransactionSignature>;
@@ -29,6 +29,8 @@ export declare class Admin extends ClearingHouse {
29
29
  updateOrderFillerRewardStructure(orderFillerRewardStructure: OrderFillerRewardStructure): Promise<TransactionSignature>;
30
30
  updateFee(fees: FeeStructure): Promise<TransactionSignature>;
31
31
  updateOracleGuardRails(oracleGuardRails: OracleGuardRails): Promise<TransactionSignature>;
32
+ updateBankWithdrawGuardThreshold(bankIndex: BN, withdrawGuardThreshold: BN): Promise<TransactionSignature>;
33
+ updateLpCooldownTime(marketIndex: BN, cooldownTime: BN): Promise<TransactionSignature>;
32
34
  updateMarketOracle(marketIndex: BN, oracle: PublicKey, oracleSource: OracleSource): Promise<TransactionSignature>;
33
35
  updateMarketMinimumQuoteAssetTradeSize(marketIndex: BN, minimumTradeSize: BN): Promise<TransactionSignature>;
34
36
  updateMarketBaseAssetAmountStepSize(marketIndex: BN, stepSize: BN): Promise<TransactionSignature>;
@@ -38,5 +40,7 @@ export declare class Admin extends ClearingHouse {
38
40
  updateFundingPaused(fundingPaused: boolean): Promise<TransactionSignature>;
39
41
  updateExchangePaused(exchangePaused: boolean): Promise<TransactionSignature>;
40
42
  disableAdminControlsPrices(): Promise<TransactionSignature>;
41
- updateOrderAuctionTime(time: BN | number): Promise<TransactionSignature>;
43
+ updateAuctionDuration(minDuration: BN | number, maxDuration: BN | number): Promise<TransactionSignature>;
44
+ updateMaxBaseAssetAmountRatio(marketIndex: BN, maxBaseAssetAmountRatio: number): Promise<TransactionSignature>;
45
+ updateMaxSlippageRatio(marketIndex: BN, maxSlippageRatio: number): Promise<TransactionSignature>;
42
46
  }
package/lib/admin.js CHANGED
@@ -58,12 +58,12 @@ class Admin extends clearingHouse_1.ClearingHouse {
58
58
  const { txSig: initializeTxSig } = await this.txSender.send(initializeTx, [], this.opts);
59
59
  return [initializeTxSig];
60
60
  }
61
- async initializeBank(mint, optimalUtilization, optimalRate, maxRate, oracle, oracleSource, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight) {
61
+ async initializeBank(mint, optimalUtilization, optimalRate, maxRate, oracle, oracleSource, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight, imfFactor = new anchor_1.BN(0), liquidationFee = numericConstants_1.ZERO) {
62
62
  const bankIndex = this.getStateAccount().numberOfBanks;
63
63
  const bank = await (0, pda_1.getBankPublicKey)(this.program.programId, bankIndex);
64
64
  const bankVault = await (0, pda_1.getBankVaultPublicKey)(this.program.programId, bankIndex);
65
65
  const bankVaultAuthority = await (0, pda_1.getBankVaultAuthorityPublicKey)(this.program.programId, bankIndex);
66
- const initializeTx = await this.program.transaction.initializeBank(optimalUtilization, optimalRate, maxRate, oracleSource, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight, {
66
+ const initializeTx = await this.program.transaction.initializeBank(optimalUtilization, optimalRate, maxRate, oracleSource, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight, imfFactor, liquidationFee, {
67
67
  accounts: {
68
68
  admin: this.wallet.publicKey,
69
69
  state: await this.getStatePublicKey(),
@@ -85,9 +85,9 @@ class Admin extends clearingHouse_1.ClearingHouse {
85
85
  });
86
86
  return txSig;
87
87
  }
88
- async initializeMarket(priceOracle, baseAssetReserve, quoteAssetReserve, periodicity, pegMultiplier = numericConstants_1.PEG_PRECISION, oracleSource = types_1.OracleSource.PYTH, marginRatioInitial = 2000, marginRatioPartial = 625, marginRatioMaintenance = 500) {
88
+ async initializeMarket(priceOracle, baseAssetReserve, quoteAssetReserve, periodicity, pegMultiplier = numericConstants_1.PEG_PRECISION, oracleSource = types_1.OracleSource.PYTH, marginRatioInitial = 2000, marginRatioMaintenance = 500, liquidationFee = numericConstants_1.ZERO) {
89
89
  const marketPublicKey = await (0, pda_1.getMarketPublicKey)(this.program.programId, this.getStateAccount().numberOfMarkets);
90
- const initializeMarketTx = await this.program.transaction.initializeMarket(baseAssetReserve, quoteAssetReserve, periodicity, pegMultiplier, oracleSource, marginRatioInitial, marginRatioPartial, marginRatioMaintenance, {
90
+ const initializeMarketTx = await this.program.transaction.initializeMarket(baseAssetReserve, quoteAssetReserve, periodicity, pegMultiplier, oracleSource, marginRatioInitial, marginRatioMaintenance, liquidationFee, {
91
91
  accounts: {
92
92
  state: await this.getStatePublicKey(),
93
93
  admin: this.wallet.publicKey,
@@ -177,10 +177,12 @@ class Admin extends clearingHouse_1.ClearingHouse {
177
177
  }
178
178
  async withdrawFromInsuranceVault(amount, recipient) {
179
179
  const state = await this.getStateAccount();
180
+ const bank = this.getQuoteAssetBankAccount();
180
181
  return await this.program.rpc.withdrawFromInsuranceVault(amount, {
181
182
  accounts: {
182
183
  admin: this.wallet.publicKey,
183
184
  state: await this.getStatePublicKey(),
185
+ bank: bank.pubkey,
184
186
  insuranceVault: state.insuranceVault,
185
187
  insuranceVaultAuthority: state.insuranceVaultAuthority,
186
188
  recipient: recipient,
@@ -188,10 +190,10 @@ class Admin extends clearingHouse_1.ClearingHouse {
188
190
  },
189
191
  });
190
192
  }
191
- async withdrawFees(marketIndex, amount, recipient) {
193
+ async withdrawFromMarketToInsuranceVault(marketIndex, amount, recipient) {
192
194
  const marketPublicKey = await (0, pda_1.getMarketPublicKey)(this.program.programId, marketIndex);
193
195
  const bank = this.getQuoteAssetBankAccount();
194
- return await this.program.rpc.withdrawFees(amount, {
196
+ return await this.program.rpc.withdrawFromMarketToInsuranceVault(amount, {
195
197
  accounts: {
196
198
  admin: this.wallet.publicKey,
197
199
  state: await this.getStatePublicKey(),
@@ -206,6 +208,7 @@ class Admin extends clearingHouse_1.ClearingHouse {
206
208
  }
207
209
  async withdrawFromInsuranceVaultToMarket(marketIndex, amount) {
208
210
  const state = await this.getStateAccount();
211
+ const bank = this.getQuoteAssetBankAccount();
209
212
  return await this.program.rpc.withdrawFromInsuranceVaultToMarket(amount, {
210
213
  accounts: {
211
214
  admin: this.wallet.publicKey,
@@ -213,7 +216,9 @@ class Admin extends clearingHouse_1.ClearingHouse {
213
216
  market: await (0, pda_1.getMarketPublicKey)(this.program.programId, marketIndex),
214
217
  insuranceVault: state.insuranceVault,
215
218
  insuranceVaultAuthority: state.insuranceVaultAuthority,
216
- bankVault: this.getQuoteAssetBankAccount().vault,
219
+ bank: bank.pubkey,
220
+ bankVault: bank.vault,
221
+ bankVaultAuthority: bank.vaultAuthority,
217
222
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
218
223
  },
219
224
  });
@@ -237,8 +242,8 @@ class Admin extends clearingHouse_1.ClearingHouse {
237
242
  },
238
243
  });
239
244
  }
240
- async updateMarginRatio(marketIndex, marginRatioInitial, marginRatioPartial, marginRatioMaintenance) {
241
- return await this.program.rpc.updateMarginRatio(marginRatioInitial, marginRatioPartial, marginRatioMaintenance, {
245
+ async updateMarginRatio(marketIndex, marginRatioInitial, marginRatioMaintenance) {
246
+ return await this.program.rpc.updateMarginRatio(marginRatioInitial, marginRatioMaintenance, {
242
247
  accounts: {
243
248
  admin: this.wallet.publicKey,
244
249
  state: await this.getStatePublicKey(),
@@ -328,6 +333,24 @@ class Admin extends clearingHouse_1.ClearingHouse {
328
333
  },
329
334
  });
330
335
  }
336
+ async updateBankWithdrawGuardThreshold(bankIndex, withdrawGuardThreshold) {
337
+ return await this.program.rpc.updateBankWithdrawGuardThreshold(withdrawGuardThreshold, {
338
+ accounts: {
339
+ admin: this.wallet.publicKey,
340
+ state: await this.getStatePublicKey(),
341
+ bank: await (0, pda_1.getBankPublicKey)(this.program.programId, bankIndex),
342
+ },
343
+ });
344
+ }
345
+ async updateLpCooldownTime(marketIndex, cooldownTime) {
346
+ return await this.program.rpc.updateLpCooldownTime(cooldownTime, {
347
+ accounts: {
348
+ admin: this.wallet.publicKey,
349
+ state: await this.getStatePublicKey(),
350
+ market: await (0, pda_1.getMarketPublicKey)(this.program.programId, marketIndex),
351
+ },
352
+ });
353
+ }
331
354
  async updateMarketOracle(marketIndex, oracle, oracleSource) {
332
355
  return await this.program.rpc.updateMarketOracle(oracle, oracleSource, {
333
356
  accounts: {
@@ -403,11 +426,29 @@ class Admin extends clearingHouse_1.ClearingHouse {
403
426
  },
404
427
  });
405
428
  }
406
- async updateOrderAuctionTime(time) {
407
- return await this.program.rpc.updateOrderAuctionTime(typeof time === 'number' ? time : time.toNumber, {
429
+ async updateAuctionDuration(minDuration, maxDuration) {
430
+ return await this.program.rpc.updateAuctionDuration(typeof minDuration === 'number' ? minDuration : minDuration.toNumber(), typeof maxDuration === 'number' ? maxDuration : maxDuration.toNumber(), {
431
+ accounts: {
432
+ admin: this.wallet.publicKey,
433
+ state: await this.getStatePublicKey(),
434
+ },
435
+ });
436
+ }
437
+ async updateMaxBaseAssetAmountRatio(marketIndex, maxBaseAssetAmountRatio) {
438
+ return await this.program.rpc.updateMaxBaseAssetAmountRatio(maxBaseAssetAmountRatio, {
439
+ accounts: {
440
+ admin: this.wallet.publicKey,
441
+ state: await this.getStatePublicKey(),
442
+ market: this.getMarketAccount(marketIndex).pubkey,
443
+ },
444
+ });
445
+ }
446
+ async updateMaxSlippageRatio(marketIndex, maxSlippageRatio) {
447
+ return await this.program.rpc.updateMaxSlippageRatio(maxSlippageRatio, {
408
448
  accounts: {
409
449
  admin: this.wallet.publicKey,
410
450
  state: await this.getStatePublicKey(),
451
+ market: this.getMarketAccount(marketIndex).pubkey,
411
452
  },
412
453
  });
413
454
  }