@drift-labs/sdk 0.1.24 → 0.1.25-master.0

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 (63) hide show
  1. package/lib/accounts/bulkAccountLoader.d.ts +1 -0
  2. package/lib/accounts/bulkAccountLoader.js +16 -2
  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/addresses.js +5 -1
  10. package/lib/admin.d.ts +1 -1
  11. package/lib/admin.js +15 -10
  12. package/lib/clearingHouse.js +26 -20
  13. package/lib/clearingHouseUser.js +18 -18
  14. package/lib/constants/markets.d.ts +4 -4
  15. package/lib/constants/markets.js +22 -0
  16. package/lib/constants/numericConstants.d.ts +1 -0
  17. package/lib/constants/numericConstants.js +2 -1
  18. package/lib/examples/makeTradeExample.js +6 -6
  19. package/lib/factory/oracleClient.d.ts +5 -0
  20. package/lib/factory/oracleClient.js +16 -0
  21. package/lib/idl/clearing_house.json +11 -1
  22. package/lib/idl/switchboard_v2.json +4663 -0
  23. package/lib/index.d.ts +4 -1
  24. package/lib/index.js +9 -2
  25. package/lib/math/amm.js +12 -12
  26. package/lib/math/conversion.js +1 -1
  27. package/lib/math/funding.d.ts +6 -6
  28. package/lib/math/funding.js +5 -17
  29. package/lib/math/market.js +2 -2
  30. package/lib/math/orders.js +9 -9
  31. package/lib/math/position.js +1 -1
  32. package/lib/math/trade.js +18 -18
  33. package/lib/mockUSDCFaucet.js +5 -1
  34. package/lib/oracles/pythClient.d.ts +14 -0
  35. package/lib/oracles/pythClient.js +53 -0
  36. package/lib/oracles/switchboardClient.d.ts +13 -0
  37. package/lib/oracles/switchboardClient.js +76 -0
  38. package/lib/oracles/types.d.ts +15 -0
  39. package/lib/oracles/types.js +2 -0
  40. package/lib/orderParams.d.ts +1 -1
  41. package/lib/orderParams.js +2 -2
  42. package/lib/orders.js +19 -19
  43. package/lib/tx/retryTxSender.js +1 -1
  44. package/lib/types.d.ts +1 -0
  45. package/package.json +2 -1
  46. package/src/accounts/bulkAccountLoader.ts +19 -0
  47. package/src/admin.ts +2 -0
  48. package/src/clearingHouse.ts +2 -0
  49. package/src/constants/markets.ts +26 -3
  50. package/src/constants/numericConstants.ts +1 -0
  51. package/src/factory/oracleClient.ts +22 -0
  52. package/src/idl/clearing_house.json +11 -1
  53. package/src/idl/switchboard_v2.json +4663 -0
  54. package/src/index.ts +4 -1
  55. package/src/math/funding.ts +9 -25
  56. package/src/oracles/pythClient.ts +49 -0
  57. package/src/oracles/switchboardClient.ts +87 -0
  58. package/src/oracles/types.ts +15 -0
  59. package/src/orderParams.ts +3 -2
  60. package/src/types.ts +1 -0
  61. package/lib/pythClient.d.ts +0 -7
  62. package/lib/pythClient.js +0 -25
  63. package/src/pythClient.ts +0 -15
