@drift-labs/sdk 0.1.23-master.3 → 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 (61) hide show
  1. package/lib/accounts/bulkAccountLoader.d.ts +2 -0
  2. package/lib/accounts/bulkAccountLoader.js +26 -11
  3. package/lib/addresses.js +5 -1
  4. package/lib/admin.d.ts +2 -2
  5. package/lib/admin.js +11 -5
  6. package/lib/clearingHouse.js +7 -1
  7. package/lib/clearingHouseUser.d.ts +12 -17
  8. package/lib/clearingHouseUser.js +114 -217
  9. package/lib/constants/markets.d.ts +4 -4
  10. package/lib/constants/markets.js +22 -0
  11. package/lib/constants/numericConstants.d.ts +2 -2
  12. package/lib/constants/numericConstants.js +3 -3
  13. package/lib/factory/oracleClient.d.ts +5 -0
  14. package/lib/factory/oracleClient.js +16 -0
  15. package/lib/idl/clearing_house.json +53 -5
  16. package/lib/idl/switchboard_v2.json +4663 -0
  17. package/lib/index.d.ts +4 -1
  18. package/lib/index.js +9 -2
  19. package/lib/math/funding.d.ts +6 -6
  20. package/lib/math/funding.js +4 -16
  21. package/lib/math/orders.d.ts +1 -0
  22. package/lib/math/orders.js +19 -1
  23. package/lib/mockUSDCFaucet.js +5 -1
  24. package/lib/oracles/pythClient.d.ts +14 -0
  25. package/lib/oracles/pythClient.js +53 -0
  26. package/lib/oracles/switchboardClient.d.ts +13 -0
  27. package/lib/oracles/switchboardClient.js +76 -0
  28. package/lib/oracles/types.d.ts +15 -0
  29. package/lib/oracles/types.js +2 -0
  30. package/lib/orderParams.d.ts +1 -1
  31. package/lib/orderParams.js +2 -2
  32. package/lib/orders.js +1 -1
  33. package/lib/types.d.ts +5 -1
  34. package/package.json +2 -1
  35. package/src/accounts/bulkAccountLoader.ts +37 -13
  36. package/src/accounts/types.js +10 -0
  37. package/src/accounts/utils.js +7 -0
  38. package/src/accounts/webSocketAccountSubscriber.js +76 -0
  39. package/src/addresses.js +83 -0
  40. package/src/admin.ts +15 -4
  41. package/src/clearingHouse.ts +2 -0
  42. package/src/clearingHouseUser.ts +161 -330
  43. package/src/constants/markets.ts +26 -3
  44. package/src/constants/numericConstants.ts +2 -2
  45. package/src/factory/oracleClient.ts +22 -0
  46. package/src/idl/clearing_house.json +53 -5
  47. package/src/idl/switchboard_v2.json +4663 -0
  48. package/src/index.ts +4 -1
  49. package/src/math/funding.ts +9 -25
  50. package/src/math/orders.ts +28 -0
  51. package/src/mockUSDCFaucet.js +171 -0
  52. package/src/oracles/pythClient.ts +49 -0
  53. package/src/oracles/switchboardClient.ts +87 -0
  54. package/src/oracles/types.ts +15 -0
  55. package/src/orderParams.ts +3 -2
  56. package/src/orders.ts +1 -1
  57. package/src/types.js +60 -0
  58. package/src/types.ts +6 -1
  59. package/lib/pythClient.d.ts +0 -7
  60. package/lib/pythClient.js +0 -25
  61. package/src/pythClient.ts +0 -15
