@drift-labs/sdk 0.2.0-master.1 → 0.2.0-master.10

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 (112) hide show
  1. package/lib/accounts/types.d.ts +1 -0
  2. package/lib/admin.d.ts +6 -3
  3. package/lib/admin.js +39 -7
  4. package/lib/clearingHouse.d.ts +13 -14
  5. package/lib/clearingHouse.js +166 -106
  6. package/lib/config.js +1 -1
  7. package/lib/constants/banks.js +8 -1
  8. package/lib/constants/numericConstants.d.ts +1 -0
  9. package/lib/constants/numericConstants.js +2 -1
  10. package/lib/factory/bigNum.d.ts +8 -2
  11. package/lib/factory/bigNum.js +14 -6
  12. package/lib/idl/clearing_house.json +277 -55
  13. package/lib/index.d.ts +2 -1
  14. package/lib/index.js +6 -1
  15. package/lib/math/amm.d.ts +6 -1
  16. package/lib/math/amm.js +124 -41
  17. package/lib/math/auction.js +4 -1
  18. package/lib/math/orders.d.ts +2 -2
  19. package/lib/math/orders.js +18 -11
  20. package/lib/math/position.js +3 -1
  21. package/lib/math/repeg.js +1 -1
  22. package/lib/math/trade.d.ts +1 -1
  23. package/lib/math/trade.js +7 -10
  24. package/lib/orderParams.d.ts +14 -5
  25. package/lib/orderParams.js +8 -96
  26. package/lib/orders.d.ts +1 -2
  27. package/lib/orders.js +6 -85
  28. package/lib/slot/SlotSubscriber.d.ts +7 -0
  29. package/lib/slot/SlotSubscriber.js +3 -0
  30. package/lib/tx/utils.js +1 -1
  31. package/lib/types.d.ts +75 -1
  32. package/lib/types.js +42 -1
  33. package/package.json +3 -3
  34. package/src/accounts/bulkAccountLoader.js +197 -0
  35. package/src/accounts/bulkUserSubscription.js +33 -0
  36. package/src/accounts/fetch.js +29 -0
  37. package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
  38. package/src/accounts/pollingOracleSubscriber.js +93 -0
  39. package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
  40. package/src/accounts/pollingUserAccountSubscriber.js +132 -0
  41. package/src/accounts/types.js +10 -0
  42. package/src/accounts/utils.js +7 -0
  43. package/src/accounts/webSocketAccountSubscriber.js +93 -0
  44. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
  45. package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
  46. package/src/addresses/marketAddresses.js +26 -0
  47. package/src/addresses/pda.js +104 -0
  48. package/src/admin.ts +60 -8
  49. package/src/assert/assert.js +9 -0
  50. package/src/clearingHouse.ts +223 -183
  51. package/src/config.ts +1 -1
  52. package/src/constants/banks.ts +8 -1
  53. package/src/constants/numericConstants.ts +1 -0
  54. package/src/events/eventList.js +77 -0
  55. package/src/events/eventSubscriber.js +139 -0
  56. package/src/events/fetchLogs.js +50 -0
  57. package/src/events/pollingLogProvider.js +64 -0
  58. package/src/events/sort.js +44 -0
  59. package/src/events/txEventCache.js +71 -0
  60. package/src/events/types.js +20 -0
  61. package/src/events/webSocketLogProvider.js +41 -0
  62. package/src/examples/makeTradeExample.js +80 -0
  63. package/src/factory/bigNum.js +364 -0
  64. package/src/factory/bigNum.ts +26 -9
  65. package/src/factory/oracleClient.js +20 -0
  66. package/src/idl/clearing_house.json +277 -55
  67. package/src/index.js +69 -0
  68. package/src/index.ts +2 -1
  69. package/src/math/amm.js +369 -0
  70. package/src/math/amm.ts +207 -52
  71. package/src/math/auction.js +42 -0
  72. package/src/math/auction.ts +5 -1
  73. package/src/math/bankBalance.js +75 -0
  74. package/src/math/conversion.js +11 -0
  75. package/src/math/funding.js +248 -0
  76. package/src/math/market.js +57 -0
  77. package/src/math/oracles.js +26 -0
  78. package/src/math/orders.js +110 -0
  79. package/src/math/orders.ts +17 -13
  80. package/src/math/position.js +140 -0
  81. package/src/math/position.ts +5 -1
  82. package/src/math/repeg.js +128 -0
  83. package/src/math/repeg.ts +2 -1
  84. package/src/math/state.js +15 -0
  85. package/src/math/trade.js +253 -0
  86. package/src/math/trade.ts +23 -25
  87. package/src/math/utils.js +0 -1
  88. package/src/mockUSDCFaucet.js +171 -0
  89. package/src/oracles/oracleClientCache.js +19 -0
  90. package/src/oracles/pythClient.js +46 -0
  91. package/src/oracles/quoteAssetOracleClient.js +32 -0
  92. package/src/oracles/switchboardClient.js +69 -0
  93. package/src/oracles/types.js +2 -0
  94. package/src/orderParams.js +20 -0
  95. package/src/orderParams.ts +20 -141
  96. package/src/orders.js +134 -0
  97. package/src/orders.ts +7 -131
  98. package/src/slot/SlotSubscriber.js +39 -0
  99. package/src/slot/SlotSubscriber.ts +11 -1
  100. package/src/token/index.js +38 -0
  101. package/src/tx/retryTxSender.js +188 -0
  102. package/src/tx/types.js +2 -0
  103. package/src/tx/utils.js +17 -0
  104. package/src/tx/utils.ts +1 -1
  105. package/src/types.js +114 -0
  106. package/src/types.ts +69 -3
  107. package/src/userName.js +20 -0
  108. package/src/util/promiseTimeout.js +14 -0
  109. package/src/util/tps.js +27 -0
  110. package/src/wallet.js +35 -0
  111. package/src/util/computeUnits.js +0 -17
  112. package/src/util/computeUnits.js.map +0 -1
