@drift-labs/sdk 0.2.0-master.15 → 0.2.0-master.18

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/accounts/types.d.ts +1 -0
  2. package/lib/constants/numericConstants.d.ts +2 -0
  3. package/lib/constants/numericConstants.js +5 -3
  4. package/lib/events/types.js +1 -0
  5. package/lib/index.d.ts +5 -0
  6. package/lib/index.js +5 -0
  7. package/lib/math/position.js +1 -1
  8. package/lib/types.d.ts +2 -0
  9. package/package.json +1 -1
  10. package/src/addresses/marketAddresses.js +26 -0
  11. package/src/assert/assert.js +9 -0
  12. package/src/constants/banks.js +42 -0
  13. package/src/constants/markets.js +42 -0
  14. package/src/constants/numericConstants.js +41 -0
  15. package/src/constants/numericConstants.ts +10 -2
  16. package/src/events/eventList.js +77 -0
  17. package/src/events/eventSubscriber.js +139 -0
  18. package/src/events/fetchLogs.js +50 -0
  19. package/src/events/pollingLogProvider.js +64 -0
  20. package/src/events/sort.js +44 -0
  21. package/src/events/txEventCache.js +71 -0
  22. package/src/events/types.js +20 -0
  23. package/src/events/types.ts +1 -0
  24. package/src/events/webSocketLogProvider.js +41 -0
  25. package/src/examples/makeTradeExample.js +80 -0
  26. package/src/factory/bigNum.js +390 -0
  27. package/src/factory/oracleClient.js +20 -0
  28. package/src/index.ts +5 -0
  29. package/src/math/amm.js +369 -0
  30. package/src/math/auction.js +42 -0
  31. package/src/math/conversion.js +11 -0
  32. package/src/math/funding.js +248 -0
  33. package/src/math/oracles.js +26 -0
  34. package/src/math/position.ts +1 -1
  35. package/src/math/repeg.js +128 -0
  36. package/src/math/state.js +15 -0
  37. package/src/math/trade.js +253 -0
  38. package/src/math/utils.js +26 -0
  39. package/src/math/utils.js.map +1 -0
  40. package/src/oracles/oracleClientCache.js +19 -0
  41. package/src/oracles/pythClient.js +46 -0
  42. package/src/oracles/quoteAssetOracleClient.js +32 -0
  43. package/src/oracles/switchboardClient.js +69 -0
  44. package/src/oracles/types.js +2 -0
  45. package/src/orderParams.js +20 -0
  46. package/src/slot/SlotSubscriber.js +39 -0
  47. package/src/token/index.js +38 -0
  48. package/src/tokenFaucet.js +189 -0
  49. package/src/tx/types.js +2 -0
  50. package/src/tx/utils.js +17 -0
  51. package/src/types.js +125 -0
  52. package/src/types.ts +2 -0
  53. package/src/userName.js +20 -0
  54. package/src/util/computeUnits.js +27 -0
  55. package/src/util/getTokenAddress.js +9 -0
  56. package/src/util/promiseTimeout.js +14 -0
  57. package/src/util/tps.js +27 -0
  58. package/src/wallet.js +35 -0
@@ -1,5 +1,6 @@
1
1
  /// <reference types="node" />
2
2
  /// <reference types="bn.js" />
3
+ /// <reference types="node" />
3
4
  import { BankAccount, MarketAccount, OracleSource, StateAccount, UserAccount, UserStatsAccount } from '../types';
4
5
  import StrictEventEmitter from 'strict-event-emitter-types';
5
6
  import { EventEmitter } from 'events';
@@ -14,7 +14,9 @@ export declare const MARK_PRICE_PRECISION_EXP: BN;
14
14
  export declare const FUNDING_RATE_PRECISION_EXP: BN;
15
15
  export declare const PEG_PRECISION_EXP: BN;
16
16
  export declare const AMM_RESERVE_PRECISION_EXP: BN;