@@ -16,6 +16,7 @@ export declare class BulkAccountLoader {
16
16
  loadPromise?: Promise<void>;
17
17
  loadPromiseResolver: () => void;
18
18
  loggingEnabled: boolean;
19
+ lastUpdate: number;
19
20
  constructor(connection: Connection, commitment: Commitment, pollingFrequency: number);
20
21
  addAccount(publicKey: PublicKey, callback: (buffer: Buffer) => void): string;
21
22
  removeAccount(publicKey: PublicKey, callbackId: string): void;
@@ -10,21 +10,24 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.BulkAccountLoader = void 0;
13
+ const web3_js_1 = require("@solana/web3.js");
13
14
  const uuid_1 = require("uuid");
14
15
  const GET_MULTIPLE_ACCOUNTS_CHUNK_SIZE = 99;
16
+ const fiveMinutes = 5 * 60 * 1000;
15
17
  class BulkAccountLoader {
16
18
  constructor(connection, commitment, pollingFrequency) {
17
19
  this.accountsToLoad = new Map();
18
20
  this.accountData = new Map();
19
21
  this.errorCallbacks = new Map();
20
22
  this.loggingEnabled = false;
23
+ this.lastUpdate = Date.now();
21
24
  this.connection = connection;
22
25
  this.commitment = commitment;
23
26
  this.pollingFrequency = pollingFrequency;
24
27
  }
25
28
  addAccount(publicKey, callback) {
26
29
  const existingSize = this.accountsToLoad.size;
27
- const callbackId = uuid_1.v4();
30
+ const callbackId = (0, uuid_1.v4)();
28
31
  const existingAccountToLoad = this.accountsToLoad.get(publicKey.toString());
29
32
  if (existingAccountToLoad) {
30
33
  existingAccountToLoad.callbacks.set(callbackId, callback);
@@ -58,7 +61,7 @@ class BulkAccountLoader {
58
61
  }
59
62
  }
60
63
  addErrorCallbacks(callback) {
61
- const callbackId = uuid_1.v4();
64
+ const callbackId = (0, uuid_1.v4)();
62
65
  this.errorCallbacks.set(callbackId, callback);
63
66
  return callbackId;
64
67
  }
@@ -98,6 +101,15 @@ class BulkAccountLoader {
98
101
  finally {
99
102
  this.loadPromiseResolver();
100
103
  this.loadPromise = undefined;
104
+ const now = Date.now();
105
+ if (now - this.lastUpdate > fiveMinutes) {
106
+ if (this.loggingEnabled) {
107
+ console.log("Haven't seen updated account in five minutes. Bulk account loader creating new Connection Object");
108
+ }
109
+ this.connection = new web3_js_1.Connection(
110
+ // @ts-ignore
111
+ this.connection._rpcEndpoint, this.connection.commitment);
112
+ }
101
113
  }
102
114
  });
103
115
  }
@@ -131,6 +143,7 @@ class BulkAccountLoader {
131
143
  buffer: newBuffer,
132
144
  });
133
145
  this.handleAccountCallbacks(accountToLoad, newBuffer);
146
+ this.lastUpdate = Date.now();
134
147
  continue;
135
148
  }
136
149
  if (newSlot <= oldRPCResponse.slot) {
@@ -143,6 +156,7 @@ class BulkAccountLoader {
143
156
  buffer: newBuffer,
144
157
  });
145
158
  this.handleAccountCallbacks(accountToLoad, newBuffer);
159
+ this.lastUpdate = Date.now();
146
160
  }
147
161
  }
148
162
  });
