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

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 (149) hide show
  1. package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
  2. package/lib/accounts/bulkUserStatsSubscription.js +21 -0
  3. package/lib/accounts/bulkUserSubscription.js +0 -1
  4. package/lib/accounts/fetch.d.ts +2 -1
  5. package/lib/accounts/fetch.js +9 -1
  6. package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
  7. package/lib/accounts/pollingUserStatsAccountSubscriber.js +113 -0
  8. package/lib/accounts/types.d.ts +14 -1
  9. package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
  10. package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
  11. package/lib/addresses/pda.d.ts +1 -0
  12. package/lib/addresses/pda.js +8 -1
  13. package/lib/admin.d.ts +9 -5
  14. package/lib/admin.js +52 -11
  15. package/lib/clearingHouse.d.ts +52 -23
  16. package/lib/clearingHouse.js +736 -200
  17. package/lib/clearingHouseConfig.d.ts +1 -0
  18. package/lib/clearingHouseUser.d.ts +24 -16
  19. package/lib/clearingHouseUser.js +223 -101
  20. package/lib/clearingHouseUserStats.d.ts +18 -0
  21. package/lib/clearingHouseUserStats.js +49 -0
  22. package/lib/clearingHouseUserStatsConfig.d.ts +14 -0
  23. package/lib/clearingHouseUserStatsConfig.js +2 -0
  24. package/lib/config.js +1 -1
  25. package/lib/constants/banks.d.ts +2 -2
  26. package/lib/constants/banks.js +12 -4
  27. package/lib/constants/numericConstants.d.ts +5 -0
  28. package/lib/constants/numericConstants.js +8 -3
  29. package/lib/events/eventList.js +3 -0
  30. package/lib/events/types.d.ts +3 -1
  31. package/lib/events/types.js +2 -0
  32. package/lib/factory/bigNum.d.ts +1 -0
  33. package/lib/factory/bigNum.js +34 -10
  34. package/lib/idl/clearing_house.json +1603 -377
  35. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  36. package/lib/index.d.ts +9 -3
  37. package/lib/index.js +13 -3
  38. package/lib/math/amm.d.ts +1 -0
  39. package/lib/math/amm.js +22 -38
  40. package/lib/math/auction.js +4 -1
  41. package/lib/math/bankBalance.d.ts +7 -1
  42. package/lib/math/bankBalance.js +77 -2
  43. package/lib/math/margin.d.ts +11 -0
  44. package/lib/math/margin.js +72 -0
  45. package/lib/math/market.d.ts +4 -1
  46. package/lib/math/market.js +35 -1
  47. package/lib/math/oracles.d.ts +3 -0
  48. package/lib/math/oracles.js +25 -5
  49. package/lib/math/orders.d.ts +6 -2
  50. package/lib/math/orders.js +62 -12
  51. package/lib/math/position.d.ts +8 -0
  52. package/lib/math/position.js +45 -12
  53. package/lib/math/trade.d.ts +1 -1
  54. package/lib/math/trade.js +7 -10
  55. package/lib/orderParams.d.ts +14 -5
  56. package/lib/orderParams.js +8 -96
  57. package/lib/slot/SlotSubscriber.d.ts +7 -0
  58. package/lib/slot/SlotSubscriber.js +3 -0
  59. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  60. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  61. package/lib/tx/retryTxSender.js +9 -2
  62. package/lib/tx/utils.js +1 -1
  63. package/lib/types.d.ts +236 -26
  64. package/lib/types.js +64 -1
  65. package/lib/util/computeUnits.js +1 -1
  66. package/lib/util/getTokenAddress.d.ts +2 -0
  67. package/lib/util/getTokenAddress.js +9 -0
  68. package/package.json +3 -3
  69. package/src/accounts/bulkUserStatsSubscription.ts +33 -0
  70. package/src/accounts/bulkUserSubscription.ts +0 -1
  71. package/src/accounts/fetch.ts +27 -2
  72. package/src/accounts/pollingUserStatsAccountSubscriber.ts +172 -0
  73. package/src/accounts/types.ts +18 -0
  74. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
  75. package/src/addresses/marketAddresses.js +26 -0
  76. package/src/addresses/pda.ts +13 -0
  77. package/src/admin.ts +82 -15
  78. package/src/assert/assert.js +9 -0
  79. package/src/clearingHouse.ts +1232 -323
  80. package/src/clearingHouseConfig.ts +1 -0
  81. package/src/clearingHouseUser.ts +343 -155
  82. package/src/clearingHouseUserStats.ts +75 -0
  83. package/src/clearingHouseUserStatsConfig.ts +18 -0
  84. package/src/config.ts +1 -1
  85. package/src/constants/banks.js +42 -0
  86. package/src/constants/banks.ts +14 -4
  87. package/src/constants/markets.js +42 -0
  88. package/src/constants/numericConstants.js +41 -0
  89. package/src/constants/numericConstants.ts +14 -2
  90. package/src/events/eventList.js +77 -0
  91. package/src/events/eventList.ts +3 -0
  92. package/src/events/eventSubscriber.js +139 -0
  93. package/src/events/sort.js +44 -0
  94. package/src/events/txEventCache.js +71 -0
  95. package/src/events/types.ts +6 -0
  96. package/src/examples/makeTradeExample.js +80 -0
  97. package/src/factory/bigNum.js +390 -0
  98. package/src/factory/bigNum.ts +42 -13
  99. package/src/factory/oracleClient.js +20 -0
  100. package/src/idl/clearing_house.json +1603 -377
  101. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  102. package/src/index.ts +9 -3
  103. package/src/math/amm.ts +54 -55
  104. package/src/math/auction.js +42 -0
  105. package/src/math/auction.ts +5 -1
  106. package/src/math/bankBalance.ts +148 -2
  107. package/src/math/conversion.js +11 -0
  108. package/src/math/funding.js +248 -0
  109. package/src/math/margin.ts +124 -0
  110. package/src/math/market.ts +66 -1
  111. package/src/math/oracles.js +26 -0
  112. package/src/math/oracles.ts +42 -5
  113. package/src/math/orders.ts +129 -13
  114. package/src/math/position.ts +64 -9
  115. package/src/math/repeg.js +128 -0
  116. package/src/math/state.js +15 -0
  117. package/src/math/trade.js +253 -0
  118. package/src/math/trade.ts +23 -25
  119. package/src/math/utils.js +0 -1
  120. package/src/oracles/oracleClientCache.js +19 -0
  121. package/src/oracles/pythClient.js +46 -0
  122. package/src/oracles/quoteAssetOracleClient.js +32 -0
  123. package/src/oracles/switchboardClient.js +69 -0
  124. package/src/oracles/types.js +2 -0
  125. package/src/orderParams.js +20 -0
  126. package/src/orderParams.ts +20 -141
  127. package/src/slot/SlotSubscriber.js +39 -0
  128. package/src/slot/SlotSubscriber.ts +11 -1
  129. package/src/token/index.js +38 -0
  130. package/src/tokenFaucet.js +189 -0
  131. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  132. package/src/tx/retryTxSender.ts +11 -3
  133. package/src/tx/types.js +2 -0
  134. package/src/tx/utils.js +17 -0
  135. package/src/tx/utils.ts +1 -1
  136. package/src/types.ts +239 -27
  137. package/src/userName.js +20 -0
  138. package/src/util/computeUnits.js +21 -11
  139. package/src/util/computeUnits.ts +1 -1
  140. package/src/util/getTokenAddress.js +9 -0
  141. package/src/util/getTokenAddress.ts +18 -0
  142. package/src/util/promiseTimeout.js +14 -0
  143. package/src/util/tps.js +27 -0
  144. package/src/wallet.js +35 -0
  145. package/tests/bn/test.ts +10 -0
  146. package/lib/orders.d.ts +0 -8
  147. package/lib/orders.js +0 -142
  148. package/src/orders.ts +0 -251
  149. package/src/util/computeUnits.js.map +0 -1
