@gearbox-protocol/sdk 17.1.0-next.2 → 17.1.0-next.3

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 (79) hide show
  1. package/dist/cjs/onchain/MultichainSDK.js +2 -27
  2. package/dist/cjs/onchain/OnchainSDK.js +5 -6
  3. package/dist/cjs/onchain/accounts/intents/borrow.js +47 -20
  4. package/dist/cjs/onchain/accounts/intents/guards.js +6 -4
  5. package/dist/cjs/onchain/accounts/intents/index.js +40 -9
  6. package/dist/cjs/onchain/accounts/intents/open-strategy.js +49 -17
  7. package/dist/cjs/onchain/accounts/intents/realize.js +55 -24
  8. package/dist/cjs/onchain/index.js +0 -5
  9. package/dist/cjs/onchain/market/credit/CreditSuite.js +6 -5
  10. package/dist/cjs/onchain/market/index.js +0 -5
  11. package/dist/cjs/onchain/market/pricefeeds/feeds/RedstonePriceFeed.js +1 -7
  12. package/dist/cjs/onchain/market/pricefeeds/index.js +0 -5
  13. package/dist/cjs/onchain/market/pricefeeds/updates/UpdatablePriceFeedRegistry.js +5 -5
  14. package/dist/cjs/onchain/market/pricefeeds/updates/index.js +0 -5
  15. package/dist/cjs/onchain/options.js +1 -7
  16. package/dist/cjs/permissionless/index.js +1 -5
  17. package/dist/cjs/permissionless/utils/index.js +1 -5
  18. package/dist/cjs/permissionless/utils/price-update/get-price-update-tx.js +5 -0
  19. package/dist/cjs/permissionless/utils/price-update/get-updatable-feeds.js +6 -4
  20. package/dist/cjs/permissionless/utils/price-update/index.js +1 -5
  21. package/dist/cjs/sdk/prepare/PrepareApi.js +83 -32
  22. package/dist/esm/onchain/MultichainSDK.js +2 -27
  23. package/dist/esm/onchain/OnchainSDK.js +5 -6
  24. package/dist/esm/onchain/accounts/intents/borrow.js +47 -20
  25. package/dist/esm/onchain/accounts/intents/guards.js +6 -4
  26. package/dist/esm/onchain/accounts/intents/index.js +40 -9
  27. package/dist/esm/onchain/accounts/intents/open-strategy.js +49 -17
  28. package/dist/esm/onchain/accounts/intents/realize.js +55 -24
  29. package/dist/esm/onchain/index.js +1 -3
  30. package/dist/esm/onchain/market/credit/CreditSuite.js +6 -5
  31. package/dist/esm/onchain/market/index.js +1 -3
  32. package/dist/esm/onchain/market/pricefeeds/feeds/RedstonePriceFeed.js +1 -7
  33. package/dist/esm/onchain/market/pricefeeds/index.js +1 -3
  34. package/dist/esm/onchain/market/pricefeeds/updates/UpdatablePriceFeedRegistry.js +5 -5
  35. package/dist/esm/onchain/market/pricefeeds/updates/index.js +1 -3
  36. package/dist/esm/onchain/options.js +1 -7
  37. package/dist/esm/permissionless/index.js +2 -3
  38. package/dist/esm/permissionless/utils/index.js +2 -3
  39. package/dist/esm/permissionless/utils/price-update/get-price-update-tx.js +5 -0
  40. package/dist/esm/permissionless/utils/price-update/get-updatable-feeds.js +6 -4
  41. package/dist/esm/permissionless/utils/price-update/index.js +2 -3
  42. package/dist/esm/sdk/prepare/PrepareApi.js +83 -32
  43. package/dist/types/onchain/MultichainSDK.d.ts +0 -10
  44. package/dist/types/onchain/OnchainSDK.d.ts +0 -10
  45. package/dist/types/onchain/accounts/index.d.ts +2 -2
  46. package/dist/types/onchain/accounts/intents/borrow.d.ts +5 -0
  47. package/dist/types/onchain/accounts/intents/guards.d.ts +6 -4
  48. package/dist/types/onchain/accounts/intents/index.d.ts +4 -4
  49. package/dist/types/onchain/accounts/intents/open-strategy.d.ts +5 -0
  50. package/dist/types/onchain/accounts/intents/realize.d.ts +5 -0
  51. package/dist/types/onchain/accounts/intents/types.d.ts +49 -6
  52. package/dist/types/onchain/index.d.ts +4 -6
  53. package/dist/types/onchain/market/credit/CreditSuite.d.ts +10 -0
  54. package/dist/types/onchain/market/index.d.ts +3 -5
  55. package/dist/types/onchain/market/pricefeeds/feeds/RedstonePriceFeed.d.ts +1 -4
  56. package/dist/types/onchain/market/pricefeeds/index.d.ts +3 -5
  57. package/dist/types/onchain/market/pricefeeds/updates/UpdatablePriceFeedRegistry.d.ts +4 -4
  58. package/dist/types/onchain/market/pricefeeds/updates/index.d.ts +3 -5
  59. package/dist/types/onchain/market/pricefeeds/updates/types.d.ts +2 -16
  60. package/dist/types/onchain/options.d.ts +0 -7
  61. package/dist/types/permissionless/index.d.ts +2 -3
  62. package/dist/types/permissionless/utils/index.d.ts +2 -3
  63. package/dist/types/permissionless/utils/price-update/get-price-update-tx.d.ts +5 -0
  64. package/dist/types/permissionless/utils/price-update/get-updatable-feeds.d.ts +9 -3
  65. package/dist/types/permissionless/utils/price-update/index.d.ts +2 -3
  66. package/dist/types/sdk/index.d.ts +2 -2
  67. package/dist/types/sdk/prepare/PrepareApi.d.ts +16 -14
  68. package/dist/types/sdk/prepare/index.d.ts +2 -2
  69. package/dist/types/sdk/prepare/types.d.ts +21 -14
  70. package/package.json +1 -5
  71. package/dist/cjs/onchain/market/pricefeeds/updates/RedstoneUpdater.js +0 -193
  72. package/dist/cjs/onchain/market/pricefeeds/updates/fetchRedstonePayloads.js +0 -95
  73. package/dist/cjs/permissionless/utils/price-update/get-price-feeds.js +0 -60
  74. package/dist/esm/onchain/market/pricefeeds/updates/RedstoneUpdater.js +0 -191
  75. package/dist/esm/onchain/market/pricefeeds/updates/fetchRedstonePayloads.js +0 -94
  76. package/dist/esm/permissionless/utils/price-update/get-price-feeds.js +0 -57
  77. package/dist/types/onchain/market/pricefeeds/updates/RedstoneUpdater.d.ts +0 -37
  78. package/dist/types/onchain/market/pricefeeds/updates/fetchRedstonePayloads.d.ts +0 -62
  79. package/dist/types/permissionless/utils/price-update/get-price-feeds.d.ts +0 -22
@@ -1,5 +1,4 @@
1
- import { getCallTouchedPriceFeeds, getCallsTouchedPriceFeeds, getCallsTouchedUpdatablePriceFeeds } from "./get-price-feeds.js";
2
1
  import { getPriceUpdateTx } from "./get-price-update-tx.js";
3
2
  import { getPrices } from "./get-prices.js";
4
- import { getUpdatablePriceFeeds } from "./get-updatable-feeds.js";
5
- export { getCallTouchedPriceFeeds, getCallsTouchedPriceFeeds, getCallsTouchedUpdatablePriceFeeds, getPriceUpdateTx, getPrices, getUpdatablePriceFeeds };
3
+ import { GetUpdatablePriceFeedsArgs, getUpdatablePriceFeeds } from "./get-updatable-feeds.js";
4
+ export { GetUpdatablePriceFeedsArgs, getPriceUpdateTx, getPrices, getUpdatablePriceFeeds };
@@ -1,5 +1,5 @@
1
1
  import { CreditAccountNotEmptyError, CreditAccountNotFoundError, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, UnexpectedFailureError, UnsupportedCollateralTokenError, UnsupportedTokenPairError, WithdrawalInProgressError, creditAccountNotEmpty, creditAccountNotFound, noStrategyTargetCollateral, unexpectedFailure } from "../model/errors/prepare-errors.js";
