@drift-labs/sdk 0.2.0-master.28 → 0.2.0-master.29

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 (53) hide show
  1. package/lib/accounts/types.d.ts +0 -1
  2. package/lib/admin.d.ts +3 -3
  3. package/lib/admin.js +5 -5
  4. package/lib/clearingHouse.d.ts +5 -0
  5. package/lib/clearingHouse.js +46 -13
  6. package/lib/clearingHouseConfig.d.ts +1 -0
  7. package/lib/clearingHouseUser.js +3 -3
  8. package/lib/config.js +1 -1
  9. package/lib/idl/clearing_house.json +122 -94
  10. package/lib/math/insurance.js +1 -1
  11. package/lib/types.d.ts +21 -38
  12. package/package.json +1 -1
  13. package/src/addresses/marketAddresses.js +26 -0
  14. package/src/admin.ts +14 -20
  15. package/src/assert/assert.js +9 -0
  16. package/src/clearingHouse.ts +74 -8
  17. package/src/clearingHouseConfig.ts +1 -0
  18. package/src/clearingHouseUser.ts +4 -4
  19. package/src/config.ts +1 -1
  20. package/src/constants/banks.js +42 -0
  21. package/src/constants/markets.js +42 -0
  22. package/src/events/eventList.js +77 -0
  23. package/src/events/txEventCache.js +71 -0
  24. package/src/examples/makeTradeExample.js +157 -0
  25. package/src/factory/bigNum.js +390 -0
  26. package/src/factory/oracleClient.js +20 -0
  27. package/src/idl/clearing_house.json +122 -94
  28. package/src/math/auction.js +42 -0
  29. package/src/math/conversion.js +11 -0
  30. package/src/math/funding.js +248 -0
  31. package/src/math/insurance.ts +2 -2
  32. package/src/math/repeg.js +128 -0
  33. package/src/math/trade.js +253 -0
  34. package/src/math/utils.js +26 -0
  35. package/src/math/utils.js.map +1 -0
  36. package/src/oracles/oracleClientCache.js +19 -0
  37. package/src/oracles/pythClient.js +46 -0
  38. package/src/oracles/quoteAssetOracleClient.js +32 -0
  39. package/src/oracles/switchboardClient.js +69 -0
  40. package/src/oracles/types.js +2 -0
  41. package/src/token/index.js +38 -0
  42. package/src/tx/types.js +2 -0
  43. package/src/tx/utils.js +17 -0
  44. package/src/types.ts +23 -39
  45. package/src/userName.js +20 -0
  46. package/src/util/computeUnits.js +27 -0
  47. package/src/util/getTokenAddress.js +9 -0
  48. package/src/util/promiseTimeout.js +14 -0
  49. package/src/util/tps.js +27 -0
  50. package/src/wallet.js +35 -0
  51. package/lib/math/state.d.ts +0 -8
  52. package/lib/math/state.js +0 -15
  53. package/src/math/state.ts +0 -14
