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

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 (58) hide show
  1. package/lib/addresses/pda.d.ts +4 -0
  2. package/lib/addresses/pda.js +27 -1
  3. package/lib/admin.d.ts +3 -0
  4. package/lib/admin.js +36 -10
  5. package/lib/clearingHouse.d.ts +11 -2
  6. package/lib/clearingHouse.js +140 -5
  7. package/lib/clearingHouseUser.d.ts +3 -1
  8. package/lib/clearingHouseUser.js +11 -9
  9. package/lib/config.js +1 -1
  10. package/lib/constants/banks.d.ts +2 -0
  11. package/lib/constants/banks.js +9 -0
  12. package/lib/constants/numericConstants.d.ts +2 -0
  13. package/lib/constants/numericConstants.js +4 -1
  14. package/lib/events/eventSubscriber.d.ts +4 -2
  15. package/lib/events/eventSubscriber.js +16 -9
  16. package/lib/events/fetchLogs.d.ts +10 -1
  17. package/lib/events/fetchLogs.js +27 -7
  18. package/lib/events/pollingLogProvider.d.ts +2 -1
  19. package/lib/events/pollingLogProvider.js +6 -2
  20. package/lib/events/sort.js +7 -10
  21. package/lib/events/types.d.ts +4 -2
  22. package/lib/events/types.js +2 -0
  23. package/lib/examples/makeTradeExample.js +13 -1
  24. package/lib/idl/clearing_house.json +1081 -173
  25. package/lib/index.d.ts +2 -0
  26. package/lib/index.js +2 -0
  27. package/lib/math/amm.d.ts +3 -1
  28. package/lib/math/amm.js +41 -3
  29. package/lib/math/insurance.d.ts +4 -0
  30. package/lib/math/insurance.js +27 -0
  31. package/lib/math/margin.d.ts +1 -1
  32. package/lib/math/margin.js +5 -7
  33. package/lib/math/position.js +1 -1
  34. package/lib/types.d.ts +79 -24
  35. package/lib/types.js +7 -4
  36. package/package.json +1 -1
  37. package/src/addresses/pda.ts +56 -0
  38. package/src/admin.ts +64 -18
  39. package/src/clearingHouse.ts +230 -10
  40. package/src/clearingHouseUser.ts +16 -11
  41. package/src/config.ts +1 -1
  42. package/src/constants/banks.ts +16 -0
  43. package/src/constants/numericConstants.ts +4 -0
  44. package/src/events/eventSubscriber.ts +20 -12
  45. package/src/events/fetchLogs.ts +35 -8
  46. package/src/events/pollingLogProvider.ts +10 -2
  47. package/src/events/sort.ts +10 -14
  48. package/src/events/types.ts +7 -1
  49. package/src/examples/makeTradeExample.ts +20 -1
  50. package/src/idl/clearing_house.json +1081 -173
  51. package/src/index.ts +2 -0
  52. package/src/math/amm.ts +67 -2
  53. package/src/math/insurance.ts +35 -0
  54. package/src/math/margin.ts +3 -10
  55. package/src/math/position.ts +2 -2
  56. package/src/types.ts +83 -24
  57. package/src/events/eventSubscriber.js +0 -139
  58. package/src/events/sort.js +0 -44
@@ -1,4 +1,6 @@
1
+ import { Program } from '@project-serum/anchor';
1
2
  import { Connection, Finality, PublicKey, TransactionSignature } from '@solana/web3.js';
