@gearbox-protocol/sdk 3.0.0-vfour.16 → 3.0.0-vfour.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.
@@ -5,7 +5,6 @@ var utils = require('viem/utils');
5
5
  var dateFns = require('date-fns');
6
6
  var chains$1 = require('viem/chains');
7
7
  var actions = require('viem/actions');
8
- var eventemitter3 = require('eventemitter3');
9
8
  var evmConnector = require('@redstone-finance/evm-connector');
10
9
  var redstoneProtocol = require('redstone-protocol');
11
10
  var sdkGov = require('@gearbox-protocol/sdk-gov');
@@ -14540,6 +14539,31 @@ var MellowLRTPriceFeedContract = class extends AbstractLPPriceFeedContract {
14540
14539
  return stack.totalValue * BigInt(1e18) / stack.totalSupply;
14541
14540
  }
14542
14541
  };
14542
+
14543
+ // src/sdk/utils/internal/Hooks.ts
14544
+ var Hooks = class {
14545
+ #reg = {};
14546
+ addHook(hookName, fn) {
14547
+ if (!this.#reg[hookName]) {
14548
+ this.#reg[hookName] = [];
14549
+ }
14550
+ this.#reg[hookName].push(fn);
14551
+ }
14552
+ removeHook(hookName, fn) {
14553
+ if (!this.#reg[hookName]) {
14554
+ return;
14555
+ }
14556
+ this.#reg[hookName] = this.#reg[hookName]?.filter((hookFn) => hookFn !== fn) ?? [];
14557
+ }
14558
+ async triggerHooks(hookName, ...args) {
14559
+ if (!this.#reg[hookName]) {
14560
+ return;
14561
+ }
14562
+ for (const fn of this.#reg[hookName]) {
14563
+ await fn(...args);
14564
+ }
14565
+ }
14566
+ };
14543
14567
  var RedstonePriceFeedContract = class extends AbstractPriceFeedContract {
14544
14568
  decimals = 8;
14545
14569
  dataServiceId;
@@ -14605,6 +14629,7 @@ var RedstonePriceFeedContract = class extends AbstractPriceFeedContract {
14605
14629
  };
14606
14630
  var RedstoneUpdater = class extends SDKConstruct {
14607
14631
  #logger;
14632
+ #cache = /* @__PURE__ */ new Map();
14608
14633
  constructor(sdk) {
14609
14634
  super(sdk);
14610
14635
  this.#logger = childLogger("RedstoneUpdater", sdk.logger);
@@ -14653,7 +14678,7 @@ var RedstoneUpdater = class extends SDKConstruct {
14653
14678
  this.#logger?.debug(
14654
14679
  `Redstone: fetching redstone payloads for ${group.size} data feeds in ${dataServiceId} with ${uniqueSignersCount} signers: ${Array.from(group).join(", ")}`
14655
14680
  );
14656
- const payloads = await this.#fetchPayloads(
14681
+ const payloads = await this.#getPayloads(
14657
14682
  dataServiceId,
14658
14683
  group,
14659
14684
  uniqueSignersCount,
@@ -14682,6 +14707,51 @@ var RedstoneUpdater = class extends SDKConstruct {
14682
14707
  }
14683
14708
  /**
14684
14709
  * Gets redstone payloads in one request for multiple feeds with the same dataServiceId and uniqueSignersCount
14710
+ * If historicalTimestamp is set, responses will be cached
14711
+ * @param dataServiceId
14712
+ * @param dataFeedsIds
14713
+ * @param uniqueSignersCount
14714
+ * @param historicalTimestamp
14715
+ * @returns
14716
+ */
14717
+ async #getPayloads(dataServiceId, dataFeedsIds, uniqueSignersCount, historicalTimestamp) {
14718
+ const fromCache = [];
14719
+ const uncached = [];
14720
+ for (const dataFeedId of dataFeedsIds) {
14721
+ const key = cacheKey(
14722
+ dataServiceId,
14723
+ dataFeedId,
14724
+ uniqueSignersCount,
14725
+ historicalTimestamp
14726
+ );
14727
+ const cached = this.#cache.get(key);
14728
+ if (historicalTimestamp && !!cached) {
14729
+ fromCache.push(cached);
14730
+ } else {
14731
+ uncached.push(dataFeedId);
14732
+ }
14733
+ }
14734
+ const fromRedstone = await this.#fetchPayloads(
14735
+ dataServiceId,
14736
+ new Set(uncached),
14737
+ uniqueSignersCount,
14738
+ historicalTimestamp
14739
+ );
14740
+ if (historicalTimestamp) {
14741
+ for (const resp of fromRedstone) {
14742
+ const key = cacheKey(
14743
+ dataServiceId,
14744
+ resp.dataFeedId,
14745
+ uniqueSignersCount,
14746
+ historicalTimestamp
14747
+ );
14748
+ this.#cache.set(key, resp);
14749
+ }
14750
+ }
14751
+ return [...fromCache, ...fromRedstone];
14752
+ }
14753
+ /**
14754
+ * Fetches redstone payloads in one request for multiple feeds with the same dataServiceId and uniqueSignersCount
14685
14755
  * Payloads are loaded in one request to avoid redstone rate limit
14686
14756
  * @param dataServiceId
14687
14757
  * @param dataFeedsIds
@@ -14690,6 +14760,9 @@ var RedstoneUpdater = class extends SDKConstruct {
14690
14760
  * @returns
14691
14761
  */
14692
14762
  async #fetchPayloads(dataServiceId, dataFeedsIds, uniqueSignersCount, historicalTimestamp) {
14763
+ if (dataFeedsIds.size === 0) {
14764
+ return [];
14765
+ }
14693
14766
  const dataPackagesIds = Array.from(dataFeedsIds);
14694
14767
  const wrapper = new evmConnector.DataServiceWrapper({
14695
14768
  dataServiceId,
@@ -14718,6 +14791,9 @@ var RedstoneUpdater = class extends SDKConstruct {
14718
14791
  });
14719
14792
  }
14720
14793
  };