package/lib/types.d.ts CHANGED
@@ -419,8 +419,6 @@ export declare type StateAccount = {
419
419
  exchangePaused: boolean;
420
420
  adminControlsPrices: boolean;
421
421
  insuranceVault: PublicKey;
422
- perpFeeStructure: FeeStructure;
423
- spotFeeStructure: FeeStructure;
424
422
  totalFee: BN;
425
423
  totalFeeWithdrawn: BN;
426
424
  whitelistMint: PublicKey;
@@ -436,6 +434,8 @@ export declare type StateAccount = {
436
434
  minPerpAuctionDuration: number;
437
435
  defaultSpotAuctionDuration: number;
438
436
  liquidationMarginBufferRatio: number;
437
+ perpFeeStructure: FeeStructure;
438
+ spotFeeStructure: FeeStructure;
439
439
  };
440
440
  export declare type PerpMarketAccount = {
441
441
  status: MarketStatus;
@@ -605,10 +605,11 @@ export declare type UserStatsAccount = {
605
605
  isReferrer: boolean;
606
606
  totalReferrerReward: BN;
607
607
  authority: PublicKey;
608
- quoteAssetInsuranceFundStake: BN;
608
+ stakedQuoteAssetAmount: BN;
609
609
  };
610
610
  export declare type UserAccount = {
611
611
  authority: PublicKey;
612
+ delegate: PublicKey;
612
613
  name: number[];
613
614
  userId: number;
614
615
  spotPositions: SpotPosition[];
@@ -733,40 +734,27 @@ export interface IWallet {
733
734
  publicKey: PublicKey;
734
735
  }
735
736
  export declare type FeeStructure = {
736
- feeNumerator: BN;
737
- feeDenominator: BN;
738
- discountTokenTiers: {
739
- firstTier: {
740
- minimumBalance: BN;
741
- discountNumerator: BN;
742
- discountDenominator: BN;
743
- };
744
- secondTier: {
745
- minimumBalance: BN;
746
- discountNumerator: BN;
747
- discountDenominator: BN;
748
- };
749
- thirdTier: {
750
- minimumBalance: BN;
751
- discountNumerator: BN;
752
- discountDenominator: BN;
753
- };
754
- fourthTier: {
755
- minimumBalance: BN;
756
- discountNumerator: BN;
757
- discountDenominator: BN;
758
- };
759
- };
760
- referralDiscount: {
761
- referrerRewardNumerator: BN;
762
- referrerRewardDenominator: BN;
763
- refereeDiscountNumerator: BN;
764
- refereeDiscountDenominator: BN;
765
- };
737
+ feeTiers: FeeTier[];
766
738
  makerRebateNumerator: BN;
767
739
  makerRebateDenominator: BN;
768
740
  fillerRewardStructure: OrderFillerRewardStructure;
769
741
  flatFillerFee: BN;
742
+ referrerRewardEpochUpperBound: BN;
743
+ };
744
+ export declare type FeeTier = {
745
+ feeNumerator: number;
746
+ feeDenominator: number;
747
+ makerRebateNumerator: number;
748
+ makerRebateDenominator: number;
749
+ referrerRewardNumerator: number;
750
+ referrerRewardDenominator: number;
751
+ refereeFeeNumerator: number;
752
+ refereeFeeDenominator: number;
753
+ };
754
+ export declare type OrderFillerRewardStructure = {
755
+ rewardNumerator: BN;
756
+ rewardDenominator: BN;
757
+ timeBasedRewardLowerBound: BN;
770
758
  };
771
759
  export declare type OracleGuardRails = {
772
760
  priceDivergence: {
@@ -780,11 +768,6 @@ export declare type OracleGuardRails = {
780
768
  };
781
769
  useForLiquidations: boolean;
782
770
  };
783
- export declare type OrderFillerRewardStructure = {
784
- rewardNumerator: BN;
785
- rewardDenominator: BN;
786
- timeBasedRewardLowerBound: BN;
787
- };
788
771
  export declare type MarginCategory = 'Initial' | 'Maintenance';
789
772
  export declare type InsuranceFundStake = {
790
773
  marketIndex: BN;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/sdk",
3
- "version": "0.2.0-master.28",
3
+ "version": "0.2.0-master.29",
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;
package/src/admin.ts CHANGED
@@ -3,12 +3,7 @@ import {
3
3
  SYSVAR_RENT_PUBKEY,
4
4
  TransactionSignature,
5
5
  } from '@solana/web3.js';
6
- import {
7
- FeeStructure,
8
- OracleGuardRails,
9
- OracleSource,
10
- OrderFillerRewardStructure,
11
- } from './types';
6
+ import { FeeStructure, OracleGuardRails, OracleSource } from './types';
12
7
  import { BN } from '@project-serum/anchor';
13
8
  import * as anchor from '@project-serum/anchor';
14
9
  import {
@@ -278,7 +273,7 @@ export class Admin extends ClearingHouse {
278
273
  marketIndex: BN,
279
274
  concentrationScale: BN
280
275
  ): Promise<TransactionSignature> {
281
- return await this.program.rpc.updateConcentrationScale(concentrationScale, {
276
+ return await this.program.rpc.updateConcentrationCoef(concentrationScale, {
282
277
  accounts: {
283
278
  state: await this.getStatePublicKey(),
284
279
  admin: this.wallet.publicKey,
@@ -611,22 +606,21 @@ export class Admin extends ClearingHouse {
611
606
  );
612
607
  }
613
608
 
614
- public async updateOrderFillerRewardStructure(
615
- orderFillerRewardStructure: OrderFillerRewardStructure
609
+ public async updatePerpFeeStructure(
610
+ feeStructure: FeeStructure
616
611
  ): Promise<TransactionSignature> {
617
- return await this.program.rpc.updateOrderFillerRewardStructure(
618
- orderFillerRewardStructure,
619
- {
620
- accounts: {
621
- admin: this.wallet.publicKey,
622
- state: await this.getStatePublicKey(),
623
- },
624
- }
625
- );
612
+ return await this.program.rpc.updatePerpFeeStructure(feeStructure, {
613
+ accounts: {
614
+ admin: this.wallet.publicKey,
615
+ state: await this.getStatePublicKey(),
616
+ },
617
+ });
626
618
  }
627
619
 
628
- public async updateFee(fees: FeeStructure): Promise<TransactionSignature> {
629
- return await this.program.rpc.updateFee(fees, {
620
+ public async updateSpotFeeStructure(
621
+ feeStructure: FeeStructure
622
+ ): Promise<TransactionSignature> {
623
+ return await this.program.rpc.updateSpotFeeStructure(feeStructure, {
630
624
  accounts: {
631
625
  admin: this.wallet.publicKey,
632
626
  state: await this.getStatePublicKey(),
@@ -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;
@@ -1,5 +1,10 @@
1
1
  import { AnchorProvider, BN, Idl, Program } from '@project-serum/anchor';
2
- import { Token, TOKEN_PROGRAM_ID } from '@solana/spl-token';
2
+ import bs58 from 'bs58';
3
+ import {
4
+ ASSOCIATED_TOKEN_PROGRAM_ID,
5
+ Token,
6
+ TOKEN_PROGRAM_ID,
7
+ } from '@solana/spl-token';
3
8
  import {
4
9
  StateAccount,
5
10
  IWallet,
@@ -97,6 +102,7 @@ export class ClearingHouse {
97
102
  _isSubscribed = false;
98
103
  txSender: TxSender;
99
104
  marketLastSlotCache = new Map<number, number>();
105
+ authority: PublicKey;
100
106
 
101
107
  public get isSubscribed() {
102
108
  return this._isSubscribed && this.accountSubscriber.isSubscribed;
@@ -121,6 +127,7 @@ export class ClearingHouse {
121
127
  this.provider
122
128
  );
123
129
 
130
+ this.authority = config.authority ?? this.wallet.publicKey;
124
131
  const userIds = config.userIds ?? [0];
125
132
  this.activeUserId = config.activeUserId ?? userIds[0];
126
133
  this.userAccountSubscriptionConfig =
@@ -138,7 +145,7 @@ export class ClearingHouse {
138
145
  clearingHouse: this,
139
146
  userStatsAccountPublicKey: getUserStatsAccountPublicKey(
140
147
  this.program.programId,
141
- this.wallet.publicKey
148
+ this.authority
142
149
  ),
143
150
  accountSubscription: this.userAccountSubscriptionConfig,
144
151
  });
@@ -203,7 +210,7 @@ export class ClearingHouse {
203
210
  ): ClearingHouseUser {
204
211
  const userAccountPublicKey = getUserAccountPublicKeySync(
205
212
  this.program.programId,
206
- this.wallet.publicKey,
213
+ this.authority,
207
214
  userId
208
215
  );
209
216
 
@@ -494,6 +501,36 @@ export class ClearingHouse {
494
501
  );
495
502
  }
496
503
 
504
+ public async updateUserDelegate(
505
+ delegate: PublicKey,
506
+ userId = 0
507
+ ): Promise<TransactionSignature> {
508
+ return await this.program.rpc.updateUserDelegate(userId, delegate, {
509
+ accounts: {
510
+ user: await this.getUserAccountPublicKey(),
511
+ authority: this.wallet.publicKey,
512
+ },
513
+ });
514
+ }
515
+
516
+ public async getUserAccountsForDelegate(
517
+ delegate: PublicKey
518
+ ): Promise<UserAccount[]> {
519
+ const programAccounts = await this.program.account.user.all([
520
+ {
521
+ memcmp: {
522
+ offset: 40,
523
+ /** data to match, as base-58 encoded string and limited to less than 129 bytes */
524
+ bytes: bs58.encode(delegate.toBuffer()),
525
+ },
526
+ },
527
+ ]);
528
+
529
+ return programAccounts.map(
530
+ (programAccount) => programAccount.account as UserAccount
531
+ );
532
+ }
533
+
497
534
  public getUser(userId?: number): ClearingHouseUser {
498
535
  userId = userId ?? this.activeUserId;
499
536
  if (!this.users.has(userId)) {
@@ -518,7 +555,7 @@ export class ClearingHouse {
518
555
 
519
556
  this.userStatsAccountPublicKey = getUserStatsAccountPublicKey(
520
557
  this.program.programId,
521
- this.wallet.publicKey
558
+ this.authority
522
559
  );
523
560
  return this.userStatsAccountPublicKey;
524
561
  }
@@ -732,7 +769,7 @@ export class ClearingHouse {
732
769
 
733
770
  const isSolMarket = spotMarketAccount.mint.equals(WRAPPED_SOL_MINT);
734
771
 
735
- const authority = this.wallet.publicKey;
772
+ const authority = this.authority;
736
773
 
737
774
  const createWSOLTokenAccount =
738
775
  isSolMarket && collateralAccountPublicKey.equals(authority);
@@ -793,7 +830,7 @@ export class ClearingHouse {
793
830
  const userAccountPublicKey = userId
794
831
  ? await getUserAccountPublicKey(
795
832
  this.program.programId,
796
- this.wallet.publicKey,
833
+ this.authority,
797
834
  userId
798
835
  )
799
836
  : await this.getUserAccountPublicKey();
@@ -841,10 +878,10 @@ export class ClearingHouse {
841
878
  );
842
879
  }
843
880
 
844
- private async checkIfAccountExists(account: PublicKey) {
881
+ private async checkIfAccountExists(account: PublicKey): Promise<boolean> {
845
882
  try {
846
883
  const accountInfo = await this.connection.getAccountInfo(account);
847
- return accountInfo && true;
884
+ return accountInfo != null;
848
885
  } catch (e) {
849
886
  // Doesn't already exist
850
887
  return false;
@@ -947,6 +984,23 @@ export class ClearingHouse {
947
984
  return result;
948
985
  }
949
986
 
987
+ public getAssociatedTokenAccountCreationIx(
988
+ tokenMintAddress: PublicKey,
989
+ associatedTokenAddress: PublicKey
990
+ ): anchor.web3.TransactionInstruction {
991
+ const createAssociatedAccountIx =
992
+ Token.createAssociatedTokenAccountInstruction(
993
+ ASSOCIATED_TOKEN_PROGRAM_ID,
994
+ TOKEN_PROGRAM_ID,
995
+ tokenMintAddress,
996
+ associatedTokenAddress,
997
+ this.wallet.publicKey,
998
+ this.wallet.publicKey
999
+ );
1000
+
1001
+ return createAssociatedAccountIx;
1002
+ }
1003
+
950
1004
  /**
951
1005
  * Creates the Clearing House User account for a user, and deposits some initial collateral
952
1006
  * @param amount
@@ -1109,6 +1163,18 @@ export class ClearingHouse {
1109
1163
  });
1110
1164
 
1111
1165
  signers.forEach((signer) => additionalSigners.push(signer));
1166
+ } else {
1167
+ const accountExists = await this.checkIfAccountExists(userTokenAccount);
1168
+
1169
+ if (!accountExists) {
1170
+ const createAssociatedTokenAccountIx =
1171
+ this.getAssociatedTokenAccountCreationIx(
1172
+ spotMarketAccount.mint,
1173
+ userTokenAccount
1174
+ );
1175
+
1176
+ tx.add(createAssociatedTokenAccountIx);
1177
+ }
1112
1178
  }
1113
1179
 
1114
1180
  const withdrawCollateral = await this.getWithdrawIx(
@@ -19,6 +19,7 @@ export type ClearingHouseConfig = {
19
19
  oracleInfos?: OracleInfo[];
20
20
  env?: DriftEnv;
21
21
  userStats?: boolean;
22
+ authority?: PublicKey; // explicitly pass an authority if signer is delegate
22
23
  };
23
24
 
24
25
  type ClearingHouseSubscriptionConfig =
@@ -1395,11 +1395,11 @@ export class ClearingHouseUser {
1395
1395
  * @returns feeForQuote : Precision QUOTE_PRECISION
1396
1396
  */
1397
1397
  public calculateFeeForQuoteAmount(quoteAmount: BN): BN {
1398
- const feeStructure = this.clearingHouse.getStateAccount().perpFeeStructure;
1399
-
1398
+ const feeTier =
1399
+ this.clearingHouse.getStateAccount().perpFeeStructure.feeTiers[0];
1400
1400
  return quoteAmount
1401
- .mul(feeStructure.feeNumerator)
1402
- .div(feeStructure.feeDenominator);
1401
+ .mul(new BN(feeTier.feeNumerator))
1402
+ .div(new BN(feeTier.feeDenominator));
1403
1403
  }
1404
1404
 
1405
1405
  /**
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: 'CUowJP5Dea7pkc2mKrkX2RuZUrPXL3u419iBRXyZEWQz',
31
+ CLEARING_HOUSE_PROGRAM_ID: '6MVFno8SFkVffGuCCQzg2wi8FvF8sPRFDNHa13ZPP9cK',
32
32
  USDC_MINT_ADDRESS: '8zGuJQqwhZafTah7Uc7Z4tXRnguqkn5KLFAP8oV6PHe2',
33
33
  PERP_MARKETS: DevnetPerpMarkets,
34
34
  SPOT_MARKETS: DevnetSpotMarkets,
@@ -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,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,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;