3
+ import { WrappedEvents } from './types';
2
4
  declare type Log = {
3
5
  txSig: TransactionSignature;
4
6
  slot: number;
@@ -7,7 +9,14 @@ declare type Log = {
7
9
  declare type FetchLogsResponse = {
8
10
  earliestTx: string;
9
11
  mostRecentTx: string;
12
+ earliestSlot: number;
13
+ mostRecentSlot: number;
10
14
  transactionLogs: Log[];
11
15
  };
12
- export declare function fetchLogs(connection: Connection, programId: PublicKey, finality: Finality, beforeTx?: TransactionSignature, untilTx?: TransactionSignature): Promise<FetchLogsResponse | undefined>;
16
+ export declare function fetchLogs(connection: Connection, programId: PublicKey, finality: Finality, beforeTx?: TransactionSignature, untilTx?: TransactionSignature, limit?: number): Promise<FetchLogsResponse>;
17
+ export declare class LogParser {
18
+ private program;
19
+ constructor(program: Program);
20
+ parseEventsFromLogs(event: Log): WrappedEvents;
21
+ }
13
22
  export {};
@@ -1,12 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.fetchLogs = void 0;
4
- async function fetchLogs(connection, programId, finality, beforeTx, untilTx) {
3
+ exports.LogParser = exports.fetchLogs = void 0;
4
+ async function fetchLogs(connection, programId, finality, beforeTx, untilTx, limit) {
5
5
  const signatures = await connection.getSignaturesForAddress(programId, {
6
6
  before: beforeTx,
7
7
  until: untilTx,
8
+ limit,
8
9
  }, finality);
9
- const sortedSignatures = signatures.sort((a, b) => a.slot < b.slot ? -1 : 1);
10
+ const sortedSignatures = signatures.sort((a, b) => a.slot === b.slot ? 0 : a.slot < b.slot ? -1 : 1);
10
11
  const filteredSignatures = sortedSignatures.filter((signature) => !signature.err);
11
12
  if (filteredSignatures.length === 0) {
12
13
  return undefined;
@@ -22,12 +23,14 @@ async function fetchLogs(connection, programId, finality, beforeTx, untilTx) {
22
23
  };
23
24
  });
24
25
  }))).flat();
25
- const earliestTx = filteredSignatures[0].signature;
26
- const mostRecentTx = filteredSignatures[filteredSignatures.length - 1].signature;
26
+ const earliest = filteredSignatures[0];
27
+ const mostRecent = filteredSignatures[filteredSignatures.length - 1];
27
28
  return {
28
29
  transactionLogs: transactionLogs,
29
- earliestTx: earliestTx,
30
- mostRecentTx: mostRecentTx,
30
+ earliestTx: earliest.signature,
31
+ mostRecentTx: mostRecent.signature,
32
+ earliestSlot: earliest.slot,
33
+ mostRecentSlot: mostRecent.slot,
31
34
  };
32
35
  }
33
36
  exports.fetchLogs = fetchLogs;
@@ -37,3 +40,20 @@ function chunk(array, size) {
37
40
  .map((_, index) => index * size)
38
41
  .map((begin) => array.slice(begin, begin + size));
39
42
  }
43
+ class LogParser {
44
+ constructor(program) {
45
+ this.program = program;
46
+ }
47
+ parseEventsFromLogs(event) {
48
+ const records = [];
49
+ // @ts-ignore
50
+ this.program._events._eventParser.parseLogs(event.logs, (eventLog) => {
51
+ eventLog.data.txSig = event.txSig;
52
+ eventLog.data.slot = event.slot;
53
+ eventLog.data.eventType = eventLog.name;
54
+ records.push(eventLog.data);
55
+ });
56
+ return records;
57
+ }
58
+ }
59
+ exports.LogParser = LogParser;
@@ -8,8 +8,9 @@ export declare class PollingLogProvider implements LogProvider {
8
8
  private intervalId;
9
9
  private mostRecentSeenTx?;
10
10
  private mutex;
11
+ private firstFetch;
11
12
  constructor(connection: Connection, programId: PublicKey, commitment: Commitment, frequency?: number);
12
- subscribe(callback: logProviderCallback): boolean;
13
+ subscribe(callback: logProviderCallback, skipHistory?: boolean): boolean;
13
14
  isSubscribed(): boolean;
14
15
  unsubscribe(): Promise<boolean>;
15
16
  }
@@ -7,9 +7,10 @@ class PollingLogProvider {
7
7
  this.connection = connection;
8
8
  this.programId = programId;
9
9
  this.frequency = frequency;
10
+ this.firstFetch = true;
10
11
  this.finality = commitment === 'finalized' ? 'finalized' : 'confirmed';
11
12
  }
