@drift-labs/sdk 0.1.23-master.2 → 0.1.24

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 (45) hide show
  1. package/lib/accounts/bulkAccountLoader.d.ts +1 -0
  2. package/lib/accounts/bulkAccountLoader.js +14 -13
  3. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +3 -3
  4. package/lib/accounts/pollingTokenAccountSubscriber.js +2 -2
  5. package/lib/accounts/pollingUserAccountSubscriber.js +4 -4
  6. package/lib/accounts/webSocketAccountSubscriber.js +2 -2
  7. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +1 -1
  8. package/lib/accounts/webSocketUserAccountSubscriber.js +2 -2
  9. package/lib/admin.d.ts +2 -2
  10. package/lib/admin.js +12 -11
  11. package/lib/clearingHouse.js +19 -19
  12. package/lib/clearingHouseUser.d.ts +12 -17
  13. package/lib/clearingHouseUser.js +125 -228
  14. package/lib/constants/numericConstants.d.ts +1 -2
  15. package/lib/constants/numericConstants.js +2 -3
  16. package/lib/examples/makeTradeExample.js +6 -6
  17. package/lib/idl/clearing_house.json +42 -4
  18. package/lib/math/amm.js +12 -12
  19. package/lib/math/conversion.js +1 -1
  20. package/lib/math/funding.js +1 -1
  21. package/lib/math/market.js +2 -2
  22. package/lib/math/orders.d.ts +2 -0
  23. package/lib/math/orders.js +44 -4
  24. package/lib/math/position.js +1 -1
  25. package/lib/math/trade.js +18 -18
  26. package/lib/orders.d.ts +3 -1
  27. package/lib/orders.js +47 -19
  28. package/lib/pythClient.js +1 -1
  29. package/lib/tx/retryTxSender.js +1 -1
  30. package/lib/types.d.ts +4 -1
  31. package/package.json +1 -1
  32. package/src/accounts/bulkAccountLoader.ts +18 -13
  33. package/src/accounts/types.js +10 -0
  34. package/src/accounts/utils.js +7 -0
  35. package/src/accounts/webSocketAccountSubscriber.js +76 -0
  36. package/src/addresses.js +83 -0
  37. package/src/admin.ts +13 -4
  38. package/src/clearingHouseUser.ts +161 -330
  39. package/src/constants/numericConstants.ts +1 -2
  40. package/src/idl/clearing_house.json +42 -4
  41. package/src/math/orders.ts +61 -0
  42. package/src/mockUSDCFaucet.js +171 -0
  43. package/src/orders.ts +56 -3
  44. package/src/types.js +60 -0
  45. package/src/types.ts +5 -1