@@ -15,6 +15,8 @@ export declare class BulkAccountLoader {
15
15
  intervalId?: NodeJS.Timer;
16
16
  loadPromise?: Promise<void>;
17
17
  loadPromiseResolver: () => void;
18
+ loggingEnabled: boolean;
19
+ lastUpdate: number;
18
20
  constructor(connection: Connection, commitment: Commitment, pollingFrequency: number);
19
21
  addAccount(publicKey: PublicKey, callback: (buffer: Buffer) => void): string;
20
22
  removeAccount(publicKey: PublicKey, callbackId: string): void;
@@ -10,13 +10,17 @@ 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();
22
+ this.loggingEnabled = false;
23
+ this.lastUpdate = Date.now();
20
24
  this.connection = connection;
21
25
  this.commitment = commitment;
22
26
  this.pollingFrequency = pollingFrequency;
@@ -78,6 +82,9 @@ class BulkAccountLoader {
78
82
  this.loadPromise = new Promise((resolver) => {
79
83
  this.loadPromiseResolver = resolver;
80
84
  });
85
+ if (this.loggingEnabled) {
86
+ console.log('Loading accounts');
87
+ }
81
88
  try {
82
89
  const chunks = this.chunks(Array.from(this.accountsToLoad.values()), GET_MULTIPLE_ACCOUNTS_CHUNK_SIZE);
83
90
  yield Promise.all(chunks.map((chunk) => {
@@ -94,6 +101,15 @@ class BulkAccountLoader {
94
101
  finally {
95
102
  this.loadPromiseResolver();
96
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
+ }
97
113
  }
98
114
  });
99
115
  }
@@ -108,17 +124,8 @@ class BulkAccountLoader {
108
124
  }),
109
125
  { commitment: this.commitment },
110
126
  ];
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
- }
127
+ // @ts-ignore
128
+ const rpcResponse = yield this.connection._rpcRequest('getMultipleAccounts', args);
122
129
  const newSlot = rpcResponse.result.context.slot;
123
130
  for (const i in accountsToLoad) {
124
131
  const accountToLoad = accountsToLoad[i];
@@ -136,6 +143,7 @@ class BulkAccountLoader {
136
143
  buffer: newBuffer,
137
144
  });
138
145
  this.handleAccountCallbacks(accountToLoad, newBuffer);
146
+ this.lastUpdate = Date.now();
139
147
  continue;
140
148
  }
141
149
  if (newSlot <= oldRPCResponse.slot) {
@@ -148,6 +156,7 @@ class BulkAccountLoader {
148
156
  buffer: newBuffer,
149
157
  });
150
158
  this.handleAccountCallbacks(accountToLoad, newBuffer);
159
+ this.lastUpdate = Date.now();
151
160
  }
152
161
  }
153
162
  });
@@ -165,12 +174,18 @@ class BulkAccountLoader {
165
174
  if (this.intervalId) {
166
175
  return;
167
176
  }
177
+ if (this.loggingEnabled) {
178
+ console.log(`startPolling`);
179
+ }
168
180
  this.intervalId = setInterval(this.load.bind(this), this.pollingFrequency);
169
181
  }
170
182
  stopPolling() {
171
183
  if (this.intervalId) {
172
184
  clearInterval(this.intervalId);
173
185
  this.intervalId = undefined;
186
+ if (this.loggingEnabled) {
187
+ console.log(`stopPolling`);
188
+ }
174
189
  }
175
190
  }
176
191
  }
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): 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>;
@@ -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
@@ -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");
@@ -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) {
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, {
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,
@@ -322,12 +327,13 @@ class Admin extends clearingHouse_1.ClearingHouse {
322
327
  });
323
328
  });
324
329
  }
325
- updateMarginRatio(marginRatioInitial, marginRatioPartial, marginRatioMaintenance) {
330
+ updateMarginRatio(marketIndex, marginRatioInitial, marginRatioPartial, marginRatioMaintenance) {
326
331
  return __awaiter(this, void 0, void 0, function* () {
327
- return yield this.program.rpc.updateMarginRatio(marginRatioInitial, marginRatioPartial, marginRatioMaintenance, {
332
+ return yield this.program.rpc.updateMarginRatio(marketIndex, marginRatioInitial, marginRatioPartial, marginRatioMaintenance, {
328
333
  accounts: {
329
334
  admin: this.wallet.publicKey,
330
335
  state: yield this.getStatePublicKey(),
336
+ markets: this.getStateAccount().markets,
331
337
  },
332
338
  });
333
339
  });
@@ -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];
@@ -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* () {
@@ -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
  }