17
+ export declare const BANK_INTEREST_PRECISION_EXP: BN;
17
18
  export declare const BANK_INTEREST_PRECISION: BN;
19
+ export declare const BANK_CUMULATIVE_INTEREST_PRECISION_EXP: BN;
18
20
  export declare const BANK_CUMULATIVE_INTEREST_PRECISION: BN;
19
21
  export declare const BANK_UTILIZATION_PRECISION: BN;
20
22
  export declare const BANK_RATE_PRECISION: BN;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
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_IMF_PRECISION = exports.BANK_IMF_PRECISION_EXP = 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;
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_IMF_PRECISION = exports.BANK_IMF_PRECISION_EXP = 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_CUMULATIVE_INTEREST_PRECISION_EXP = exports.BANK_INTEREST_PRECISION = exports.BANK_INTEREST_PRECISION_EXP = 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
4
  const __1 = require("../");
5
5
  exports.ZERO = new __1.BN(0);
6
6
  exports.ONE = new __1.BN(1);
@@ -16,8 +16,10 @@ exports.MARK_PRICE_PRECISION_EXP = new __1.BN(10);
16
16
  exports.FUNDING_RATE_PRECISION_EXP = exports.MARK_PRICE_PRECISION_EXP.mul(exports.FUNDING_PAYMENT_PRECISION_EXP);
17
17
  exports.PEG_PRECISION_EXP = new __1.BN(3);
18
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);
19
+ exports.BANK_INTEREST_PRECISION_EXP = new __1.BN(6);
20
+ exports.BANK_INTEREST_PRECISION = new __1.BN(10).pow(exports.BANK_INTEREST_PRECISION_EXP);
21
+ exports.BANK_CUMULATIVE_INTEREST_PRECISION_EXP = new __1.BN(10);
22
+ exports.BANK_CUMULATIVE_INTEREST_PRECISION = new __1.BN(10).pow(exports.BANK_CUMULATIVE_INTEREST_PRECISION_EXP);
21
23
  exports.BANK_UTILIZATION_PRECISION = new __1.BN(1000000);
22
24
  exports.BANK_RATE_PRECISION = new __1.BN(1000000);
23
25
  exports.BANK_WEIGHT_PRECISION = new __1.BN(100);
@@ -8,6 +8,7 @@ exports.DefaultEventSubscriptionOptions = {
8
8
  'LiquidationRecord',
9
9
  'OrderRecord',
10
10
  'FundingRateRecord',
11
+ 'SettlePnlRecord',
11
12
  ],
12
13
  maxEventsPerType: 4096,
13
14
  orderBy: 'blockchain',
package/lib/index.d.ts CHANGED
@@ -11,14 +11,19 @@ export * from './accounts/fetch';
11
11
  export * from './accounts/webSocketClearingHouseAccountSubscriber';
12
12
  export * from './accounts/bulkAccountLoader';
13
13
  export * from './accounts/bulkUserSubscription';
14
+ export * from './accounts/bulkUserStatsSubscription';
14
15
  export * from './accounts/pollingClearingHouseAccountSubscriber';
15
16
  export * from './accounts/pollingOracleSubscriber';
16
17
  export * from './accounts/pollingTokenAccountSubscriber';
18
+ export * from './accounts/pollingUserAccountSubscriber';
19
+ export * from './accounts/pollingUserStatsAccountSubscriber';
17
20
  export * from './accounts/types';
18
21
  export * from './addresses/pda';
19
22
  export * from './admin';
20
23
  export * from './clearingHouseUser';
21
24
  export * from './clearingHouseUserConfig';
25
+ export * from './clearingHouseUserStats';
26
+ export * from './clearingHouseUserStatsConfig';
22
27
  export * from './clearingHouse';
23
28
  export * from './factory/oracleClient';
24
29
  export * from './factory/bigNum';
package/lib/index.js CHANGED
@@ -34,14 +34,19 @@ __exportStar(require("./accounts/fetch"), exports);
34
34
  __exportStar(require("./accounts/webSocketClearingHouseAccountSubscriber"), exports);