@@ -54,7 +54,7 @@ class PollingClearingHouseAccountSubscriber {
54
54
  if (this.accountsToPoll.size > 0) {
55
55
  return;
56
56
  }
57
- const statePublicKey = yield addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
57
+ const statePublicKey = yield (0, 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(utils_1.capitalize(accountToPoll.key), buffer);
130
+ const account = this.program.account[accountToPoll.key].coder.accounts.decode((0, 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(utils_1.capitalize(accountToPoll.key), buffer);
148
+ this[accountToPoll.key] = this.program.account[accountToPoll.key].coder.accounts.decode((0, 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 = token_1.parseTokenAccount(buffer);
40
+ const tokenAccount = (0, 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 = token_1.parseTokenAccount(buffer);
54
+ this.tokenAccount = (0, 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 addresses_1.getUserAccountPublicKey(this.program.programId, this.authority);
45
+ const userPublicKey = yield (0, 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 addresses_1.getUserOrdersAccountPublicKey(this.program.programId, userPublicKey);
57
+ const userOrdersPublicKey = yield (0, 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(utils_1.capitalize(accountToPoll.key), buffer);
88
+ const account = this.program.account[accountToPoll.key].coder.accounts.decode((0, 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(utils_1.capitalize(accountToPoll.key), buffer);
120
+ this[accountToPoll.key] = this.program.account[accountToPoll.key].coder.accounts.decode((0, 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(utils_1.capitalize(this.accountName), newBuffer);
50
+ this.data = this.program.account[this.accountName].coder.accounts.decode((0, 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(utils_1.capitalize(this.accountName), newBuffer);
64
+ this.data = this.program.account[this.accountName].coder.accounts.decode((0, 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 addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
38
+ const statePublicKey = yield (0, 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 addresses_1.getUserAccountPublicKey(this.program.programId, this.authority);
30
+ const userPublicKey = yield (0, 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 addresses_1.getUserOrdersAccountPublicKey(this.program.programId, userPublicKey);
42
+ const userOrdersPublicKey = yield (0, 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/addresses.js CHANGED
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
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, marginRatioInitial?: number, marginRatioPartial?: number, marginRatioMaintenance?: number): Promise<TransactionSignature>;
14
+ initializeMarket(marketIndex: BN, priceOracle: PublicKey, baseAssetReserve: BN, quoteAssetReserve: BN, periodicity: BN, pegMultiplier?: BN, oracleSource?: OracleSource, 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>;
package/lib/admin.js CHANGED
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -30,6 +34,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
30
34
  Object.defineProperty(exports, "__esModule", { value: true });
31
35
  exports.Admin = void 0;
32
36
  const web3_js_1 = require("@solana/web3.js");
37
+ const types_1 = require("./types");
33
38
  const anchor_1 = require("@project-serum/anchor");
34
39
  const anchor = __importStar(require("@project-serum/anchor"));
35
40
  const addresses_1 = require("./addresses");
@@ -41,8 +46,8 @@ const amm_1 = require("./math/amm");
41
46
  const clearingHouse_2 = require("./factory/clearingHouse");
42
47
  class Admin extends clearingHouse_1.ClearingHouse {
43
48
  static from(connection, wallet, clearingHouseProgramId, opts = anchor_1.Provider.defaultOptions()) {
44
- const config = clearingHouse_2.getWebSocketClearingHouseConfig(connection, wallet, clearingHouseProgramId, opts);
45
- return clearingHouse_2.getAdmin(config);
49
+ const config = (0, clearingHouse_2.getWebSocketClearingHouseConfig)(connection, wallet, clearingHouseProgramId, opts);
50
+ return (0, clearingHouse_2.getAdmin)(config);
46
51
  }
47
52
  initialize(usdcMint, adminControlsPrices) {
48
53
  return __awaiter(this, void 0, void 0, function* () {
@@ -61,7 +66,7 @@ class Admin extends clearingHouse_1.ClearingHouse {
61
66
  const tradeHistory = anchor.web3.Keypair.generate();
62
67
  const liquidationHistory = anchor.web3.Keypair.generate();
63
68
  const curveHistory = anchor.web3.Keypair.generate();
64
- const [clearingHouseStatePublicKey, clearingHouseNonce] = yield addresses_1.getClearingHouseStateAccountPublicKeyAndNonce(this.program.programId);
69
+ const [clearingHouseStatePublicKey, clearingHouseNonce] = yield (0, addresses_1.getClearingHouseStateAccountPublicKeyAndNonce)(this.program.programId);
65
70
  const initializeTx = yield this.program.transaction.initialize(clearingHouseNonce, collateralVaultNonce, insuranceVaultNonce, adminControlsPrices, {
66
71
  accounts: {
67
72
  admin: this.wallet.publicKey,
@@ -118,8 +123,8 @@ class Admin extends clearingHouse_1.ClearingHouse {
118
123
  initializeOrderState() {
119
124
  return __awaiter(this, void 0, void 0, function* () {
120
125
  const orderHistory = anchor.web3.Keypair.generate();
121
- const [orderStatePublicKey, orderStateNonce] = yield addresses_1.getOrderStateAccountPublicKeyAndNonce(this.program.programId);
122
- const clearingHouseStatePublicKey = yield addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
126
+ const [orderStatePublicKey, orderStateNonce] = yield (0, addresses_1.getOrderStateAccountPublicKeyAndNonce)(this.program.programId);
127
+ const clearingHouseStatePublicKey = yield (0, addresses_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
123
128
  const initializeOrderStateTx = yield this.program.transaction.initializeOrderState(orderStateNonce, {
124
129
  accounts: {
125
130
  admin: this.wallet.publicKey,
@@ -136,12 +141,12 @@ class Admin extends clearingHouse_1.ClearingHouse {
136
141
  return yield this.txSender.send(initializeOrderStateTx, [orderHistory], this.opts);
137
142
  });
138
143
  }
139
- initializeMarket(marketIndex, priceOracle, baseAssetReserve, quoteAssetReserve, periodicity, pegMultiplier = numericConstants_1.PEG_PRECISION, marginRatioInitial = 2000, marginRatioPartial = 625, marginRatioMaintenance = 500) {
144
+ initializeMarket(marketIndex, priceOracle, baseAssetReserve, quoteAssetReserve, periodicity, pegMultiplier = numericConstants_1.PEG_PRECISION, oracleSource = types_1.OracleSource.PYTH, marginRatioInitial = 2000, marginRatioPartial = 625, marginRatioMaintenance = 500) {
140
145
  return __awaiter(this, void 0, void 0, function* () {
141
146
  if (this.getMarketsAccount().markets[marketIndex.toNumber()].initialized) {
142
147
  throw Error(`MarketIndex ${marketIndex.toNumber()} already initialized`);
143
148
  }
144
- const initializeMarketTx = yield this.program.transaction.initializeMarket(marketIndex, baseAssetReserve, quoteAssetReserve, periodicity, pegMultiplier, marginRatioInitial, marginRatioPartial, marginRatioMaintenance, {
149
+ const initializeMarketTx = yield this.program.transaction.initializeMarket(marketIndex, baseAssetReserve, quoteAssetReserve, periodicity, pegMultiplier, oracleSource, marginRatioInitial, marginRatioPartial, marginRatioMaintenance, {
145
150
  accounts: {
146
151
  state: yield this.getStatePublicKey(),
147
152
  admin: this.wallet.publicKey,
@@ -202,8 +207,8 @@ class Admin extends clearingHouse_1.ClearingHouse {
202
207
  moveAmmToPrice(marketIndex, targetPrice) {
203
208
  return __awaiter(this, void 0, void 0, function* () {
204
209
  const market = this.getMarket(marketIndex);
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));
210
+ const [direction, tradeSize, _] = (0, trade_1.calculateTargetPriceTrade)(market, targetPrice);
211
+ const [newQuoteAssetAmount, newBaseAssetAmount] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, 'quote', tradeSize, (0, amm_1.getSwapDirection)('quote', direction));
207
212
  const state = this.getStateAccount();
208
213
  return yield this.program.rpc.moveAmmPrice(newBaseAssetAmount, newQuoteAssetAmount, marketIndex, {
209
214
  accounts: {
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -73,8 +77,8 @@ class ClearingHouse {
73
77
  * @returns
74
78
  */
75
79
  static from(connection, wallet, clearingHouseProgramId, opts = anchor_1.Provider.defaultOptions()) {
76
- const config = clearingHouse_1.getWebSocketClearingHouseConfig(connection, wallet, clearingHouseProgramId, opts);
77
- return clearingHouse_1.getClearingHouse(config);
80
+ const config = (0, clearingHouse_1.getWebSocketClearingHouseConfig)(connection, wallet, clearingHouseProgramId, opts);
81
+ return (0, clearingHouse_1.getClearingHouse)(config);
78
82
  }
79
83
  /**
80
84
  *
@@ -126,7 +130,7 @@ class ClearingHouse {
126
130
  if (this.statePublicKey) {
127
131
  return this.statePublicKey;
128
132
  }
129
- this.statePublicKey = yield addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
133
+ this.statePublicKey = yield (0, addresses_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
130
134
  return this.statePublicKey;
131
135
  });
132
136
  }
@@ -168,7 +172,7 @@ class ClearingHouse {
168
172
  if (this.orderStatePublicKey) {
169
173
  return this.orderStatePublicKey;
170
174
  }
171
- this.orderStatePublicKey = yield addresses_1.getOrderStateAccountPublicKey(this.program.programId);
175
+ this.orderStatePublicKey = yield (0, addresses_1.getOrderStateAccountPublicKey)(this.program.programId);
172
176
  return this.orderStatePublicKey;
173
177
  });
174
178
  }
@@ -189,6 +193,8 @@ class ClearingHouse {
189
193
  this.program = newProgram;
190
194
  this.userAccountPublicKey = undefined;
191
195
  this.userAccount = undefined;
196
+ this.userOrdersAccountPublicKey = undefined;
197
+ this.userOrdersExist = undefined;
192
198
  }
193
199
  initializeUserAccount() {
194
200
  return __awaiter(this, void 0, void 0, function* () {
@@ -202,7 +208,7 @@ class ClearingHouse {
202
208
  }
203
209
  getInitializeUserInstructions() {
204
210
  return __awaiter(this, void 0, void 0, function* () {
205
- const [userAccountPublicKey, userAccountNonce] = yield addresses_1.getUserAccountPublicKeyAndNonce(this.program.programId, this.wallet.publicKey);
211
+ const [userAccountPublicKey, userAccountNonce] = yield (0, addresses_1.getUserAccountPublicKeyAndNonce)(this.program.programId, this.wallet.publicKey);
206
212
  const remainingAccounts = [];
207
213
  const optionalAccounts = {
208
214
  whitelistToken: false,
@@ -243,7 +249,7 @@ class ClearingHouse {
243
249
  if (!userAccountPublicKey) {
244
250
  userAccountPublicKey = yield this.getUserAccountPublicKey();
245
251
  }
246
- const [userOrdersAccountPublicKey, userOrdersAccountNonce] = yield addresses_1.getUserOrdersAccountPublicKeyAndNonce(this.program.programId, userAccountPublicKey);
252
+ const [userOrdersAccountPublicKey, userOrdersAccountNonce] = yield (0, addresses_1.getUserOrdersAccountPublicKeyAndNonce)(this.program.programId, userAccountPublicKey);
247
253
  return yield this.program.instruction.initializeUserOrders(userOrdersAccountNonce, {
248
254
  accounts: {
249
255
  user: userAccountPublicKey,
@@ -265,7 +271,7 @@ class ClearingHouse {
265
271
  if (this.userAccountPublicKey) {
266
272
  return this.userAccountPublicKey;
267
273
  }
268
- this.userAccountPublicKey = yield addresses_1.getUserAccountPublicKey(this.program.programId, this.wallet.publicKey);
274
+ this.userAccountPublicKey = yield (0, addresses_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey);
269
275
  return this.userAccountPublicKey;
270
276
  });
271
277
  }
@@ -287,7 +293,7 @@ class ClearingHouse {
287
293
  if (this.userOrdersAccountPublicKey) {
288
294
  return this.userOrdersAccountPublicKey;
289
295
  }
290
- this.userOrdersAccountPublicKey = yield addresses_1.getUserOrdersAccountPublicKey(this.program.programId, yield this.getUserAccountPublicKey());
296
+ this.userOrdersAccountPublicKey = yield (0, addresses_1.getUserOrdersAccountPublicKey)(this.program.programId, yield this.getUserAccountPublicKey());
291
297
  return this.userOrdersAccountPublicKey;
292
298
  });
293
299
  }
@@ -380,7 +386,7 @@ class ClearingHouse {
380
386
  }
381
387
  withdrawCollateral(amount, collateralAccountPublicKey) {
382
388
  return __awaiter(this, void 0, void 0, function* () {
383
- return this.txSender.send(utils_1.wrapInTx(yield this.getWithdrawCollateralIx(amount, collateralAccountPublicKey)), [], this.opts);
389
+ return this.txSender.send((0, utils_1.wrapInTx)(yield this.getWithdrawCollateralIx(amount, collateralAccountPublicKey)), [], this.opts);
384
390
  });
385
391
  }
386
392
  getWithdrawCollateralIx(amount, collateralAccountPublicKey) {
@@ -409,7 +415,7 @@ class ClearingHouse {
409
415
  }
410
416
  openPosition(direction, amount, marketIndex, limitPrice, discountToken, referrer) {
411
417
  return __awaiter(this, void 0, void 0, function* () {
412
- return yield this.txSender.send(utils_1.wrapInTx(yield this.getOpenPositionIx(direction, amount, marketIndex, limitPrice, discountToken, referrer)), [], this.opts);
418
+ return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getOpenPositionIx(direction, amount, marketIndex, limitPrice, discountToken, referrer)), [], this.opts);
413
419
  });
414
420
  }
415
421
  getOpenPositionIx(direction, amount, marketIndex, limitPrice, discountToken, referrer) {
@@ -475,7 +481,7 @@ class ClearingHouse {
475
481
  }
476
482
  placeOrder(orderParams, discountToken, referrer) {
477
483
  return __awaiter(this, void 0, void 0, function* () {
478
- return yield this.txSender.send(utils_1.wrapInTx(yield this.getPlaceOrderIx(orderParams, discountToken, referrer)), [], this.opts);
484
+ return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getPlaceOrderIx(orderParams, discountToken, referrer)), [], this.opts);
479
485
  });
480
486
  }
481
487
  getPlaceOrderIx(orderParams, discountToken, referrer) {
@@ -527,7 +533,7 @@ class ClearingHouse {
527
533
  }
528
534
  cancelOrder(orderId) {
529
535
  return __awaiter(this, void 0, void 0, function* () {
530
- return yield this.txSender.send(utils_1.wrapInTx(yield this.getCancelOrderIx(orderId)), [], this.opts);
536
+ return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getCancelOrderIx(orderId)), [], this.opts);
531
537
  });
532
538
  }
533
539
  getCancelOrderIx(orderId) {
@@ -554,7 +560,7 @@ class ClearingHouse {
554
560
  }
555
561
  cancelOrderByUserId(userOrderId) {
556
562
  return __awaiter(this, void 0, void 0, function* () {
557
- return yield this.txSender.send(utils_1.wrapInTx(yield this.getCancelOrderByUserIdIx(userOrderId)), [], this.opts);
563
+ return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getCancelOrderByUserIdIx(userOrderId)), [], this.opts);
558
564
  });
559
565
  }
560
566
  getCancelOrderByUserIdIx(userOrderId) {
@@ -581,7 +587,7 @@ class ClearingHouse {
581
587
  }
582
588
  fillOrder(userAccountPublicKey, userOrdersAccountPublicKey, order) {
583
589
  return __awaiter(this, void 0, void 0, function* () {
584
- return yield this.txSender.send(utils_1.wrapInTx(yield this.getFillOrderIx(userAccountPublicKey, userOrdersAccountPublicKey, order)), [], this.opts);
590
+ return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getFillOrderIx(userAccountPublicKey, userOrdersAccountPublicKey, order)), [], this.opts);
585
591
  });
586
592
  }
587
593
  getFillOrderIx(userAccountPublicKey, userOrdersAccountPublicKey, order) {
@@ -639,7 +645,7 @@ class ClearingHouse {
639
645
  }
640
646
  placeAndFillOrder(orderParams, discountToken, referrer) {
641
647
  return __awaiter(this, void 0, void 0, function* () {
642
- return yield this.txSender.send(utils_1.wrapInTx(yield this.getPlaceAndFillOrderIx(orderParams, discountToken, referrer)), [], this.opts);
648
+ return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getPlaceAndFillOrderIx(orderParams, discountToken, referrer)), [], this.opts);
643
649
  });
644
650
  }
645
651
  getPlaceAndFillOrderIx(orderParams, discountToken, referrer) {
@@ -700,7 +706,7 @@ class ClearingHouse {
700
706
  */
701
707
  closePosition(marketIndex, discountToken, referrer) {
702
708
  return __awaiter(this, void 0, void 0, function* () {
703
- return yield this.txSender.send(utils_1.wrapInTx(yield this.getClosePositionIx(marketIndex, discountToken, referrer)), [], this.opts);
709
+ return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getClosePositionIx(marketIndex, discountToken, referrer)), [], this.opts);
704
710
  });
705
711
  }
706
712
  getClosePositionIx(marketIndex, discountToken, referrer) {
@@ -748,7 +754,7 @@ class ClearingHouse {
748
754
  }
749
755
  liquidate(liquidateeUserAccountPublicKey) {
750
756
  return __awaiter(this, void 0, void 0, function* () {
751
- return this.txSender.send(utils_1.wrapInTx(yield this.getLiquidateIx(liquidateeUserAccountPublicKey)), [], this.opts);
757
+ return this.txSender.send((0, utils_1.wrapInTx)(yield this.getLiquidateIx(liquidateeUserAccountPublicKey)), [], this.opts);
752
758
  });
753
759
  }
754
760
  getLiquidateIx(liquidateeUserAccountPublicKey) {
@@ -792,7 +798,7 @@ class ClearingHouse {
792
798
  }
793
799
  updateFundingRate(oracle, marketIndex) {
794
800
  return __awaiter(this, void 0, void 0, function* () {
795
- return this.txSender.send(utils_1.wrapInTx(yield this.getUpdateFundingRateIx(oracle, marketIndex)), [], this.opts);
801
+ return this.txSender.send((0, utils_1.wrapInTx)(yield this.getUpdateFundingRateIx(oracle, marketIndex)), [], this.opts);
796
802
  });
797
803
  }
798
804
  getUpdateFundingRateIx(oracle, marketIndex) {
@@ -810,7 +816,7 @@ class ClearingHouse {
810
816
  }
811
817
  settleFundingPayment(userAccount, userPositionsAccount) {
812
818
  return __awaiter(this, void 0, void 0, function* () {
813
- return this.txSender.send(utils_1.wrapInTx(yield this.getSettleFundingPaymentIx(userAccount, userPositionsAccount)), [], this.opts);
819
+ return this.txSender.send((0, utils_1.wrapInTx)(yield this.getSettleFundingPaymentIx(userAccount, userPositionsAccount)), [], this.opts);
814
820
  });
815
821
  }
816
822
  getSettleFundingPaymentIx(userAccount, userPositionsAccount) {
@@ -39,8 +39,8 @@ class ClearingHouseUser {
39
39
  static from(clearingHouse, authority) {
40
40
  if (clearingHouse.accountSubscriber.type !== 'websocket')
41
41
  throw 'This method only works for clearing houses with a websocket account listener. Try using the getClearingHouseUser factory method to initialize a ClearingHouseUser instead';
42
- const config = clearingHouseUser_1.getWebSocketClearingHouseUserConfig(clearingHouse, authority);
43
- return clearingHouseUser_1.getClearingHouseUser(config);
42
+ const config = (0, clearingHouseUser_1.getWebSocketClearingHouseUserConfig)(clearingHouse, authority);
43
+ return (0, clearingHouseUser_1.getClearingHouseUser)(config);
44
44
  }
45
45
  /**
46
46
  * Subscribe to ClearingHouseUser state accounts
@@ -113,7 +113,7 @@ class ClearingHouseUser {
113
113
  if (this.userAccountPublicKey) {
114
114
  return this.userAccountPublicKey;
115
115
  }
116
- this.userAccountPublicKey = yield addresses_1.getUserAccountPublicKey(this.clearingHouse.program.programId, this.authority);
116
+ this.userAccountPublicKey = yield (0, addresses_1.getUserAccountPublicKey)(this.clearingHouse.program.programId, this.authority);
117
117
  return this.userAccountPublicKey;
118
118
  });
119
119
  }
@@ -122,7 +122,7 @@ class ClearingHouseUser {
122
122
  if (this.userOrdersAccountPublicKey) {
123
123
  return this.userOrdersAccountPublicKey;
124
124
  }
125
- this.userOrdersAccountPublicKey = yield _1.getUserOrdersAccountPublicKey(this.clearingHouse.program.programId, yield this.getUserAccountPublicKey());
125
+ this.userOrdersAccountPublicKey = yield (0, _1.getUserOrdersAccountPublicKey)(this.clearingHouse.program.programId, yield this.getUserAccountPublicKey());
126
126
  return this.userOrdersAccountPublicKey;
127
127
  });
128
128
  }
@@ -155,7 +155,7 @@ class ClearingHouseUser {
155
155
  getInitialMarginRequirement() {
156
156
  return this.getUserPositionsAccount().positions.reduce((marginRequirement, marketPosition) => {
157
157
  const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
158
- return marginRequirement.add(_1.calculateBaseAssetValue(market, marketPosition)
158
+ return marginRequirement.add((0, _1.calculateBaseAssetValue)(market, marketPosition)
159
159
  .mul(new _1.BN(market.marginRatioInitial))
160
160
  .div(numericConstants_1.MARGIN_PRECISION));
161
161
  }, numericConstants_1.ZERO);
@@ -166,7 +166,7 @@ class ClearingHouseUser {
166
166
  getPartialMarginRequirement() {
167
167
  return this.getUserPositionsAccount().positions.reduce((marginRequirement, marketPosition) => {
168
168
  const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
169
- return marginRequirement.add(_1.calculateBaseAssetValue(market, marketPosition)
169
+ return marginRequirement.add((0, _1.calculateBaseAssetValue)(market, marketPosition)
170
170
  .mul(new _1.BN(market.marginRatioPartial))
171
171
  .div(numericConstants_1.MARGIN_PRECISION));
172
172
  }, numericConstants_1.ZERO);
@@ -180,7 +180,7 @@ class ClearingHouseUser {
180
180
  .positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
181
181
  .reduce((pnl, marketPosition) => {
182
182
  const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
183
- return pnl.add(_1.calculatePositionPNL(market, marketPosition, withFunding));
183
+ return pnl.add((0, _1.calculatePositionPNL)(market, marketPosition, withFunding));
184
184
  }, numericConstants_1.ZERO);
185
185
  }
186
186
  /**
@@ -192,7 +192,7 @@ class ClearingHouseUser {
192
192
  .positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
193
193
  .reduce((pnl, marketPosition) => {
194
194
  const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
195
- return pnl.add(_1.calculatePositionFundingPNL(market, marketPosition));
195
+ return pnl.add((0, _1.calculatePositionFundingPNL)(market, marketPosition));
196
196
  }, numericConstants_1.ZERO);
197
197
  }
198
198
  /**
@@ -210,7 +210,7 @@ class ClearingHouseUser {
210
210
  getTotalPositionValue() {
211
211
  return this.getUserPositionsAccount().positions.reduce((positionValue, marketPosition) => {
212
212
  const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
213
- return positionValue.add(_1.calculateBaseAssetValue(market, marketPosition));
213
+ return positionValue.add((0, _1.calculateBaseAssetValue)(market, marketPosition));
214
214
  }, numericConstants_1.ZERO);
215
215
  }
216
216
  /**
@@ -220,7 +220,7 @@ class ClearingHouseUser {
220
220
  getPositionValue(marketIndex) {
221
221
  const userPosition = this.getUserPosition(marketIndex) || this.getEmptyPosition(marketIndex);
222
222
  const market = this.clearingHouse.getMarket(userPosition.marketIndex);
223
- return _1.calculateBaseAssetValue(market, userPosition);
223
+ return (0, _1.calculateBaseAssetValue)(market, userPosition);
224
224
  }
225
225
  getPositionSide(currentPosition) {
226
226
  if (currentPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
@@ -239,10 +239,10 @@ class ClearingHouseUser {
239
239
  */
240
240
  getPositionEstimatedExitPriceAndPnl(position, amountToClose) {
241
241
  const market = this.clearingHouse.getMarket(position.marketIndex);
242
- const entryPrice = position_1.calculateEntryPrice(position);
242
+ const entryPrice = (0, position_1.calculateEntryPrice)(position);
243
243
  if (amountToClose) {
244
244
  if (amountToClose.eq(numericConstants_1.ZERO)) {
245
- return [_1.calculateMarkPrice(market), numericConstants_1.ZERO];
245
+ return [(0, _1.calculateMarkPrice)(market), numericConstants_1.ZERO];
246
246
  }
247
247
  position = {
248
248
  baseAssetAmount: amountToClose,
@@ -251,7 +251,7 @@ class ClearingHouseUser {
251
251
  quoteAssetAmount: position.quoteAssetAmount,
252
252
  };
253
253
  }
254
- const baseAssetValue = _1.calculateBaseAssetValue(market, position);
254
+ const baseAssetValue = (0, _1.calculateBaseAssetValue)(market, position);
255
255
  if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
256
256
  return [numericConstants_1.ZERO, numericConstants_1.ZERO];
257
257
  }
@@ -376,13 +376,13 @@ class ClearingHouseUser {
376
376
  if (proposedBaseAssetAmount.eq(numericConstants_1.ZERO))
377
377
  return new _1.BN(-1);
378
378
  const market = this.clearingHouse.getMarket(proposedMarketPosition.marketIndex);
379
- const proposedMarketPositionValue = _1.calculateBaseAssetValue(market, proposedMarketPosition);
379
+ const proposedMarketPositionValue = (0, _1.calculateBaseAssetValue)(market, proposedMarketPosition);
380
380
  // total position value after trade
381
381
  const totalPositionValueAfterTrade = totalPositionValueExcludingTargetMarket.add(proposedMarketPositionValue);
382
382
  const marginRequirementExcludingTargetMarket = this.getUserPositionsAccount().positions.reduce((totalMarginRequirement, position) => {
383
383
  if (!position.marketIndex.eq(marketPosition.marketIndex)) {
384
384
  const market = this.clearingHouse.getMarket(position.marketIndex);
385
- const positionValue = _1.calculateBaseAssetValue(market, position);
385
+ const positionValue = (0, _1.calculateBaseAssetValue)(market, position);
386
386
  const marketMarginRequirement = positionValue
387
387
  .mul(partial
388
388
  ? new _1.BN(market.marginRatioPartial)
@@ -426,13 +426,13 @@ class ClearingHouseUser {
426
426
  }
427
427
  let markPriceAfterTrade;
428
428
  if (positionBaseSizeChange.eq(numericConstants_1.ZERO)) {
429
- markPriceAfterTrade = _1.calculateMarkPrice(this.clearingHouse.getMarket(marketPosition.marketIndex));
429
+ markPriceAfterTrade = (0, _1.calculateMarkPrice)(this.clearingHouse.getMarket(marketPosition.marketIndex));
430
430
  }
431
431
  else {
432
432
  const direction = positionBaseSizeChange.gt(numericConstants_1.ZERO)
433
433
  ? _1.PositionDirection.LONG
434
434
  : _1.PositionDirection.SHORT;
435
- markPriceAfterTrade = _1.calculateTradeSlippage(direction, positionBaseSizeChange.abs(), this.clearingHouse.getMarket(marketPosition.marketIndex), 'base')[3]; // newPrice after swap
435
+ markPriceAfterTrade = (0, _1.calculateTradeSlippage)(direction, positionBaseSizeChange.abs(), this.clearingHouse.getMarket(marketPosition.marketIndex), 'base')[3]; // newPrice after swap
436
436
  }
437
437
  if (priceDelta.gt(markPriceAfterTrade)) {
438
438
  return new _1.BN(-1);
@@ -483,7 +483,7 @@ class ClearingHouseUser {
483
483
  getMaxTradeSizeUSDC(targetMarketIndex, tradeSide) {
484
484
  const currentPosition = this.getUserPosition(targetMarketIndex) ||
485
485
  this.getEmptyPosition(targetMarketIndex);
486
- const targetSide = types_1.isVariant(tradeSide, 'short') ? 'short' : 'long';
486
+ const targetSide = (0, types_1.isVariant)(tradeSide, 'short') ? 'short' : 'long';
487
487
  const currentPositionSide = (currentPosition === null || currentPosition === void 0 ? void 0 : currentPosition.baseAssetAmount.isNeg())
488
488
  ? 'short'
489
489
  : 'long';