12
- subscribe(callback) {
13
+ subscribe(callback, skipHistory) {
13
14
  if (this.intervalId) {
14
15
  return true;
15
16
  }
@@ -19,7 +20,10 @@ class PollingLogProvider {
19
20
  }
20
21
  this.mutex = 1;
21
22
  try {
22
- const response = await (0, fetchLogs_1.fetchLogs)(this.connection, this.programId, this.finality, undefined, this.mostRecentSeenTx);
23
+ const response = await (0, fetchLogs_1.fetchLogs)(this.connection, this.programId, this.finality, undefined, this.mostRecentSeenTx,
24
+ // If skipping history, only fetch one log back, not the maximum amount available
25
+ skipHistory && this.firstFetch ? 1 : undefined);
26
+ this.firstFetch = false;
23
27
  if (response === undefined) {
24
28
  return;
25
29
  }
@@ -11,17 +11,14 @@ function clientSortDescFn() {
11
11
  function defaultBlockchainSortFn(currentEvent, newEvent) {
12
12
  return currentEvent.slot <= newEvent.slot ? 'less than' : 'greater than';
13
13
  }
14
- function orderRecordSortFn(currentEvent, newEvent) {
15
- const currentEventMarketIndex = !currentEvent.maker.equals(index_1.PublicKey.default)
16
- ? currentEvent.makerOrder.marketIndex
17
- : currentEvent.takerOrder.marketIndex;
18
- const newEventMarketIndex = !newEvent.maker.equals(index_1.PublicKey.default)
19
- ? newEvent.makerOrder.marketIndex
20
- : newEvent.takerOrder.marketIndex;
14
+ function orderActionRecordSortFn(currentEvent, newEvent) {
15
+ var _a, _b;
16
+ const currentEventMarketIndex = currentEvent.marketIndex;
17
+ const newEventMarketIndex = newEvent.marketIndex;
21
18
  if (!currentEventMarketIndex.eq(newEventMarketIndex)) {
22
19
  return currentEvent.ts.lte(newEvent.ts) ? 'less than' : 'greater than';
23
20
  }
24
- if (currentEvent.fillRecordId.gt(index_1.ZERO) && newEvent.fillRecordId.gt(index_1.ZERO)) {
21
+ if (((_a = currentEvent.fillRecordId) === null || _a === void 0 ? void 0 : _a.gt(index_1.ZERO)) && ((_b = newEvent.fillRecordId) === null || _b === void 0 ? void 0 : _b.gt(index_1.ZERO))) {
25
22
  return currentEvent.fillRecordId.lte(newEvent.fillRecordId)
26
23
  ? 'less than'
27
24
  : 'greater than';
@@ -35,8 +32,8 @@ function getSortFn(orderBy, orderDir, eventType) {
35
32
  return orderDir === 'asc' ? clientSortAscFn : clientSortDescFn;
36
33
  }
37
34
  switch (eventType) {
38
- case 'OrderRecord':
39
- return orderRecordSortFn;
35
+ case 'OrderActionRecord':
36
+ return orderActionRecordSortFn;
40
37
  default:
41
38
  return defaultBlockchainSortFn;
42
39
  }
@@ -1,5 +1,5 @@
1
1
  import { Commitment, TransactionSignature } from '@solana/web3.js';
2
- import { DepositRecord, FundingPaymentRecord, FundingRateRecord, LiquidationRecord, NewUserRecord, OrderRecord, SettlePnlRecord } from '../index';
2
+ import { DepositRecord, FundingPaymentRecord, FundingRateRecord, LiquidationRecord, NewUserRecord, OrderActionRecord, OrderRecord, SettlePnlRecord, LPRecord } from '../index';
3
3
  export declare type EventSubscriptionOptions = {
4
4
  eventTypes?: EventType[];
5
5
  maxEventsPerType?: number;
@@ -27,8 +27,10 @@ export declare type EventMap = {
27
27
  LiquidationRecord: Event<LiquidationRecord>;
28
28
  FundingRateRecord: Event<FundingRateRecord>;
29
29
  OrderRecord: Event<OrderRecord>;
30
+ OrderActionRecord: Event<OrderActionRecord>;
30
31
  SettlePnlRecord: Event<SettlePnlRecord>;
31
32
  NewUserRecord: Event<NewUserRecord>;
33
+ LPRecord: Event<LPRecord>;
32
34
  };
33
35
  export declare type EventType = keyof EventMap;
34
36
  export interface EventSubscriberEvents {
@@ -38,7 +40,7 @@ export declare type SortFn = (currentRecord: EventMap[EventType], newRecord: Eve
38
40
  export declare type logProviderCallback = (txSig: TransactionSignature, slot: number, logs: string[]) => void;
39
41
  export interface LogProvider {
40
42
  isSubscribed(): boolean;
41
- subscribe(callback: logProviderCallback): boolean;
43
+ subscribe(callback: logProviderCallback, skipHistory?: boolean): boolean;
42
44
  unsubscribe(): Promise<boolean>;
43
45
  }
44
46
  export declare type WebSocketLogProviderConfig = {
@@ -7,9 +7,11 @@ exports.DefaultEventSubscriptionOptions = {
7
7
  'FundingPaymentRecord',
8
8
  'LiquidationRecord',
9
9
  'OrderRecord',
10
+ 'OrderActionRecord',
10
11
  'FundingRateRecord',
11
12
  'NewUserRecord',
12
13
  'SettlePnlRecord',
14
+ 'LPRecord',
13
15
  ],
14
16
  maxEventsPerType: 4096,
15
17
  orderBy: 'blockchain',
@@ -11,9 +11,10 @@ const getTokenAddress = (mintAddress, userPubKey) => {
11
11
  return spl_token_1.Token.getAssociatedTokenAddress(new web3_js_1.PublicKey(`ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL`), spl_token_1.TOKEN_PROGRAM_ID, new web3_js_1.PublicKey(mintAddress), new web3_js_1.PublicKey(userPubKey));
12
12
  };
13
13
  exports.getTokenAddress = getTokenAddress;
14
+ const cluster = 'devnet';
14
15
  const main = async () => {
15
16
  // Initialize Drift SDK
16
- const sdkConfig = (0, __2.initialize)({ env: 'devnet' });
17
+ const sdkConfig = (0, __2.initialize)({ env: cluster });
17
18
  // Set up the Wallet and Provider
18
19
  const privateKey = process.env.BOT_PRIVATE_KEY; // stored as an array string
19
20
  const keypair = web3_js_1.Keypair.fromSecretKey(Uint8Array.from(JSON.parse(privateKey)));
@@ -30,16 +31,27 @@ const main = async () => {
30
31
  const usdcTokenAddress = await (0, exports.getTokenAddress)(sdkConfig.USDC_MINT_ADDRESS, wallet.publicKey.toString());
31
32
  // Set up the Drift Clearing House
32
33
  const clearingHousePublicKey = new web3_js_1.PublicKey(sdkConfig.CLEARING_HOUSE_PROGRAM_ID);
34
+ const bulkAccountLoader = new __2.BulkAccountLoader(connection, 'confirmed', 1000);
33
35
  const clearingHouse = new __2.ClearingHouse({
34
36
  connection,
35
37
  wallet: provider.wallet,
36
38
  programID: clearingHousePublicKey,
39
+ marketIndexes: __2.Markets[cluster].map((market) => market.marketIndex),
40
+ bankIndexes: banks_1.Banks[cluster].map((bank) => bank.bankIndex),
41
+ accountSubscription: {
42
+ type: 'polling',
43
+ accountLoader: bulkAccountLoader,
44
+ },
37
45
  });
38
46
  await clearingHouse.subscribe();
39
47
  // Set up Clearing House user client
40
48
  const user = new __2.ClearingHouseUser({
41
49
  clearingHouse,
42
50
  userAccountPublicKey: await clearingHouse.getUserAccountPublicKey(),
51
+ accountSubscription: {
52
+ type: 'polling',
53
+ accountLoader: bulkAccountLoader,
54
+ },
43
55
  });
44
56
  //// Check if clearing house account exists for the current wallet
45
57
  const userAccountExists = await user.exists();