@drift-labs/sdk 0.2.0-master.32 → 0.2.0-master.33

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 (108) hide show
  1. package/lib/accounts/bulkAccountLoader.js +2 -1
  2. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +2 -2
  3. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +8 -8
  4. package/lib/accounts/types.d.ts +1 -0
  5. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +2 -2
  6. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +7 -7
  7. package/lib/addresses/marketAddresses.js +1 -1
  8. package/lib/addresses/pda.d.ts +4 -4
  9. package/lib/addresses/pda.js +23 -22
  10. package/lib/admin.d.ts +30 -32
  11. package/lib/admin.js +111 -119
  12. package/lib/clearingHouse.d.ts +43 -34
  13. package/lib/clearingHouse.js +353 -193
  14. package/lib/clearingHouseConfig.d.ts +2 -2
  15. package/lib/clearingHouseUser.d.ts +26 -5
  16. package/lib/clearingHouseUser.js +151 -51
  17. package/lib/config.d.ts +2 -0
  18. package/lib/config.js +5 -1
  19. package/lib/constants/numericConstants.d.ts +1 -0
  20. package/lib/constants/numericConstants.js +3 -2
  21. package/lib/dlob/DLOB.d.ts +18 -11
  22. package/lib/dlob/DLOB.js +179 -107
  23. package/lib/dlob/DLOBNode.js +2 -10
  24. package/lib/dlob/NodeList.js +1 -1
  25. package/lib/events/eventSubscriber.d.ts +1 -0
  26. package/lib/events/eventSubscriber.js +11 -4
  27. package/lib/events/fetchLogs.d.ts +3 -1
  28. package/lib/events/fetchLogs.js +13 -5
  29. package/lib/events/pollingLogProvider.js +1 -1
  30. package/lib/events/types.d.ts +1 -1
  31. package/lib/events/webSocketLogProvider.js +1 -1
  32. package/lib/factory/bigNum.d.ts +5 -4
  33. package/lib/factory/bigNum.js +36 -6
  34. package/lib/idl/clearing_house.json +1527 -1242
  35. package/lib/index.d.ts +3 -0
  36. package/lib/index.js +3 -0
  37. package/lib/math/amm.js +9 -9
  38. package/lib/math/exchangeStatus.d.ts +4 -0
  39. package/lib/math/exchangeStatus.js +18 -0
  40. package/lib/math/funding.js +10 -10
  41. package/lib/math/margin.js +6 -1
  42. package/lib/math/market.js +9 -9
  43. package/lib/math/orders.d.ts +7 -3
  44. package/lib/math/orders.js +39 -31
  45. package/lib/math/repeg.js +3 -3
  46. package/lib/math/spotBalance.js +3 -3
  47. package/lib/math/spotPosition.js +2 -2
  48. package/lib/serum/serumFulfillmentConfigMap.d.ts +10 -0
  49. package/lib/serum/serumFulfillmentConfigMap.js +17 -0
  50. package/lib/serum/serumSubscriber.d.ts +4 -0
  51. package/lib/serum/serumSubscriber.js +16 -1
  52. package/lib/types.d.ts +60 -75
  53. package/lib/types.js +2 -1
  54. package/lib/userMap/userMap.d.ts +17 -1
  55. package/lib/userMap/userMap.js +12 -0
  56. package/lib/userName.d.ts +1 -0
  57. package/lib/userName.js +3 -2
  58. package/package.json +1 -1
  59. package/src/accounts/bulkAccountLoader.ts +5 -1
  60. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +9 -9
  61. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +8 -8
  62. package/src/addresses/marketAddresses.ts +2 -2
  63. package/src/addresses/pda.ts +20 -20
  64. package/src/admin.ts +246 -221
  65. package/src/assert/assert.js +9 -0
  66. package/src/clearingHouse.ts +556 -236
  67. package/src/clearingHouseConfig.ts +2 -2
  68. package/src/clearingHouseUser.ts +237 -87
  69. package/src/config.ts +8 -1
  70. package/src/constants/numericConstants.ts +5 -1
  71. package/src/dlob/DLOB.ts +257 -120
  72. package/src/dlob/DLOBNode.ts +2 -14
  73. package/src/dlob/NodeList.ts +1 -1
  74. package/src/events/eventList.js +77 -0
  75. package/src/events/eventSubscriber.ts +18 -4
  76. package/src/events/fetchLogs.ts +20 -5
  77. package/src/events/pollingLogProvider.ts +1 -1
  78. package/src/events/types.ts +2 -1
  79. package/src/events/webSocketLogProvider.ts +1 -1
  80. package/src/examples/makeTradeExample.js +157 -0
  81. package/src/factory/bigNum.ts +59 -6
  82. package/src/idl/clearing_house.json +1527 -1242
  83. package/src/idl/pyth.json +98 -2
  84. package/src/index.ts +3 -0
  85. package/src/math/amm.ts +9 -9
  86. package/src/math/exchangeStatus.ts +31 -0
  87. package/src/math/funding.ts +20 -10
  88. package/src/math/margin.ts +7 -1
  89. package/src/math/market.ts +9 -9
  90. package/src/math/orders.ts +44 -29
  91. package/src/math/repeg.ts +3 -3
  92. package/src/math/spotBalance.ts +4 -4
  93. package/src/math/spotPosition.ts +2 -2
  94. package/src/serum/serumFulfillmentConfigMap.ts +26 -0
  95. package/src/serum/serumSubscriber.ts +20 -1
  96. package/src/token/index.js +38 -0
  97. package/src/tx/types.js +2 -0
  98. package/src/tx/utils.js +17 -0
  99. package/src/types.ts +65 -51
  100. package/src/userMap/userMap.ts +25 -1
  101. package/src/userName.ts +2 -1
  102. package/src/util/computeUnits.js +27 -0
  103. package/src/util/getTokenAddress.js +9 -0
  104. package/src/util/promiseTimeout.js +14 -0
  105. package/src/util/tps.js +27 -0
  106. package/tests/bn/test.ts +22 -1
  107. package/tests/dlob/helpers.ts +252 -81
  108. package/tests/dlob/test.ts +1040 -219
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseTokenAccount = void 0;
4
+ const spl_token_1 = require("@solana/spl-token");
5
+ const web3_js_1 = require("@solana/web3.js");
6
+ function parseTokenAccount(data) {
7
+ const accountInfo = spl_token_1.AccountLayout.decode(data);
8
+ accountInfo.mint = new web3_js_1.PublicKey(accountInfo.mint);
9
+ accountInfo.owner = new web3_js_1.PublicKey(accountInfo.owner);
10
+ accountInfo.amount = spl_token_1.u64.fromBuffer(accountInfo.amount);
11
+ if (accountInfo.delegateOption === 0) {
12
+ accountInfo.delegate = null;
13
+ // eslint-disable-next-line new-cap
14
+ accountInfo.delegatedAmount = new spl_token_1.u64(0);
15
+ }
16
+ else {
17
+ accountInfo.delegate = new web3_js_1.PublicKey(accountInfo.delegate);
18
+ accountInfo.delegatedAmount = spl_token_1.u64.fromBuffer(accountInfo.delegatedAmount);
19
+ }
20
+ accountInfo.isInitialized = accountInfo.state !== 0;
21
+ accountInfo.isFrozen = accountInfo.state === 2;
22
+ if (accountInfo.isNativeOption === 1) {
23
+ accountInfo.rentExemptReserve = spl_token_1.u64.fromBuffer(accountInfo.isNative);
24
+ accountInfo.isNative = true;
25
+ }
26
+ else {
27
+ accountInfo.rentExemptReserve = null;
28
+ accountInfo.isNative = false;
29
+ }
30
+ if (accountInfo.closeAuthorityOption === 0) {
31
+ accountInfo.closeAuthority = null;
32
+ }
33
+ else {
34
+ accountInfo.closeAuthority = new web3_js_1.PublicKey(accountInfo.closeAuthority);
35
+ }
36
+ return accountInfo;
37
+ }
38
+ exports.parseTokenAccount = parseTokenAccount;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.wrapInTx = void 0;
4
+ const web3_js_1 = require("@solana/web3.js");
5
+ const COMPUTE_UNITS_DEFAULT = 200000;
6
+ function wrapInTx(instruction, computeUnits = 600000 // TODO, requires less code change
7
+ ) {
8
+ const tx = new web3_js_1.Transaction();
9
+ if (computeUnits != COMPUTE_UNITS_DEFAULT) {
10
+ tx.add(web3_js_1.ComputeBudgetProgram.requestUnits({
11
+ units: computeUnits,
12
+ additionalFee: 0,
13
+ }));
14
+ }
15
+ return tx.add(instruction);
16
+ }
17
+ exports.wrapInTx = wrapInTx;
package/src/types.ts CHANGED
@@ -169,7 +169,7 @@ export type NewUserRecord = {
169
169
  ts: BN;
170
170
  userAuthority: PublicKey;
171
171
  user: PublicKey;
172
- userId: number;
172
+ subAccount: number;
173
173
  name: number[];
174
174
  referrer: PublicKey;
175
175
  };
