@drift-labs/sdk 2.26.0-beta.0 → 2.26.0-beta.2

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 (71) hide show
  1. package/examples/phoenix.ts +40 -0
  2. package/lib/addresses/pda.d.ts +0 -1
  3. package/lib/adminClient.d.ts +0 -1
  4. package/lib/constants/numericConstants.d.ts +59 -61
  5. package/lib/constants/spotMarkets.d.ts +0 -1
  6. package/lib/dlob/DLOB.d.ts +38 -3
  7. package/lib/dlob/DLOB.js +69 -0
  8. package/lib/dlob/DLOBApiClient.js +1 -1
  9. package/lib/dlob/DLOBNode.d.ts +0 -1
  10. package/lib/dlob/DLOBSubscriber.d.ts +34 -0
  11. package/lib/dlob/DLOBSubscriber.js +100 -0
  12. package/lib/dlob/NodeList.d.ts +0 -1
  13. package/lib/dlob/orderBookLevels.d.ts +44 -0
  14. package/lib/dlob/orderBookLevels.js +137 -0
  15. package/lib/dlob/types.d.ts +2 -0
  16. package/lib/driftClient.d.ts +28 -11
  17. package/lib/driftClient.js +158 -55
  18. package/lib/driftClientConfig.d.ts +3 -0
  19. package/lib/factory/bigNum.d.ts +7 -8
  20. package/lib/idl/drift.json +1 -1
  21. package/lib/index.d.ts +3 -0
  22. package/lib/index.js +3 -0
  23. package/lib/math/amm.d.ts +1 -2
  24. package/lib/math/auction.d.ts +0 -1
  25. package/lib/math/conversion.d.ts +1 -2
  26. package/lib/math/funding.d.ts +0 -1
  27. package/lib/math/insurance.d.ts +0 -1
  28. package/lib/math/margin.d.ts +0 -1
  29. package/lib/math/market.d.ts +0 -1
  30. package/lib/math/oracles.d.ts +0 -1
  31. package/lib/math/orders.d.ts +0 -1
  32. package/lib/math/position.d.ts +0 -1
  33. package/lib/math/repeg.d.ts +0 -1
  34. package/lib/math/spotBalance.d.ts +0 -1
  35. package/lib/math/spotMarket.d.ts +0 -1
  36. package/lib/math/spotPosition.d.ts +0 -1
  37. package/lib/math/trade.d.ts +0 -1
  38. package/lib/math/utils.d.ts +0 -1
  39. package/lib/oracles/pythClient.d.ts +1 -2
  40. package/lib/oracles/types.d.ts +0 -1
  41. package/lib/orderParams.d.ts +0 -1
  42. package/lib/phoenix/phoenixFulfillmentConfigMap.d.ts +10 -0
  43. package/lib/phoenix/phoenixFulfillmentConfigMap.js +17 -0
  44. package/lib/phoenix/phoenixSubscriber.d.ts +34 -0
  45. package/lib/phoenix/phoenixSubscriber.js +79 -0
  46. package/lib/serum/serumSubscriber.d.ts +5 -2
  47. package/lib/serum/serumSubscriber.js +22 -0
  48. package/lib/tokenFaucet.d.ts +0 -1
  49. package/lib/types.d.ts +1 -1
  50. package/lib/user.d.ts +0 -1
  51. package/package.json +1 -1
  52. package/src/assert/assert.js +9 -0
  53. package/src/dlob/DLOB.ts +177 -17
  54. package/src/dlob/DLOBApiClient.ts +3 -1
  55. package/src/dlob/DLOBSubscriber.ts +141 -0
  56. package/src/dlob/orderBookLevels.ts +243 -0
  57. package/src/dlob/types.ts +2 -0
  58. package/src/driftClient.ts +231 -66
  59. package/src/driftClientConfig.ts +3 -0
  60. package/src/idl/drift.json +1 -1
  61. package/src/index.ts +3 -0
  62. package/src/phoenix/phoenixFulfillmentConfigMap.ts +26 -0
  63. package/src/phoenix/phoenixSubscriber.ts +156 -0
  64. package/src/serum/serumSubscriber.ts +27 -1
  65. package/src/token/index.js +38 -0
  66. package/src/types.ts +1 -0
  67. package/src/util/computeUnits.js +27 -0
  68. package/src/util/getTokenAddress.js +9 -0
  69. package/src/util/promiseTimeout.js +14 -0
  70. package/src/util/tps.js +27 -0
  71. package/tests/dlob/helpers.ts +3 -0