35
35
  __exportStar(require("./accounts/bulkAccountLoader"), exports);
36
36
  __exportStar(require("./accounts/bulkUserSubscription"), exports);
37
+ __exportStar(require("./accounts/bulkUserStatsSubscription"), exports);
37
38
  __exportStar(require("./accounts/pollingClearingHouseAccountSubscriber"), exports);
38
39
  __exportStar(require("./accounts/pollingOracleSubscriber"), exports);
39
40
  __exportStar(require("./accounts/pollingTokenAccountSubscriber"), exports);
41
+ __exportStar(require("./accounts/pollingUserAccountSubscriber"), exports);
42
+ __exportStar(require("./accounts/pollingUserStatsAccountSubscriber"), exports);
40
43
  __exportStar(require("./accounts/types"), exports);
41
44
  __exportStar(require("./addresses/pda"), exports);
42
45
  __exportStar(require("./admin"), exports);
43
46
  __exportStar(require("./clearingHouseUser"), exports);
44
47
  __exportStar(require("./clearingHouseUserConfig"), exports);
48
+ __exportStar(require("./clearingHouseUserStats"), exports);
49
+ __exportStar(require("./clearingHouseUserStatsConfig"), exports);
45
50
  __exportStar(require("./clearingHouse"), exports);
46
51
  __exportStar(require("./factory/oracleClient"), exports);
47
52
  __exportStar(require("./factory/bigNum"), exports);
@@ -81,7 +81,7 @@ function calculateUnsettledPnl(market, marketPosition, oraclePriceData) {
81
81
  if (unrealizedPnl.gt(numericConstants_1.ZERO)) {
82
82
  const fundingPnL = calculatePositionFundingPNL(market, marketPosition).div(numericConstants_1.PRICE_TO_QUOTE_PRECISION);
83
83
  const maxPositivePnl = __1.BN.max(marketPosition.quoteAssetAmount
84
- .add(marketPosition.quoteEntryAmount)
84
+ .sub(marketPosition.quoteEntryAmount)
85
85
  .add(fundingPnL), numericConstants_1.ZERO);
86
86
  unsettledPnl = __1.BN.min(maxPositivePnl, unrealizedPnl);
87
87
  }
package/lib/types.d.ts CHANGED
@@ -470,6 +470,8 @@ export declare type UserStatsAccount = {
470
470
  totalReferralReward: BN;
471
471
  totalRefereeDiscount: BN;
472
472
  };
473
+ authority: PublicKey;
474
+ referrer: PublicKey;
473
475
  };