@@ -266,8 +266,8 @@ export type FundingRateRecord = {
266
266
  oraclePriceTwap: BN;
267
267
  markPriceTwap: BN;
268
268
  periodRevenue: BN;
269
- netBaseAssetAmount: BN;
270
- netUnsettledLpBaseAssetAmount: BN;
269
+ baseAssetAmountWithAmm: BN;
270
+ baseAssetAmountWithUnsettledLp: BN;
271
271
  };
272
272
 
273
273
  export type FundingPaymentRecord = {
@@ -413,7 +413,6 @@ export type OrderActionRecord = {
413
413
  makerOrderBaseAssetAmount: BN | null;
414
414
  makerOrderCumulativeBaseAssetAmountFilled: BN | null;
415
415
  makerOrderCumulativeQuoteAssetAmountFilled: BN | null;
416
- makerOrderFee: BN | null;
417
416
  oraclePrice: BN;
418
417
  };
419
418
 
@@ -425,7 +424,6 @@ export type StateAccount = {
425
424
  oracleGuardRails: OracleGuardRails;
426
425
  numberOfMarkets: number;
427
426
  numberOfSpotMarkets: number;
428
- minOrderQuoteAssetAmount: BN;
429
427
  minPerpAuctionDuration: number;
430
428
  defaultMarketOrderTimeInForce: number;
431
429
  defaultSpotAuctionDuration: number;
@@ -436,20 +434,19 @@ export type StateAccount = {
436
434
  srmVault: PublicKey;
437
435
  perpFeeStructure: FeeStructure;
438
436
  spotFeeStructure: FeeStructure;
437
+ lpCooldownTime: BN;
439
438
  };
440
439
 
441
440
  export type PerpMarketAccount = {
442
441
  status: MarketStatus;
443
442
  contractType: ContractType;
444
443
  expiryTs: BN;
445
- settlementPrice: BN;
444
+ expiryPrice: BN;
446
445
  marketIndex: number;
447
446
  pubkey: PublicKey;
447
+ name: number[];
448
448
  amm: AMM;
449
- baseAssetAmount: BN;
450
- baseAssetAmountLong: BN;
451
- baseAssetAmountShort: BN;
452
- openInterest: BN;
449
+ numberOfUsers: BN;
453
450
  marginRatioInitial: number;
454
451
  marginRatioMaintenance: number;
455
452
  nextFillRecordId: BN;
@@ -457,15 +454,17 @@ export type PerpMarketAccount = {
457
454
  liquidatorFee: BN;
458
455
  ifLiquidationFee: BN;
459
456
  imfFactor: BN;
460
- unrealizedImfFactor: BN;
461
- unrealizedMaxImbalance: BN;
462
- unrealizedInitialAssetWeight: number;
463
- unrealizedMaintenanceAssetWeight: number;
464
- revenueWithdrawSinceLastSettle: BN;
465
- maxRevenueWithdrawPerPeriod: BN;
466
- lastRevenueWithdrawTs: BN;
467
- quoteSettledInsurance: BN;
468
- quoteMaxInsurance: BN;
457
+ unrealizedPnlImfFactor: BN;
458
+ unrealizedPnlMaxImbalance: BN;
459
+ unrealizedPnlInitialAssetWeight: number;
460
+ unrealizedPnlMaintenanceAssetWeight: number;
461
+ insuranceClaim: {
462
+ revenueWithdrawSinceLastSettle: BN;
463
+ maxRevenueWithdrawPerPeriod: BN;
464
+ lastRevenueWithdrawTs: BN;
465
+ quoteSettledInsurance: BN;
466
+ quoteMaxInsurance: BN;
467
+ };
469
468
  };
470
469
 
471
470
  export type HistoricalOracleData = {
@@ -481,7 +480,7 @@ export type HistoricalIndexData = {
481
480
  lastIndexBidPrice: BN;
482
481
  lastIndexAskPrice: BN;
483
482
  lastIndexPriceTwap: BN;
484
- lastIndexPriceTwap5Min: BN;
483
+ lastIndexPriceTwap5min: BN;
485
484
  lastIndexPriceTwapTs: BN;
486
485
  };
487
486
 
@@ -499,15 +498,20 @@ export type SpotMarketAccount = {
499
498
  historicalOracleData: HistoricalOracleData;
500
499
  historicalIndexData: HistoricalIndexData;
501
500
 
502
- insuranceFundVault: PublicKey;
503
- insuranceWithdrawEscrowPeriod: BN;
504
- revenuePool: PoolBalance;
501
+ insuranceFund: {
502
+ vault: PublicKey;
503
+ totalShares: BN;
504
+ userShares: BN;
505
+ sharesBase: BN;
506
+ unstakingPeriod: BN;
507
+ lastRevenueSettleTs: BN;
508
+ revenueSettlePeriod: BN;
509
+ totalFactor: number;
510
+ userFactor: number;
511
+ };
505
512
 
506
- totalIfShares: BN;
507
- userIfShares: BN;
513
+ revenuePool: PoolBalance;
508
514
 
509
- userIfFactor: number;
510
- totalIfFactor: number;
511
515
  ifLiquidationFee: BN;
512
516
 
513
517
  decimals: number;
@@ -535,13 +539,14 @@ export type SpotMarketAccount = {
535
539
  utilizationTwap: BN;
536
540
 
537
541
  orderStepSize: BN;
542
+ orderTickSize: BN;
538
543
  nextFillRecordId: BN;
539
544
  spotFeePool: PoolBalance;
540
545
  totalSpotFee: BN;
541
546
  };
542
547
 
543
548
  export type PoolBalance = {
544
- balance: BN;
549
+ scaledBalance: BN;
545
550
  marketIndex: number;
546
551
  };
547
552
 
@@ -575,14 +580,16 @@ export type AMM = {
575
580
  cumulativeFeePerLp: BN;
576
581
  cumulativeNetBaseAssetAmountPerLp: BN;
577
582
  userLpShares: BN;
578
- netUnsettledLpBaseAssetAmount: BN;
579
- minimumQuoteAssetTradeSize: BN;
580
- baseAssetAmountStepSize: BN;
581
- maxBaseAssetAmountRatio: number;
583
+ baseAssetAmountWithUnsettledLp: BN;
584
+ orderStepSize: BN;
585
+ orderTickSize: BN;
586
+ maxFillReserveFraction: number;
582
587
  maxSlippageRatio: number;
583
588
  baseSpread: number;
584
589
  curveUpdateIntensity: number;
585
- netBaseAssetAmount: BN;
590
+ baseAssetAmountWithAmm: BN;
591
+ baseAssetAmountLong: BN;
592
+ baseAssetAmountShort: BN;
586
593
  quoteAssetAmountLong: BN;
587
594
  quoteAssetAmountShort: BN;
588
595
  terminalQuoteAssetReserve: BN;
@@ -597,8 +604,10 @@ export type AMM = {
597
604
  longSpread: BN;
598
605
  shortSpread: BN;
599
606
  maxSpread: number;
600
- marketPosition: PerpPosition;
601
- marketPositionPerLp: PerpPosition;
607
+
608
+ baseAssetAmountPerLp: BN;
609
+ quoteAssetAmountPerLp: BN;
610
+
602
611
  ammJitIntensity: number;
603
612
  maxBaseAssetReserve: BN;
604
613
  minBaseAssetReserve: BN;
@@ -623,7 +632,7 @@ export type PerpPosition = {
623
632
  };
624
633
 
625
634
  export type UserStatsAccount = {
626
- numberOfUsers: number;
635
+ numberOfSubAccounts: number;
627
636
  makerVolume30D: BN;
628
637
  takerVolume30D: BN;
629
638
  fillerVolume30D: BN;
@@ -635,33 +644,38 @@ export type UserStatsAccount = {
635
644
  totalFeeRebate: BN;
636
645
  totalTokenDiscount: BN;
637
646
  totalRefereeDiscount: BN;
647
+ totalReferrerReward: BN;
648
+ current_epoch_referrer_reward: BN;
638
649
  };
639
650
  referrer: PublicKey;
640
651
  isReferrer: boolean;
641
- totalReferrerReward: BN;
642
652
  authority: PublicKey;
643
- stakedQuoteAssetAmount: BN;
653
+ ifStakedQuoteAssetAmount: BN;
644
654
  };
645
655
 
646
656
  export type UserAccount = {
647
657
  authority: PublicKey;
648
658
  delegate: PublicKey;
649
659
  name: number[];
650
- userId: number;
660
+ subAccountId: number;
651
661
  spotPositions: SpotPosition[];
652
662
  perpPositions: PerpPosition[];
653
663
  orders: Order[];
654
- beingLiquidated: boolean;
655
- bankrupt: boolean;
664
+ isBeingLiquidated: boolean;
665
+ isBankrupt: boolean;
656
666
  nextLiquidationId: number;
657
667
  nextOrderId: number;
658
- customMarginRatio: number;
668
+ maxMarginRatio: number;
669
+ lastAddPerpLpSharesTs: BN;
670
+ settledPerpPnl: BN;
671
+ totalDeposits: BN;
672
+ totalWithdraws: BN;
659
673
  };
660
674
 
661
675
  export type SpotPosition = {
662
676
  marketIndex: number;
663
677
  balanceType: SpotBalanceType;
664
- balance: BN;
678
+ scaledBalance: BN;
665
679
  openOrders: number;
666
680
  openBids: BN;
667
681
  openAsks: BN;
@@ -672,7 +686,6 @@ export type Order = {
672
686
  status: OrderStatus;
673
687
  orderType: OrderType;
674
688
  marketType: MarketType;
675
- ts: BN;
676
689
  slot: BN;
677
690
  orderId: number;
678
691
  userOrderId: number;
@@ -682,7 +695,6 @@ export type Order = {
682
695
  baseAssetAmountFilled: BN;
683
696
  quoteAssetAmount: BN;
684
697
  quoteAssetAmountFilled: BN;
685
- fee: BN;
686
698
  direction: PositionDirection;
687
699
  reduceOnly: boolean;
688
700
  triggerPrice: BN;
@@ -691,11 +703,11 @@ export type Order = {
691
703
  existingPositionDirection: PositionDirection;
692
704
  postOnly: boolean;
693
705
  immediateOrCancel: boolean;
694
- oraclePriceOffset: BN;
706
+ oraclePriceOffset: number;
695
707
  auctionDuration: number;
696
708
  auctionStartPrice: BN;
697
709
  auctionEndPrice: BN;
698
- timeInForce: number;
710
+ maxTs: BN;
699
711
  };
700
712
 
701
713
  export type OrderParams = {
@@ -712,10 +724,11 @@ export type OrderParams = {
712
724
  triggerPrice: BN | null;
713
725
  triggerCondition: OrderTriggerCondition;
714
726
  positionLimit: BN;
715
- oraclePriceOffset: BN | null;
727
+ oraclePriceOffset: number | null;
716
728
  auctionDuration: number | null;
717
- timeInForce: number | null;
729
+ maxTs: BN | null;
718
730
  auctionStartPrice: BN | null;
731
+ auctionEndPrice: BN | null;
719
732
  };
720
733
 
721
734
  export type NecessaryOrderParams = {
@@ -729,7 +742,7 @@ export type OptionalOrderParams = {
729
742
  [Property in keyof OrderParams]?: OrderParams[Property];
730
743
  } & NecessaryOrderParams;
731
744
 
732
- export const DefaultOrderParams = {
745
+ export const DefaultOrderParams: OrderParams = {
733
746
  orderType: OrderType.MARKET,
734
747
  marketType: MarketType.PERP,
735
748
  userOrderId: 0,
@@ -745,8 +758,9 @@ export const DefaultOrderParams = {
745
758
  positionLimit: ZERO,
746
759
  oraclePriceOffset: null,
747
760
  auctionDuration: null,
748
- timeInForce: null,
761
+ maxTs: null,
749
762
  auctionStartPrice: null,
763
+ auctionEndPrice: null,
750
764
  };
751
765
 
752
766
  export type MakerInfo = {
@@ -10,7 +10,18 @@ import { ProgramAccount } from '@project-serum/anchor';
10
10
 
11
11
  import { PublicKey } from '@solana/web3.js';
12
12
 
13
- export class UserMap {
13
+ export interface UserMapInterface {
14
+ fetchAllUsers(): Promise<void>;
15
+ addPubkey(userAccountPublicKey: PublicKey): Promise<void>;
16
+ has(key: string): boolean;
17
+ get(key: string): ClearingHouseUser | undefined;
18
+ mustGet(key: string): Promise<ClearingHouseUser>;
19
+ getUserAuthority(key: string): PublicKey | undefined;
20
+ updateWithOrderRecord(record: OrderRecord): Promise<void>;
21
+ values(): IterableIterator<ClearingHouseUser>;
22
+ }
23
+
24
+ export class UserMap implements UserMapInterface {
14
25
  private userMap = new Map<string, ClearingHouseUser>();
15
26
  private clearingHouse: ClearingHouse;
16
27
  private accountSubscription: ClearingHouseUserAccountSubscriptionConfig;
@@ -90,6 +101,19 @@ export class UserMap {
90
101
  return user;
91
102
  }
92
103
 
104
+ /**
105
+ * gets the Authority for a particular userAccountPublicKey, if no ClearingHouseUser exists, undefined is returned
106
+ * @param key userAccountPublicKey to get ClearngHouseUserFor
107
+ * @returns authority PublicKey | undefined
108
+ */
109
+ public getUserAuthority(key: string): PublicKey | undefined {
110
+ const chUser = this.userMap.get(key);
111
+ if (!chUser) {
112
+ return undefined;
113
+ }
114
+ return chUser.getUserAccount().authority;
115
+ }
116
+
93
117
  public async updateWithOrderRecord(record: OrderRecord) {
94
118
  await this.addPubkey(record.user);
95
119
  }
package/src/userName.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  export const MAX_NAME_LENGTH = 32;
2
2
 
3
3
  export const DEFAULT_USER_NAME = 'Main Account';
4
+ export const DEFAULT_MARKET_NAME = 'Default Market Name';
4
5
 
5
6
  export function encodeName(name: string): number[] {
6
7
  if (name.length > MAX_NAME_LENGTH) {
7
- throw Error(`User name (${name}) longer than 32 characters`);
8
+ throw Error(`Name (${name}) longer than 32 characters`);
8
9
  }
9
10
 
10
11
  const buffer = Buffer.alloc(32);
@@ -0,0 +1,27 @@
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.findComputeUnitConsumption = void 0;
13
+ function findComputeUnitConsumption(programId, connection, txSignature, commitment = 'confirmed') {
14
+ return __awaiter(this, void 0, void 0, function* () {
15
+ const tx = yield connection.getTransaction(txSignature, { commitment });
16
+ const computeUnits = [];
17
+ const regex = new RegExp(`Program ${programId.toString()} consumed ([0-9]{0,6}) of ([0-9]{0,7}) compute units`);
18
+ tx.meta.logMessages.forEach((logMessage) => {
19
+ const match = logMessage.match(regex);
20
+ if (match && match[1]) {
21
+ computeUnits.push(match[1]);
22
+ }
23
+ });
24
+ return computeUnits;
25
+ });
26
+ }
27
+ exports.findComputeUnitConsumption = findComputeUnitConsumption;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getTokenAddress = void 0;
4
+ const spl_token_1 = require("@solana/spl-token");
5
+ const web3_js_1 = require("@solana/web3.js");
6
+ const getTokenAddress = (mintAddress, userPubKey) => {
7
+ return spl_token_1.Token.getAssociatedTokenAddress(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, new web3_js_1.PublicKey(mintAddress), new web3_js_1.PublicKey(userPubKey));
8
+ };
9
+ exports.getTokenAddress = getTokenAddress;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.promiseTimeout = void 0;
4
+ function promiseTimeout(promise, timeoutMs) {
5
+ let timeoutId;
6
+ const timeoutPromise = new Promise((resolve) => {
7
+ timeoutId = setTimeout(() => resolve(null), timeoutMs);
8
+ });
9
+ return Promise.race([promise, timeoutPromise]).then((result) => {
10
+ clearTimeout(timeoutId);
11
+ return result;
12
+ });
13
+ }
14
+ exports.promiseTimeout = promiseTimeout;
@@ -0,0 +1,27 @@
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.estimateTps = void 0;
13
+ function estimateTps(programId, connection, failed) {
14
+ return __awaiter(this, void 0, void 0, function* () {
15
+ let signatures = yield connection.getSignaturesForAddress(programId, undefined, 'finalized');
16
+ if (failed) {
17
+ signatures = signatures.filter((signature) => signature.err);
18
+ }
19
+ const numberOfSignatures = signatures.length;
20
+ if (numberOfSignatures === 0) {
21
+ return 0;
22
+ }
23
+ return (numberOfSignatures /
24
+ (signatures[0].blockTime - signatures[numberOfSignatures - 1].blockTime));
25
+ });
26
+ }
27
+ exports.estimateTps = estimateTps;
package/tests/bn/test.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { BN } from '../../src';
1
+ import { BN } from '../../src/index';
2
2
  import { expect } from 'chai';
3
3
  import { BigNum } from '../../src/factory/bigNum';
4
4
  import {
@@ -6,6 +6,7 @@ import {
6
6
  BASE_PRECISION_EXP,
7
7
  TEN_THOUSAND,
8
8
  } from '../../src/constants/numericConstants';
9
+
9
10
  // if you used the '@types/mocha' method to install mocha type definitions, uncomment the following line
10
11
  // import 'mocha';
11
12
 
@@ -266,4 +267,24 @@ describe('BigNum Tests', () => {
266
267
  const val10 = BigNum.from('100000000000', 6);
267
268
  expect(val10.prettyPrint(true)).to.equal('100,000');
268
269
  });
270
+
271
+ it('can round up and down', () => {
272
+ const val1 = BigNum.from('1234', 1);
273
+ expect(val1.toRounded(3).toString()).to.equal('1230');
274
+
275
+ const val2 = BigNum.from('1236', 1);
276
+ expect(val2.toRounded(3).toString()).to.equal('1240');
277
+
278
+ const val3 = BigNum.from('123456789', 5);
279
+ expect(val3.toRounded(4).print()).to.equal('1235.00000');
280
+
281
+ const val4 = BigNum.from('123456789', 5);
282
+ expect(val4.toRounded(3).print()).to.equal('1230.00000');
283
+
284
+ const val5 = BigNum.from('123000000', 5);
285
+ expect(val5.toRounded(3).print()).to.equal('1230.00000');
286
+
287
+ const val6 = BigNum.from('0', 5);
288
+ expect(val6.toRounded(3).print()).to.equal('0.00000');
289
+ });
269
290
  });