@@ -0,0 +1,40 @@
1
+ import { Connection, PublicKey } from '@solana/web3.js';
2
+ import { PRICE_PRECISION, PhoenixSubscriber } from '../src';
3
+ import { PROGRAM_ID } from '@ellipsis-labs/phoenix-sdk';
4
+
5
+ export async function listenToBook(): Promise<void> {
6
+ const connection = new Connection('https://api.mainnet-beta.solana.com');
7
+
8
+ const phoenixSubscriber = new PhoenixSubscriber({
9
+ connection,
10
+ programId: PROGRAM_ID,
11
+ marketAddress: new PublicKey(
12
+ '4DoNfFBfF7UokCC2FQzriy7yHK6DY6NVdYpuekQ5pRgg'
13
+ ),
14
+ accountSubscription: {
15
+ type: 'websocket',
16
+ },
17
+ });
18
+
19
+ await phoenixSubscriber.subscribe();
20
+
21
+ for (let i = 0; i < 10; i++) {
22
+ const bid = phoenixSubscriber.getBestBid().toNumber() / PRICE_PRECISION;
23
+ const ask = phoenixSubscriber.getBestAsk().toNumber() / PRICE_PRECISION;
24
+ console.log(`iter ${i}:`, bid.toFixed(3), '@', ask.toFixed(3));
25
+ await new Promise((r) => setTimeout(r, 2000));
26
+ }
27
+
28
+ await phoenixSubscriber.unsubscribe();
29
+ }
30
+
31
+ (async function () {
32
+ try {
33
+ await listenToBook();
34
+ } catch (err) {
35
+ console.log('Error: ', err);
36
+ process.exit(1);
37
+ }
38
+
39
+ process.exit(0);
40
+ })();
@@ -1,4 +1,3 @@
1
- /// <reference types="bn.js" />
2
1
  import { PublicKey } from '@solana/web3.js';
3
2
  import { BN } from '@coral-xyz/anchor';
4
3
  export declare function getDriftStateAccountPublicKeyAndNonce(programId: PublicKey): Promise<[PublicKey, number]>;
@@ -1,4 +1,3 @@
1
- /// <reference types="bn.js" />
2
1
  import { PublicKey, TransactionSignature } from '@solana/web3.js';
3
2
  import { FeeStructure, OracleGuardRails, OracleSource, ExchangeStatus, MarketStatus, ContractTier, AssetTier, SpotFulfillmentConfigStatus } from './types';
4
3
  import { BN } from '@coral-xyz/anchor';