474
476
  export declare type UserAccount = {
475
477
  authority: PublicKey;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/sdk",
3
- "version": "0.2.0-master.15",
3
+ "version": "0.2.0-master.18",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "author": "crispheaney",
@@ -0,0 +1,26 @@
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.getMarketAddress = void 0;
13
+ const pda_1 = require("./pda");
14
+ const CACHE = new Map();
15
+ function getMarketAddress(programId, marketIndex) {
16
+ return __awaiter(this, void 0, void 0, function* () {
17
+ const cacheKey = `${programId.toString()}-${marketIndex.toString()}`;
18
+ if (CACHE.has(cacheKey)) {
19
+ return CACHE.get(cacheKey);
20
+ }
21
+ const publicKey = yield pda_1.getMarketPublicKey(programId, marketIndex);
22
+ CACHE.set(cacheKey, publicKey);
23
+ return publicKey;
24
+ });
25
+ }
26
+ exports.getMarketAddress = getMarketAddress;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assert = void 0;
4
+ function assert(condition, error) {
5
+ if (!condition) {
6
+ throw new Error(error || 'Unspecified AssertionError');
7
+ }
8
+ }
9
+ exports.assert = assert;
@@ -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
+ };
@@ -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);
@@ -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;
@@ -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,50 @@
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.fetchLogs = void 0;
13
+ function fetchLogs(connection, programId, finality, beforeTx, untilTx) {
14
+ return __awaiter(this, void 0, void 0, function* () {
15
+ const signatures = yield connection.getSignaturesForAddress(programId, {
16
+ before: beforeTx,
17
+ until: untilTx,
18
+ }, finality);
19
+ const sortedSignatures = signatures.sort((a, b) => a.slot < b.slot ? -1 : 1);
20
+ const filteredSignatures = sortedSignatures.filter((signature) => !signature.err);
21
+ if (filteredSignatures.length === 0) {
22
+ return undefined;
23
+ }
24
+ const chunkedSignatures = chunk(filteredSignatures, 100);
25
+ const transactionLogs = (yield Promise.all(chunkedSignatures.map((chunk) => __awaiter(this, void 0, void 0, function* () {
26
+ const transactions = yield connection.getTransactions(chunk.map((confirmedSignature) => confirmedSignature.signature), finality);
27
+ return transactions.map((transaction) => {
28
+ return {
29
+ txSig: transaction.transaction.signatures[0],
30
+ slot: transaction.slot,
31
+ logs: transaction.meta.logMessages,
32
+ };
33
+ });
34
+ })))).flat();
35
+ const earliestTx = filteredSignatures[0].signature;
36
+ const mostRecentTx = filteredSignatures[filteredSignatures.length - 1].signature;
37
+ return {
38
+ transactionLogs: transactionLogs,
39
+ earliestTx: earliestTx,
40
+ mostRecentTx: mostRecentTx,
41
+ };
42
+ });
43
+ }
44
+ exports.fetchLogs = fetchLogs;
45
+ function chunk(array, size) {
46
+ return new Array(Math.ceil(array.length / size))
47
+ .fill(null)
48
+ .map((_, index) => index * size)
49
+ .map((begin) => array.slice(begin, begin + size));
50
+ }
@@ -0,0 +1,64 @@
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.PollingLogProvider = void 0;
13
+ const fetchLogs_1 = require("./fetchLogs");
14
+ class PollingLogProvider {
15
+ constructor(connection, programId, commitment, frequency = 15 * 1000) {
16
+ this.connection = connection;
17
+ this.programId = programId;
18
+ this.frequency = frequency;
19
+ this.finality = commitment === 'finalized' ? 'finalized' : 'confirmed';
20
+ }
21
+ subscribe(callback) {
22
+ if (this.intervalId) {
23
+ return true;
24
+ }
25
+ this.intervalId = setInterval(() => __awaiter(this, void 0, void 0, function* () {
26
+ if (this.mutex === 1) {
27
+ return;
28
+ }
29
+ this.mutex = 1;
30
+ try {
31
+ const response = yield fetchLogs_1.fetchLogs(this.connection, this.programId, this.finality, undefined, this.mostRecentSeenTx);
32
+ if (response === undefined) {
33
+ return;
34
+ }
35
+ const { mostRecentTx, transactionLogs } = response;
36
+ for (const { txSig, slot, logs } of transactionLogs) {
37
+ callback(txSig, slot, logs);
38
+ }
39
+ this.mostRecentSeenTx = mostRecentTx;
40
+ }
41
+ catch (e) {
42
+ console.error('PollingLogProvider threw an Error');
43
+ console.error(e);
44
+ }
45
+ finally {
46
+ this.mutex = 0;
47
+ }
48
+ }), this.frequency);
49
+ return true;
50
+ }
51
+ isSubscribed() {
52
+ return this.intervalId !== undefined;
53
+ }
54
+ unsubscribe() {
55
+ return __awaiter(this, void 0, void 0, function* () {
56
+ if (this.intervalId !== undefined) {
57
+ clearInterval(this.intervalId);
58
+ this.intervalId = undefined;
59
+ }
60
+ return true;
61
+ });
62
+ }
63
+ }
64
+ exports.PollingLogProvider = PollingLogProvider;