@@ -15,6 +15,7 @@ export declare class BulkAccountLoader {
15
15
  intervalId?: NodeJS.Timer;
16
16
  loadPromise?: Promise<void>;
17
17
  loadPromiseResolver: () => void;
18
+ loggingEnabled: boolean;
18
19
  constructor(connection: Connection, commitment: Commitment, pollingFrequency: number);
19
20
  addAccount(publicKey: PublicKey, callback: (buffer: Buffer) => void): string;
20
21
  removeAccount(publicKey: PublicKey, callbackId: string): void;
@@ -17,13 +17,14 @@ class BulkAccountLoader {
17
17
  this.accountsToLoad = new Map();
18
18
  this.accountData = new Map();
19
19
  this.errorCallbacks = new Map();
20
+ this.loggingEnabled = false;
20
21
  this.connection = connection;
21
22
  this.commitment = commitment;
22
23
  this.pollingFrequency = pollingFrequency;
23
24
  }
24
25
  addAccount(publicKey, callback) {
25
26
  const existingSize = this.accountsToLoad.size;
26
- const callbackId = (0, uuid_1.v4)();
27
+ const callbackId = uuid_1.v4();
27
28
  const existingAccountToLoad = this.accountsToLoad.get(publicKey.toString());
28
29
  if (existingAccountToLoad) {
29
30
  existingAccountToLoad.callbacks.set(callbackId, callback);
@@ -57,7 +58,7 @@ class BulkAccountLoader {
57
58
  }
58
59
  }
59
60
  addErrorCallbacks(callback) {
60
- const callbackId = (0, uuid_1.v4)();
61
+ const callbackId = uuid_1.v4();
61
62
  this.errorCallbacks.set(callbackId, callback);
62
63
  return callbackId;
63
64
  }
@@ -78,6 +79,9 @@ class BulkAccountLoader {
78
79
  this.loadPromise = new Promise((resolver) => {
79
80
  this.loadPromiseResolver = resolver;
80
81
  });
82
+ if (this.loggingEnabled) {
83
+ console.log('Loading accounts');
84
+ }
81
85
  try {
82
86
  const chunks = this.chunks(Array.from(this.accountsToLoad.values()), GET_MULTIPLE_ACCOUNTS_CHUNK_SIZE);
83
87
  yield Promise.all(chunks.map((chunk) => {
@@ -108,17 +112,8 @@ class BulkAccountLoader {
108
112
  }),
109
113
  { commitment: this.commitment },
110
114
  ];
111
- let rpcResponse;
112
- try {
113
- // @ts-ignore
114
- rpcResponse = yield this.connection._rpcRequest('getMultipleAccounts', args);
115
- }
116
- catch (e) {
117
- for (const [_, callback] of this.errorCallbacks) {
118
- callback(e);
119
- }
120
- return;
121
- }
115
+ // @ts-ignore
116
+ const rpcResponse = yield this.connection._rpcRequest('getMultipleAccounts', args);
122
117
  const newSlot = rpcResponse.result.context.slot;
123
118
  for (const i in accountsToLoad) {
124
119
  const accountToLoad = accountsToLoad[i];
@@ -165,12 +160,18 @@ class BulkAccountLoader {
165
160
  if (this.intervalId) {
166
161
  return;
167
162
  }
163
+ if (this.loggingEnabled) {
164
+ console.log(`startPolling`);
165
+ }
168
166
  this.intervalId = setInterval(this.load.bind(this), this.pollingFrequency);
169
167
  }
170
168
  stopPolling() {
171
169
  if (this.intervalId) {
172
170
  clearInterval(this.intervalId);
173
171
  this.intervalId = undefined;
172
+ if (this.loggingEnabled) {
173
+ console.log(`stopPolling`);
174
+ }
174
175
  }
175
176
  }
176
177
  }
@@ -54,7 +54,7 @@ class PollingClearingHouseAccountSubscriber {
54
54
  if (this.accountsToPoll.size > 0) {
55
55
  return;
56
56
  }
57
- const statePublicKey = yield (0, addresses_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
57
+ const statePublicKey = yield addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
58
58
  const state = (yield this.program.account.state.fetch(statePublicKey));
59
59
  this.accountsToPoll.set(statePublicKey.toString(), {
60
60
  key: 'state',
@@ -127,7 +127,7 @@ class PollingClearingHouseAccountSubscriber {
127
127
  return __awaiter(this, void 0, void 0, function* () {
128
128
  for (const [_, accountToPoll] of this.accountsToPoll) {
129
129
  accountToPoll.callbackId = this.accountLoader.addAccount(accountToPoll.publicKey, (buffer) => {
130
- const account = this.program.account[accountToPoll.key].coder.accounts.decode((0, utils_1.capitalize)(accountToPoll.key), buffer);
130
+ const account = this.program.account[accountToPoll.key].coder.accounts.decode(utils_1.capitalize(accountToPoll.key), buffer);
131
131
  this[accountToPoll.key] = account;
132
132
  // @ts-ignore
133
133
  this.eventEmitter.emit(accountToPoll.eventType, account);
@@ -145,7 +145,7 @@ class PollingClearingHouseAccountSubscriber {
145
145
  for (const [_, accountToPoll] of this.accountsToPoll) {
146
146
  const buffer = this.accountLoader.getAccountData(accountToPoll.publicKey);
147
147
  if (buffer) {
148
- this[accountToPoll.key] = this.program.account[accountToPoll.key].coder.accounts.decode((0, utils_1.capitalize)(accountToPoll.key), buffer);
148
+ this[accountToPoll.key] = this.program.account[accountToPoll.key].coder.accounts.decode(utils_1.capitalize(accountToPoll.key), buffer);
149
149
  }
150
150
  }
151
151
  });
@@ -37,7 +37,7 @@ class PollingTokenAccountSubscriber {
37
37
  return;
38
38
  }
39
39
  this.callbackId = this.accountLoader.addAccount(this.publicKey, (buffer) => {
40
- const tokenAccount = (0, token_1.parseTokenAccount)(buffer);
40
+ const tokenAccount = token_1.parseTokenAccount(buffer);
41
41
  this.tokenAccount = tokenAccount;
42
42
  // @ts-ignore
43
43
  this.eventEmitter.emit('tokenAccountUpdate', tokenAccount);
@@ -51,7 +51,7 @@ class PollingTokenAccountSubscriber {
51
51
  return __awaiter(this, void 0, void 0, function* () {
52
52
  yield this.accountLoader.load();
53
53
  const buffer = this.accountLoader.getAccountData(this.publicKey);
54
- this.tokenAccount = (0, token_1.parseTokenAccount)(buffer);
54
+ this.tokenAccount = token_1.parseTokenAccount(buffer);
55
55
  });
56
56
  }
57
57
  unsubscribe() {
@@ -42,7 +42,7 @@ class PollingUserAccountSubscriber {
42
42
  return;
43
43
  }
44
44
  if (!userPublicKeys) {
45
- const userPublicKey = yield (0, addresses_1.getUserAccountPublicKey)(this.program.programId, this.authority);
45
+ const userPublicKey = yield addresses_1.getUserAccountPublicKey(this.program.programId, this.authority);
46
46
  const userAccount = (yield this.program.account.user.fetch(userPublicKey));
47
47
  this.accountsToPoll.set(userPublicKey.toString(), {
48
48
  key: 'user',
@@ -54,7 +54,7 @@ class PollingUserAccountSubscriber {
54
54
  publicKey: userAccount.positions,
55
55
  eventType: 'userPositionsData',
56
56
  });
57
- const userOrdersPublicKey = yield (0, addresses_1.getUserOrdersAccountPublicKey)(this.program.programId, userPublicKey);
57
+ const userOrdersPublicKey = yield addresses_1.getUserOrdersAccountPublicKey(this.program.programId, userPublicKey);
58
58
  this.accountsToPoll.set(userOrdersPublicKey.toString(), {
59
59
  key: 'userOrders',
60
60
  publicKey: userOrdersPublicKey,
@@ -85,7 +85,7 @@ class PollingUserAccountSubscriber {
85
85
  if (!buffer) {
86
86
  return;
87
87
  }
88
- const account = this.program.account[accountToPoll.key].coder.accounts.decode((0, utils_1.capitalize)(accountToPoll.key), buffer);
88
+ const account = this.program.account[accountToPoll.key].coder.accounts.decode(utils_1.capitalize(accountToPoll.key), buffer);
89
89
  this[accountToPoll.key] = account;
90
90
  // @ts-ignore
91
91
  this.eventEmitter.emit(accountToPoll.eventType, account);
@@ -117,7 +117,7 @@ class PollingUserAccountSubscriber {
117
117
  for (const [_, accountToPoll] of this.accountsToPoll) {
118
118
  const buffer = this.accountLoader.getAccountData(accountToPoll.publicKey);
119
119
  if (buffer) {
120
- this[accountToPoll.key] = this.program.account[accountToPoll.key].coder.accounts.decode((0, utils_1.capitalize)(accountToPoll.key), buffer);
120
+ this[accountToPoll.key] = this.program.account[accountToPoll.key].coder.accounts.decode(utils_1.capitalize(accountToPoll.key), buffer);
121
121
  }
122
122
  }
123
123
  });
@@ -47,7 +47,7 @@ class WebSocketAccountSubscriber {
47
47
  slot: newSlot,
48
48
  };
49
49
  if (newBuffer) {
50
- this.data = this.program.account[this.accountName].coder.accounts.decode((0, utils_1.capitalize)(this.accountName), newBuffer);
50
+ this.data = this.program.account[this.accountName].coder.accounts.decode(utils_1.capitalize(this.accountName), newBuffer);
51
51
  this.onChange(this.data);
52
52
  }
53
53
  return;
@@ -61,7 +61,7 @@ class WebSocketAccountSubscriber {
61
61
  buffer: newBuffer,
62
62
  slot: newSlot,
63
63
  };
64
- this.data = this.program.account[this.accountName].coder.accounts.decode((0, utils_1.capitalize)(this.accountName), newBuffer);
64
+ this.data = this.program.account[this.accountName].coder.accounts.decode(utils_1.capitalize(this.accountName), newBuffer);
65
65
  this.onChange(this.data);
66
66
  }
67
67
  }
@@ -35,7 +35,7 @@ class WebSocketClearingHouseAccountSubscriber {
35
35
  this.subscriptionPromise = new Promise((res) => {
36
36
  this.subscriptionPromiseResolver = res;
37
37
  });
38
- const statePublicKey = yield (0, addresses_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
38
+ const statePublicKey = yield addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
39
39
  // create and activate main state account subscription
40
40
  this.stateAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('state', this.program, statePublicKey);
41
41
  yield this.stateAccountSubscriber.subscribe((data) => {
@@ -27,7 +27,7 @@ class WebSocketUserAccountSubscriber {
27
27
  if (this.isSubscribed) {
28
28
  return true;
29
29
  }
30
- const userPublicKey = yield (0, addresses_1.getUserAccountPublicKey)(this.program.programId, this.authority);
30
+ const userPublicKey = yield addresses_1.getUserAccountPublicKey(this.program.programId, this.authority);
31
31
  this.userDataAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('user', this.program, userPublicKey);
32
32
  yield this.userDataAccountSubscriber.subscribe((data) => {
33
33
  this.eventEmitter.emit('userAccountData', data);
@@ -39,7 +39,7 @@ class WebSocketUserAccountSubscriber {
39
39
  this.eventEmitter.emit('userPositionsData', data);
40
40
  this.eventEmitter.emit('update');
41
41
  });
42
- const userOrdersPublicKey = yield (0, addresses_1.getUserOrdersAccountPublicKey)(this.program.programId, userPublicKey);
42
+ const userOrdersPublicKey = yield addresses_1.getUserOrdersAccountPublicKey(this.program.programId, userPublicKey);
43
43
  this.userOrdersAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('userOrders', this.program, userOrdersPublicKey);
44
44
  yield this.userOrdersAccountSubscriber.subscribe((data) => {
45
45
  this.eventEmitter.emit('userOrdersData', data);
package/lib/admin.d.ts CHANGED
@@ -11,7 +11,7 @@ export declare class Admin extends ClearingHouse {
11
11
  TransactionSignature
12
12
  ]>;
13
13
  initializeOrderState(): Promise<TransactionSignature>;
14
- initializeMarket(marketIndex: BN, priceOracle: PublicKey, baseAssetReserve: BN, quoteAssetReserve: BN, periodicity: BN, pegMultiplier?: BN): Promise<TransactionSignature>;
14
+ initializeMarket(marketIndex: BN, priceOracle: PublicKey, baseAssetReserve: BN, quoteAssetReserve: BN, periodicity: BN, pegMultiplier?: BN, marginRatioInitial?: number, marginRatioPartial?: number, marginRatioMaintenance?: number): Promise<TransactionSignature>;
15
15
  moveAmmPrice(baseAssetReserve: BN, quoteAssetReserve: BN, marketIndex: BN): Promise<TransactionSignature>;
16
16
  updateK(sqrtK: BN, marketIndex: BN): Promise<TransactionSignature>;
17
17
  updateCurveHistory(): Promise<TransactionSignature>;
@@ -23,7 +23,7 @@ export declare class Admin extends ClearingHouse {
23
23
  withdrawFees(marketIndex: BN, amount: BN, recipient: PublicKey): Promise<TransactionSignature>;
24
24
  withdrawFromInsuranceVaultToMarket(marketIndex: BN, amount: BN): Promise<TransactionSignature>;
25
25
  updateAdmin(admin: PublicKey): Promise<TransactionSignature>;
26
- updateMarginRatio(marginRatioInitial: BN, marginRatioPartial: BN, marginRatioMaintenance: BN): Promise<TransactionSignature>;
26
+ updateMarginRatio(marketIndex: BN, marginRatioInitial: number, marginRatioPartial: number, marginRatioMaintenance: number): Promise<TransactionSignature>;
27
27
  updatePartialLiquidationClosePercentage(numerator: BN, denominator: BN): Promise<TransactionSignature>;
28
28
  updatePartialLiquidationPenaltyPercentage(numerator: BN, denominator: BN): Promise<TransactionSignature>;
29
29
  updateFullLiquidationPenaltyPercentage(numerator: BN, denominator: BN): Promise<TransactionSignature>;
package/lib/admin.js CHANGED
@@ -41,8 +41,8 @@ const amm_1 = require("./math/amm");
41
41
  const clearingHouse_2 = require("./factory/clearingHouse");
42
42
  class Admin extends clearingHouse_1.ClearingHouse {
43
43
  static from(connection, wallet, clearingHouseProgramId, opts = anchor_1.Provider.defaultOptions()) {
44
- const config = (0, clearingHouse_2.getWebSocketClearingHouseConfig)(connection, wallet, clearingHouseProgramId, opts);
45
- return (0, clearingHouse_2.getAdmin)(config);
44
+ const config = clearingHouse_2.getWebSocketClearingHouseConfig(connection, wallet, clearingHouseProgramId, opts);
45
+ return clearingHouse_2.getAdmin(config);
46
46
  }
47
47
  initialize(usdcMint, adminControlsPrices) {
48
48
  return __awaiter(this, void 0, void 0, function* () {
@@ -61,7 +61,7 @@ class Admin extends clearingHouse_1.ClearingHouse {
61
61
  const tradeHistory = anchor.web3.Keypair.generate();
62
62
  const liquidationHistory = anchor.web3.Keypair.generate();
63
63
  const curveHistory = anchor.web3.Keypair.generate();
64
- const [clearingHouseStatePublicKey, clearingHouseNonce] = yield (0, addresses_1.getClearingHouseStateAccountPublicKeyAndNonce)(this.program.programId);
64
+ const [clearingHouseStatePublicKey, clearingHouseNonce] = yield addresses_1.getClearingHouseStateAccountPublicKeyAndNonce(this.program.programId);
65
65
  const initializeTx = yield this.program.transaction.initialize(clearingHouseNonce, collateralVaultNonce, insuranceVaultNonce, adminControlsPrices, {
66
66
  accounts: {
67
67
  admin: this.wallet.publicKey,
@@ -118,8 +118,8 @@ class Admin extends clearingHouse_1.ClearingHouse {
118
118
  initializeOrderState() {
119
119
  return __awaiter(this, void 0, void 0, function* () {
120
120
  const orderHistory = anchor.web3.Keypair.generate();
121
- const [orderStatePublicKey, orderStateNonce] = yield (0, addresses_1.getOrderStateAccountPublicKeyAndNonce)(this.program.programId);
122
- const clearingHouseStatePublicKey = yield (0, addresses_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
121
+ const [orderStatePublicKey, orderStateNonce] = yield addresses_1.getOrderStateAccountPublicKeyAndNonce(this.program.programId);
122
+ const clearingHouseStatePublicKey = yield addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
123
123
  const initializeOrderStateTx = yield this.program.transaction.initializeOrderState(orderStateNonce, {
124
124
  accounts: {
125
125
  admin: this.wallet.publicKey,
@@ -136,12 +136,12 @@ class Admin extends clearingHouse_1.ClearingHouse {
136
136
  return yield this.txSender.send(initializeOrderStateTx, [orderHistory], this.opts);
137
137
  });
138
138
  }
139
- initializeMarket(marketIndex, priceOracle, baseAssetReserve, quoteAssetReserve, periodicity, pegMultiplier = numericConstants_1.PEG_PRECISION) {
139
+ initializeMarket(marketIndex, priceOracle, baseAssetReserve, quoteAssetReserve, periodicity, pegMultiplier = numericConstants_1.PEG_PRECISION, marginRatioInitial = 2000, marginRatioPartial = 625, marginRatioMaintenance = 500) {
140
140
  return __awaiter(this, void 0, void 0, function* () {
141
141
  if (this.getMarketsAccount().markets[marketIndex.toNumber()].initialized) {
142
142
  throw Error(`MarketIndex ${marketIndex.toNumber()} already initialized`);
143
143
  }
144
- const initializeMarketTx = yield this.program.transaction.initializeMarket(marketIndex, baseAssetReserve, quoteAssetReserve, periodicity, pegMultiplier, {
144
+ const initializeMarketTx = yield this.program.transaction.initializeMarket(marketIndex, baseAssetReserve, quoteAssetReserve, periodicity, pegMultiplier, marginRatioInitial, marginRatioPartial, marginRatioMaintenance, {
145
145
  accounts: {
146
146
  state: yield this.getStatePublicKey(),
147
147
  admin: this.wallet.publicKey,
@@ -202,8 +202,8 @@ class Admin extends clearingHouse_1.ClearingHouse {
202
202
  moveAmmToPrice(marketIndex, targetPrice) {
203
203
  return __awaiter(this, void 0, void 0, function* () {
204
204
  const market = this.getMarket(marketIndex);
205
- const [direction, tradeSize, _] = (0, trade_1.calculateTargetPriceTrade)(market, targetPrice);
206
- const [newQuoteAssetAmount, newBaseAssetAmount] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, 'quote', tradeSize, (0, amm_1.getSwapDirection)('quote', direction));
205
+ const [direction, tradeSize, _] = trade_1.calculateTargetPriceTrade(market, targetPrice);
206
+ const [newQuoteAssetAmount, newBaseAssetAmount] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'quote', tradeSize, amm_1.getSwapDirection('quote', direction));
207
207
  const state = this.getStateAccount();
208
208
  return yield this.program.rpc.moveAmmPrice(newBaseAssetAmount, newQuoteAssetAmount, marketIndex, {
209
209
  accounts: {
@@ -322,12 +322,13 @@ class Admin extends clearingHouse_1.ClearingHouse {
322
322
  });
323
323
  });
324
324
  }
325
- updateMarginRatio(marginRatioInitial, marginRatioPartial, marginRatioMaintenance) {
325
+ updateMarginRatio(marketIndex, marginRatioInitial, marginRatioPartial, marginRatioMaintenance) {
326
326
  return __awaiter(this, void 0, void 0, function* () {
327
- return yield this.program.rpc.updateMarginRatio(marginRatioInitial, marginRatioPartial, marginRatioMaintenance, {
327
+ return yield this.program.rpc.updateMarginRatio(marketIndex, marginRatioInitial, marginRatioPartial, marginRatioMaintenance, {
328
328
  accounts: {
329
329
  admin: this.wallet.publicKey,
330
330
  state: yield this.getStatePublicKey(),
331
+ markets: this.getStateAccount().markets,
331
332
  },
332
333
  });
333
334
  });
@@ -73,8 +73,8 @@ class ClearingHouse {
73
73
  * @returns
74
74
  */
75
75
  static from(connection, wallet, clearingHouseProgramId, opts = anchor_1.Provider.defaultOptions()) {
76
- const config = (0, clearingHouse_1.getWebSocketClearingHouseConfig)(connection, wallet, clearingHouseProgramId, opts);
77
- return (0, clearingHouse_1.getClearingHouse)(config);
76
+ const config = clearingHouse_1.getWebSocketClearingHouseConfig(connection, wallet, clearingHouseProgramId, opts);
77
+ return clearingHouse_1.getClearingHouse(config);
78
78
  }
79
79
  /**
80
80
  *
@@ -126,7 +126,7 @@ class ClearingHouse {
126
126
  if (this.statePublicKey) {
127
127
  return this.statePublicKey;
128
128
  }
129
- this.statePublicKey = yield (0, addresses_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
129
+ this.statePublicKey = yield addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
130
130
  return this.statePublicKey;
131
131
  });
132
132
  }
@@ -168,7 +168,7 @@ class ClearingHouse {
168
168
  if (this.orderStatePublicKey) {
169
169
  return this.orderStatePublicKey;
170
170
  }
171
- this.orderStatePublicKey = yield (0, addresses_1.getOrderStateAccountPublicKey)(this.program.programId);
171
+ this.orderStatePublicKey = yield addresses_1.getOrderStateAccountPublicKey(this.program.programId);
172
172
  return this.orderStatePublicKey;
173
173
  });
174
174
  }
@@ -202,7 +202,7 @@ class ClearingHouse {
202
202
  }
203
203
  getInitializeUserInstructions() {
204
204
  return __awaiter(this, void 0, void 0, function* () {
205
- const [userAccountPublicKey, userAccountNonce] = yield (0, addresses_1.getUserAccountPublicKeyAndNonce)(this.program.programId, this.wallet.publicKey);
205
+ const [userAccountPublicKey, userAccountNonce] = yield addresses_1.getUserAccountPublicKeyAndNonce(this.program.programId, this.wallet.publicKey);
206
206
  const remainingAccounts = [];
207
207
  const optionalAccounts = {
208
208
  whitelistToken: false,
@@ -243,7 +243,7 @@ class ClearingHouse {
243
243
  if (!userAccountPublicKey) {
244
244
  userAccountPublicKey = yield this.getUserAccountPublicKey();
245
245
  }
246
- const [userOrdersAccountPublicKey, userOrdersAccountNonce] = yield (0, addresses_1.getUserOrdersAccountPublicKeyAndNonce)(this.program.programId, userAccountPublicKey);
246
+ const [userOrdersAccountPublicKey, userOrdersAccountNonce] = yield addresses_1.getUserOrdersAccountPublicKeyAndNonce(this.program.programId, userAccountPublicKey);
247
247
  return yield this.program.instruction.initializeUserOrders(userOrdersAccountNonce, {
248
248
  accounts: {
249
249
  user: userAccountPublicKey,
@@ -265,7 +265,7 @@ class ClearingHouse {
265
265
  if (this.userAccountPublicKey) {
266
266
  return this.userAccountPublicKey;
267
267
  }
268
- this.userAccountPublicKey = yield (0, addresses_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey);
268
+ this.userAccountPublicKey = yield addresses_1.getUserAccountPublicKey(this.program.programId, this.wallet.publicKey);
269
269
  return this.userAccountPublicKey;
270
270
  });
271
271
  }
@@ -287,7 +287,7 @@ class ClearingHouse {
287
287
  if (this.userOrdersAccountPublicKey) {
288
288
  return this.userOrdersAccountPublicKey;
289
289
  }
290
- this.userOrdersAccountPublicKey = yield (0, addresses_1.getUserOrdersAccountPublicKey)(this.program.programId, yield this.getUserAccountPublicKey());
290
+ this.userOrdersAccountPublicKey = yield addresses_1.getUserOrdersAccountPublicKey(this.program.programId, yield this.getUserAccountPublicKey());
291
291
  return this.userOrdersAccountPublicKey;
292
292
  });
293
293
  }
@@ -380,7 +380,7 @@ class ClearingHouse {
380
380
  }
381
381
  withdrawCollateral(amount, collateralAccountPublicKey) {
382
382
  return __awaiter(this, void 0, void 0, function* () {
383
- return this.txSender.send((0, utils_1.wrapInTx)(yield this.getWithdrawCollateralIx(amount, collateralAccountPublicKey)), [], this.opts);
383
+ return this.txSender.send(utils_1.wrapInTx(yield this.getWithdrawCollateralIx(amount, collateralAccountPublicKey)), [], this.opts);
384
384
  });
385
385
  }
386
386
  getWithdrawCollateralIx(amount, collateralAccountPublicKey) {
@@ -409,7 +409,7 @@ class ClearingHouse {
409
409
  }
410
410
  openPosition(direction, amount, marketIndex, limitPrice, discountToken, referrer) {
411
411
  return __awaiter(this, void 0, void 0, function* () {
412
- return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getOpenPositionIx(direction, amount, marketIndex, limitPrice, discountToken, referrer)), [], this.opts);
412
+ return yield this.txSender.send(utils_1.wrapInTx(yield this.getOpenPositionIx(direction, amount, marketIndex, limitPrice, discountToken, referrer)), [], this.opts);
413
413
  });
414
414
  }
415
415
  getOpenPositionIx(direction, amount, marketIndex, limitPrice, discountToken, referrer) {
@@ -475,7 +475,7 @@ class ClearingHouse {
475
475
  }
476
476
  placeOrder(orderParams, discountToken, referrer) {
477
477
  return __awaiter(this, void 0, void 0, function* () {
478
- return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getPlaceOrderIx(orderParams, discountToken, referrer)), [], this.opts);
478
+ return yield this.txSender.send(utils_1.wrapInTx(yield this.getPlaceOrderIx(orderParams, discountToken, referrer)), [], this.opts);
479
479
  });
480
480
  }
481
481
  getPlaceOrderIx(orderParams, discountToken, referrer) {
@@ -527,7 +527,7 @@ class ClearingHouse {
527
527
  }
528
528
  cancelOrder(orderId) {
529
529
  return __awaiter(this, void 0, void 0, function* () {
530
- return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getCancelOrderIx(orderId)), [], this.opts);
530
+ return yield this.txSender.send(utils_1.wrapInTx(yield this.getCancelOrderIx(orderId)), [], this.opts);
531
531
  });
532
532
  }
533
533
  getCancelOrderIx(orderId) {
@@ -554,7 +554,7 @@ class ClearingHouse {
554
554
  }
555
555
  cancelOrderByUserId(userOrderId) {
556
556
  return __awaiter(this, void 0, void 0, function* () {
557
- return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getCancelOrderByUserIdIx(userOrderId)), [], this.opts);
557
+ return yield this.txSender.send(utils_1.wrapInTx(yield this.getCancelOrderByUserIdIx(userOrderId)), [], this.opts);
558
558
  });
559
559
  }
560
560
  getCancelOrderByUserIdIx(userOrderId) {
@@ -581,7 +581,7 @@ class ClearingHouse {
581
581
  }
582
582
  fillOrder(userAccountPublicKey, userOrdersAccountPublicKey, order) {
583
583
  return __awaiter(this, void 0, void 0, function* () {
584
- return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getFillOrderIx(userAccountPublicKey, userOrdersAccountPublicKey, order)), [], this.opts);
584
+ return yield this.txSender.send(utils_1.wrapInTx(yield this.getFillOrderIx(userAccountPublicKey, userOrdersAccountPublicKey, order)), [], this.opts);
585
585
  });
586
586
  }
587
587
  getFillOrderIx(userAccountPublicKey, userOrdersAccountPublicKey, order) {
@@ -639,7 +639,7 @@ class ClearingHouse {
639
639
  }
640
640
  placeAndFillOrder(orderParams, discountToken, referrer) {
641
641
  return __awaiter(this, void 0, void 0, function* () {
642
- return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getPlaceAndFillOrderIx(orderParams, discountToken, referrer)), [], this.opts);
642
+ return yield this.txSender.send(utils_1.wrapInTx(yield this.getPlaceAndFillOrderIx(orderParams, discountToken, referrer)), [], this.opts);
643
643
  });
644
644
  }
645
645
  getPlaceAndFillOrderIx(orderParams, discountToken, referrer) {
@@ -700,7 +700,7 @@ class ClearingHouse {
700
700
  */
701
701
  closePosition(marketIndex, discountToken, referrer) {
702
702
  return __awaiter(this, void 0, void 0, function* () {
703
- return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getClosePositionIx(marketIndex, discountToken, referrer)), [], this.opts);
703
+ return yield this.txSender.send(utils_1.wrapInTx(yield this.getClosePositionIx(marketIndex, discountToken, referrer)), [], this.opts);
704
704
  });
705
705
  }
706
706
  getClosePositionIx(marketIndex, discountToken, referrer) {
@@ -748,7 +748,7 @@ class ClearingHouse {
748
748
  }
749
749
  liquidate(liquidateeUserAccountPublicKey) {
750
750
  return __awaiter(this, void 0, void 0, function* () {
751
- return this.txSender.send((0, utils_1.wrapInTx)(yield this.getLiquidateIx(liquidateeUserAccountPublicKey)), [], this.opts);
751
+ return this.txSender.send(utils_1.wrapInTx(yield this.getLiquidateIx(liquidateeUserAccountPublicKey)), [], this.opts);
752
752
  });
753
753
  }
754
754
  getLiquidateIx(liquidateeUserAccountPublicKey) {
@@ -792,7 +792,7 @@ class ClearingHouse {
792
792
  }
793
793
  updateFundingRate(oracle, marketIndex) {
794
794
  return __awaiter(this, void 0, void 0, function* () {
795
- return this.txSender.send((0, utils_1.wrapInTx)(yield this.getUpdateFundingRateIx(oracle, marketIndex)), [], this.opts);
795
+ return this.txSender.send(utils_1.wrapInTx(yield this.getUpdateFundingRateIx(oracle, marketIndex)), [], this.opts);
796
796
  });
797
797
  }
798
798
  getUpdateFundingRateIx(oracle, marketIndex) {
@@ -810,7 +810,7 @@ class ClearingHouse {
810
810
  }
811
811
  settleFundingPayment(userAccount, userPositionsAccount) {
812
812
  return __awaiter(this, void 0, void 0, function* () {
813
- return this.txSender.send((0, utils_1.wrapInTx)(yield this.getSettleFundingPaymentIx(userAccount, userPositionsAccount)), [], this.opts);
813
+ return this.txSender.send(utils_1.wrapInTx(yield this.getSettleFundingPaymentIx(userAccount, userPositionsAccount)), [], this.opts);
814
814
  });
815
815
  }
816
816
  getSettleFundingPaymentIx(userAccount, userPositionsAccount) {
@@ -4,7 +4,7 @@ import { PublicKey } from '@solana/web3.js';
4
4
  import { EventEmitter } from 'events';
5
5
  import StrictEventEmitter from 'strict-event-emitter-types';
6
6
  import { ClearingHouse } from './clearingHouse';
7
- import { Order, UserAccount, UserOrdersAccount, UserPosition, UserPositionsAccount } from './types';
7
+ import { MarginCategory, Order, UserAccount, UserOrdersAccount, UserPosition, UserPositionsAccount } from './types';
8
8
  import { UserAccountSubscriber, UserAccountEvents } from './accounts/types';
9
9
  import { PositionDirection, BN } from '.';
10
10
  export declare class ClearingHouseUser {
@@ -62,12 +62,17 @@ export declare class ClearingHouseUser {
62
62
  * calculates Buying Power = FC * MAX_LEVERAGE
63
63
  * @returns : Precision QUOTE_PRECISION
64
64
  */
65
- getBuyingPower(): BN;
65
+ getBuyingPower(marketIndex: BN | number): BN;
66
66
  /**
67
- * calculates Free Collateral = (TC - TPV) * MAX_LEVERAGE
67
+ * calculates Free Collateral = Total collateral - initial margin requirement
68
68
  * @returns : Precision QUOTE_PRECISION
69
69
  */
70
70
  getFreeCollateral(): BN;
71
+ getInitialMarginRequirement(): BN;
72
+ /**
73
+ * @returns The partial margin requirement in USDC. : QUOTE_PRECISION
74
+ */
75
+ getPartialMarginRequirement(): BN;
71
76
  /**
72
77
  * calculates unrealized position price pnl
73
78
  * @returns : Precision QUOTE_PRECISION
@@ -109,7 +114,7 @@ export declare class ClearingHouseUser {
109
114
  * @params category {Initial, Partial, Maintenance}
110
115
  * @returns : Precision TEN_THOUSAND
111
116
  */
112
- getMaxLeverage(category?: 'Initial' | 'Partial' | 'Maintenance'): BN;
117
+ getMaxLeverage(marketIndex: BN | number, category?: MarginCategory): BN;
113
118
  /**
114
119
  * calculates margin ratio: total collateral / |total position value|
115
120
  * @returns : Precision TEN_THOUSAND
@@ -123,20 +128,12 @@ export declare class ClearingHouseUser {
123
128
  needsToSettleFundingPayment(): boolean;
124
129
  /**
125
130
  * Calculate the liquidation price of a position, with optional parameter to calculate the liquidation price after a trade
126
- * @param targetMarket
127
- * @param positionBaseSizeChange // change in position size to calculate liquidation price for : Precision 10^13
128
- * @param partial
129
- * @returns Precision : MARK_PRICE_PRECISION
130
- */
131
- liquidationPriceOld(targetMarket: Pick<UserPosition, 'marketIndex'>, positionBaseSizeChange?: BN, partial?: boolean): BN;
132
- /**
133
- * Calculate the liquidation price of a position, with optional parameter to calculate the liquidation price after a trade
134
- * @param targetMarket
131
+ * @param marketPosition
135
132
  * @param positionBaseSizeChange // change in position size to calculate liquidation price for : Precision 10^13
136
133
  * @param partial
137
134
  * @returns Precision : MARK_PRICE_PRECISION
138
135
  */
139
- liquidationPrice(targetMarket: Pick<UserPosition, 'marketIndex'>, positionBaseSizeChange?: BN, partial?: boolean): BN;
136
+ liquidationPrice(marketPosition: Pick<UserPosition, 'marketIndex'>, positionBaseSizeChange?: BN, partial?: boolean): BN;
140
137
  /**
141
138
  * Calculates the estimated liquidation price for a position after closing a quote amount of the position.
142
139
  * @param positionMarketIndex
@@ -163,10 +160,9 @@ export declare class ClearingHouseUser {
163
160
  *
164
161
  * @param targetMarketIndex
165
162
  * @param tradeSide
166
- * @param userMaxLeverageSetting - leverage : Precision TEN_THOUSAND
167
163
  * @returns tradeSizeAllowed : Precision QUOTE_PRECISION
168
164
  */
169
- getMaxTradeSizeUSDC(targetMarketIndex: BN, tradeSide: PositionDirection, userMaxLeverageSetting: BN): BN;
165
+ getMaxTradeSizeUSDC(targetMarketIndex: BN, tradeSide: PositionDirection): BN;
170
166
  /**
171
167
  * Returns the leverage ratio for the account after adding (or subtracting) the given quote size to the given position
172
168
  * @param targetMarketIndex
@@ -187,5 +183,4 @@ export declare class ClearingHouseUser {
187
183
  * @returns positionValue : Precision QUOTE_PRECISION
188
184
  */
189
185
  private getTotalPositionValueExcludingMarket;
190
- canFillOrder(order: Order): boolean;
191
186
  }