@@ -1,62 +1,60 @@
1
- /// <reference types="bn.js" />
2
- import { BN } from '../';
3
- export declare const ZERO: BN;
4
- export declare const ONE: BN;
5
- export declare const TWO: BN;
6
- export declare const THREE: BN;
7
- export declare const FOUR: BN;
8
- export declare const FIVE: BN;
9
- export declare const SIX: BN;
10
- export declare const SEVEN: BN;
11
- export declare const EIGHT: BN;
12
- export declare const NINE: BN;
13
- export declare const TEN: BN;
14
- export declare const TEN_THOUSAND: BN;
15
- export declare const BN_MAX: BN;
16
- export declare const TEN_MILLION: BN;
17
- export declare const MAX_LEVERAGE: BN;
18
- export declare const MAX_LEVERAGE_ORDER_SIZE: BN;
19
- export declare const PERCENTAGE_PRECISION_EXP: BN;
20
- export declare const PERCENTAGE_PRECISION: BN;
21
- export declare const CONCENTRATION_PRECISION: BN;
22
- export declare const QUOTE_PRECISION_EXP: BN;
23
- export declare const FUNDING_RATE_BUFFER_PRECISION_EXP: BN;
24
- export declare const PRICE_PRECISION_EXP: BN;
25
- export declare const FUNDING_RATE_PRECISION_EXP: BN;
26
- export declare const PEG_PRECISION_EXP: BN;
27
- export declare const AMM_RESERVE_PRECISION_EXP: BN;
28
- export declare const SPOT_MARKET_RATE_PRECISION_EXP: BN;
29
- export declare const SPOT_MARKET_RATE_PRECISION: BN;
30
- export declare const SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION_EXP: BN;
31
- export declare const SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION: BN;
32
- export declare const SPOT_MARKET_UTILIZATION_PRECISION_EXP: BN;
33
- export declare const SPOT_MARKET_UTILIZATION_PRECISION: BN;
34
- export declare const SPOT_MARKET_WEIGHT_PRECISION: BN;
35
- export declare const SPOT_MARKET_BALANCE_PRECISION_EXP: BN;
36
- export declare const SPOT_MARKET_BALANCE_PRECISION: BN;
37
- export declare const SPOT_MARKET_IMF_PRECISION_EXP: BN;
38
- export declare const SPOT_MARKET_IMF_PRECISION: BN;
39
- export declare const LIQUIDATION_FEE_PRECISION: BN;
40
- export declare const QUOTE_PRECISION: BN;
41
- export declare const PRICE_PRECISION: BN;
42
- export declare const FUNDING_RATE_PRECISION: BN;
43
- export declare const FUNDING_RATE_BUFFER_PRECISION: BN;
44
- export declare const PEG_PRECISION: BN;
45
- export declare const AMM_RESERVE_PRECISION: BN;
46
- export declare const BASE_PRECISION: BN;
47
- export declare const BASE_PRECISION_EXP: BN;
48
- export declare const AMM_TO_QUOTE_PRECISION_RATIO: BN;
49
- export declare const PRICE_DIV_PEG: BN;
50
- export declare const PRICE_TO_QUOTE_PRECISION: BN;
51
- export declare const AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO: BN;
52
- export declare const MARGIN_PRECISION: BN;
53
- export declare const BID_ASK_SPREAD_PRECISION: BN;
54
- export declare const LIQUIDATION_PCT_PRECISION: BN;
55
- export declare const FIVE_MINUTE: BN;
56
- export declare const ONE_HOUR: BN;
57
- export declare const ONE_YEAR: BN;
1
+ export declare const ZERO: any;
2
+ export declare const ONE: any;
3
+ export declare const TWO: any;
4
+ export declare const THREE: any;
5
+ export declare const FOUR: any;
6
+ export declare const FIVE: any;
7
+ export declare const SIX: any;
8
+ export declare const SEVEN: any;
9
+ export declare const EIGHT: any;
10
+ export declare const NINE: any;
11
+ export declare const TEN: any;
12
+ export declare const TEN_THOUSAND: any;
13
+ export declare const BN_MAX: any;
14
+ export declare const TEN_MILLION: any;
15
+ export declare const MAX_LEVERAGE: any;
16
+ export declare const MAX_LEVERAGE_ORDER_SIZE: any;
17
+ export declare const PERCENTAGE_PRECISION_EXP: any;
18
+ export declare const PERCENTAGE_PRECISION: any;
19
+ export declare const CONCENTRATION_PRECISION: any;
20
+ export declare const QUOTE_PRECISION_EXP: any;
21
+ export declare const FUNDING_RATE_BUFFER_PRECISION_EXP: any;
22
+ export declare const PRICE_PRECISION_EXP: any;
23
+ export declare const FUNDING_RATE_PRECISION_EXP: any;
24
+ export declare const PEG_PRECISION_EXP: any;
25
+ export declare const AMM_RESERVE_PRECISION_EXP: any;
26
+ export declare const SPOT_MARKET_RATE_PRECISION_EXP: any;
27
+ export declare const SPOT_MARKET_RATE_PRECISION: any;
28
+ export declare const SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION_EXP: any;
29
+ export declare const SPOT_MARKET_CUMULATIVE_INTEREST_PRECISION: any;
30
+ export declare const SPOT_MARKET_UTILIZATION_PRECISION_EXP: any;
31
+ export declare const SPOT_MARKET_UTILIZATION_PRECISION: any;
32
+ export declare const SPOT_MARKET_WEIGHT_PRECISION: any;
33
+ export declare const SPOT_MARKET_BALANCE_PRECISION_EXP: any;
34
+ export declare const SPOT_MARKET_BALANCE_PRECISION: any;
35
+ export declare const SPOT_MARKET_IMF_PRECISION_EXP: any;
36
+ export declare const SPOT_MARKET_IMF_PRECISION: any;
37
+ export declare const LIQUIDATION_FEE_PRECISION: any;
38
+ export declare const QUOTE_PRECISION: any;
39
+ export declare const PRICE_PRECISION: any;
40
+ export declare const FUNDING_RATE_PRECISION: any;
41
+ export declare const FUNDING_RATE_BUFFER_PRECISION: any;
42
+ export declare const PEG_PRECISION: any;
43
+ export declare const AMM_RESERVE_PRECISION: any;
44
+ export declare const BASE_PRECISION: any;
45
+ export declare const BASE_PRECISION_EXP: any;
46
+ export declare const AMM_TO_QUOTE_PRECISION_RATIO: any;
47
+ export declare const PRICE_DIV_PEG: any;
48
+ export declare const PRICE_TO_QUOTE_PRECISION: any;
49
+ export declare const AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO: any;
50
+ export declare const MARGIN_PRECISION: any;
51
+ export declare const BID_ASK_SPREAD_PRECISION: any;
52
+ export declare const LIQUIDATION_PCT_PRECISION: any;
53
+ export declare const FIVE_MINUTE: any;
54
+ export declare const ONE_HOUR: any;
55
+ export declare const ONE_YEAR: any;
58
56
  export declare const QUOTE_SPOT_MARKET_INDEX = 0;