@@ -0,0 +1,75 @@
1
+ import { ClearingHouse } from './clearingHouse';
2
+ import { PublicKey } from '@solana/web3.js';
3
+ import { DataAndSlot, UserStatsAccountSubscriber } from './accounts/types';
4
+ import { ClearingHouseUserStatsConfig } from './clearingHouseUserStatsConfig';
5
+ import { PollingUserStatsAccountSubscriber } from './accounts/pollingUserStatsAccountSubscriber';
6
+ import { WebSocketUserStatsAccountSubscriber } from './accounts/webSocketUserStatsAccountSubsriber';
7
+ import { ReferrerInfo, UserStatsAccount } from './types';
8
+ import {
9
+ getUserAccountPublicKeySync,
10
+ getUserStatsAccountPublicKey,
11
+ } from './addresses/pda';
12
+
13
+ export class ClearingHouseUserStats {
14
+ clearingHouse: ClearingHouse;
15
+ userStatsAccountPublicKey: PublicKey;
16
+ accountSubscriber: UserStatsAccountSubscriber;
17
+ isSubscribed: boolean;
18
+
19
+ public constructor(config: ClearingHouseUserStatsConfig) {
20
+ this.clearingHouse = config.clearingHouse;
21
+ this.userStatsAccountPublicKey = config.userStatsAccountPublicKey;
22
+ if (config.accountSubscription?.type === 'polling') {
23
+ this.accountSubscriber = new PollingUserStatsAccountSubscriber(
24
+ config.clearingHouse.program,
25
+ config.userStatsAccountPublicKey,
26
+ config.accountSubscription.accountLoader
27
+ );
28
+ } else {
29
+ this.accountSubscriber = new WebSocketUserStatsAccountSubscriber(
30
+ config.clearingHouse.program,
31
+ config.userStatsAccountPublicKey
32
+ );
33
+ }
34
+ }
35
+
36
+ public async subscribe(): Promise<boolean> {
37
+ this.isSubscribed = await this.accountSubscriber.subscribe();
38
+ return this.isSubscribed;
39
+ }
40
+
41
+ public async fetchAccounts(): Promise<void> {
42
+ await this.accountSubscriber.fetch();
43
+ }
44
+
45
+ public async unsubscribe(): Promise<void> {
46
+ await this.accountSubscriber.unsubscribe();
47
+ this.isSubscribed = false;
48
+ }
49
+
50
+ public getAccountAndSlot(): DataAndSlot<UserStatsAccount> {
51
+ return this.accountSubscriber.getUserStatsAccountAndSlot();
52
+ }
53
+
54
+ public getAccount(): UserStatsAccount {
55
+ return this.accountSubscriber.getUserStatsAccountAndSlot().data;
56
+ }
57
+
58
+ public getReferrerInfo(): ReferrerInfo | undefined {
59
+ if (this.getAccount().referrer.equals(PublicKey.default)) {
60
+ return undefined;
61
+ } else {
62
+ return {
63
+ referrer: getUserAccountPublicKeySync(
64
+ this.clearingHouse.program.programId,
65
+ this.getAccount().referrer,
66
+ 0
67
+ ),
68
+ referrerStats: getUserStatsAccountPublicKey(
69
+ this.clearingHouse.program.programId,
70
+ this.getAccount().referrer
71
+ ),
72
+ };
73
+ }
74
+ }
75
+ }
@@ -0,0 +1,18 @@
1
+ import { ClearingHouse } from './clearingHouse';
2
+ import { PublicKey } from '@solana/web3.js';
3
+ import { BulkAccountLoader } from './accounts/bulkAccountLoader';
4
+
5
+ export type ClearingHouseUserStatsConfig = {
6
+ accountSubscription?: ClearingHouseUserStatsAccountSubscriptionConfig;
7
+ clearingHouse: ClearingHouse;
8
+ userStatsAccountPublicKey: PublicKey;
9
+ };
10
+
11
+ export type ClearingHouseUserStatsAccountSubscriptionConfig =
12
+ | {
13
+ type: 'websocket';
14
+ }
15
+ | {
16
+ type: 'polling';
17
+ accountLoader: BulkAccountLoader;
18
+ };
package/src/config.ts CHANGED
@@ -28,7 +28,7 @@ export const configs: { [key in DriftEnv]: DriftConfig } = {
28
28
  devnet: {
29
29
  ENV: 'devnet',
30
30
  PYTH_ORACLE_MAPPING_ADDRESS: 'BmA9Z6FjioHJPpjT39QazZyhDRUdZy2ezwx4GiDdE2u2',
31
- CLEARING_HOUSE_PROGRAM_ID: '9jwr5nC2f9yAraXrg4UzHXmCX3vi9FQkjD6p9e8bRqNa',
31
+ CLEARING_HOUSE_PROGRAM_ID: '65sz7dRiWDRPZjiRxcTxPM7AE6VK4Nag9HEK6oBJXhJn',
32
32
  USDC_MINT_ADDRESS: '8zGuJQqwhZafTah7Uc7Z4tXRnguqkn5KLFAP8oV6PHe2',
33
33
  MARKETS: DevnetMarkets,
34
34
  BANKS: DevnetBanks,
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Banks = exports.MainnetBanks = exports.DevnetBanks = exports.WRAPPED_SOL_MINT = void 0;
4
+ const web3_js_1 = require("@solana/web3.js");
5
+ const __1 = require("../");
6
+ exports.WRAPPED_SOL_MINT = new web3_js_1.PublicKey('So11111111111111111111111111111111111111112');
7
+ exports.DevnetBanks = [
8
+ {
9
+ symbol: 'USDC',
10
+ bankIndex: new __1.BN(0),
11
+ oracle: web3_js_1.PublicKey.default,
12
+ oracleSource: __1.OracleSource.QUOTE_ASSET,
13
+ mint: new web3_js_1.PublicKey('8zGuJQqwhZafTah7Uc7Z4tXRnguqkn5KLFAP8oV6PHe2'),
14
+ },
15
+ {
16
+ symbol: 'SOL',
17
+ bankIndex: new __1.BN(1),
18
+ oracle: new web3_js_1.PublicKey('J83w4HKfqxwcq3BEMMkPFSppX3gqekLyLJBexebFVkix'),
19
+ oracleSource: __1.OracleSource.PYTH,
20
+ mint: new web3_js_1.PublicKey(exports.WRAPPED_SOL_MINT),
21
+ },
22
+ {
23
+ symbol: 'BTC',
24
+ bankIndex: new __1.BN(2),
25
+ oracle: new web3_js_1.PublicKey('HovQMDrbAgAYPCmHVSrezcSmkMtXSSUsLDFANExrZh2J'),
26
+ oracleSource: __1.OracleSource.PYTH,
27
+ mint: new web3_js_1.PublicKey('3BZPwbcqB5kKScF3TEXxwNfx5ipV13kbRVDvfVp5c6fv'),
28
+ },
29
+ ];
30
+ exports.MainnetBanks = [
31
+ {
32
+ symbol: 'USDC',
33
+ bankIndex: new __1.BN(0),
34
+ oracle: web3_js_1.PublicKey.default,
35
+ oracleSource: __1.OracleSource.QUOTE_ASSET,
36
+ mint: new web3_js_1.PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),
37
+ },
38
+ ];
39
+ exports.Banks = {
40
+ devnet: exports.DevnetBanks,
41
+ 'mainnet-beta': exports.MainnetBanks,
42
+ };
@@ -1,6 +1,5 @@
1
- import { BN, OracleSource } from '../';
2
- import { DriftEnv } from '../';
3
1
  import { PublicKey } from '@solana/web3.js';
2
+ import { BN, DriftEnv, OracleSource } from '../';
4
3
 
5
4
  export type BankConfig = {
6
5
  symbol: string;
@@ -10,6 +9,10 @@ export type BankConfig = {
10
9
  oracleSource: OracleSource;
11
10
  };
12
11
 
12
+ export const WRAPPED_SOL_MINT = new PublicKey(
13
+ 'So11111111111111111111111111111111111111112'
14
+ );
15
+
13
16
  export const DevnetBanks: BankConfig[] = [
14
17
  {
15
18
  symbol: 'USDC',
@@ -19,11 +22,18 @@ export const DevnetBanks: BankConfig[] = [
19
22
  mint: new PublicKey('8zGuJQqwhZafTah7Uc7Z4tXRnguqkn5KLFAP8oV6PHe2'),
20
23
  },
21
24
  {
22
- symbol: 'BTC',
25
+ symbol: 'SOL',
23
26
  bankIndex: new BN(1),
27
+ oracle: new PublicKey('J83w4HKfqxwcq3BEMMkPFSppX3gqekLyLJBexebFVkix'),
28
+ oracleSource: OracleSource.PYTH,
29
+ mint: new PublicKey(WRAPPED_SOL_MINT),
30
+ },
31
+ {
32
+ symbol: 'BTC',
33
+ bankIndex: new BN(2),
24
34
  oracle: new PublicKey('HovQMDrbAgAYPCmHVSrezcSmkMtXSSUsLDFANExrZh2J'),
25
35
  oracleSource: OracleSource.PYTH,
26
- mint: new PublicKey('Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr'),
36
+ mint: new PublicKey('3BZPwbcqB5kKScF3TEXxwNfx5ipV13kbRVDvfVp5c6fv'),
27
37
  },
28
38
  ];
29
39
 
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Markets = exports.MainnetMarkets = exports.DevnetMarkets = void 0;
4
+ const __1 = require("../");
5
+ const web3_js_1 = require("@solana/web3.js");
6
+ exports.DevnetMarkets = [
7
+ {
8
+ fullName: 'Solana',
9
+ category: ['L1', 'Infra'],
10
+ symbol: 'SOL-PERP',
11
+ baseAssetSymbol: 'SOL',
12
+ marketIndex: new __1.BN(0),
13
+ oracle: new web3_js_1.PublicKey('J83w4HKfqxwcq3BEMMkPFSppX3gqekLyLJBexebFVkix'),
14
+ launchTs: 1655751353000,
15
+ oracleSource: __1.OracleSource.PYTH,
16
+ },
17
+ {
18
+ fullName: 'Bitcoin',
19
+ category: ['L1', 'Payment'],
20
+ symbol: 'BTC-PERP',
21
+ baseAssetSymbol: 'BTC',
22
+ marketIndex: new __1.BN(1),
23
+ oracle: new web3_js_1.PublicKey('HovQMDrbAgAYPCmHVSrezcSmkMtXSSUsLDFANExrZh2J'),
24
+ launchTs: 1655751353000,
25
+ oracleSource: __1.OracleSource.PYTH,
26
+ },
27
+ {
28
+ fullName: 'Ethereum',
29
+ category: ['L1', 'Infra'],
30
+ symbol: 'ETH-PERP',
31
+ baseAssetSymbol: 'ETH',
32
+ marketIndex: new __1.BN(2),
33
+ oracle: new web3_js_1.PublicKey('EdVCmQ9FSPcVe5YySXDPCRmc8aDQLKJ9xvYBMZPie1Vw'),
34
+ launchTs: 1637691133472,
35
+ oracleSource: __1.OracleSource.PYTH,
36
+ },
37
+ ];
38
+ exports.MainnetMarkets = [];
39
+ exports.Markets = {
40
+ devnet: exports.DevnetMarkets,
41
+ 'mainnet-beta': [],
42
+ };
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QUOTE_ASSET_BANK_INDEX = exports.ONE_YEAR = exports.BID_ASK_SPREAD_PRECISION = exports.MARGIN_PRECISION = exports.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO = exports.PRICE_TO_QUOTE_PRECISION = exports.PRICE_DIV_PEG = exports.AMM_TO_QUOTE_PRECISION_RATIO = exports.BASE_PRECISION_EXP = exports.BASE_PRECISION = exports.AMM_RESERVE_PRECISION = exports.PEG_PRECISION = exports.FUNDING_PAYMENT_PRECISION = exports.MARK_PRICE_PRECISION = exports.QUOTE_PRECISION = exports.LIQUIDATION_FEE_PRECISION = exports.BANK_BALANCE_PRECISION = exports.BANK_BALANCE_PRECISION_EXP = exports.BANK_WEIGHT_PRECISION = exports.BANK_RATE_PRECISION = exports.BANK_UTILIZATION_PRECISION = exports.BANK_CUMULATIVE_INTEREST_PRECISION = exports.BANK_INTEREST_PRECISION = exports.AMM_RESERVE_PRECISION_EXP = exports.PEG_PRECISION_EXP = exports.FUNDING_RATE_PRECISION_EXP = exports.MARK_PRICE_PRECISION_EXP = exports.FUNDING_PAYMENT_PRECISION_EXP = exports.QUOTE_PRECISION_EXP = exports.MAX_LEVERAGE = exports.TEN_MILLION = exports.BN_MAX = exports.TEN_THOUSAND = exports.TEN = exports.TWO = exports.ONE = exports.ZERO = void 0;
4
+ const __1 = require("../");
5
+ exports.ZERO = new __1.BN(0);
6
+ exports.ONE = new __1.BN(1);
7
+ exports.TWO = new __1.BN(2);
8
+ exports.TEN = new __1.BN(10);
9
+ exports.TEN_THOUSAND = new __1.BN(10000);
10
+ exports.BN_MAX = new __1.BN(Number.MAX_SAFE_INTEGER);
11
+ exports.TEN_MILLION = exports.TEN_THOUSAND.mul(exports.TEN_THOUSAND);
12
+ exports.MAX_LEVERAGE = new __1.BN(5);
13
+ exports.QUOTE_PRECISION_EXP = new __1.BN(6);
14
+ exports.FUNDING_PAYMENT_PRECISION_EXP = new __1.BN(4);
15
+ exports.MARK_PRICE_PRECISION_EXP = new __1.BN(10);
16
+ exports.FUNDING_RATE_PRECISION_EXP = exports.MARK_PRICE_PRECISION_EXP.mul(exports.FUNDING_PAYMENT_PRECISION_EXP);
17
+ exports.PEG_PRECISION_EXP = new __1.BN(3);
18
+ exports.AMM_RESERVE_PRECISION_EXP = new __1.BN(13);
19
+ exports.BANK_INTEREST_PRECISION = new __1.BN(1000000);
20
+ exports.BANK_CUMULATIVE_INTEREST_PRECISION = new __1.BN(10000000000);
21
+ exports.BANK_UTILIZATION_PRECISION = new __1.BN(1000000);
22
+ exports.BANK_RATE_PRECISION = new __1.BN(1000000);
23
+ exports.BANK_WEIGHT_PRECISION = new __1.BN(100);
24
+ exports.BANK_BALANCE_PRECISION_EXP = new __1.BN(6);
25
+ exports.BANK_BALANCE_PRECISION = new __1.BN(10).pow(exports.BANK_BALANCE_PRECISION_EXP);
26
+ exports.LIQUIDATION_FEE_PRECISION = new __1.BN(1000000);
27
+ exports.QUOTE_PRECISION = new __1.BN(10).pow(exports.QUOTE_PRECISION_EXP);
28
+ exports.MARK_PRICE_PRECISION = new __1.BN(10).pow(exports.MARK_PRICE_PRECISION_EXP);
29
+ exports.FUNDING_PAYMENT_PRECISION = new __1.BN(10).pow(exports.FUNDING_PAYMENT_PRECISION_EXP);
30
+ exports.PEG_PRECISION = new __1.BN(10).pow(exports.PEG_PRECISION_EXP);
31
+ exports.AMM_RESERVE_PRECISION = new __1.BN(10).pow(exports.AMM_RESERVE_PRECISION_EXP);
32
+ exports.BASE_PRECISION = exports.AMM_RESERVE_PRECISION;
33
+ exports.BASE_PRECISION_EXP = exports.AMM_RESERVE_PRECISION_EXP;
34
+ exports.AMM_TO_QUOTE_PRECISION_RATIO = exports.AMM_RESERVE_PRECISION.div(exports.QUOTE_PRECISION); // 10^7
35
+ exports.PRICE_DIV_PEG = exports.MARK_PRICE_PRECISION.div(exports.PEG_PRECISION); //10^7
36
+ exports.PRICE_TO_QUOTE_PRECISION = exports.MARK_PRICE_PRECISION.div(exports.QUOTE_PRECISION);
37
+ exports.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO = exports.AMM_RESERVE_PRECISION.mul(exports.PEG_PRECISION).div(exports.QUOTE_PRECISION); // 10^10
38
+ exports.MARGIN_PRECISION = exports.TEN_THOUSAND;
39
+ exports.BID_ASK_SPREAD_PRECISION = new __1.BN(1000000);
40
+ exports.ONE_YEAR = new __1.BN(31536000);
41
+ exports.QUOTE_ASSET_BANK_INDEX = new __1.BN(0);
@@ -19,8 +19,16 @@ export const FUNDING_RATE_PRECISION_EXP = MARK_PRICE_PRECISION_EXP.mul(
19
19
  export const PEG_PRECISION_EXP = new BN(3);
20
20
  export const AMM_RESERVE_PRECISION_EXP = new BN(13);
21
21
 
22
- export const BANK_INTEREST_PRECISION = new BN(1000000);
23
- export const BANK_CUMULATIVE_INTEREST_PRECISION = new BN(10000000000);
22
+ export const BANK_INTEREST_PRECISION_EXP = new BN(6);
23
+ export const BANK_INTEREST_PRECISION = new BN(10).pow(
24
+ BANK_INTEREST_PRECISION_EXP
25
+ );
26
+
27
+ export const BANK_CUMULATIVE_INTEREST_PRECISION_EXP = new BN(10);
28
+ export const BANK_CUMULATIVE_INTEREST_PRECISION = new BN(10).pow(
29
+ BANK_CUMULATIVE_INTEREST_PRECISION_EXP
30
+ );
31
+
24
32
  export const BANK_UTILIZATION_PRECISION = new BN(1000000);
25
33
  export const BANK_RATE_PRECISION = new BN(1000000);
26
34
  export const BANK_WEIGHT_PRECISION = new BN(100);
@@ -28,6 +36,10 @@ export const BANK_BALANCE_PRECISION_EXP = new BN(6);
28
36
  export const BANK_BALANCE_PRECISION = new BN(10).pow(
29
37
  BANK_BALANCE_PRECISION_EXP
30
38
  );
39
+ export const BANK_IMF_PRECISION_EXP = new BN(6);
40
+
41
+ export const BANK_IMF_PRECISION = new BN(10).pow(BANK_IMF_PRECISION_EXP);
42
+ export const LIQUIDATION_FEE_PRECISION = new BN(1000000);
31
43
 
32
44
  export const QUOTE_PRECISION = new BN(10).pow(QUOTE_PRECISION_EXP);
33
45
  export const MARK_PRICE_PRECISION = new BN(10).pow(MARK_PRICE_PRECISION_EXP);
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EventList = void 0;
4
+ class Node {
5
+ constructor(event, next, prev) {
6
+ this.event = event;
7
+ this.next = next;
8
+ this.prev = prev;
9
+ }
10
+ }
11
+ class EventList {
12
+ constructor(eventType, maxSize, sortFn, orderDirection) {
13
+ this.eventType = eventType;
14
+ this.maxSize = maxSize;
15
+ this.sortFn = sortFn;
16
+ this.orderDirection = orderDirection;
17
+ this.size = 0;
18
+ }
19
+ insert(event) {
20
+ this.size++;
21
+ const newNode = new Node(event);
22
+ if (this.head === undefined) {
23
+ this.head = this.tail = newNode;
24
+ return;
25
+ }
26
+ if (this.sortFn(this.head.event, newNode.event) ===
27
+ (this.orderDirection === 'asc' ? 'less than' : 'greater than')) {
28
+ this.head.prev = newNode;
29
+ newNode.next = this.head;
30
+ this.head = newNode;
31
+ }
32
+ else {
33
+ let currentNode = this.head;
34
+ while (currentNode.next !== undefined &&
35
+ this.sortFn(currentNode.next.event, newNode.event) !==
36
+ (this.orderDirection === 'asc' ? 'less than' : 'greater than')) {
37
+ currentNode = currentNode.next;
38
+ }
39
+ newNode.next = currentNode.next;
40
+ if (currentNode.next !== undefined) {
41
+ newNode.next.prev = newNode;
42
+ }
43
+ currentNode.next = newNode;
44
+ newNode.prev = currentNode;
45
+ }
46
+ if (this.size > this.maxSize) {
47
+ this.detach();
48
+ }
49
+ }
50
+ detach() {
51
+ const node = this.tail;
52
+ if (node.prev !== undefined) {
53
+ node.prev.next = node.next;
54
+ }
55
+ else {
56
+ this.head = node.next;
57
+ }
58
+ if (node.next !== undefined) {
59
+ node.next.prev = node.prev;
60
+ }
61
+ else {
62
+ this.tail = node.prev;
63
+ }
64
+ this.size--;
65
+ }
66
+ toArray() {
67
+ return Array.from(this);
68
+ }
69
+ *[Symbol.iterator]() {
70
+ let node = this.head;
71
+ while (node) {
72
+ yield node.event;
73
+ node = node.next;
74
+ }
75
+ }
76
+ }
77
+ exports.EventList = EventList;
@@ -53,7 +53,10 @@ export class EventList<Type extends EventType> {
53
53
  newNode.next = currentNode.next;
54
54
  if (currentNode.next !== undefined) {
55
55
  newNode.next.prev = newNode;
56
+ } else {
57
+ this.tail = newNode;
56
58
  }
59
+
57
60
  currentNode.next = newNode;
58
61
  newNode.prev = currentNode;
59
62
  }
@@ -0,0 +1,139 @@
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.EventSubscriber = void 0;
13
+ const types_1 = require("./types");
14
+ const txEventCache_1 = require("./txEventCache");
15
+ const eventList_1 = require("./eventList");
16
+ const pollingLogProvider_1 = require("./pollingLogProvider");
17
+ const fetchLogs_1 = require("./fetchLogs");
18
+ const webSocketLogProvider_1 = require("./webSocketLogProvider");
19
+ const events_1 = require("events");
20
+ const sort_1 = require("./sort");
21
+ class EventSubscriber {
22
+ constructor(connection, program, options = types_1.DefaultEventSubscriptionOptions) {
23
+ this.connection = connection;
24
+ this.program = program;
25
+ this.options = options;
26
+ this.awaitTxPromises = new Map();
27
+ this.awaitTxResolver = new Map();
28
+ this.options = Object.assign({}, types_1.DefaultEventSubscriptionOptions, options);
29
+ this.txEventCache = new txEventCache_1.TxEventCache(this.options.maxTx);
30
+ this.eventListMap = new Map();
31
+ for (const eventType of this.options.eventTypes) {
32
+ this.eventListMap.set(eventType, new eventList_1.EventList(eventType, this.options.maxEventsPerType, sort_1.getSortFn(this.options.orderBy, this.options.orderDir, eventType), this.options.orderDir));
33
+ }
34
+ this.eventEmitter = new events_1.EventEmitter();
35
+ if (this.options.logProviderConfig.type === 'websocket') {
36
+ this.logProvider = new webSocketLogProvider_1.WebSocketLogProvider(this.connection, this.program.programId, this.options.commitment);
37
+ }
38
+ else {
39
+ this.logProvider = new pollingLogProvider_1.PollingLogProvider(this.connection, this.program.programId, options.commitment, this.options.logProviderConfig.frequency);
40
+ }
41
+ }
42
+ subscribe() {
43
+ if (this.logProvider.isSubscribed()) {
44
+ return true;
45
+ }
46
+ this.fetchPreviousTx().catch((e) => {
47
+ console.error('Error fetching previous txs in event subscriber');
48
+ console.error(e);
49
+ });
50
+ return this.logProvider.subscribe((txSig, slot, logs) => {
51
+ this.handleTxLogs(txSig, slot, logs);
52
+ });
53
+ }
54
+ handleTxLogs(txSig, slot, logs) {
55
+ if (this.txEventCache.has(txSig)) {
56
+ return;
57
+ }
58
+ const wrappedEvents = this.parseEventsFromLogs(txSig, slot, logs);
59
+ for (const wrappedEvent of wrappedEvents) {
60
+ this.eventListMap.get(wrappedEvent.eventType).insert(wrappedEvent);
61
+ this.eventEmitter.emit('newEvent', wrappedEvent);
62
+ }
63
+ if (this.awaitTxPromises.has(txSig)) {
64
+ this.awaitTxPromises.delete(txSig);
65
+ this.awaitTxResolver.get(txSig)();
66
+ this.awaitTxResolver.delete(txSig);
67
+ }
68
+ this.txEventCache.add(txSig, wrappedEvents);
69
+ }
70
+ fetchPreviousTx() {
71
+ return __awaiter(this, void 0, void 0, function* () {
72
+ if (!this.options.untilTx) {
73
+ return;
74
+ }
75
+ let txFetched = 0;
76
+ let beforeTx = undefined;
77
+ const untilTx = this.options.untilTx;
78
+ while (txFetched < this.options.maxTx) {
79
+ const response = yield fetchLogs_1.fetchLogs(this.connection, this.program.programId, this.options.commitment === 'finalized' ? 'finalized' : 'confirmed', beforeTx, untilTx);
80
+ if (response === undefined) {
81
+ break;
82
+ }
83
+ txFetched += response.transactionLogs.length;
84
+ beforeTx = response.earliestTx;
85
+ for (const { txSig, slot, logs } of response.transactionLogs) {
86
+ this.handleTxLogs(txSig, slot, logs);
87
+ }
88
+ }
89
+ });
90
+ }
91
+ unsubscribe() {
92
+ return __awaiter(this, void 0, void 0, function* () {
93
+ return yield this.logProvider.unsubscribe();
94
+ });
95
+ }
96
+ parseEventsFromLogs(txSig, slot, logs) {
97
+ const records = [];
98
+ // @ts-ignore
99
+ this.program._events._eventParser.parseLogs(logs, (event) => {
100
+ const expectRecordType = this.eventListMap.has(event.name);
101
+ if (expectRecordType) {
102
+ event.data.txSig = txSig;
103
+ event.data.slot = slot;
104
+ event.data.eventType = event.name;
105
+ records.push(event.data);
106
+ }
107
+ });
108
+ return records;
109
+ }
110
+ awaitTx(txSig) {
111
+ if (this.awaitTxPromises.has(txSig)) {
112
+ return this.awaitTxPromises.get(txSig);
113
+ }
114
+ if (this.txEventCache.has(txSig)) {
115
+ return Promise.resolve();
116
+ }
117
+ const promise = new Promise((resolve) => {
118
+ this.awaitTxResolver.set(txSig, resolve);
119
+ });
120
+ this.awaitTxPromises.set(txSig, promise);
121
+ return promise;
122
+ }
123
+ getEventList(eventType) {
124
+ return this.eventListMap.get(eventType);
125
+ }
126
+ /**
127
+ * This requires the EventList be cast to an array, which requires reallocation of memory.
128
+ * Would bias to using getEventList over getEvents
129
+ *
130
+ * @param eventType
131
+ */
132
+ getEventsArray(eventType) {
133
+ return this.eventListMap.get(eventType).toArray();
134
+ }
135
+ getEventsByTx(txSig) {
136
+ return this.txEventCache.get(txSig);
137
+ }
138
+ }
139
+ exports.EventSubscriber = EventSubscriber;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getSortFn = void 0;
4
+ const index_1 = require("../index");
5
+ function clientSortAscFn() {
6
+ return 'less than';
7
+ }
8
+ function clientSortDescFn() {
9
+ return 'greater than';
10
+ }
11
+ function defaultBlockchainSortFn(currentEvent, newEvent) {
12
+ return currentEvent.slot <= newEvent.slot ? 'less than' : 'greater than';
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;
21
+ if (!currentEventMarketIndex.eq(newEventMarketIndex)) {
22
+ return currentEvent.ts.lte(newEvent.ts) ? 'less than' : 'greater than';
23
+ }
24
+ if (currentEvent.fillRecordId.gt(index_1.ZERO) && newEvent.fillRecordId.gt(index_1.ZERO)) {
25
+ return currentEvent.fillRecordId.lte(newEvent.fillRecordId)
26
+ ? 'less than'
27
+ : 'greater than';
28
+ }
29
+ else {
30
+ return currentEvent.ts.lte(newEvent.ts) ? 'less than' : 'greater than';
31
+ }
32
+ }
33
+ function getSortFn(orderBy, orderDir, eventType) {
34
+ if (orderBy === 'client') {
35
+ return orderDir === 'asc' ? clientSortAscFn : clientSortDescFn;
36
+ }
37
+ switch (eventType) {
38
+ case 'OrderRecord':
39
+ return orderRecordSortFn;
40
+ default:
41
+ return defaultBlockchainSortFn;
42
+ }
43
+ }
44
+ exports.getSortFn = getSortFn;
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TxEventCache = void 0;
4
+ class Node {
5
+ constructor(key, value, next, prev) {
6
+ this.key = key;
7
+ this.value = value;
8
+ this.next = next;
9
+ this.prev = prev;
10
+ }
11
+ }
12
+ // lru cache
13
+ class TxEventCache {
14
+ constructor(maxTx = 1024) {
15
+ this.maxTx = maxTx;
16
+ this.size = 0;
17
+ this.cacheMap = {};
18
+ }
19
+ add(key, events) {
20
+ const existingNode = this.cacheMap[key];
21
+ if (existingNode) {
22
+ this.detach(existingNode);
23
+ this.size--;
24
+ }
25
+ else if (this.size === this.maxTx) {
26
+ delete this.cacheMap[this.tail.key];
27
+ this.detach(this.tail);
28
+ this.size--;
29
+ }
30
+ // Write to head of LinkedList
31
+ if (!this.head) {
32
+ this.head = this.tail = new Node(key, events);
33
+ }
34
+ else {
35
+ const node = new Node(key, events, this.head);
36
+ this.head.prev = node;
37
+ this.head = node;
38
+ }
39
+ // update cacheMap with LinkedList key and Node reference
40
+ this.cacheMap[key] = this.head;
41
+ this.size++;
42
+ }
43
+ has(key) {
44
+ return this.cacheMap.hasOwnProperty(key);
45
+ }
46
+ get(key) {
47
+ var _a;
48
+ return (_a = this.cacheMap[key]) === null || _a === void 0 ? void 0 : _a.value;
49
+ }
50
+ detach(node) {
51
+ if (node.prev !== undefined) {
52
+ node.prev.next = node.next;
53
+ }
54
+ else {
55
+ this.head = node.next;
56
+ }
57
+ if (node.next !== undefined) {
58
+ node.next.prev = node.prev;
59
+ }
60
+ else {
61
+ this.tail = node.prev;
62
+ }
63
+ }
64
+ clear() {
65
+ this.head = undefined;
66
+ this.tail = undefined;
67
+ this.size = 0;
68
+ this.cacheMap = {};
69
+ }
70
+ }
71
+ exports.TxEventCache = TxEventCache;
@@ -4,7 +4,9 @@ import {
4
4
  FundingPaymentRecord,
5
5
  FundingRateRecord,
6
6
  LiquidationRecord,
7
+ NewUserRecord,
7
8
  OrderRecord,
9
+ SettlePnlRecord,
8
10
  } from '../index';
9
11
 
10
12
  export type EventSubscriptionOptions = {
@@ -27,6 +29,8 @@ export const DefaultEventSubscriptionOptions: EventSubscriptionOptions = {
27
29
  'LiquidationRecord',
28
30
  'OrderRecord',
29
31
  'FundingRateRecord',
32
+ 'NewUserRecord',
33
+ 'SettlePnlRecord',
30
34
  ],
31
35
  maxEventsPerType: 4096,
32
36
  orderBy: 'blockchain',
@@ -59,6 +63,8 @@ export type EventMap = {
59
63
  LiquidationRecord: Event<LiquidationRecord>;
60
64
  FundingRateRecord: Event<FundingRateRecord>;
61
65
  OrderRecord: Event<OrderRecord>;
66
+ SettlePnlRecord: Event<SettlePnlRecord>;
67
+ NewUserRecord: Event<NewUserRecord>;
62
68
  };
63
69
 
64
70
  export type EventType = keyof EventMap;