2
- import { ExecutionCost, OperationState, PathLossRate, RouteErrors, WithdrawCeilings } from "../onchain/accounts/intents/types.js";
2
+ import { ExecutionCost, OperationState, PathLossRate, RouteErrors, WithPartialState, WithdrawCeilings } from "../onchain/accounts/intents/types.js";
3
3
  import { BorrowState } from "../onchain/accounts/intents/borrow.js";
4
4
  import { LeverageBand } from "../onchain/accounts/intents/leverage-band.js";
5
5
  import { PoolOperationError } from "../onchain/validation/bundles/checkPoolOperation.js";
@@ -39,4 +39,4 @@ import { SourceUnavailableError } from "./errors/SourceUnavailableError.js";
39
39
  import { assertSameChains } from "./errors/assertSameChains.js";
40
40
  import { everyChainFailed } from "./errors/everyChainFailed.js";
41
41
  import "./errors/index.js";
42
- export { AbstractNamespace, AccountFlowError, AccountPrepareRequest, AddCollateralParams, AdjustLeverageParams, AllSourcesFailedError, AnalyticsNamespace, BorrowParams, BorrowPrepareRequest, BorrowResult, type BorrowState, ChainOf, ChainRef, CheckOperationProps, type CreditAccountNotEmptyError, type CreditAccountNotFoundError, DEFAULT_MAX_OFFCHAIN_LAG, DEFAULT_MAX_STATE_AGE, DelayedStrategyResult, DepositStrategyParams, EmptyCreditAccountResult, EnsureFreshChains, type EntityMerger, ExecuteApi, type ExecutionCost, type FilterResult, FinalizeParams, FinalizeResult, GearboxSDK, GearboxSDKOptions, IAnalytics, IAnalyticsByMode, IGearboxSDK, ILiquidations, ILiquidationsByMode, INotices, INoticesByMode, IOpportunities, IOpportunitiesBase, IOpportunitiesByMode, IOpportunitiesExecute, IOpportunitiesOffchainBranch, IOpportunitiesOffchainOnly, IOpportunitiesOnchainBranch, IOpportunitiesOnchainOnly, IOpportunitiesPrepare, IOpportunityMergers, IPositionMergers, IPositions, IPositionsBase, IPositionsByMode, IPositionsOffchainBranch, IPositionsOffchainOnly, IPositionsOnchainBranch, IPositionsOnchainOnly, IPreview, IPreviewByMode, type LeverageBand, LiquidationsNamespace, type ListMerger, LpParams, LpRedeemParams, LpResult, LpState, MaxBorrowParams, type MergeListResult, MergedQuery, MissingSourceError, Mode, type MultipleDelayedWithdrawalsError, NamespaceOptions, type NoDelayedRouteError, type NoRecordedIntentError, NoSourceServedError, type NoStrategyTargetCollateralError, OffchainByMode, OffchainSource, OnchainByMode, OnchainSource, OpenEmptyPrepareRequest, OpenFlowError, OpenPrepareRequest, OpenStrategyParams, OpenStrategyResult, type OperationState, OpportunitiesNamespace, type PathLossRate, PlainMultichainSDKOptions, PoolInput, type PoolOperationError, PoolPrepareRequest, PositionInput, PositionsNamespace, PrepareApi, PrepareOptions, PrepareRequest, PreviewNamespace, RepayStrategyParams, type RouteErrors, SourceChainMismatchError, SourceUnavailableError, StrategyInput, StrategyResult, StrategyRoutesResult, type UnexpectedFailureError, type UnsupportedCollateralTokenError, type UnsupportedTokenPairError, WithRouteErrors, type WithdrawCeilings, WithdrawCollateralParams, WithdrawStrategyParams, type WithdrawalInProgressError, assertSameChains, creditAccountNotEmpty, creditAccountNotFound, everyChainFailed, filterResponse, mergeChainList, mergeChainOne, noStrategyTargetCollateral, unexpectedFailure };
42
+ export { AbstractNamespace, AccountFlowError, AccountPrepareRequest, AddCollateralParams, AdjustLeverageParams, AllSourcesFailedError, AnalyticsNamespace, BorrowParams, BorrowPrepareRequest, BorrowResult, type BorrowState, ChainOf, ChainRef, CheckOperationProps, type CreditAccountNotEmptyError, type CreditAccountNotFoundError, DEFAULT_MAX_OFFCHAIN_LAG, DEFAULT_MAX_STATE_AGE, DelayedStrategyResult, DepositStrategyParams, EmptyCreditAccountResult, EnsureFreshChains, type EntityMerger, ExecuteApi, type ExecutionCost, type FilterResult, FinalizeParams, FinalizeResult, GearboxSDK, GearboxSDKOptions, IAnalytics, IAnalyticsByMode, IGearboxSDK, ILiquidations, ILiquidationsByMode, INotices, INoticesByMode, IOpportunities, IOpportunitiesBase, IOpportunitiesByMode, IOpportunitiesExecute, IOpportunitiesOffchainBranch, IOpportunitiesOffchainOnly, IOpportunitiesOnchainBranch, IOpportunitiesOnchainOnly, IOpportunitiesPrepare, IOpportunityMergers, IPositionMergers, IPositions, IPositionsBase, IPositionsByMode, IPositionsOffchainBranch, IPositionsOffchainOnly, IPositionsOnchainBranch, IPositionsOnchainOnly, IPreview, IPreviewByMode, type LeverageBand, LiquidationsNamespace, type ListMerger, LpParams, LpRedeemParams, LpResult, LpState, MaxBorrowParams, type MergeListResult, MergedQuery, MissingSourceError, Mode, type MultipleDelayedWithdrawalsError, NamespaceOptions, type NoDelayedRouteError, type NoRecordedIntentError, NoSourceServedError, type NoStrategyTargetCollateralError, OffchainByMode, OffchainSource, OnchainByMode, OnchainSource, OpenEmptyPrepareRequest, OpenFlowError, OpenPrepareRequest, OpenStrategyParams, OpenStrategyResult, type OperationState, OpportunitiesNamespace, type PathLossRate, PlainMultichainSDKOptions, PoolInput, type PoolOperationError, PoolPrepareRequest, PositionInput, PositionsNamespace, PrepareApi, PrepareOptions, PrepareRequest, PreviewNamespace, RepayStrategyParams, type RouteErrors, SourceChainMismatchError, SourceUnavailableError, StrategyInput, StrategyResult, StrategyRoutesResult, type UnexpectedFailureError, type UnsupportedCollateralTokenError, type UnsupportedTokenPairError, type WithPartialState, WithRouteErrors, type WithdrawCeilings, WithdrawCollateralParams, WithdrawStrategyParams, type WithdrawalInProgressError, assertSameChains, creditAccountNotEmpty, creditAccountNotFound, everyChainFailed, filterResponse, mergeChainList, mergeChainOne, noStrategyTargetCollateral, unexpectedFailure };
@@ -8,11 +8,13 @@ import { Asset } from "../../onchain/base/types.js";
8
8
  import { OnchainSDK } from "../../onchain/OnchainSDK.js";
9
9
  import { MultichainSDK } from "../../onchain/MultichainSDK.js";
10
10
  import { MultichainConstruct } from "../../onchain/base/MultichainConstruct.js";
11
- import { WithdrawCeilings } from "../../onchain/accounts/intents/types.js";
11
+ import { OperationState, WithPartialState, WithdrawCeilings } from "../../onchain/accounts/intents/types.js";
12
+ import { BorrowState } from "../../onchain/accounts/intents/borrow.js";
12
13
  import { LeverageBand } from "../../onchain/accounts/intents/leverage-band.js";