14794
+ function cacheKey(dataServiceId, dataFeedId, uniqueSignersCount, historicalTimestamp = 0) {
14795
+ return `${dataServiceId}:${dataFeedId}:${uniqueSignersCount}:${historicalTimestamp}`;
14796
+ }
14721
14797
  function groupDataPackages(signedDataPackages) {
14722
14798
  const packagesByDataFeedId = {};
14723
14799
  for (const p of signedDataPackages) {
@@ -14838,6 +14914,7 @@ var ZeroPriceFeedContract = class extends AbstractPriceFeedContract {
14838
14914
  // src/sdk/market/pricefeeds/PriceFeedsRegister.ts
14839
14915
  var PriceFeedRegister = class extends SDKConstruct {
14840
14916
  logger;
14917
+ #hooks = new Hooks();
14841
14918
  #feeds = new AddressMap();
14842
14919
  #redstoneUpdater;
14843
14920
  // public readonly zeroPriceFeed: ZeroPriceFeedContract;
@@ -14846,6 +14923,8 @@ var PriceFeedRegister = class extends SDKConstruct {
14846
14923
  this.logger = childLogger("PriceFeedRegister", sdk.logger);
14847
14924
  this.#redstoneUpdater = new RedstoneUpdater(sdk);
14848
14925
  }
14926
+ addHook = this.#hooks.addHook.bind(this);
14927
+ removeHook = this.#hooks.removeHook.bind(this);
14849
14928
  /**
14850
14929
  * Returns RawTxs to update price feeds
14851
14930
  * @param priceFeeds top-level price feeds, actual updatable price feeds will be derived. If not provided will use all price feeds that are attached
@@ -14875,7 +14954,9 @@ var PriceFeedRegister = class extends SDKConstruct {
14875
14954
  txs.push(tx);
14876
14955
  }
14877
14956
  }
14878
- return { txs, timestamp: maxTimestamp };
14957
+ const result = { txs, timestamp: maxTimestamp };
14958
+ await this.#hooks.triggerHooks("updatesGenerated", result);
14959
+ return result;
14879
14960
  }
14880
14961
  get(address) {
14881
14962
  return this.#feeds.get(address);
@@ -15003,7 +15084,7 @@ var PriceOracleContract = class extends BaseContract {
15003
15084
  * Generates updates for all updateable price feeds in this oracle (including dependencies)
15004
15085
  * @returns
15005
15086
  */
15006
- async updateRedstonePriceFeeds() {
15087
+ async updatePriceFeeds() {
15007
15088
  const updatables = [];
15008
15089
  for (const node of this.#priceFeedTree) {
15009
15090
  if (node.updatable) {
@@ -15399,6 +15480,7 @@ var SWAP_OPERATIONS = {
15399
15480
  };
15400
15481
  var RouterV3Contract = class extends BaseContract {
15401
15482
  #connectors;
15483
+ #hooks = new Hooks();
15402
15484
  constructor(sdk, address) {
15403
15485
  super(sdk, {
15404
15486
  addr: address,
@@ -15407,6 +15489,8 @@ var RouterV3Contract = class extends BaseContract {
15407
15489
  });
15408
15490
  this.#connectors = sdkGov.getConnectors(sdk.provider.networkType);
15409
15491
  }
15492
+ addHook = this.#hooks.addHook.bind(this);
15493
+ removeHook = this.#hooks.removeHook.bind(this);
15410
15494
  /**
15411
15495
  * Finds all available swaps for NORMAL tokens
15412
15496
  * @param ca
@@ -15540,7 +15624,10 @@ var RouterV3Contract = class extends BaseContract {
15540
15624
  */
15541
15625
  async findBestClosePath(ca, cm, slippage) {
15542
15626
  const { pathOptions, expected, leftover, connectors } = this.getFindClosePathInput(ca, cm);
15543
- this.sdk.emit("foundPathOptions", { pathOptions });
15627
+ await this.#hooks.triggerHooks("foundPathOptions", {
15628
+ creditAccount: ca.creditAccount,
15629
+ pathOptions
15630
+ });
15544
15631
  let results = [];
15545
15632
  for (const po of pathOptions) {
15546
15633
  const { result: result2 } = await this.contract.simulate.findBestClosePath(
@@ -15575,7 +15662,7 @@ var RouterV3Contract = class extends BaseContract {
15575
15662
  })),
15576
15663
  underlyingBalance: underlyingBalance + bestResult.minAmount
15577
15664
  };
15578
- this.sdk.emit("foundBestClosePath", {
15665
+ await this.#hooks.triggerHooks("foundBestClosePath", {
15579
15666
  creditAccount: ca.creditAccount,
15580
15667
  ...result
15581
15668
  });
@@ -15635,7 +15722,7 @@ function assetsMap(assets) {
15635
15722
  }
15636
15723
 
15637
15724
  // src/sdk/GearboxSDK.ts
15638
- var GearboxSDK = class _GearboxSDK extends eventemitter3.EventEmitter {
15725
+ var GearboxSDK = class _GearboxSDK {
15639
15726
  // Represents chain object
15640
15727
  #provider;
15641
15728
  // Block which was use for data query
@@ -15698,7 +15785,6 @@ var GearboxSDK = class _GearboxSDK extends eventemitter3.EventEmitter {
15698
15785
  }).#attach(addressProvider, riskCurators);
15699
15786
  }
15700
15787
  constructor(options) {
15701
- super();
15702
15788
  this.#provider = options.provider;
15703
15789
  this.logger = options.logger;
15704
15790
  this.priceFeeds = new PriceFeedRegister(this);
@@ -1,5 +1,4 @@
1
1
  import { Address, Chain, PublicClient, Transport, Hex, Abi, DecodeFunctionDataReturnType, Log, ContractFunctionName, EncodeFunctionDataParameters, TransactionReceipt, GetContractReturnType, Client, Prettify, TestActions, WalletClient, TestRpcSchema, Block, ContractFunctionParameters, CallParameters, MulticallContracts, Narrow, AbiStateMutability, MulticallResults, GetChainContractAddressErrorType, ReadContractErrorType, GetContractErrorReturnType, EncodeFunctionDataErrorType, DecodeFunctionResultErrorType } from 'viem';
2
- import { EventEmitter } from 'eventemitter3';
3
2
  import { RouterComponentRegister, TokenTypeToResolver } from '@gearbox-protocol/sdk-gov';
4
3
  import { AbiParametersToPrimitiveTypes, ExtractAbiFunction } from 'abitype';
5
4
 
@@ -14867,15 +14866,28 @@ declare class MellowLRTPriceFeedContract extends AbstractLPPriceFeedContract<abi
14867
14866
  getValue(): Promise<bigint>;
14868
14867
  }
14869
14868
 
14869
+ interface IHooks<HookMap extends Record<string, any[]>> {
14870
+ addHook: <K extends keyof HookMap>(hookName: K, fn: (...args: HookMap[K]) => void | Promise<void>) => void;
14871
+ removeHook: <K extends keyof HookMap>(hookName: K, fn: (...args: HookMap[K]) => void | Promise<void>) => void;
14872
+ }
14873
+
14874
+ type PriceFeedRegisterHooks = {
14875
+ /**
14876
+ * Emitted when transactions to update price feeds have been generated, but before they're used anywhere
14877
+ */
14878
+ updatesGenerated: [UpdatePriceFeedsResult];
14879
+ };
14870
14880
  /**
14871
14881
  * PriceFeedRegister acts as a chain-level cache to avoid creating multiple contract instances.
14872
14882
  * It's reused by PriceFeedFactory belonging to different markets
14873
14883
  *
14874
14884
  **/
14875
- declare class PriceFeedRegister extends SDKConstruct {
14885
+ declare class PriceFeedRegister extends SDKConstruct implements IHooks<PriceFeedRegisterHooks> {
14876
14886
  #private;
14877
14887
  readonly logger?: ILogger;
14878
14888
  constructor(sdk: GearboxSDK);
14889
+ addHook: <K extends "updatesGenerated">(hookName: K, fn: (...args: PriceFeedRegisterHooks[K]) => void | Promise<void>) => void;
14890
+ removeHook: <K extends "updatesGenerated">(hookName: K, fn: (...args: PriceFeedRegisterHooks[K]) => void | Promise<void>) => void;
14879
14891
  /**
14880
14892
  * Returns RawTxs to update price feeds
14881
14893
  * @param priceFeeds top-level price feeds, actual updatable price feeds will be derived. If not provided will use all price feeds that are attached
@@ -16869,7 +16881,7 @@ declare class PriceOracleContract extends BaseContract<abi$1> {
16869
16881
  * Generates updates for all updateable price feeds in this oracle (including dependencies)
16870
16882
  * @returns
16871
16883
  */
16872
- updateRedstonePriceFeeds(): Promise<UpdatePriceFeedsResult>;
16884
+ updatePriceFeeds(): Promise<UpdatePriceFeedsResult>;
16873
16885
  /**
16874
16886
  * Converts previously obtained price updates into CreditFacade multicall entries
16875
16887
  * @param creditFacade
@@ -16968,6 +16980,29 @@ interface FindClosePathInput {
16968
16980
  leftover: Asset[];
16969
16981
  connectors: Address[];
16970
16982
  }
16983
+ type RouterHooks = {
16984
+ /**
16985
+ * Internal router event
16986
+ */
16987
+ foundPathOptions: [
16988
+ {
16989
+ creditAccount: Address;
16990
+ pathOptions: PathOptionSerie[];
16991
+ }
16992
+ ];
16993
+ /**
16994
+ * Internal router event
16995
+ */
16996
+ foundBestClosePath: [
16997
+ {
16998
+ creditAccount: Address;
16999
+ amount: bigint;
17000
+ minAmount: bigint;
17001
+ calls: MultiCall[];
17002
+ underlyingBalance: bigint;
17003
+ }
17004
+ ];
17005
+ };
16971
17006
  /**
16972
17007
  * Slice of credit manager data required for router operations
16973
17008
  */
@@ -16975,9 +17010,11 @@ interface CreditManagerSlice {
16975
17010
  address: Address;
16976
17011
  collateralTokens: Address[];
16977
17012
  }
16978
- declare class RouterV3Contract extends BaseContract<abi> {
17013
+ declare class RouterV3Contract extends BaseContract<abi> implements IHooks<RouterHooks> {
16979
17014
  #private;
16980
17015
  constructor(sdk: GearboxSDK, address: Address);
17016
+ addHook: <K extends keyof RouterHooks>(hookName: K, fn: (...args: RouterHooks[K]) => void | Promise<void>) => void;
17017
+ removeHook: <K extends keyof RouterHooks>(hookName: K, fn: (...args: RouterHooks[K]) => void | Promise<void>) => void;
16981
17018
  /**
16982
17019
  * Finds all available swaps for NORMAL tokens
16983
17020
  * @param ca
@@ -17035,27 +17072,6 @@ declare class RouterV3Contract extends BaseContract<abi> {
17035
17072
  getAvailableConnectors(collateralTokens: Address[]): Address[];
17036
17073
  }
17037
17074
 
17038
- interface SDKEventsMap {
17039
- /**
17040
- * Emitted by router
17041
- */
17042
- foundPathOptions: [{
17043
- pathOptions: PathOptionSerie[];
17044
- }];
17045
- /**
17046
- * Emitted by router
17047
- */
17048
- foundBestClosePath: [
17049
- {
17050
- creditAccount: Address;
17051
- amount: bigint;
17052
- minAmount: bigint;
17053
- calls: MultiCall[];
17054
- underlyingBalance: bigint;
17055
- }
17056
- ];
17057
- }
17058
-
17059
17075
  interface SDKAttachOptions {
17060
17076
  /**
17061
17077
  * Account address for contract write simulations
@@ -17090,7 +17106,7 @@ interface SDKAttachOptions {
17090
17106
  */
17091
17107
  logger?: ILogger;
17092
17108
  }
17093
- declare class GearboxSDK extends EventEmitter<SDKEventsMap> {
17109
+ declare class GearboxSDK {
17094
17110
  #private;
17095
17111
  readonly logger?: ILogger;
17096
17112
  /**
@@ -17407,4 +17423,4 @@ type MulticallErrorType = GetChainContractAddressErrorType | ReadContractErrorTy
17407
17423
  */
17408
17424
  declare function simulateMulticall<const contracts extends readonly unknown[], chain extends Chain | undefined, allowFailure extends boolean = true>(client: Client<Transport, chain>, parameters: MulticallParameters<contracts, allowFailure>): Promise<MulticallReturnType<contracts, allowFailure>>;
17409
17425
 
17410
- export { type ACLState, type ACLStateHuman, ADDRESS_0X0, ADDRESS_PROVIDER, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DEGEN_DISTRIBUTOR, AP_DEGEN_NFT, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MULTI_PAUSE, AP_PARTIAL_LIQUIDATION_BOT, AP_PRICE_ORACLE, AP_ROUTER, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, AbstractPriceFeedContract, type AccountFactoryStateHuman, AddressLabeller, AddressMap, AddressProviderContractV3_1, type AddressProviderV3State, type AddressProviderV3StateHuman, type AnvilActions, type AnvilClient, type AnvilClientConfig, type Asset, type AssetPriceFeedState, type AssetPriceFeedStateHuman, BalancerStablePriceFeedContract, BalancerWeightedPriceFeedContract, BaseContract, type BaseContractOptions, type BaseContractState, type BaseContractStateHuman, type BasePriceFeedState, type BasePriceFeedStateHuman, BotListContract, type BotListState, type BotListStateHuman, BotPermissions, type BoundedOracleState, type BoundedOracleStateHuman, BoundedPriceFeedContract, ChainlinkPriceFeedContract, CompositePriceFeedContract, type ContractMethod, type ContractsRegisterState, type ContractsRegisterStateHuman, type ControllerTimelockV3State, type ControllerTimelockV3StateHuman, type CoreState, type CoreStateHuman, type CreditAccountData, type CreditAccountFilter, CreditAccountsService, CreditConfiguratorContract, type CreditConfiguratorState, type CreditConfiguratorStateHuman, CreditFacadeContract, type CreditFacadeState, type CreditFacadeStateHuman, CreditFactory, type CreditFactoryState, type CreditFactoryStateHuman, CreditManagerContract, type CreditManagerData, type CreditManagerDebtParams, type CreditManagerDebtParamsHuman, type CreditManagerDebtParamsStruct, type CreditManagerState, type CreditManagerStateHuman, CurveCryptoPriceFeedContract, type CurvePoolStruct, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, type DataCompressorV3State, type DegenDistributorState, type DegenDistributorStateHuman, type DegenNFT2State, type DegenNFT2StateHuman, Erc4626PriceFeedContract, type EtherscanURLParam, type FindClosePathInput, GaugeContract, type GaugeParams, type GaugeParamsHuman, type GaugeState, type GaugeStateHuman, GearStakingContract, type GearStakingV3State, type GearStakingV3StateHuman, GearboxSDK, type GearboxState, type GearboxStateHuman, type ILPPriceFeedContract, type ILogger, type IPriceFeedContract, LinearModelContract, type LinearModelState, type LinearModelStateHuman, type LogFn, MAX_UINT256, MIN_INT96, type MarketData, MarketFactory, MarketRegister, type MarketState, type MarketStateHuman, MellowLRTPriceFeedContract, type MultiCall, type MultiPauseState, type MulticallErrorType, type MulticallParameters, type MulticallReturnType, NOT_DEPLOYED, NO_VERSION, type NetworkType, type OnDemandPriceUpdate, type OpenStrategyResult, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PRICE_DECIMALS, PRICE_DECIMALS_POW, type PathOption, type PathOptionSerie, type PeripheryState, type PeripheryStateHuman, type PolicyStruct, type PolicyStructHuman, PoolContract, type PoolData, PoolFactory, type PoolFactoryState, type PoolFactoryStateHuman, PoolQuotaKeeperContract, type PoolQuotaKeeperData, type PoolQuotaKeeperState, type PoolQuotaKeeperStateHuman, type PoolState, type PoolStateHuman, type PriceFactoryStateHuman, type PriceFeedConstructorArgs, type PriceFeedContractType, type PriceFeedMapEntry, PriceFeedRef, PriceFeedRegister, type PriceFeedState, type PriceFeedStateHuman, type PriceFeedTreeNode, type PriceFeedUsageType, PriceOracleContract, type PriceOracleData, type PriceOracleState, type PriceOracleV3State, type PriceOracleV3StateHuman, Provider, type ProviderOptions, type QuotaParams, type QuotaParamsHuman, RAY, RAY_DECIMALS_POW, type RateKeeperData, type RawTx, type ReadContractOptions, RedstonePriceFeedContract, type RedstonePriceFeedState, type RedstonePriceFeedStateHuman, type RouterCloseResult, type RouterComponentRegisterHuman, type RouterResult, type RouterState, type RouterStateHuman, RouterV3Contract, type RouterV3ContractState, type RouterV3ContractStateHuman, type SDKAttachOptions, SDKConstruct, type SDKEventsMap, SUPPORTED_CHAINS, type SwapOperation, type SwapTask, TIMELOCK, type TVL, type TokenMetaData, type TokenTypeToResolverHuman, USDC, type UpdatePriceFeedsResult, VotingContractStatus, WAD, WAD_DECIMALS_POW, WstETHPriceFeedContract, YearnPriceFeedContract, type ZapperInfo, type ZapperInfoHuman, type ZapperRegisterState, type ZapperRegisterStateHuman, ZeroPriceFeedContract, botPermissionsToString, bytes32ToString, chains, childLogger, convertBaseContractState, convertCoreStateToHuman, convertCreditFactoryStateToHuman, convertGaugeStateToHuman, convertGearboxStateToHuman, convertGearboxStateToHumanLA, convertLinearModelStateToHuman, convertPeripheryStateToHuman, convertPoolFactoryStateToHuman, convertPoolQuotaKeeperStateToHuman, convertPoolStateToHuman, convertPriceFeedStateToHuman, convertPriceOracleStateToHuman, convertRouterStateToHuman, convertRouterV3StateToHuman, convertZapperRegisterStateToHuman, createAnvilClient, createRawTx, detectNetwork, etherscanUrl, filterDust, fmtBinaryMask, formatBN, formatBNvalue, formatBn4dig, formatDuration, formatNumberToString_, halfRAY, isAnvil, json_parse, json_stringify, numberWithCommas, percentFmt, simulateMulticall, toHumanFormat };
17426
+ export { type ACLState, type ACLStateHuman, ADDRESS_0X0, ADDRESS_PROVIDER, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DEGEN_DISTRIBUTOR, AP_DEGEN_NFT, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MULTI_PAUSE, AP_PARTIAL_LIQUIDATION_BOT, AP_PRICE_ORACLE, AP_ROUTER, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, AbstractPriceFeedContract, type AccountFactoryStateHuman, AddressLabeller, AddressMap, AddressProviderContractV3_1, type AddressProviderV3State, type AddressProviderV3StateHuman, type AnvilActions, type AnvilClient, type AnvilClientConfig, type Asset, type AssetPriceFeedState, type AssetPriceFeedStateHuman, BalancerStablePriceFeedContract, BalancerWeightedPriceFeedContract, BaseContract, type BaseContractOptions, type BaseContractState, type BaseContractStateHuman, type BasePriceFeedState, type BasePriceFeedStateHuman, BotListContract, type BotListState, type BotListStateHuman, BotPermissions, type BoundedOracleState, type BoundedOracleStateHuman, BoundedPriceFeedContract, ChainlinkPriceFeedContract, CompositePriceFeedContract, type ContractMethod, type ContractsRegisterState, type ContractsRegisterStateHuman, type ControllerTimelockV3State, type ControllerTimelockV3StateHuman, type CoreState, type CoreStateHuman, type CreditAccountData, type CreditAccountFilter, CreditAccountsService, CreditConfiguratorContract, type CreditConfiguratorState, type CreditConfiguratorStateHuman, CreditFacadeContract, type CreditFacadeState, type CreditFacadeStateHuman, CreditFactory, type CreditFactoryState, type CreditFactoryStateHuman, CreditManagerContract, type CreditManagerData, type CreditManagerDebtParams, type CreditManagerDebtParamsHuman, type CreditManagerDebtParamsStruct, type CreditManagerState, type CreditManagerStateHuman, CurveCryptoPriceFeedContract, type CurvePoolStruct, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, type DataCompressorV3State, type DegenDistributorState, type DegenDistributorStateHuman, type DegenNFT2State, type DegenNFT2StateHuman, Erc4626PriceFeedContract, type EtherscanURLParam, type FindClosePathInput, GaugeContract, type GaugeParams, type GaugeParamsHuman, type GaugeState, type GaugeStateHuman, GearStakingContract, type GearStakingV3State, type GearStakingV3StateHuman, GearboxSDK, type GearboxState, type GearboxStateHuman, type ILPPriceFeedContract, type ILogger, type IPriceFeedContract, LinearModelContract, type LinearModelState, type LinearModelStateHuman, type LogFn, MAX_UINT256, MIN_INT96, type MarketData, MarketFactory, MarketRegister, type MarketState, type MarketStateHuman, MellowLRTPriceFeedContract, type MultiCall, type MultiPauseState, type MulticallErrorType, type MulticallParameters, type MulticallReturnType, NOT_DEPLOYED, NO_VERSION, type NetworkType, type OnDemandPriceUpdate, type OpenStrategyResult, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PRICE_DECIMALS, PRICE_DECIMALS_POW, type PathOption, type PathOptionSerie, type PeripheryState, type PeripheryStateHuman, type PolicyStruct, type PolicyStructHuman, PoolContract, type PoolData, PoolFactory, type PoolFactoryState, type PoolFactoryStateHuman, PoolQuotaKeeperContract, type PoolQuotaKeeperData, type PoolQuotaKeeperState, type PoolQuotaKeeperStateHuman, type PoolState, type PoolStateHuman, type PriceFactoryStateHuman, type PriceFeedConstructorArgs, type PriceFeedContractType, type PriceFeedMapEntry, PriceFeedRef, PriceFeedRegister, type PriceFeedRegisterHooks, type PriceFeedState, type PriceFeedStateHuman, type PriceFeedTreeNode, type PriceFeedUsageType, PriceOracleContract, type PriceOracleData, type PriceOracleState, type PriceOracleV3State, type PriceOracleV3StateHuman, Provider, type ProviderOptions, type QuotaParams, type QuotaParamsHuman, RAY, RAY_DECIMALS_POW, type RateKeeperData, type RawTx, type ReadContractOptions, RedstonePriceFeedContract, type RedstonePriceFeedState, type RedstonePriceFeedStateHuman, type RouterCloseResult, type RouterComponentRegisterHuman, type RouterHooks, type RouterResult, type RouterState, type RouterStateHuman, RouterV3Contract, type RouterV3ContractState, type RouterV3ContractStateHuman, type SDKAttachOptions, SDKConstruct, SUPPORTED_CHAINS, type SwapOperation, type SwapTask, TIMELOCK, type TVL, type TokenMetaData, type TokenTypeToResolverHuman, USDC, type UpdatePriceFeedsResult, VotingContractStatus, WAD, WAD_DECIMALS_POW, WstETHPriceFeedContract, YearnPriceFeedContract, type ZapperInfo, type ZapperInfoHuman, type ZapperRegisterState, type ZapperRegisterStateHuman, ZeroPriceFeedContract, botPermissionsToString, bytes32ToString, chains, childLogger, convertBaseContractState, convertCoreStateToHuman, convertCreditFactoryStateToHuman, convertGaugeStateToHuman, convertGearboxStateToHuman, convertGearboxStateToHumanLA, convertLinearModelStateToHuman, convertPeripheryStateToHuman, convertPoolFactoryStateToHuman, convertPoolQuotaKeeperStateToHuman, convertPoolStateToHuman, convertPriceFeedStateToHuman, convertPriceOracleStateToHuman, convertRouterStateToHuman, convertRouterV3StateToHuman, convertZapperRegisterStateToHuman, createAnvilClient, createRawTx, detectNetwork, etherscanUrl, filterDust, fmtBinaryMask, formatBN, formatBNvalue, formatBn4dig, formatDuration, formatNumberToString_, halfRAY, isAnvil, json_parse, json_stringify, numberWithCommas, percentFmt, simulateMulticall, toHumanFormat };
@@ -1,5 +1,4 @@
1
1
  import { Address, Chain, PublicClient, Transport, Hex, Abi, DecodeFunctionDataReturnType, Log, ContractFunctionName, EncodeFunctionDataParameters, TransactionReceipt, GetContractReturnType, Client, Prettify, TestActions, WalletClient, TestRpcSchema, Block, ContractFunctionParameters, CallParameters, MulticallContracts, Narrow, AbiStateMutability, MulticallResults, GetChainContractAddressErrorType, ReadContractErrorType, GetContractErrorReturnType, EncodeFunctionDataErrorType, DecodeFunctionResultErrorType } from 'viem';
2
- import { EventEmitter } from 'eventemitter3';
3
2
  import { RouterComponentRegister, TokenTypeToResolver } from '@gearbox-protocol/sdk-gov';
4
3
  import { AbiParametersToPrimitiveTypes, ExtractAbiFunction } from 'abitype';
5
4
 
@@ -14867,15 +14866,28 @@ declare class MellowLRTPriceFeedContract extends AbstractLPPriceFeedContract<abi
14867
14866
  getValue(): Promise<bigint>;
14868
14867
  }
14869
14868
 
14869
+ interface IHooks<HookMap extends Record<string, any[]>> {
14870
+ addHook: <K extends keyof HookMap>(hookName: K, fn: (...args: HookMap[K]) => void | Promise<void>) => void;
14871
+ removeHook: <K extends keyof HookMap>(hookName: K, fn: (...args: HookMap[K]) => void | Promise<void>) => void;
14872
+ }
14873
+
14874
+ type PriceFeedRegisterHooks = {
14875
+ /**
14876
+ * Emitted when transactions to update price feeds have been generated, but before they're used anywhere
14877
+ */
14878
+ updatesGenerated: [UpdatePriceFeedsResult];
14879
+ };
14870
14880
  /**
14871
14881
  * PriceFeedRegister acts as a chain-level cache to avoid creating multiple contract instances.
14872
14882
  * It's reused by PriceFeedFactory belonging to different markets
14873
14883
  *
14874
14884
  **/
14875
- declare class PriceFeedRegister extends SDKConstruct {
14885
+ declare class PriceFeedRegister extends SDKConstruct implements IHooks<PriceFeedRegisterHooks> {
14876
14886
  #private;
14877
14887
  readonly logger?: ILogger;
14878
14888
  constructor(sdk: GearboxSDK);
14889
+ addHook: <K extends "updatesGenerated">(hookName: K, fn: (...args: PriceFeedRegisterHooks[K]) => void | Promise<void>) => void;
14890
+ removeHook: <K extends "updatesGenerated">(hookName: K, fn: (...args: PriceFeedRegisterHooks[K]) => void | Promise<void>) => void;
14879
14891
  /**
14880
14892
  * Returns RawTxs to update price feeds
14881
14893
  * @param priceFeeds top-level price feeds, actual updatable price feeds will be derived. If not provided will use all price feeds that are attached
@@ -16869,7 +16881,7 @@ declare class PriceOracleContract extends BaseContract<abi$1> {
16869
16881
  * Generates updates for all updateable price feeds in this oracle (including dependencies)
16870
16882
  * @returns
16871
16883
  */
16872
- updateRedstonePriceFeeds(): Promise<UpdatePriceFeedsResult>;
16884
+ updatePriceFeeds(): Promise<UpdatePriceFeedsResult>;
16873
16885
  /**
16874
16886
  * Converts previously obtained price updates into CreditFacade multicall entries
16875
16887
  * @param creditFacade
@@ -16968,6 +16980,29 @@ interface FindClosePathInput {
16968
16980
  leftover: Asset[];
16969
16981
  connectors: Address[];
16970
16982
  }
16983
+ type RouterHooks = {
16984
+ /**
16985
+ * Internal router event
16986
+ */
16987
+ foundPathOptions: [
16988
+ {
16989
+ creditAccount: Address;
16990
+ pathOptions: PathOptionSerie[];
16991
+ }
16992
+ ];
16993
+ /**
16994
+ * Internal router event
16995
+ */
16996
+ foundBestClosePath: [
16997
+ {
16998
+ creditAccount: Address;
16999
+ amount: bigint;
17000
+ minAmount: bigint;
17001
+ calls: MultiCall[];
17002
+ underlyingBalance: bigint;
17003
+ }
17004
+ ];
17005
+ };
16971
17006
  /**
16972
17007
  * Slice of credit manager data required for router operations
16973
17008
  */
@@ -16975,9 +17010,11 @@ interface CreditManagerSlice {
16975
17010
  address: Address;
16976
17011
  collateralTokens: Address[];
16977
17012
  }
16978
- declare class RouterV3Contract extends BaseContract<abi> {
17013
+ declare class RouterV3Contract extends BaseContract<abi> implements IHooks<RouterHooks> {
16979
17014
  #private;
16980
17015
  constructor(sdk: GearboxSDK, address: Address);
17016
+ addHook: <K extends keyof RouterHooks>(hookName: K, fn: (...args: RouterHooks[K]) => void | Promise<void>) => void;
17017
+ removeHook: <K extends keyof RouterHooks>(hookName: K, fn: (...args: RouterHooks[K]) => void | Promise<void>) => void;
16981
17018
  /**
16982
17019
  * Finds all available swaps for NORMAL tokens
16983
17020
  * @param ca
@@ -17035,27 +17072,6 @@ declare class RouterV3Contract extends BaseContract<abi> {
17035
17072
  getAvailableConnectors(collateralTokens: Address[]): Address[];
17036
17073
  }
17037
17074
 
17038
- interface SDKEventsMap {
17039
- /**
17040
- * Emitted by router
17041
- */
17042
- foundPathOptions: [{
17043
- pathOptions: PathOptionSerie[];
17044
- }];
17045
- /**
17046
- * Emitted by router
17047
- */
17048
- foundBestClosePath: [
17049
- {
17050
- creditAccount: Address;
17051
- amount: bigint;
17052
- minAmount: bigint;
17053
- calls: MultiCall[];
17054
- underlyingBalance: bigint;
17055
- }
17056
- ];
17057
- }
17058
-
17059
17075
  interface SDKAttachOptions {
17060
17076
  /**
17061
17077
  * Account address for contract write simulations
@@ -17090,7 +17106,7 @@ interface SDKAttachOptions {
17090
17106
  */
17091
17107
  logger?: ILogger;
17092
17108
  }
17093
- declare class GearboxSDK extends EventEmitter<SDKEventsMap> {
17109
+ declare class GearboxSDK {
17094
17110
  #private;
17095
17111
  readonly logger?: ILogger;
17096
17112
  /**
@@ -17407,4 +17423,4 @@ type MulticallErrorType = GetChainContractAddressErrorType | ReadContractErrorTy
17407
17423
  */
17408
17424
  declare function simulateMulticall<const contracts extends readonly unknown[], chain extends Chain | undefined, allowFailure extends boolean = true>(client: Client<Transport, chain>, parameters: MulticallParameters<contracts, allowFailure>): Promise<MulticallReturnType<contracts, allowFailure>>;
17409
17425
 
17410
- export { type ACLState, type ACLStateHuman, ADDRESS_0X0, ADDRESS_PROVIDER, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DEGEN_DISTRIBUTOR, AP_DEGEN_NFT, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MULTI_PAUSE, AP_PARTIAL_LIQUIDATION_BOT, AP_PRICE_ORACLE, AP_ROUTER, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, AbstractPriceFeedContract, type AccountFactoryStateHuman, AddressLabeller, AddressMap, AddressProviderContractV3_1, type AddressProviderV3State, type AddressProviderV3StateHuman, type AnvilActions, type AnvilClient, type AnvilClientConfig, type Asset, type AssetPriceFeedState, type AssetPriceFeedStateHuman, BalancerStablePriceFeedContract, BalancerWeightedPriceFeedContract, BaseContract, type BaseContractOptions, type BaseContractState, type BaseContractStateHuman, type BasePriceFeedState, type BasePriceFeedStateHuman, BotListContract, type BotListState, type BotListStateHuman, BotPermissions, type BoundedOracleState, type BoundedOracleStateHuman, BoundedPriceFeedContract, ChainlinkPriceFeedContract, CompositePriceFeedContract, type ContractMethod, type ContractsRegisterState, type ContractsRegisterStateHuman, type ControllerTimelockV3State, type ControllerTimelockV3StateHuman, type CoreState, type CoreStateHuman, type CreditAccountData, type CreditAccountFilter, CreditAccountsService, CreditConfiguratorContract, type CreditConfiguratorState, type CreditConfiguratorStateHuman, CreditFacadeContract, type CreditFacadeState, type CreditFacadeStateHuman, CreditFactory, type CreditFactoryState, type CreditFactoryStateHuman, CreditManagerContract, type CreditManagerData, type CreditManagerDebtParams, type CreditManagerDebtParamsHuman, type CreditManagerDebtParamsStruct, type CreditManagerState, type CreditManagerStateHuman, CurveCryptoPriceFeedContract, type CurvePoolStruct, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, type DataCompressorV3State, type DegenDistributorState, type DegenDistributorStateHuman, type DegenNFT2State, type DegenNFT2StateHuman, Erc4626PriceFeedContract, type EtherscanURLParam, type FindClosePathInput, GaugeContract, type GaugeParams, type GaugeParamsHuman, type GaugeState, type GaugeStateHuman, GearStakingContract, type GearStakingV3State, type GearStakingV3StateHuman, GearboxSDK, type GearboxState, type GearboxStateHuman, type ILPPriceFeedContract, type ILogger, type IPriceFeedContract, LinearModelContract, type LinearModelState, type LinearModelStateHuman, type LogFn, MAX_UINT256, MIN_INT96, type MarketData, MarketFactory, MarketRegister, type MarketState, type MarketStateHuman, MellowLRTPriceFeedContract, type MultiCall, type MultiPauseState, type MulticallErrorType, type MulticallParameters, type MulticallReturnType, NOT_DEPLOYED, NO_VERSION, type NetworkType, type OnDemandPriceUpdate, type OpenStrategyResult, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PRICE_DECIMALS, PRICE_DECIMALS_POW, type PathOption, type PathOptionSerie, type PeripheryState, type PeripheryStateHuman, type PolicyStruct, type PolicyStructHuman, PoolContract, type PoolData, PoolFactory, type PoolFactoryState, type PoolFactoryStateHuman, PoolQuotaKeeperContract, type PoolQuotaKeeperData, type PoolQuotaKeeperState, type PoolQuotaKeeperStateHuman, type PoolState, type PoolStateHuman, type PriceFactoryStateHuman, type PriceFeedConstructorArgs, type PriceFeedContractType, type PriceFeedMapEntry, PriceFeedRef, PriceFeedRegister, type PriceFeedState, type PriceFeedStateHuman, type PriceFeedTreeNode, type PriceFeedUsageType, PriceOracleContract, type PriceOracleData, type PriceOracleState, type PriceOracleV3State, type PriceOracleV3StateHuman, Provider, type ProviderOptions, type QuotaParams, type QuotaParamsHuman, RAY, RAY_DECIMALS_POW, type RateKeeperData, type RawTx, type ReadContractOptions, RedstonePriceFeedContract, type RedstonePriceFeedState, type RedstonePriceFeedStateHuman, type RouterCloseResult, type RouterComponentRegisterHuman, type RouterResult, type RouterState, type RouterStateHuman, RouterV3Contract, type RouterV3ContractState, type RouterV3ContractStateHuman, type SDKAttachOptions, SDKConstruct, type SDKEventsMap, SUPPORTED_CHAINS, type SwapOperation, type SwapTask, TIMELOCK, type TVL, type TokenMetaData, type TokenTypeToResolverHuman, USDC, type UpdatePriceFeedsResult, VotingContractStatus, WAD, WAD_DECIMALS_POW, WstETHPriceFeedContract, YearnPriceFeedContract, type ZapperInfo, type ZapperInfoHuman, type ZapperRegisterState, type ZapperRegisterStateHuman, ZeroPriceFeedContract, botPermissionsToString, bytes32ToString, chains, childLogger, convertBaseContractState, convertCoreStateToHuman, convertCreditFactoryStateToHuman, convertGaugeStateToHuman, convertGearboxStateToHuman, convertGearboxStateToHumanLA, convertLinearModelStateToHuman, convertPeripheryStateToHuman, convertPoolFactoryStateToHuman, convertPoolQuotaKeeperStateToHuman, convertPoolStateToHuman, convertPriceFeedStateToHuman, convertPriceOracleStateToHuman, convertRouterStateToHuman, convertRouterV3StateToHuman, convertZapperRegisterStateToHuman, createAnvilClient, createRawTx, detectNetwork, etherscanUrl, filterDust, fmtBinaryMask, formatBN, formatBNvalue, formatBn4dig, formatDuration, formatNumberToString_, halfRAY, isAnvil, json_parse, json_stringify, numberWithCommas, percentFmt, simulateMulticall, toHumanFormat };
17426
+ export { type ACLState, type ACLStateHuman, ADDRESS_0X0, ADDRESS_PROVIDER, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DEGEN_DISTRIBUTOR, AP_DEGEN_NFT, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MULTI_PAUSE, AP_PARTIAL_LIQUIDATION_BOT, AP_PRICE_ORACLE, AP_ROUTER, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, AbstractPriceFeedContract, type AccountFactoryStateHuman, AddressLabeller, AddressMap, AddressProviderContractV3_1, type AddressProviderV3State, type AddressProviderV3StateHuman, type AnvilActions, type AnvilClient, type AnvilClientConfig, type Asset, type AssetPriceFeedState, type AssetPriceFeedStateHuman, BalancerStablePriceFeedContract, BalancerWeightedPriceFeedContract, BaseContract, type BaseContractOptions, type BaseContractState, type BaseContractStateHuman, type BasePriceFeedState, type BasePriceFeedStateHuman, BotListContract, type BotListState, type BotListStateHuman, BotPermissions, type BoundedOracleState, type BoundedOracleStateHuman, BoundedPriceFeedContract, ChainlinkPriceFeedContract, CompositePriceFeedContract, type ContractMethod, type ContractsRegisterState, type ContractsRegisterStateHuman, type ControllerTimelockV3State, type ControllerTimelockV3StateHuman, type CoreState, type CoreStateHuman, type CreditAccountData, type CreditAccountFilter, CreditAccountsService, CreditConfiguratorContract, type CreditConfiguratorState, type CreditConfiguratorStateHuman, CreditFacadeContract, type CreditFacadeState, type CreditFacadeStateHuman, CreditFactory, type CreditFactoryState, type CreditFactoryStateHuman, CreditManagerContract, type CreditManagerData, type CreditManagerDebtParams, type CreditManagerDebtParamsHuman, type CreditManagerDebtParamsStruct, type CreditManagerState, type CreditManagerStateHuman, CurveCryptoPriceFeedContract, type CurvePoolStruct, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, type DataCompressorV3State, type DegenDistributorState, type DegenDistributorStateHuman, type DegenNFT2State, type DegenNFT2StateHuman, Erc4626PriceFeedContract, type EtherscanURLParam, type FindClosePathInput, GaugeContract, type GaugeParams, type GaugeParamsHuman, type GaugeState, type GaugeStateHuman, GearStakingContract, type GearStakingV3State, type GearStakingV3StateHuman, GearboxSDK, type GearboxState, type GearboxStateHuman, type ILPPriceFeedContract, type ILogger, type IPriceFeedContract, LinearModelContract, type LinearModelState, type LinearModelStateHuman, type LogFn, MAX_UINT256, MIN_INT96, type MarketData, MarketFactory, MarketRegister, type MarketState, type MarketStateHuman, MellowLRTPriceFeedContract, type MultiCall, type MultiPauseState, type MulticallErrorType, type MulticallParameters, type MulticallReturnType, NOT_DEPLOYED, NO_VERSION, type NetworkType, type OnDemandPriceUpdate, type OpenStrategyResult, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PRICE_DECIMALS, PRICE_DECIMALS_POW, type PathOption, type PathOptionSerie, type PeripheryState, type PeripheryStateHuman, type PolicyStruct, type PolicyStructHuman, PoolContract, type PoolData, PoolFactory, type PoolFactoryState, type PoolFactoryStateHuman, PoolQuotaKeeperContract, type PoolQuotaKeeperData, type PoolQuotaKeeperState, type PoolQuotaKeeperStateHuman, type PoolState, type PoolStateHuman, type PriceFactoryStateHuman, type PriceFeedConstructorArgs, type PriceFeedContractType, type PriceFeedMapEntry, PriceFeedRef, PriceFeedRegister, type PriceFeedRegisterHooks, type PriceFeedState, type PriceFeedStateHuman, type PriceFeedTreeNode, type PriceFeedUsageType, PriceOracleContract, type PriceOracleData, type PriceOracleState, type PriceOracleV3State, type PriceOracleV3StateHuman, Provider, type ProviderOptions, type QuotaParams, type QuotaParamsHuman, RAY, RAY_DECIMALS_POW, type RateKeeperData, type RawTx, type ReadContractOptions, RedstonePriceFeedContract, type RedstonePriceFeedState, type RedstonePriceFeedStateHuman, type RouterCloseResult, type RouterComponentRegisterHuman, type RouterHooks, type RouterResult, type RouterState, type RouterStateHuman, RouterV3Contract, type RouterV3ContractState, type RouterV3ContractStateHuman, type SDKAttachOptions, SDKConstruct, SUPPORTED_CHAINS, type SwapOperation, type SwapTask, TIMELOCK, type TVL, type TokenMetaData, type TokenTypeToResolverHuman, USDC, type UpdatePriceFeedsResult, VotingContractStatus, WAD, WAD_DECIMALS_POW, WstETHPriceFeedContract, YearnPriceFeedContract, type ZapperInfo, type ZapperInfoHuman, type ZapperRegisterState, type ZapperRegisterStateHuman, ZeroPriceFeedContract, botPermissionsToString, bytes32ToString, chains, childLogger, convertBaseContractState, convertCoreStateToHuman, convertCreditFactoryStateToHuman, convertGaugeStateToHuman, convertGearboxStateToHuman, convertGearboxStateToHumanLA, convertLinearModelStateToHuman, convertPeripheryStateToHuman, convertPoolFactoryStateToHuman, convertPoolQuotaKeeperStateToHuman, convertPoolStateToHuman, convertPriceFeedStateToHuman, convertPriceOracleStateToHuman, convertRouterStateToHuman, convertRouterV3StateToHuman, convertZapperRegisterStateToHuman, createAnvilClient, createRawTx, detectNetwork, etherscanUrl, filterDust, fmtBinaryMask, formatBN, formatBNvalue, formatBn4dig, formatDuration, formatNumberToString_, halfRAY, isAnvil, json_parse, json_stringify, numberWithCommas, percentFmt, simulateMulticall, toHumanFormat };
@@ -3,7 +3,6 @@ import { formatAbiItem, getAction } from 'viem/utils';
3
3
  import { intervalToDuration, formatDuration as formatDuration$1 } from 'date-fns';
4
4
  import { mainnet, arbitrum, optimism, base } from 'viem/chains';
5
5
  import { simulateContract } from 'viem/actions';
6
- import { EventEmitter } from 'eventemitter3';
7
6
  import { DataServiceWrapper } from '@redstone-finance/evm-connector';
8
7
  import { RedstonePayload } from 'redstone-protocol';
9
8
  import { getConnectors, decimals, getTokenSymbol, RouterComponent, TokenType, tokenDataByNetwork, contractParams, curveTokens, balancerLpTokens, isCurveLPToken, yearnTokens, convexTokens, isBalancerLPToken } from '@gearbox-protocol/sdk-gov';
@@ -14538,6 +14537,31 @@ var MellowLRTPriceFeedContract = class extends AbstractLPPriceFeedContract {
14538
14537
  return stack.totalValue * BigInt(1e18) / stack.totalSupply;
14539
14538
  }
14540
14539
  };
14540
+
14541
+ // src/sdk/utils/internal/Hooks.ts
14542
+ var Hooks = class {
14543
+ #reg = {};
14544
+ addHook(hookName, fn) {
14545
+ if (!this.#reg[hookName]) {
14546
+ this.#reg[hookName] = [];
14547
+ }
14548
+ this.#reg[hookName].push(fn);
14549
+ }
14550
+ removeHook(hookName, fn) {
14551
+ if (!this.#reg[hookName]) {
14552
+ return;
14553
+ }
14554
+ this.#reg[hookName] = this.#reg[hookName]?.filter((hookFn) => hookFn !== fn) ?? [];
14555
+ }
14556
+ async triggerHooks(hookName, ...args) {
14557
+ if (!this.#reg[hookName]) {
14558
+ return;
14559
+ }
14560
+ for (const fn of this.#reg[hookName]) {
14561
+ await fn(...args);
14562
+ }
14563
+ }
14564
+ };
14541
14565
  var RedstonePriceFeedContract = class extends AbstractPriceFeedContract {
14542
14566
  decimals = 8;
14543
14567
  dataServiceId;
@@ -14603,6 +14627,7 @@ var RedstonePriceFeedContract = class extends AbstractPriceFeedContract {
14603
14627
  };
14604
14628
  var RedstoneUpdater = class extends SDKConstruct {
14605
14629
  #logger;
14630
+ #cache = /* @__PURE__ */ new Map();
14606
14631
  constructor(sdk) {
14607
14632
  super(sdk);
14608
14633
  this.#logger = childLogger("RedstoneUpdater", sdk.logger);
@@ -14651,7 +14676,7 @@ var RedstoneUpdater = class extends SDKConstruct {
14651
14676
  this.#logger?.debug(
14652
14677
  `Redstone: fetching redstone payloads for ${group.size} data feeds in ${dataServiceId} with ${uniqueSignersCount} signers: ${Array.from(group).join(", ")}`
14653
14678
  );
14654
- const payloads = await this.#fetchPayloads(
14679
+ const payloads = await this.#getPayloads(
14655
14680
  dataServiceId,
14656
14681
  group,
14657
14682
  uniqueSignersCount,
@@ -14680,6 +14705,51 @@ var RedstoneUpdater = class extends SDKConstruct {
14680
14705
  }
14681
14706
  /**
14682
14707
  * Gets redstone payloads in one request for multiple feeds with the same dataServiceId and uniqueSignersCount
14708
+ * If historicalTimestamp is set, responses will be cached
14709
+ * @param dataServiceId
14710
+ * @param dataFeedsIds
14711
+ * @param uniqueSignersCount
14712
+ * @param historicalTimestamp
14713
+ * @returns
14714
+ */
14715
+ async #getPayloads(dataServiceId, dataFeedsIds, uniqueSignersCount, historicalTimestamp) {
14716
+ const fromCache = [];
14717
+ const uncached = [];
14718
+ for (const dataFeedId of dataFeedsIds) {
14719
+ const key = cacheKey(
14720
+ dataServiceId,
14721
+ dataFeedId,
14722
+ uniqueSignersCount,
14723
+ historicalTimestamp
14724
+ );
14725
+ const cached = this.#cache.get(key);
14726
+ if (historicalTimestamp && !!cached) {
14727
+ fromCache.push(cached);
14728
+ } else {
14729
+ uncached.push(dataFeedId);
14730
+ }
14731
+ }
14732
+ const fromRedstone = await this.#fetchPayloads(
14733
+ dataServiceId,
14734
+ new Set(uncached),
14735
+ uniqueSignersCount,
14736
+ historicalTimestamp
14737
+ );
14738
+ if (historicalTimestamp) {
14739
+ for (const resp of fromRedstone) {
14740
+ const key = cacheKey(
14741
+ dataServiceId,
14742
+ resp.dataFeedId,
14743
+ uniqueSignersCount,
14744
+ historicalTimestamp
14745
+ );
14746
+ this.#cache.set(key, resp);
14747
+ }
14748
+ }
14749
+ return [...fromCache, ...fromRedstone];
14750
+ }
14751
+ /**
14752
+ * Fetches redstone payloads in one request for multiple feeds with the same dataServiceId and uniqueSignersCount
14683
14753
  * Payloads are loaded in one request to avoid redstone rate limit
14684
14754
  * @param dataServiceId
14685
14755
  * @param dataFeedsIds
@@ -14688,6 +14758,9 @@ var RedstoneUpdater = class extends SDKConstruct {
14688
14758
  * @returns
14689
14759
  */
14690
14760
  async #fetchPayloads(dataServiceId, dataFeedsIds, uniqueSignersCount, historicalTimestamp) {
14761
+ if (dataFeedsIds.size === 0) {
14762
+ return [];
14763
+ }
14691
14764
  const dataPackagesIds = Array.from(dataFeedsIds);
14692
14765
  const wrapper = new DataServiceWrapper({
14693
14766
  dataServiceId,
@@ -14716,6 +14789,9 @@ var RedstoneUpdater = class extends SDKConstruct {
14716
14789
  });
14717
14790
  }
14718
14791
  };
14792
+ function cacheKey(dataServiceId, dataFeedId, uniqueSignersCount, historicalTimestamp = 0) {
14793
+ return `${dataServiceId}:${dataFeedId}:${uniqueSignersCount}:${historicalTimestamp}`;
14794
+ }
14719
14795
  function groupDataPackages(signedDataPackages) {
14720
14796
  const packagesByDataFeedId = {};
14721
14797
  for (const p of signedDataPackages) {
@@ -14836,6 +14912,7 @@ var ZeroPriceFeedContract = class extends AbstractPriceFeedContract {
14836
14912
  // src/sdk/market/pricefeeds/PriceFeedsRegister.ts
14837
14913
  var PriceFeedRegister = class extends SDKConstruct {
14838
14914
  logger;
14915
+ #hooks = new Hooks();
14839
14916
  #feeds = new AddressMap();
14840
14917
  #redstoneUpdater;
14841
14918
  // public readonly zeroPriceFeed: ZeroPriceFeedContract;
@@ -14844,6 +14921,8 @@ var PriceFeedRegister = class extends SDKConstruct {
14844
14921
  this.logger = childLogger("PriceFeedRegister", sdk.logger);
14845
14922
  this.#redstoneUpdater = new RedstoneUpdater(sdk);
14846
14923
  }
14924
+ addHook = this.#hooks.addHook.bind(this);
14925
+ removeHook = this.#hooks.removeHook.bind(this);
14847
14926
  /**
14848
14927
  * Returns RawTxs to update price feeds
14849
14928
  * @param priceFeeds top-level price feeds, actual updatable price feeds will be derived. If not provided will use all price feeds that are attached
@@ -14873,7 +14952,9 @@ var PriceFeedRegister = class extends SDKConstruct {
14873
14952
  txs.push(tx);
14874
14953
  }
14875
14954
  }
14876
- return { txs, timestamp: maxTimestamp };
14955
+ const result = { txs, timestamp: maxTimestamp };
14956
+ await this.#hooks.triggerHooks("updatesGenerated", result);
14957
+ return result;
14877
14958
  }
14878
14959
  get(address) {
14879
14960
  return this.#feeds.get(address);
@@ -15001,7 +15082,7 @@ var PriceOracleContract = class extends BaseContract {
15001
15082
  * Generates updates for all updateable price feeds in this oracle (including dependencies)
15002
15083
  * @returns
15003
15084
  */
15004
- async updateRedstonePriceFeeds() {
15085
+ async updatePriceFeeds() {
15005
15086
  const updatables = [];
15006
15087
  for (const node of this.#priceFeedTree) {
15007
15088
  if (node.updatable) {
@@ -15397,6 +15478,7 @@ var SWAP_OPERATIONS = {
15397
15478
  };
15398
15479
  var RouterV3Contract = class extends BaseContract {
15399
15480
  #connectors;
15481
+ #hooks = new Hooks();
15400
15482
  constructor(sdk, address) {
15401
15483
  super(sdk, {
15402
15484
  addr: address,
@@ -15405,6 +15487,8 @@ var RouterV3Contract = class extends BaseContract {
15405
15487
  });
15406
15488
  this.#connectors = getConnectors(sdk.provider.networkType);
15407
15489
  }
15490
+ addHook = this.#hooks.addHook.bind(this);
15491
+ removeHook = this.#hooks.removeHook.bind(this);
15408
15492
  /**
15409
15493
  * Finds all available swaps for NORMAL tokens
15410
15494
  * @param ca
@@ -15538,7 +15622,10 @@ var RouterV3Contract = class extends BaseContract {
15538
15622
  */
15539
15623
  async findBestClosePath(ca, cm, slippage) {
15540
15624
  const { pathOptions, expected, leftover, connectors } = this.getFindClosePathInput(ca, cm);
15541
- this.sdk.emit("foundPathOptions", { pathOptions });
15625
+ await this.#hooks.triggerHooks("foundPathOptions", {
15626
+ creditAccount: ca.creditAccount,
15627
+ pathOptions
15628
+ });
15542
15629
  let results = [];
15543
15630
  for (const po of pathOptions) {
15544
15631
  const { result: result2 } = await this.contract.simulate.findBestClosePath(
@@ -15573,7 +15660,7 @@ var RouterV3Contract = class extends BaseContract {
15573
15660
  })),
15574
15661
  underlyingBalance: underlyingBalance + bestResult.minAmount
15575
15662
  };
15576
- this.sdk.emit("foundBestClosePath", {
15663
+ await this.#hooks.triggerHooks("foundBestClosePath", {
15577
15664
  creditAccount: ca.creditAccount,
15578
15665
  ...result
15579
15666
  });
@@ -15633,7 +15720,7 @@ function assetsMap(assets) {
15633
15720
  }
15634
15721
 
15635
15722
  // src/sdk/GearboxSDK.ts
15636
- var GearboxSDK = class _GearboxSDK extends EventEmitter {
15723
+ var GearboxSDK = class _GearboxSDK {
15637
15724
  // Represents chain object
15638
15725
  #provider;
15639
15726
  // Block which was use for data query
@@ -15696,7 +15783,6 @@ var GearboxSDK = class _GearboxSDK extends EventEmitter {
15696
15783
  }).#attach(addressProvider, riskCurators);
15697
15784
  }
15698
15785
  constructor(options) {
15699
- super();
15700
15786
  this.#provider = options.provider;
15701
15787
  this.logger = options.logger;
15702
15788
  this.priceFeeds = new PriceFeedRegister(this);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gearbox-protocol/sdk",
3
- "version": "3.0.0-vfour.16",
3
+ "version": "3.0.0-vfour.18",
4
4
  "description": "Gearbox SDK",
5
5
  "license": "MIT",
6
6
  "sideEffects": false,
@@ -46,9 +46,8 @@
46
46
  "@redstone-finance/evm-connector": "^0.6.2",
47
47
  "abitype": "^1.0.6",
48
48
  "date-fns": "^4.1.0",
49
- "eventemitter3": "^5.0.1",
50
49
  "redstone-protocol": "^1.0.5",
51
- "viem": "^2.21.16"
50
+ "viem": ">=2.21.0 <3.0.0"
52
51
  },
53
52
  "devDependencies": {
54
53
  "@commitlint/cli": "^19.5.0",