package/src/types.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { PublicKey, Transaction } from '@solana/web3.js';
2
- import { BN } from '.';
2
+ import { BN, ZERO } from '.';
3
3
 
4
4
  // # Utility Types / Enums / Constants
5
5
  export class SwapDirection {
@@ -17,6 +17,11 @@ export class PositionDirection {
17
17
  static readonly SHORT = { short: {} };
18
18
  }
19
19
 
20
+ export class DepositDirection {
21
+ static readonly DEPOSIT = { deposit: {} };
22
+ static readonly WITHDRAW = { withdraw: {} };
23
+ }
24
+
20
25
  export class OracleSource {
21
26
  static readonly PYTH = { pyth: {} };
22
27
  static readonly SWITCHBOARD = { switchboard: {} };
@@ -48,6 +53,20 @@ export class OrderAction {
48
53
  static readonly CANCEL = { cancel: {} };
49
54
  static readonly EXPIRE = { expire: {} };
50
55
  static readonly FILL = { fill: {} };
56
+ static readonly TRIGGER = { trigger: {} };
57
+ }
58
+
59
+ export class OrderActionExplanation {
60
+ static readonly NONE = { none: {} };
61
+ static readonly BREACHED_MARGIN_REQUIREMENT = {
62
+ breachedMarginRequirement: {},
63
+ };
64
+ static readonly ORACLE_PRICE_BREACHED_LIMIT_PRICE = {
65
+ oraclePriceBreachedLimitPrice: {},
66
+ };
67
+ static readonly MARKET_ORDER_FILLED_TO_LIMIT_PRICE = {
68
+ marketOrderFilledToLimitPrice: {},
69
+ };
51
70
  }
52
71
 
53
72
  export class OrderTriggerCondition {
@@ -91,6 +110,7 @@ export type DepositRecord = {
91
110
  };
92
111
  bankIndex: BN;
93
112
  amount: BN;
113
+ oraclePrice: BN;
94
114
  from?: PublicKey;
95
115
  to?: PublicKey;
96
116
  };
@@ -163,7 +183,10 @@ export type OrderRecord = {
163
183
  maker: PublicKey;
164
184
  takerOrder: Order;
165
185
  makerOrder: Order;
186
+ takerUnsettledPnl: BN;
187
+ makerUnsettledPnl: BN;
166
188
  action: OrderAction;
189
+ actionExplanation: OrderActionExplanation;
167
190
  filler: PublicKey;
168
191
  fillRecordId: BN;
169
192
  marketIndex: BN;
@@ -260,6 +283,8 @@ export type AMM = {
260
283
  lastMarkPriceTwapTs: BN;
261
284
  lastOraclePriceTwap: BN;
262
285
  lastOraclePriceTwapTs: BN;
286
+ lastOracleMarkSpreadPct: BN;
287
+ lastOracleConfPct: BN;
263
288
  oracle: PublicKey;
264
289
  oracleSource: OracleSource;
265
290
  fundingPeriod: BN;
@@ -274,6 +299,8 @@ export type AMM = {
274
299
  totalFee: BN;
275
300
  minimumQuoteAssetTradeSize: BN;
276
301
  baseAssetAmountStepSize: BN;
302
+ maxBaseAssetAmountRatio: number;
303
+ maxSlippageRatio: number;
277
304
  lastOraclePrice: BN;
278
305
  baseSpread: number;
279
306
  curveUpdateIntensity: number;
@@ -290,6 +317,7 @@ export type AMM = {
290
317
  lastAskPriceTwap: BN;
291
318
  longSpread: BN;
292
319
  shortSpread: BN;
320
+ maxSpread: number;
293
321
  };
294
322
 
295
323
  // # User Account Types
@@ -347,8 +375,9 @@ export type Order = {
347
375
  reduceOnly: boolean;
348
376
  triggerPrice: BN;
349
377
  triggerCondition: OrderTriggerCondition;
378
+ triggered: boolean;
350
379
  discountTier: OrderDiscountTier;
351
- existingPositionDirection: PositionDirection,
380
+ existingPositionDirection: PositionDirection;
352
381
  referrer: PublicKey;
353
382
  postOnly: boolean;
354
383
  immediateOrCancel: boolean;
@@ -362,7 +391,6 @@ export type OrderParams = {
362
391
  orderType: OrderType;
363
392
  userOrderId: number;
364
393
  direction: PositionDirection;
365
- quoteAssetAmount: BN;
366
394
  baseAssetAmount: BN;
367
395
  price: BN;
368
396
  marketIndex: BN;
@@ -381,11 +409,49 @@ export type OrderParams = {
381
409
  };
382
410
  };
383
411
 
412
+ export type NecessaryOrderParams = {
413
+ orderType: OrderType;
414
+ marketIndex: BN;
415
+ baseAssetAmount: BN;
416
+ direction: PositionDirection;
417
+ };
418
+
419
+ export type OptionalOrderParams = {
420
+ [Property in keyof OrderParams]?: OrderParams[Property];
421
+ } & NecessaryOrderParams;
422
+
423
+ export const DefaultOrderParams = {
424
+ orderType: OrderType.MARKET,
425
+ userOrderId: 0,
426
+ direction: PositionDirection.LONG,
427
+ baseAssetAmount: ZERO,
428
+ price: ZERO,
429
+ marketIndex: ZERO,
430
+ reduceOnly: false,
431
+ postOnly: false,
432
+ immediateOrCancel: false,
433
+ triggerPrice: ZERO,
434
+ triggerCondition: OrderTriggerCondition.ABOVE,
435
+ positionLimit: ZERO,
436
+ oraclePriceOffset: ZERO,
437
+ padding0: ZERO,
438
+ padding1: ZERO,
439
+ optionalAccounts: {
440
+ discountToken: false,
441
+ referrer: false,
442
+ },
443
+ };
444
+
384
445
  export type MakerInfo = {
385
446
  maker: PublicKey;
386
447
  order: Order;
387
448
  };
388
449
 
450
+ export type TakerInfo = {
451
+ taker: PublicKey;
452
+ order: Order;
453
+ };
454
+
389
455
  // # Misc Types
390
456
  export interface IWallet {
391
457
  signTransaction(tx: Transaction): Promise<Transaction>;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decodeName = exports.encodeName = exports.DEFAULT_USER_NAME = exports.MAX_NAME_LENGTH = void 0;
4
+ exports.MAX_NAME_LENGTH = 32;
5
+ exports.DEFAULT_USER_NAME = 'Main Account';
6
+ function encodeName(name) {
7
+ if (name.length > exports.MAX_NAME_LENGTH) {
8
+ throw Error(`User name (${name}) longer than 32 characters`);
9
+ }
10
+ const buffer = Buffer.alloc(32);
11
+ buffer.fill(name);
12
+ buffer.fill(' ', name.length);
13
+ return Array(...buffer);
14
+ }
15
+ exports.encodeName = encodeName;
16
+ function decodeName(bytes) {
17
+ const buffer = Buffer.from(bytes);
18
+ return buffer.toString('utf8').trim();
19
+ }
20
+ exports.decodeName = decodeName;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.promiseTimeout = void 0;
4
+ function promiseTimeout(promise, timeoutMs) {
5
+ let timeoutId;
6
+ const timeoutPromise = new Promise((resolve) => {
7
+ timeoutId = setTimeout(() => resolve(null), timeoutMs);
8
+ });
9
+ return Promise.race([promise, timeoutPromise]).then((result) => {
10
+ clearTimeout(timeoutId);
11
+ return result;
12
+ });
13
+ }
14
+ exports.promiseTimeout = promiseTimeout;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.estimateTps = void 0;
13
+ function estimateTps(programId, connection, failed) {
14
+ return __awaiter(this, void 0, void 0, function* () {
15
+ let signatures = yield connection.getSignaturesForAddress(programId, undefined, 'finalized');
16
+ if (failed) {
17
+ signatures = signatures.filter((signature) => signature.err);
18
+ }
19
+ const numberOfSignatures = signatures.length;
20
+ if (numberOfSignatures === 0) {
21
+ return 0;
22
+ }
23
+ return (numberOfSignatures /
24
+ (signatures[0].blockTime - signatures[numberOfSignatures - 1].blockTime));
25
+ });
26
+ }
27
+ exports.estimateTps = estimateTps;
package/src/wallet.js ADDED
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.Wallet = void 0;
13
+ class Wallet {
14
+ constructor(payer) {
15
+ this.payer = payer;
16
+ }
17
+ signTransaction(tx) {
18
+ return __awaiter(this, void 0, void 0, function* () {
19
+ tx.partialSign(this.payer);
20
+ return tx;
21
+ });
22
+ }
23
+ signAllTransactions(txs) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ return txs.map((t) => {
26
+ t.partialSign(this.payer);
27
+ return t;
28
+ });
29
+ });
30
+ }
31
+ get publicKey() {
32
+ return this.payer.publicKey;
33
+ }
34
+ }
35
+ exports.Wallet = Wallet;
@@ -1,17 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.findComputeUnitConsumption = void 0;
4
- async function findComputeUnitConsumption(programId, connection, txSignature, commitment = 'confirmed') {
5
- const tx = await connection.getTransaction(txSignature, { commitment });
6
- const computeUnits = [];
7
- const regex = new RegExp(`Program ${programId.toString()} consumed ([0-9]{0,6}) of 200000 compute units`);
8
- tx.meta.logMessages.forEach((logMessage) => {
9
- const match = logMessage.match(regex);
10
- if (match && match[1]) {
11
- computeUnits.push(match[1]);
12
- }
13
- });
14
- return computeUnits;
15
- }
16
- exports.findComputeUnitConsumption = findComputeUnitConsumption;
17
- //# sourceMappingURL=computeUnits.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"computeUnits.js","sourceRoot":"","sources":["computeUnits.ts"],"names":[],"mappings":";;;AAEO,KAAK,UAAU,0BAA0B,CAC/C,SAAoB,EACpB,UAAsB,EACtB,WAAmB,EACnB,aAAuB,WAAW;IAElC,MAAM,EAAE,GAAG,MAAM,UAAU,CAAC,cAAc,CAAC,WAAW,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;IACxE,MAAM,YAAY,GAAG,EAAE,CAAC;IACxB,MAAM,KAAK,GAAG,IAAI,MAAM,CACvB,WAAW,SAAS,CAAC,QAAQ,EAAE,gDAAgD,CAC/E,CAAC;IACF,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE;QAC1C,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACtC,IAAI,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC,EAAE;YACtB,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;SAC5B;IACF,CAAC,CAAC,CAAC;IACH,OAAO,YAAY,CAAC;AACrB,CAAC;AAlBD,gEAkBC"}