14
+ import { OpenStrategyState } from "../../onchain/accounts/intents/open-strategy.js";
13
15
  import { PoolOperationError } from "../../onchain/validation/bundles/checkPoolOperation.js";
14
16
  import "../../onchain/index.js";
15
- import { AccountFlowError, AddCollateralParams, AdjustLeverageParams, BorrowParams, BorrowResult, DepositStrategyParams, EmptyCreditAccountResult, FinalizeParams, FinalizeResult, IOpportunitiesPrepare, LpParams, LpRedeemParams, LpResult, MaxBorrowParams, OpenFlowError, OpenStrategyParams, OpenStrategyResult, PoolInput, PositionInput, RepayStrategyParams, StrategyInput, StrategyResult, StrategyRoutesResult, WithRouteErrors, WithdrawCollateralParams, WithdrawStrategyParams } from "./types.js";
17
+ import { AccountFlowError, AddCollateralParams, AdjustLeverageParams, BorrowParams, BorrowResult, DepositStrategyParams, EmptyCreditAccountResult, FinalizeParams, FinalizeResult, IOpportunitiesPrepare, LpParams, LpRedeemParams, LpResult, LpState, MaxBorrowParams, OpenFlowError, OpenStrategyParams, OpenStrategyResult, PoolInput, PositionInput, RepayStrategyParams, StrategyInput, StrategyResult, StrategyRoutesResult, WithRouteErrors, WithdrawCollateralParams, WithdrawStrategyParams } from "./types.js";
16
18
  import { EnsureFreshChains } from "../types.js";
17
19
  import { Address } from "viem";
18
20
  //#region src/sdk/prepare/PrepareApi.d.ts
@@ -51,19 +53,19 @@ declare class PrepareApi extends MultichainConstruct implements IOpportunitiesPr
51
53
  /**
52
54
  * {@inheritDoc IOpportunitiesPrepare.finalize}
53
55
  **/
54
- finalize(position: PositionInput, params: FinalizeParams): Promise<SDKReturn<FinalizeResult, AccountFlowError | NoRecordedIntentError | NoDelayedRouteError | WithdrawalInProgressError | UnsupportedTokenPairError>>;
56
+ finalize(position: PositionInput, params: FinalizeParams): Promise<SDKReturn<FinalizeResult, (AccountFlowError | NoRecordedIntentError | NoDelayedRouteError | WithdrawalInProgressError | UnsupportedTokenPairError) & WithPartialState<OperationState>>>;
55
57
  /**
56
58
  * {@inheritDoc IOpportunitiesPrepare.deposit}
57
59
  **/
58
- deposit(pool: PoolInput, params: LpParams): Promise<SDKReturn<LpResult, UnsupportedTokenPairError | UnexpectedFailureError | PoolOperationError>>;
60
+ deposit(pool: PoolInput, params: LpParams): Promise<SDKReturn<LpResult, (UnsupportedTokenPairError | UnexpectedFailureError | PoolOperationError) & WithPartialState<LpState>>>;
59
61
  /**
60
62
  * {@inheritDoc IOpportunitiesPrepare.withdraw}
61
63
  **/
62
- withdraw(pool: PoolInput, params: LpParams): Promise<SDKReturn<LpResult, UnsupportedTokenPairError | UnexpectedFailureError | PoolOperationError>>;
64
+ withdraw(pool: PoolInput, params: LpParams): Promise<SDKReturn<LpResult, (UnsupportedTokenPairError | UnexpectedFailureError | PoolOperationError) & WithPartialState<LpState>>>;
63
65
  /**
64
66
  * {@inheritDoc IOpportunitiesPrepare.redeem}
65
67
  **/
66
- redeem(pool: PoolInput, params: LpRedeemParams): Promise<SDKReturn<LpResult, UnsupportedTokenPairError | UnexpectedFailureError | PoolOperationError>>;
68
+ redeem(pool: PoolInput, params: LpRedeemParams): Promise<SDKReturn<LpResult, (UnsupportedTokenPairError | UnexpectedFailureError | PoolOperationError) & WithPartialState<LpState>>>;
67
69
  /**
68
70
  * {@inheritDoc IOpportunitiesPrepare.openEmptyCreditAccount}
69
71
  **/
@@ -71,19 +73,19 @@ declare class PrepareApi extends MultichainConstruct implements IOpportunitiesPr
71
73
  /**
72
74
  * {@inheritDoc IOpportunitiesPrepare.openNewStrategy}
73
75
  **/
74
- openNewStrategy(strategy: StrategyInput, params: OpenStrategyParams): Promise<SDKReturn<OpenStrategyResult, OpenFlowError | DebtOutOfRangeError | LeverageOutOfRangeError | UnsupportedTokenPairError | InsufficientPoolLiquidityError | NoStrategyTargetCollateralError | CreditAccountNotFoundError | CreditAccountNotEmptyError>>;
76
+ openNewStrategy(strategy: StrategyInput, params: OpenStrategyParams): Promise<SDKReturn<OpenStrategyResult, (OpenFlowError | DebtOutOfRangeError | LeverageOutOfRangeError | UnsupportedTokenPairError | InsufficientPoolLiquidityError | NoStrategyTargetCollateralError | CreditAccountNotFoundError | CreditAccountNotEmptyError) & WithPartialState<OpenStrategyState>>>;
75
77
  /**
76
78
  * {@inheritDoc IOpportunitiesPrepare.borrow}
77
79
  **/
78
- borrow(strategy: StrategyInput, params: BorrowParams): Promise<SDKReturn<BorrowResult, OpenFlowError | DebtOutOfRangeError | UnsupportedCollateralTokenError | UnsupportedTokenPairError | InsufficientPoolLiquidityError | CreditAccountNotFoundError | CreditAccountNotEmptyError>>;
80
+ borrow(strategy: StrategyInput, params: BorrowParams): Promise<SDKReturn<BorrowResult, (OpenFlowError | DebtOutOfRangeError | UnsupportedCollateralTokenError | UnsupportedTokenPairError | InsufficientPoolLiquidityError | CreditAccountNotFoundError | CreditAccountNotEmptyError) & WithPartialState<BorrowState>>>;
79
81
  /**
80
82
  * {@inheritDoc IOpportunitiesPrepare.depositStrategy}
81
83
  **/
82
- depositStrategy(position: PositionInput, params: DepositStrategyParams): Promise<SDKReturn<StrategyResult, AccountFlowError | DebtOutOfRangeError | LeverageOutOfRangeError | UnsupportedCollateralTokenError | UnsupportedTokenPairError | InsufficientPoolLiquidityError>>;
84
+ depositStrategy(position: PositionInput, params: DepositStrategyParams): Promise<SDKReturn<StrategyResult, (AccountFlowError | DebtOutOfRangeError | LeverageOutOfRangeError | UnsupportedCollateralTokenError | UnsupportedTokenPairError | InsufficientPoolLiquidityError) & WithPartialState<OperationState>>>;
83
85
  /**
84
86
  * {@inheritDoc IOpportunitiesPrepare.withdrawStrategy}
85
87
  **/
86
- withdrawStrategy(position: PositionInput, params: WithdrawStrategyParams): Promise<SDKReturn<StrategyRoutesResult, (AccountFlowError | DebtOutOfRangeError | UnsupportedTokenPairError | NoDelayedRouteError | MultipleDelayedWithdrawalsError | WithdrawalInProgressError) & WithRouteErrors>>;
88
+ withdrawStrategy(position: PositionInput, params: WithdrawStrategyParams): Promise<SDKReturn<StrategyRoutesResult, (AccountFlowError | DebtOutOfRangeError | UnsupportedTokenPairError | NoDelayedRouteError | MultipleDelayedWithdrawalsError | WithdrawalInProgressError) & WithRouteErrors & WithPartialState<OperationState>>>;
87
89
  /**
88
90
  * {@inheritDoc IOpportunitiesPrepare.maxWithdraw}
89
91
  **/