59
- export declare const LAMPORTS_PRECISION: BN;
60
- export declare const LAMPORTS_EXP: BN;
61
- export declare const OPEN_ORDER_MARGIN_REQUIREMENT: BN;
62
- export declare const DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT: BN;
57
+ export declare const LAMPORTS_PRECISION: any;
58
+ export declare const LAMPORTS_EXP: any;
59
+ export declare const OPEN_ORDER_MARGIN_REQUIREMENT: any;
60
+ export declare const DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT: any;
@@ -1,4 +1,3 @@
1
- /// <reference types="bn.js" />
2
1
  import { PublicKey } from '@solana/web3.js';
3
2
  import { BN, DriftEnv, OracleSource } from '../';
4
3
  export type SpotMarketConfig = {
@@ -1,9 +1,8 @@
1
- /// <reference types="bn.js" />
2
1
  import { NodeList } from './NodeList';
3
- import { MarketType, BN, DriftClient, Order, SpotMarketAccount, PerpMarketAccount, OraclePriceData, SlotSubscriber, MarketTypeStr, StateAccount, UserMap, OrderRecord, OrderActionRecord } from '..';
2
+ import { BN, DLOBNode, DLOBNodeType, DriftClient, MarketType, MarketTypeStr, OraclePriceData, Order, OrderActionRecord, OrderRecord, PerpMarketAccount, SlotSubscriber, SpotMarketAccount, StateAccount, TriggerOrderNode, UserMap } from '..';
4
3
  import { PublicKey } from '@solana/web3.js';
5
- import { DLOBNode, DLOBNodeType, TriggerOrderNode } from '..';
6
4
  import { DLOBOrders } from './DLOBOrders';
5
+ import { L2OrderBook, L2OrderBookGenerator, L3OrderBook } from './orderBookLevels';
7
6
  export type MarketNodeLists = {
8
7
  restingLimit: {
9
8
  ask: NodeList<'restingLimit'>;
@@ -100,5 +99,41 @@ export declare class DLOB {
100
99
  printTopOfOrderLists(sdkConfig: any, driftClient: DriftClient, slotSubscriber: SlotSubscriber, marketIndex: number, marketType: MarketType): void;
101
100
  getDLOBOrders(): DLOBOrders;
102
101
  getNodeLists(): Generator<NodeList<DLOBNodeType>>;
102
+ /**
103
+ * Get an L2 view of the order book for a given market.
104
+ *
105
+ * @param marketIndex
106
+ * @param marketType
107
+ * @param slot
108
+ * @param oraclePriceData
109
+ * @param depth how many levels of the order book to return
110
+ * @param fallbackAsk best ask for fallback liquidity, only relevant for perps
111
+ * @param fallbackBid best bid for fallback liquidity, only relevant for perps
112
+ * @param fallbackL2Generators L2 generators for fallback liquidity e.g. vAMM {@link getVammL2Generator}, openbook {@link SerumSubscriber}
113
+ */
114
+ getL2({ marketIndex, marketType, slot, oraclePriceData, depth, fallbackAsk, fallbackBid, fallbackL2Generators, }: {
115
+ marketIndex: number;
116
+ marketType: MarketType;
117
+ slot: number;
118
+ oraclePriceData: OraclePriceData;
119
+ depth: number;
120
+ fallbackAsk?: BN;
121
+ fallbackBid?: BN;
122
+ fallbackL2Generators?: L2OrderBookGenerator[];
123
+ }): L2OrderBook;
124
+ /**
125
+ * Get an L3 view of the order book for a given market. Does not include fallback liquidity sources
126
+ *
127
+ * @param marketIndex
128
+ * @param marketType
129
+ * @param slot
130
+ * @param oraclePriceData
131
+ */
132
+ getL3({ marketIndex, marketType, slot, oraclePriceData, }: {
133
+ marketIndex: number;
134
+ marketType: MarketType;
135
+ slot: number;
136
+ oraclePriceData: OraclePriceData;
137
+ }): L3OrderBook;
103
138
  }
104
139
  export {};
package/lib/dlob/DLOB.js CHANGED
@@ -4,6 +4,7 @@ exports.DLOB = void 0;
4
4
  const NodeList_1 = require("./NodeList");
5
5
  const __1 = require("..");
6
6
  const exchangeStatus_1 = require("../math/exchangeStatus");
7
+ const orderBookLevels_1 = require("./orderBookLevels");
7
8
  const SUPPORTED_ORDER_TYPES = [
8
9
  'market',
9
10
  'limit',
@@ -954,5 +955,73 @@ class DLOB {
954
955
  yield nodeLists.trigger.below;
955
956
  }
956
957
  }
958
+ /**
959
+ * Get an L2 view of the order book for a given market.
960
+ *
961
+ * @param marketIndex
962
+ * @param marketType
963
+ * @param slot
964
+ * @param oraclePriceData
965
+ * @param depth how many levels of the order book to return
966
+ * @param fallbackAsk best ask for fallback liquidity, only relevant for perps
967
+ * @param fallbackBid best bid for fallback liquidity, only relevant for perps
968
+ * @param fallbackL2Generators L2 generators for fallback liquidity e.g. vAMM {@link getVammL2Generator}, openbook {@link SerumSubscriber}
969
+ */
970
+ getL2({ marketIndex, marketType, slot, oraclePriceData, depth, fallbackAsk, fallbackBid, fallbackL2Generators = [], }) {
971
+ const makerAskL2LevelGenerator = (0, orderBookLevels_1.getL2GeneratorFromDLOBNodes)(this.getMakerLimitAsks(marketIndex, slot, marketType, oraclePriceData, fallbackBid), oraclePriceData, slot);
972
+ const fallbackAskGenerators = fallbackL2Generators.map((fallbackL2Generator) => {
973
+ return fallbackL2Generator.getL2Asks();
974
+ });
975
+ const askL2LevelGenerator = (0, orderBookLevels_1.mergeL2LevelGenerators)([makerAskL2LevelGenerator, ...fallbackAskGenerators], (a, b) => {
976
+ return a.price.lt(b.price);
977
+ });
978
+ const asks = (0, orderBookLevels_1.createL2Levels)(askL2LevelGenerator, depth);
979
+ const makerBidGenerator = (0, orderBookLevels_1.getL2GeneratorFromDLOBNodes)(this.getMakerLimitBids(marketIndex, slot, marketType, oraclePriceData, fallbackAsk), oraclePriceData, slot);
980
+ const fallbackBidGenerators = fallbackL2Generators.map((fallbackOrders) => {
981
+ return fallbackOrders.getL2Bids();
982
+ });
983
+ const bidL2LevelGenerator = (0, orderBookLevels_1.mergeL2LevelGenerators)([makerBidGenerator, ...fallbackBidGenerators], (a, b) => {
984
+ return a.price.gt(b.price);
985
+ });
986
+ const bids = (0, orderBookLevels_1.createL2Levels)(bidL2LevelGenerator, depth);
987
+ return {
988
+ bids,
989
+ asks,
990
+ };
991
+ }
992
+ /**
993
+ * Get an L3 view of the order book for a given market. Does not include fallback liquidity sources
994
+ *
995
+ * @param marketIndex
996
+ * @param marketType
997
+ * @param slot
998
+ * @param oraclePriceData
999
+ */
1000
+ getL3({ marketIndex, marketType, slot, oraclePriceData, }) {
1001
+ const bids = [];
1002
+ const asks = [];
1003
+ const restingAsks = this.getRestingLimitAsks(marketIndex, slot, marketType, oraclePriceData);
1004
+ for (const ask of restingAsks) {
1005
+ asks.push({
1006
+ price: ask.getPrice(oraclePriceData, slot),
1007
+ size: ask.order.baseAssetAmount.sub(ask.order.baseAssetAmountFilled),
1008
+ maker: ask.userAccount,
1009
+ orderId: ask.order.orderId,
1010
+ });
1011
+ }
1012
+ const restingBids = this.getRestingLimitBids(marketIndex, slot, marketType, oraclePriceData);
1013
+ for (const bid of restingBids) {
1014
+ bids.push({
1015
+ price: bid.getPrice(oraclePriceData, slot),
1016
+ size: bid.order.baseAssetAmount.sub(bid.order.baseAssetAmountFilled),
1017
+ maker: bid.userAccount,
1018
+ orderId: bid.order.orderId,
1019
+ });
1020
+ }
1021
+ return {
1022
+ bids,
1023
+ asks,
1024
+ };
1025
+ }
957
1026
  }
958
1027
  exports.DLOB = DLOB;
@@ -16,7 +16,7 @@ class DLOBApiClient {
16
16
  async getDLOB(slot) {
17
17
  const r = await (0, node_fetch_1.default)(this.url);
18
18
  if (!r.ok) {
19
- throw new Error(`Failed to fetch DLOB from ${this.url}`);
19
+ throw new Error(`Failed to fetch DLOB from ${this.url}. Status: ${r.status}, ${r.statusText}`);
20
20
  }
21
21
  const resp = await r.json();
22
22
  const responseSlot = resp['slot'];
@@ -1,4 +1,3 @@
1
- /// <reference types="bn.js" />
2
1
  import { BN, OraclePriceData, Order } from '..';
3
2
  import { PublicKey } from '@solana/web3.js';
4
3
  export interface DLOBNode {
@@ -4,7 +4,11 @@ import { DLOB } from './DLOB';
4
4
  import { EventEmitter } from 'events';
5
5
  import StrictEventEmitter from 'strict-event-emitter-types';
6
6
  import { DLOBSource, DLOBSubscriberEvents, DLOBSubscriptionConfig, SlotSource } from './types';
7
+ import { DriftClient } from '../driftClient';
8
+ import { MarketType } from '../types';
9
+ import { L2OrderBook, L2OrderBookGenerator, L3OrderBook } from './orderBookLevels';
7
10
  export declare class DLOBSubscriber {
11
+ driftClient: DriftClient;
8
12
  dlobSource: DLOBSource;
9
13
  slotSource: SlotSource;
10
14
  updateFrequency: number;
@@ -15,5 +19,35 @@ export declare class DLOBSubscriber {
15
19
  subscribe(): Promise<void>;
16
20
  updateDLOB(): Promise<void>;
17
21
  getDLOB(): DLOB;
22
+ /**
23
+ * Get the L2 order book for a given market.
24
+ *
25
+ * @param marketName e.g. "SOL-PERP" or "SOL". If not provided, marketIndex and marketType must be provided.
26
+ * @param marketIndex
27
+ * @param marketType
28
+ * @param depth Number of orders to include in the order book. Defaults to 10.
29
+ * @param includeVamm Whether to include the VAMM orders in the order book. Defaults to false. If true, creates vAMM generator {@link getVammL2Generator} and adds it to fallbackL2Generators.
30
+ * @param fallbackL2Generators L2 generators for fallback liquidity e.g. vAMM {@link getVammL2Generator}, openbook {@link SerumSubscriber}
31
+ */
32
+ getL2({ marketName, marketIndex, marketType, depth, includeVamm, fallbackL2Generators, }: {
33
+ marketName?: string;
34
+ marketIndex?: number;
35
+ marketType?: MarketType;
36
+ depth?: number;
37
+ includeVamm?: boolean;
38
+ fallbackL2Generators?: L2OrderBookGenerator[];
39
+ }): L2OrderBook;
40
+ /**
41
+ * Get the L3 order book for a given market.
42
+ *
43
+ * @param marketName e.g. "SOL-PERP" or "SOL". If not provided, marketIndex and marketType must be provided.
44
+ * @param marketIndex
45
+ * @param marketType
46
+ */
47
+ getL3({ marketName, marketIndex, marketType, }: {
48
+ marketName?: string;
49
+ marketIndex?: number;
50
+ marketType?: MarketType;
51
+ }): L3OrderBook;
18
52
  unsubscribe(): Promise<void>;
19
53
  }
@@ -3,9 +3,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DLOBSubscriber = void 0;
4
4
  const DLOB_1 = require("./DLOB");
5
5
  const events_1 = require("events");
6
+ const types_1 = require("../types");
7
+ const orderBookLevels_1 = require("./orderBookLevels");
8
+ const market_1 = require("../math/market");
6
9
  class DLOBSubscriber {
7
10
  constructor(config) {
8
11
  this.dlob = new DLOB_1.DLOB();
12
+ this.driftClient = config.driftClient;
9
13
  this.dlobSource = config.dlobSource;
10
14
  this.slotSource = config.slotSource;
11
15
  this.updateFrequency = config.updateFrequency;
@@ -32,6 +36,102 @@ class DLOBSubscriber {
32
36
  getDLOB() {
33
37
  return this.dlob;
34
38
  }
39
+ /**
40
+ * Get the L2 order book for a given market.
41
+ *
42
+ * @param marketName e.g. "SOL-PERP" or "SOL". If not provided, marketIndex and marketType must be provided.
43
+ * @param marketIndex
44
+ * @param marketType
45
+ * @param depth Number of orders to include in the order book. Defaults to 10.
46
+ * @param includeVamm Whether to include the VAMM orders in the order book. Defaults to false. If true, creates vAMM generator {@link getVammL2Generator} and adds it to fallbackL2Generators.
47
+ * @param fallbackL2Generators L2 generators for fallback liquidity e.g. vAMM {@link getVammL2Generator}, openbook {@link SerumSubscriber}
48
+ */
49
+ getL2({ marketName, marketIndex, marketType, depth = 10, includeVamm = false, fallbackL2Generators = [], }) {
50
+ if (marketName) {
51
+ const derivedMarketInfo = this.driftClient.getMarketIndexAndType(marketName);
52
+ if (!derivedMarketInfo) {
53
+ throw new Error(`Market ${marketName} not found`);
54
+ }
55
+ marketIndex = derivedMarketInfo.marketIndex;
56
+ marketType = derivedMarketInfo.marketType;
57
+ }
58
+ else {
59
+ if (marketIndex === undefined || marketType === undefined) {
60
+ throw new Error('Either marketName or marketIndex and marketType must be provided');
61
+ }
62
+ }
63
+ let oraclePriceData;
64
+ let fallbackBid;
65
+ let fallbackAsk;
66
+ const isPerp = (0, types_1.isVariant)(marketType, 'perp');
67
+ if (isPerp) {
68
+ const perpMarketAccount = this.driftClient.getPerpMarketAccount(marketIndex);
69
+ oraclePriceData = this.driftClient.getOraclePriceDataAndSlot(perpMarketAccount.amm.oracle);
70
+ fallbackBid = (0, market_1.calculateBidPrice)(perpMarketAccount, oraclePriceData);
71
+ fallbackAsk = (0, market_1.calculateAskPrice)(perpMarketAccount, oraclePriceData);
72
+ }
73
+ else {
74
+ oraclePriceData =
75
+ this.driftClient.getOracleDataForSpotMarket(marketIndex);
76
+ }
77
+ if (isPerp && includeVamm) {
78
+ fallbackL2Generators = [
79
+ (0, orderBookLevels_1.getVammL2Generator)({
80
+ marketAccount: this.driftClient.getPerpMarketAccount(marketIndex),
81
+ oraclePriceData,
82
+ numOrders: depth,
83
+ }),
84
+ ];
85
+ }
86
+ return this.dlob.getL2({
87
+ marketIndex,
88
+ marketType,
89
+ depth,
90
+ oraclePriceData,
91
+ slot: this.slotSource.getSlot(),
92
+ fallbackBid,
93
+ fallbackAsk,
94
+ fallbackL2Generators: fallbackL2Generators,
95
+ });
96
+ }
97
+ /**
98
+ * Get the L3 order book for a given market.
99
+ *
100
+ * @param marketName e.g. "SOL-PERP" or "SOL". If not provided, marketIndex and marketType must be provided.
101
+ * @param marketIndex
102
+ * @param marketType
103
+ */
104
+ getL3({ marketName, marketIndex, marketType, }) {
105
+ if (marketName) {
106
+ const derivedMarketInfo = this.driftClient.getMarketIndexAndType(marketName);
107
+ if (!derivedMarketInfo) {
108
+ throw new Error(`Market ${marketName} not found`);
109
+ }
110
+ marketIndex = derivedMarketInfo.marketIndex;
111
+ marketType = derivedMarketInfo.marketType;
112
+ }
113
+ else {
114
+ if (marketIndex === undefined || marketType === undefined) {
115
+ throw new Error('Either marketName or marketIndex and marketType must be provided');
116
+ }
117
+ }
118
+ let oraclePriceData;
119
+ const isPerp = (0, types_1.isVariant)(marketType, 'perp');
120
+ if (isPerp) {
121
+ oraclePriceData =
122
+ this.driftClient.getOracleDataForPerpMarket(marketIndex);
123
+ }
124
+ else {
125
+ oraclePriceData =
126
+ this.driftClient.getOracleDataForSpotMarket(marketIndex);
127
+ }
128
+ return this.dlob.getL3({
129
+ marketIndex,
130
+ marketType,
131
+ oraclePriceData,
132
+ slot: this.slotSource.getSlot(),
133
+ });
134
+ }
35
135
  async unsubscribe() {
36
136
  if (this.intervalId) {
37
137
  clearInterval(this.intervalId);
@@ -1,4 +1,3 @@
1
- /// <reference types="bn.js" />
2
1
  import { BN, MarketTypeStr, Order } from '..';
3
2
  import { PublicKey } from '@solana/web3.js';
4
3
  import { DLOBNode, DLOBNodeMap } from './DLOBNode';
@@ -0,0 +1,44 @@
1
+ import { BN, DLOBNode, OraclePriceData, PerpMarketAccount } from '..';
2
+ import { PublicKey } from '@solana/web3.js';
3
+ type liquiditySource = 'serum' | 'vamm' | 'dlob';
4
+ export type L2Level = {
5
+ price: BN;
6
+ size: BN;
7
+ sources: {
8
+ [key in liquiditySource]?: BN;
9
+ };
10
+ };
11
+ export type L2OrderBook = {
12
+ asks: L2Level[];
13
+ bids: L2Level[];
14
+ };
15
+ export interface L2OrderBookGenerator {
16
+ getL2Asks(): Generator<L2Level>;
17
+ getL2Bids(): Generator<L2Level>;
18
+ }
19
+ export type L3Level = {
20
+ price: BN;
21
+ size: BN;
22
+ maker: PublicKey;
23
+ orderId: number;
24
+ };
25
+ export type L3OrderBook = {
26
+ asks: L3Level[];
27
+ bids: L3Level[];
28
+ };
29
+ /**
30
+ * Get an {@link Generator<L2Level>} generator from a {@link Generator<DLOBNode>}
31
+ * @param dlobNodes e.g. {@link DLOB#getMakerLimitAsks} or {@link DLOB#getMakerLimitBids}
32
+ * @param oraclePriceData
33
+ * @param slot
34
+ */
35
+ export declare function getL2GeneratorFromDLOBNodes(dlobNodes: Generator<DLOBNode>, oraclePriceData: OraclePriceData, slot: number): Generator<L2Level>;
36
+ export declare function mergeL2LevelGenerators(l2LevelGenerators: Generator<L2Level>[], compare: (a: L2Level, b: L2Level) => boolean): Generator<L2Level>;
37
+ export declare function createL2Levels(generator: Generator<L2Level>, depth: number): L2Level[];
38
+ export declare function getVammL2Generator({ marketAccount, oraclePriceData, numOrders, now, }: {
39
+ marketAccount: PerpMarketAccount;
40
+ oraclePriceData: OraclePriceData;
41
+ numOrders: number;
42
+ now?: BN;
43
+ }): L2OrderBookGenerator;
44
+ export {};