@@ -91,7 +93,7 @@ declare class PrepareApi extends MultichainConstruct implements IOpportunitiesPr
91
93
  /**
92
94
  * {@inheritDoc IOpportunitiesPrepare.repayStrategy}
93
95
  **/
94
- repayStrategy(position: PositionInput, params: RepayStrategyParams): Promise<SDKReturn<StrategyResult, AccountFlowError | DebtOutOfRangeError | UnsupportedCollateralTokenError>>;
96
+ repayStrategy(position: PositionInput, params: RepayStrategyParams): Promise<SDKReturn<StrategyResult, (AccountFlowError | DebtOutOfRangeError | UnsupportedCollateralTokenError) & WithPartialState<OperationState>>>;
95
97
  /**
96
98
  * {@inheritDoc IOpportunitiesPrepare.maxRepay}
97
99
  **/
@@ -99,15 +101,15 @@ declare class PrepareApi extends MultichainConstruct implements IOpportunitiesPr
99
101
  /**
100
102
  * {@inheritDoc IOpportunitiesPrepare.adjustLeverage}
101
103
  **/
102
- adjustLeverage(position: PositionInput, params: AdjustLeverageParams): Promise<SDKReturn<StrategyRoutesResult, (AccountFlowError | DebtOutOfRangeError | UnsupportedTokenPairError | NoDelayedRouteError | MultipleDelayedWithdrawalsError | WithdrawalInProgressError | InsufficientPoolLiquidityError | LeverageOutOfRangeError) & WithRouteErrors>>;
104
+ adjustLeverage(position: PositionInput, params: AdjustLeverageParams): Promise<SDKReturn<StrategyRoutesResult, (AccountFlowError | DebtOutOfRangeError | UnsupportedTokenPairError | NoDelayedRouteError | MultipleDelayedWithdrawalsError | WithdrawalInProgressError | InsufficientPoolLiquidityError | LeverageOutOfRangeError) & WithRouteErrors & WithPartialState<OperationState>>>;
103
105
  /**
104
106
  * {@inheritDoc IOpportunitiesPrepare.addCollateral}
105
107
  **/
106
- addCollateral(position: PositionInput, params: AddCollateralParams): Promise<SDKReturn<StrategyResult, AccountFlowError>>;
108
+ addCollateral(position: PositionInput, params: AddCollateralParams): Promise<SDKReturn<StrategyResult, AccountFlowError & WithPartialState<OperationState>>>;
107
109
  /**
108
110
  * {@inheritDoc IOpportunitiesPrepare.withdrawCollateral}
109
111
  **/
110
- withdrawCollateral(position: PositionInput, params: WithdrawCollateralParams): Promise<SDKReturn<StrategyResult, AccountFlowError>>;
112
+ withdrawCollateral(position: PositionInput, params: WithdrawCollateralParams): Promise<SDKReturn<StrategyResult, AccountFlowError & WithPartialState<OperationState>>>;
111
113
  /**
112
114
  * {@inheritDoc IOpportunitiesPrepare.leverageBand}
113
115
  **/
@@ -1,9 +1,9 @@
1
1
  import { CreditAccountNotEmptyError, CreditAccountNotFoundError, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, UnexpectedFailureError, UnsupportedCollateralTokenError, UnsupportedTokenPairError, WithdrawalInProgressError, creditAccountNotEmpty, creditAccountNotFound, noStrategyTargetCollateral, unexpectedFailure } from "../../model/errors/prepare-errors.js";
2
2
  import "../../model/index.js";
3
- import { ExecutionCost, OperationState, PathLossRate, RouteErrors, WithdrawCeilings } from "../../onchain/accounts/intents/types.js";
3
+ import { ExecutionCost, OperationState, PathLossRate, RouteErrors, WithPartialState, WithdrawCeilings } from "../../onchain/accounts/intents/types.js";
4
4
  import { BorrowState } from "../../onchain/accounts/intents/borrow.js";
5
5
  import { LeverageBand } from "../../onchain/accounts/intents/leverage-band.js";
6
6
  import { PoolOperationError } from "../../onchain/validation/bundles/checkPoolOperation.js";
7
7
  import { AccountFlowError, AddCollateralParams, AdjustLeverageParams, BorrowParams, BorrowResult, DelayedStrategyResult, DepositStrategyParams, EmptyCreditAccountResult, FinalizeParams, FinalizeResult, IOpportunitiesPrepare, LpParams, LpRedeemParams, LpResult, LpState, MaxBorrowParams, OpenFlowError, OpenStrategyParams, OpenStrategyResult, PoolInput, PositionInput, PrepareOptions, RepayStrategyParams, StrategyInput, StrategyResult, StrategyRoutesResult, WithRouteErrors, WithdrawCollateralParams, WithdrawStrategyParams } from "./types.js";
8
8
  import { ChainOf, PrepareApi } from "./PrepareApi.js";
9
- export { AccountFlowError, AddCollateralParams, AdjustLeverageParams, BorrowParams, BorrowResult, type BorrowState, ChainOf, type CreditAccountNotEmptyError, type CreditAccountNotFoundError, DelayedStrategyResult, DepositStrategyParams, EmptyCreditAccountResult, type ExecutionCost, FinalizeParams, FinalizeResult, IOpportunitiesPrepare, type LeverageBand, LpParams, LpRedeemParams, LpResult, LpState, MaxBorrowParams, type MultipleDelayedWithdrawalsError, type NoDelayedRouteError, type NoRecordedIntentError, type NoStrategyTargetCollateralError, OpenFlowError, OpenStrategyParams, OpenStrategyResult, type OperationState, type PathLossRate, PoolInput, type PoolOperationError, PositionInput, PrepareApi, PrepareOptions, RepayStrategyParams, type RouteErrors, StrategyInput, StrategyResult, StrategyRoutesResult, type UnexpectedFailureError, type UnsupportedCollateralTokenError, type UnsupportedTokenPairError, WithRouteErrors, type WithdrawCeilings, WithdrawCollateralParams, WithdrawStrategyParams, type WithdrawalInProgressError, creditAccountNotEmpty, creditAccountNotFound, noStrategyTargetCollateral, unexpectedFailure };
9
+ export { AccountFlowError, AddCollateralParams, AdjustLeverageParams, BorrowParams, BorrowResult, type BorrowState, ChainOf, type CreditAccountNotEmptyError, type CreditAccountNotFoundError, DelayedStrategyResult, DepositStrategyParams, EmptyCreditAccountResult, type ExecutionCost, FinalizeParams, FinalizeResult, IOpportunitiesPrepare, type LeverageBand, LpParams, LpRedeemParams, LpResult, LpState, MaxBorrowParams, type MultipleDelayedWithdrawalsError, type NoDelayedRouteError, type NoRecordedIntentError, type NoStrategyTargetCollateralError, OpenFlowError, OpenStrategyParams, OpenStrategyResult, type OperationState, type PathLossRate, PoolInput, type PoolOperationError, PositionInput, PrepareApi, PrepareOptions, RepayStrategyParams, type RouteErrors, StrategyInput, StrategyResult, StrategyRoutesResult, type UnexpectedFailureError, type UnsupportedCollateralTokenError, type UnsupportedTokenPairError, type WithPartialState, WithRouteErrors, type WithdrawCeilings, WithdrawCollateralParams, WithdrawStrategyParams, type WithdrawalInProgressError, creditAccountNotEmpty, creditAccountNotFound, noStrategyTargetCollateral, unexpectedFailure };
@@ -11,7 +11,7 @@ import { Asset } from "../../onchain/base/types.js";
11
11
  import { MultiCall } from "../../onchain/types/transactions.js";
12
12
  import { PoolSimulation } from "../../onchain/pools/types.js";
13
13
  import { AccountCalculatorOperation } from "../../onchain/accounts/intents/operations.js";
14
- import { ClaimRemainder, DelayedStart, ExecutionCost, OperationState, PathLossRate, ResumableIntent, RouteErrors, WithdrawCeilings } from "../../onchain/accounts/intents/types.js";
14
+ import { ClaimRemainder, DelayedStart, ExecutionCost, OperationState, PathLossRate, ResumableIntent, RouteErrors, WithPartialState, WithdrawCeilings } from "../../onchain/accounts/intents/types.js";
15
15
  import { BorrowState } from "../../onchain/accounts/intents/borrow.js";
16
16
  import { LeverageBand } from "../../onchain/accounts/intents/leverage-band.js";
17
17
  import { OpenStrategyState } from "../../onchain/accounts/intents/open-strategy.js";
@@ -537,6 +537,13 @@ interface FinalizeParams extends PrepareOptions {
537
537
  * throws: a chain that cannot be reached or a crash on the way arrives as
538
538
  * `unexpectedFailure` with the cause attached.
539
539
  *
540
+ * Every method that reports a state reports one when it refuses too: the error
541
+ * carries `state`, the same shape the answer beside it would have had, with
542
+ * the fields the request never got far enough to say left out — see
543
+ * {@link WithPartialState}. A form that asked "what would this do to my
544
+ * position" is told as much of it as there was, and can explain the no in
545
+ * numbers rather than in a code alone.
546
+ *
540
547
  * The bare readers stay outside the envelope. The ones that read an account
541
548
  * answer their number and throw on an account or chain the SDK does not hold;
542
549
  * the synchronous ones ({@link leverageBand}, {@link withdrawableCollaterals},
@@ -551,7 +558,7 @@ interface IOpportunitiesPrepare {
551
558
  * loaded already; the wait is for the one thing that is not, the shares the
552
559
  * wallet holds, without which {@link LpState.netValue} cannot be said.
553
560
  **/
554
- deposit(pool: PoolInput, params: LpParams): Promise<SDKReturn<LpResult, UnsupportedTokenPairError | UnexpectedFailureError | PoolOperationError>>;
561
+ deposit(pool: PoolInput, params: LpParams): Promise<SDKReturn<LpResult, (UnsupportedTokenPairError | UnexpectedFailureError | PoolOperationError) & WithPartialState<LpState>>>;
555
562
  /**
556
563
  * Taking underlying out of a pool: `amount` is the `tokenOut` the wallet
557
564
  * wants back, and the pool burns whatever shares that costs.
@@ -559,12 +566,12 @@ interface IOpportunitiesPrepare {
559
566
  * The LP counterpart of {@link withdrawStrategy} / {@link withdrawCollateral},
560
567
  * which act on credit accounts.
561
568
  **/
562
- withdraw(pool: PoolInput, params: LpParams): Promise<SDKReturn<LpResult, UnsupportedTokenPairError | UnexpectedFailureError | PoolOperationError>>;
569
+ withdraw(pool: PoolInput, params: LpParams): Promise<SDKReturn<LpResult, (UnsupportedTokenPairError | UnexpectedFailureError | PoolOperationError) & WithPartialState<LpState>>>;
563
570
  /**
564
571
  * Redeeming pool shares: `amount` is the `tokenIn` the wallet parts with,
565
572
  * and the reported state is the underlying it converts to.
566
573
  **/
567
- redeem(pool: PoolInput, params: LpRedeemParams): Promise<SDKReturn<LpResult, UnsupportedTokenPairError | UnexpectedFailureError | PoolOperationError>>;
574
+ redeem(pool: PoolInput, params: LpRedeemParams): Promise<SDKReturn<LpResult, (UnsupportedTokenPairError | UnexpectedFailureError | PoolOperationError) & WithPartialState<LpState>>>;
568
575
  /**
569
576
  * Opening a leveraged position from wallet collateral.
570
577
  *
@@ -574,7 +581,7 @@ interface IOpportunitiesPrepare {
574
581
  * `creditAccount` puts the position on an account the wallet already holds
575
582
  * rather than creating one.
576
583
  **/
577
- openNewStrategy(strategy: StrategyInput, params: OpenStrategyParams): Promise<SDKReturn<OpenStrategyResult, OpenFlowError | DebtOutOfRangeError | LeverageOutOfRangeError | UnsupportedTokenPairError | InsufficientPoolLiquidityError | NoStrategyTargetCollateralError | CreditAccountNotFoundError | CreditAccountNotEmptyError>>;
584
+ openNewStrategy(strategy: StrategyInput, params: OpenStrategyParams): Promise<SDKReturn<OpenStrategyResult, (OpenFlowError | DebtOutOfRangeError | LeverageOutOfRangeError | UnsupportedTokenPairError | InsufficientPoolLiquidityError | NoStrategyTargetCollateralError | CreditAccountNotFoundError | CreditAccountNotEmptyError) & WithPartialState<OpenStrategyState>>>;
578
585
  /**
579
586
  * Handing a wallet an account that holds nothing: no collateral, no debt, no
580
587
  * quotas and no route quoted. It exists so a wallet can hold an account
@@ -602,14 +609,14 @@ interface IOpportunitiesPrepare {
602
609
  * `creditAccount` draws the loan on an account the wallet already holds
603
610
  * instead of opening another, as {@link openNewStrategy} does.
604
611
  **/
605
- borrow(strategy: StrategyInput, params: BorrowParams): Promise<SDKReturn<BorrowResult, OpenFlowError | DebtOutOfRangeError | UnsupportedCollateralTokenError | UnsupportedTokenPairError | InsufficientPoolLiquidityError | CreditAccountNotFoundError | CreditAccountNotEmptyError>>;
612
+ borrow(strategy: StrategyInput, params: BorrowParams): Promise<SDKReturn<BorrowResult, (OpenFlowError | DebtOutOfRangeError | UnsupportedCollateralTokenError | UnsupportedTokenPairError | InsufficientPoolLiquidityError | CreditAccountNotFoundError | CreditAccountNotEmptyError) & WithPartialState<BorrowState>>>;
606
613
  /**
607
614
  * Growing a position: collateral in, debt drawn on top, both converted into
608
615
  * the position token.
609
616
  *
610
617
  * Leverage stays put unless `targetLeverage` asks for more.
611
618
  **/
612
- depositStrategy(position: PositionInput, params: DepositStrategyParams): Promise<SDKReturn<StrategyResult, AccountFlowError | DebtOutOfRangeError | LeverageOutOfRangeError | UnsupportedCollateralTokenError | UnsupportedTokenPairError | InsufficientPoolLiquidityError>>;
619
+ depositStrategy(position: PositionInput, params: DepositStrategyParams): Promise<SDKReturn<StrategyResult, (AccountFlowError | DebtOutOfRangeError | LeverageOutOfRangeError | UnsupportedCollateralTokenError | UnsupportedTokenPairError | InsufficientPoolLiquidityError) & WithPartialState<OperationState>>>;
613
620
  /**
614
621
  * Shrinking a position: part of its net value goes to the wallet and debt is
615
622
  * repaid in the same proportion, so leverage is unchanged.
@@ -635,7 +642,7 @@ interface IOpportunitiesPrepare {
635
642
  * @see withdrawCollateral to move an asset out without touching debt, which
636
643
  * raises leverage instead.
637
644
  **/
638
- withdrawStrategy(position: PositionInput, params: WithdrawStrategyParams): Promise<SDKReturn<StrategyRoutesResult, (AccountFlowError | DebtOutOfRangeError | UnsupportedTokenPairError | NoDelayedRouteError | MultipleDelayedWithdrawalsError | WithdrawalInProgressError) & WithRouteErrors>>;
645
+ withdrawStrategy(position: PositionInput, params: WithdrawStrategyParams): Promise<SDKReturn<StrategyRoutesResult, (AccountFlowError | DebtOutOfRangeError | UnsupportedTokenPairError | NoDelayedRouteError | MultipleDelayedWithdrawalsError | WithdrawalInProgressError) & WithRouteErrors & WithPartialState<OperationState>>>;
639
646
  /**
640
647
  * How much {@link withdrawStrategy} can take out, every end of it, in
641
648
  * underlying units: `safePartial` is the largest partial withdrawal the flow
@@ -680,7 +687,7 @@ interface IOpportunitiesPrepare {
680
687
  * 10bps margin for the interest still to come, and whatever the facade does
681
688
  * not take stays on the account.
682
689
  **/
683
- repayStrategy(position: PositionInput, params: RepayStrategyParams): Promise<SDKReturn<StrategyResult, AccountFlowError | DebtOutOfRangeError | UnsupportedCollateralTokenError>>;
690
+ repayStrategy(position: PositionInput, params: RepayStrategyParams): Promise<SDKReturn<StrategyResult, (AccountFlowError | DebtOutOfRangeError | UnsupportedCollateralTokenError) & WithPartialState<OperationState>>>;
684
691
  /**
685
692
  * Debt {@link repayStrategy} would have to cover to clear the account, in
686
693
  * underlying units: principal, interest and fees as of this read. Interest
@@ -698,12 +705,12 @@ interface IOpportunitiesPrepare {
698
705
  * buys instead, so there the delayed route is always absent with
699
706
  * `errors.delayed` set to `noDelayedRoute`.
700
707
  **/
701
- adjustLeverage(position: PositionInput, params: AdjustLeverageParams): Promise<SDKReturn<StrategyRoutesResult, (AccountFlowError | DebtOutOfRangeError | UnsupportedTokenPairError | NoDelayedRouteError | MultipleDelayedWithdrawalsError | WithdrawalInProgressError | InsufficientPoolLiquidityError | LeverageOutOfRangeError) & WithRouteErrors>>;
708
+ adjustLeverage(position: PositionInput, params: AdjustLeverageParams): Promise<SDKReturn<StrategyRoutesResult, (AccountFlowError | DebtOutOfRangeError | UnsupportedTokenPairError | NoDelayedRouteError | MultipleDelayedWithdrawalsError | WithdrawalInProgressError | InsufficientPoolLiquidityError | LeverageOutOfRangeError) & WithRouteErrors & WithPartialState<OperationState>>>;
702
709
  /**
703
710
  * Putting the position token onto the account at fixed debt, which lowers
704
711
  * leverage and raises the health factor.
705
712
  **/
706
- addCollateral(position: PositionInput, params: AddCollateralParams): Promise<SDKReturn<StrategyResult, AccountFlowError>>;
713
+ addCollateral(position: PositionInput, params: AddCollateralParams): Promise<SDKReturn<StrategyResult, AccountFlowError & WithPartialState<OperationState>>>;
707
714
  /**
708
715
  * Moving one asset that already sits on the account out to the wallet, at
709
716
  * fixed debt — so TVL falls and leverage rises.
@@ -711,7 +718,7 @@ interface IOpportunitiesPrepare {
711
718
  * @see withdrawStrategy for the deleveraging withdrawal, which repays debt in
712
719
  * proportion and leaves leverage unchanged.
713
720
  **/
714
- withdrawCollateral(position: PositionInput, params: WithdrawCollateralParams): Promise<SDKReturn<StrategyResult, AccountFlowError>>;
721
+ withdrawCollateral(position: PositionInput, params: WithdrawCollateralParams): Promise<SDKReturn<StrategyResult, AccountFlowError & WithPartialState<OperationState>>>;
715
722
  /**
716
723
  * The leverages a deposit of a given size can reach in this market: the
717
724
  * range a leverage slider should mark as available.
@@ -819,7 +826,7 @@ interface IOpportunitiesPrepare {
819
826
  * the result serves that share and `remainder` says what is left, see
820
827
  * {@link FinalizeResult.remainder}.
821
828
  **/
822
- finalize(position: PositionInput, params: FinalizeParams): Promise<SDKReturn<FinalizeResult, AccountFlowError | NoRecordedIntentError | NoDelayedRouteError | WithdrawalInProgressError | UnsupportedTokenPairError>>;
829
+ finalize(position: PositionInput, params: FinalizeParams): Promise<SDKReturn<FinalizeResult, (AccountFlowError | NoRecordedIntentError | NoDelayedRouteError | WithdrawalInProgressError | UnsupportedTokenPairError) & WithPartialState<OperationState>>>;
823
830
  }
824
831
  //#endregion
825
- export { AccountFlowError, AddCollateralParams, AdjustLeverageParams, BorrowParams, BorrowResult, type BorrowState, type CreditAccountNotEmptyError, type CreditAccountNotFoundError, DelayedStrategyResult, DepositStrategyParams, EmptyCreditAccountResult, type ExecutionCost, FinalizeParams, FinalizeResult, IOpportunitiesPrepare, type LeverageBand, LpParams, LpRedeemParams, LpResult, LpState, MaxBorrowParams, type MultipleDelayedWithdrawalsError, type NoDelayedRouteError, type NoRecordedIntentError, type NoStrategyTargetCollateralError, OpenFlowError, OpenStrategyParams, OpenStrategyResult, type OperationState, type PathLossRate, PoolInput, type PoolOperationError, PositionInput, PrepareOptions, RepayStrategyParams, type RouteErrors, StrategyInput, StrategyResult, StrategyRoutesResult, type UnexpectedFailureError, type UnsupportedCollateralTokenError, type UnsupportedTokenPairError, WithRouteErrors, type WithdrawCeilings, WithdrawCollateralParams, WithdrawStrategyParams, type WithdrawalInProgressError };
832
+ export { AccountFlowError, AddCollateralParams, AdjustLeverageParams, BorrowParams, BorrowResult, type BorrowState, type CreditAccountNotEmptyError, type CreditAccountNotFoundError, DelayedStrategyResult, DepositStrategyParams, EmptyCreditAccountResult, type ExecutionCost, FinalizeParams, FinalizeResult, IOpportunitiesPrepare, type LeverageBand, LpParams, LpRedeemParams, LpResult, LpState, MaxBorrowParams, type MultipleDelayedWithdrawalsError, type NoDelayedRouteError, type NoRecordedIntentError, type NoStrategyTargetCollateralError, OpenFlowError, OpenStrategyParams, OpenStrategyResult, type OperationState, type PathLossRate, PoolInput, type PoolOperationError, PositionInput, PrepareOptions, RepayStrategyParams, type RouteErrors, StrategyInput, StrategyResult, StrategyRoutesResult, type UnexpectedFailureError, type UnsupportedCollateralTokenError, type UnsupportedTokenPairError, type WithPartialState, WithRouteErrors, type WithdrawCeilings, WithdrawCollateralParams, WithdrawStrategyParams, type WithdrawalInProgressError };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gearbox-protocol/sdk",
3
- "version": "17.1.0-next.2",
3
+ "version": "17.1.0-next.3",
4
4
  "description": "Gearbox SDK",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -88,10 +88,6 @@
88
88
  "typecheck:ci": "tsc --noEmit"
89
89
  },
90
90
  "dependencies": {
91
- "@redstone-finance/evm-connector": "^0.9.0",
92
- "@redstone-finance/protocol": "^0.9.0",
93
- "@redstone-finance/sdk": "^0.9.0",
94
- "@redstone-finance/utils": "^0.9.0",
95
91
  "abitype": "^1.3.0",
96
92
  "date-fns": "^4.4.0",
97
93
  "viem": ">=2.23.15 <3.0.0",
@@ -1,193 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_onchain_utils_AddressMap = require("../../../utils/AddressMap.js");
3
- require("../../../utils/index.js");
4
- const require_onchain_base_SDKConstruct = require("../../../base/SDKConstruct.js");
5
- require("../../../base/index.js");
6
- const require_onchain_market_pricefeeds_updates_fetchRedstonePayloads = require("./fetchRedstonePayloads.js");
7
- const require_onchain_market_pricefeeds_updates_PriceUpdatesCache = require("./PriceUpdatesCache.js");
8
- const require_onchain_market_pricefeeds_updates_PriceUpdateTx = require("./PriceUpdateTx.js");
9
- let zod_v4 = require("zod/v4");
10
- //#region src/onchain/market/pricefeeds/updates/RedstoneUpdater.ts
11
- var RedstoneUpdateTx = class extends require_onchain_market_pricefeeds_updates_PriceUpdateTx.PriceUpdateTx {
12
- name = "redstone";
13
- };
14
- const RedstoneOptions = zod_v4.z.object({
15
- /**
16
- * Fixed redstone historic timestamp in ms
17
- * Set to true to enable redstone historical mode using timestamp from attach block
18
- */
19
- historicTimestamp: zod_v4.z.union([zod_v4.z.number().nonnegative(), zod_v4.z.literal(true)]).optional(),
20
- /**
21
- * Override redstone gateways. Can be used to set caching proxies, to avoid rate limiting
22
- */
23
- gateways: zod_v4.z.array(zod_v4.z.url()).optional(),
24
- /**
25
- * TTL for redstone cache in milliseconds
26
- * If 0, disables caching
27
- * If not set, uses some default value
28
- * Cache is always enabled in historical mode
29
- */
30
- cacheTTL: zod_v4.z.number().nonnegative().optional(),
31
- /**
32
- * When true, an error will be thrown when redstone is unable to fetch data for some feeds
33
- */
34
- failOnMissingFeeds: zod_v4.z.boolean().optional(),
35
- /**
36
- * Enable redstone internal logging
37
- */
38
- enableLogging: zod_v4.z.boolean().optional()
39
- });
40
- /**
41
- * Class to update multiple redstone price feeds at once
42
- */
43
- var RedstoneUpdater = class extends require_onchain_base_SDKConstruct.SDKConstruct {
44
- #cache;
45
- #historicalTimestampMs;
46
- #gateways;
47
- #failOnMissingFeeds;
48
- #enableLogging;
49
- constructor(sdk, opts = {}) {
50
- super(sdk);
51
- this.#failOnMissingFeeds = opts.failOnMissingFeeds;
52
- this.#enableLogging = opts.enableLogging;
53
- this.#gateways = opts.gateways?.length ? opts.gateways : void 0;
54
- let ts = opts.historicTimestamp;
55
- if (ts) {
56
- ts = ts === true ? Number(this.sdk.timestamp) * 1e3 : ts;
57
- this.#historicalTimestampMs = 6e4 * Math.floor(ts / 6e4);
58
- this.logger?.debug(`using historical timestamp ${this.#historicalTimestampMs}`);
59
- }
60
- this.#cache = opts.cache ?? new require_onchain_market_pricefeeds_updates_PriceUpdatesCache.PriceUpdatesCache({
61
- ttl: opts.cacheTTL ?? 225e3,
62
- historical: !!ts
63
- });
64
- }
65
- async getUpdateTxs(feeds) {
66
- if (feeds.length === 0) return [];
67
- this.logger?.debug(`generating update transactions for ${feeds.length} redstone price feeds`);
68
- const groupedFeeds = {};
69
- const priceFeeds = /* @__PURE__ */ new Map();
70
- for (const feed of feeds) {
71
- if (!isRedstone(feed)) continue;
72
- const key = `${feed.dataServiceId}:${feed.signersThreshold}`;
73
- if (!groupedFeeds[key]) groupedFeeds[key] = /* @__PURE__ */ new Set();
74
- groupedFeeds[key].add(feed.dataId);
75
- const pfsForDataId = priceFeeds.get(feed.dataId) ?? new require_onchain_utils_AddressMap.AddressMap();
76
- pfsForDataId.upsert(feed.address, feed);
77
- priceFeeds.set(feed.dataId, pfsForDataId);
78
- }
79
- const results = [];
80
- let [minTimestamp, maxTimestamp] = [Number.POSITIVE_INFINITY, 0];
81
- for (const [key, group] of Object.entries(groupedFeeds)) {
82
- const [dataServiceId, signersStr] = key.split(":");
83
- const uniqueSignersCount = parseInt(signersStr, 10);
84
- const payloads = await this.#safeGetPayloads(dataServiceId, group, uniqueSignersCount);
85
- for (const { dataFeedId, data, timestamp, cached } of payloads) {
86
- const pfsForDataId = priceFeeds.get(dataFeedId);
87
- if (!pfsForDataId) throw new Error(`cannot get price feed addresses for ${dataFeedId}`);
88
- for (const priceFeed of pfsForDataId.values()) {
89
- minTimestamp = Math.min(minTimestamp, timestamp);
90
- maxTimestamp = Math.max(maxTimestamp, timestamp);
91
- results.push(new RedstoneUpdateTx(priceFeed.createPriceUpdateTx(data), {
92
- dataFeedId,
93
- dataServiceId,
94
- priceFeed: priceFeed.address,
95
- timestamp,
96
- cached
97
- }));
98
- }
99
- }
100
- }
101
- let tsRange = "";
102
- if (results.length) {
103
- const minDelta = BigInt(minTimestamp) - this.sdk.timestamp;
104
- tsRange = `, timestamps ${minTimestamp} (${minDelta})`;
105
- if (minTimestamp !== maxTimestamp) {
106
- const maxDelta = BigInt(maxTimestamp) - this.sdk.timestamp;
107
- tsRange = `${tsRange} - ${maxTimestamp} (${maxDelta})`;
108
- }
109
- }
110
- this.logger?.debug(`generated ${results.length} update transactions for redstone price feeds: ${Array.from(priceFeeds.keys()).join(", ")}${tsRange}`);
111
- return results;
112
- }
113
- get historical() {
114
- return !!this.#historicalTimestampMs;
115
- }
116
- /**
117
- * Gets payloads, retries once if it has expired while inflight
118
- * @param dataServiceId
119
- * @param dataFeedsIds
120
- * @param uniqueSignersCount
121
- * @returns
122
- */
123
- async #safeGetPayloads(dataServiceId, dataFeedsIds, uniqueSignersCount) {
124
- let result = await this.#getPayloads(dataServiceId, dataFeedsIds, uniqueSignersCount);
125
- if (this.#historicalTimestampMs) return result;
126
- let expired = false;
127
- for (const { timestamp, dataFeedId } of result) {
128
- const delta = Number(this.sdk.timestamp) - timestamp;
129
- if (delta >= 240 && delta < 255) {
130
- this.logger?.warn(`payload for ${dataFeedId} has expired by ${delta} seconds`);
131
- expired = true;
132
- }
133
- }
134
- if (expired) result = await this.#getPayloads(dataServiceId, dataFeedsIds, uniqueSignersCount);
135
- return result;
136
- }
137
- /**
138
- * Gets redstone payloads in one request for multiple feeds with the same dataServiceId and uniqueSignersCount
139
- * If historicalTimestamp is set, responses will be cached
140
- * @param dataServiceId
141
- * @param dataFeedsIds
142
- * @param uniqueSignersCount
143
- * @returns
144
- */
145
- async #getPayloads(dataServiceId, dataFeedsIds, uniqueSignersCount) {
146
- this.logger?.debug(`getting redstone payloads for ${dataFeedsIds.size} data feeds in ${dataServiceId} with ${uniqueSignersCount} signers: ${Array.from(dataFeedsIds).join(", ")}`);
147
- const fromCache = [];
148
- const uncached = [];
149
- for (const dataFeedId of dataFeedsIds) {
150
- const cached = this.#cache.get(dataServiceId, dataFeedId, uniqueSignersCount);
151
- if (cached) fromCache.push({
152
- ...cached,
153
- cached: true
154
- });
155
- else uncached.push(dataFeedId);
156
- }
157
- const fromRedstone = await this.#fetchPayloads(dataServiceId, new Set(uncached), uniqueSignersCount);
158
- for (const resp of fromRedstone) this.#cache.set(resp, dataServiceId, resp.dataFeedId, uniqueSignersCount);
159
- this.logger?.debug(`got ${fromRedstone.length} new redstone updates and ${fromCache.length} from cache`);
160
- return [...fromCache, ...fromRedstone];
161
- }
162
- /**
163
- * Fetches redstone payloads in one request for multiple feeds with the same dataServiceId and uniqueSignersCount
164
- * Payloads are loaded in one request to avoid redstone rate limit
165
- * @param dataServiceId
166
- * @param dataFeedsIds
167
- * @param uniqueSignersCount
168
- * @returns
169
- */
170
- async #fetchPayloads(dataServiceId, dataFeedsIds, uniqueSignersCount) {
171
- if (dataFeedsIds.size === 0) return [];
172
- const dataPackagesIds = Array.from(dataFeedsIds);
173
- const tsStr = this.#historicalTimestampMs ? ` with historical timestamp ${this.#historicalTimestampMs}` : "";
174
- this.logger?.debug(`fetching redstone payloads for ${dataFeedsIds.size} data feeds in ${dataServiceId} with ${uniqueSignersCount} signers: ${dataPackagesIds.join(", ")}${tsStr}`);
175
- return require_onchain_market_pricefeeds_updates_fetchRedstonePayloads.fetchRedstonePayloads({
176
- dataServiceId,
177
- dataFeedsIds,
178
- uniqueSignersCount,
179
- historicalTimestampMs: this.#historicalTimestampMs,
180
- gateways: this.#gateways,
181
- failOnMissingFeeds: this.#failOnMissingFeeds,
182
- enableLogging: this.#enableLogging,
183
- logger: this.logger,
184
- metadataTimestampMs: Number(this.sdk.timestamp) * 1e3
185
- });
186
- }
187
- };
188
- function isRedstone(pf) {
189
- return pf.contractType === "PRICE_FEED::REDSTONE";
190
- }
191
- //#endregion
192
- exports.RedstoneOptions = RedstoneOptions;
193
- exports.RedstoneUpdater = RedstoneUpdater;
@@ -1,95 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_onchain_utils_retry = require("../../../utils/retry.js");
3
- require("../../../utils/index.js");
4
- let viem = require("viem");
5
- let _redstone_finance_evm_connector = require("@redstone-finance/evm-connector");
6
- let _redstone_finance_protocol = require("@redstone-finance/protocol");
7
- let _redstone_finance_sdk = require("@redstone-finance/sdk");
8
- let _redstone_finance_utils = require("@redstone-finance/utils");
9
- //#region src/onchain/market/pricefeeds/updates/fetchRedstonePayloads.ts
10
- /**
11
- * Fetches redstone payloads from Redstone API
12
- */
13
- async function fetchRedstonePayloads(options) {
14
- const { dataServiceId, dataFeedsIds, uniqueSignersCount, historicalTimestampMs, gateways, failOnMissingFeeds, enableLogging, logger, returnPrices } = options;
15
- const metadataTimestampMs = historicalTimestampMs ?? options.metadataTimestampMs;
16
- const dataPackagesIds = Array.from(new Set(dataFeedsIds));
17
- if (dataPackagesIds.length === 0) return [];
18
- const wrapper = new _redstone_finance_evm_connector.DataServiceWrapper({
19
- dataServiceId,
20
- dataPackagesIds,
21
- uniqueSignersCount,
22
- authorizedSigners: (0, _redstone_finance_sdk.getSignersForDataServiceId)(dataServiceId),
23
- historicalTimestamp: historicalTimestampMs,
24
- urls: gateways,
25
- ignoreMissingFeed: !failOnMissingFeeds,
26
- enableEnhancedLogs: enableLogging
27
- });
28
- if (metadataTimestampMs) wrapper.setMetadataTimestamp(metadataTimestampMs);
29
- const dataPayload = await require_onchain_utils_retry.retry(() => wrapper.prepareRedstonePayload(true), {
30
- attempts: 5,
31
- interval: historicalTimestampMs ? 30500 : 250
32
- });
33
- const packagesByDataFeedId = groupDataPackages(_redstone_finance_protocol.RedstonePayload.parse((0, viem.toBytes)(`0x${dataPayload}`)).signedDataPackages);
34
- const result = [];
35
- for (const dataFeedId of dataFeedsIds) {
36
- const signedDataPackages = packagesByDataFeedId[dataFeedId];
37
- if (!signedDataPackages) {
38
- if (failOnMissingFeeds) throw new Error(`cannot find data packages for ${dataFeedId}`);
39
- logger?.warn(`cannot find data packages for ${dataFeedId}`);
40
- continue;
41
- }
42
- if (signedDataPackages.length !== uniqueSignersCount) {
43
- if (failOnMissingFeeds) throw new Error(`got ${signedDataPackages.length} data packages for ${dataFeedId}, but expected ${uniqueSignersCount}`);
44
- logger?.warn(`got ${signedDataPackages.length} data packages for ${dataFeedId}, but expected ${uniqueSignersCount}`);
45
- continue;
46
- }
47
- result.push(getCalldataWithTimestamp(dataFeedId, signedDataPackages, wrapper.getUnsignedMetadata(), returnPrices));
48
- }
49
- return result;
50
- }
51
- /**
52
- * Groups SignedDataPackages by dataFeedId
53
- * @param signedDataPackages
54
- * @returns
55
- */
56
- function groupDataPackages(signedDataPackages) {
57
- const packagesByDataFeedId = {};
58
- for (const p of signedDataPackages) {
59
- const { dataPoints } = p.dataPackage;
60
- const dataFeedId0 = dataPoints[0].dataFeedId;
61
- for (const dp of dataPoints) if (dp.dataFeedId !== dataFeedId0) throw new Error(`data package contains data points with different dataFeedIds: ${dp.dataFeedId} and ${dataFeedId0}`);
62
- if (!packagesByDataFeedId[dataFeedId0]) packagesByDataFeedId[dataFeedId0] = [];
63
- packagesByDataFeedId[dataFeedId0].push(p);
64
- }
65
- return packagesByDataFeedId;
66
- }
67
- function getCalldataWithTimestamp(dataFeedId, packages, unsignedMetadata, returnPrices) {
68
- const bytesToAdd = 32 - _redstone_finance_protocol.RedstonePayload.prepare(packages, unsignedMetadata).length / 2 % 32;
69
- const newUnsignedMetadata = unsignedMetadata + "_".repeat(bytesToAdd);
70
- const payload = _redstone_finance_protocol.RedstonePayload.prepare(packages, newUnsignedMetadata);
71
- let timestamp = 0;
72
- for (const p of packages) {
73
- const newTimestamp = p.dataPackage.timestampMilliseconds / 1e3;
74
- if (timestamp === 0) timestamp = newTimestamp;
75
- else if (timestamp !== newTimestamp) throw new Error("Timestamps are not equal");
76
- }
77
- const base = {
78
- dataFeedId,
79
- data: (0, viem.encodeAbiParameters)([{ type: "uint256" }, { type: "bytes" }], [BigInt(timestamp), `0x${payload}`]),
80
- timestamp,
81
- cached: false
82
- };
83
- if (returnPrices) {
84
- const prices = packages.flatMap((p) => p.dataPackage.dataPoints).map((dp) => BigInt(`0x${Buffer.from(dp.value).toString("hex")}`));
85
- const medianPrice = BigInt(_redstone_finance_utils.MathUtils.getMedianOfBigNumbers(prices));
86
- return {
87
- ...base,
88
- price: medianPrice,
89
- decimals: 8
90
- };
91
- }
92
- return base;
93
- }
94
- //#endregion
95
- exports.fetchRedstonePayloads = fetchRedstonePayloads;