@gearbox-protocol/sdk 16.0.0-next.40 → 16.0.0-next.42

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 (49) hide show
  1. package/dist/cjs/model/errors.js +1 -0
  2. package/dist/cjs/model/index.js +1 -0
  3. package/dist/cjs/onchain/accounts/intents/open-strategy.js +1 -1
  4. package/dist/cjs/onchain/positions/PositionsService.js +1 -11
  5. package/dist/cjs/sdk/execute/ExecuteApi.js +4 -4
  6. package/dist/cjs/sdk/index.js +5 -0
  7. package/dist/cjs/sdk/prepare/PrepareApi.js +326 -93
  8. package/dist/cjs/sdk/prepare/errors.js +90 -0
  9. package/dist/cjs/sdk/prepare/index.js +5 -0
  10. package/dist/esm/dev/AccountOpener.js +1 -1
  11. package/dist/esm/dev/withdrawalUtils.js +1 -1
  12. package/dist/esm/model/errors.js +1 -0
  13. package/dist/esm/model/index.js +1 -0
  14. package/dist/esm/onchain/accounts/CreditAccountsServiceV310.js +2 -2
  15. package/dist/esm/onchain/accounts/intents/open-strategy.js +1 -1
  16. package/dist/esm/onchain/accounts/liquidations/LiquidationsService.js +1 -1
  17. package/dist/esm/onchain/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.js +1 -1
  18. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.js +1 -1
  19. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.js +1 -1
  20. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.js +1 -1
  21. package/dist/esm/onchain/base/TokensMeta.js +3 -3
  22. package/dist/esm/onchain/core/createAddressProvider.js +1 -1
  23. package/dist/esm/onchain/market/adapters/contracts/AccountMigratorAdapterContract.js +1 -1
  24. package/dist/esm/onchain/market/adapters/contracts/ERC4626AdapterContract.js +1 -1
  25. package/dist/esm/onchain/market/credit/CreditFacadeV310BaseContract.js +1 -1
  26. package/dist/esm/onchain/market/pool/PoolV310Contract.js +1 -1
  27. package/dist/esm/onchain/market/zapper/IETHZapperContract.js +1 -1
  28. package/dist/esm/onchain/market/zapper/ZapperContract.js +1 -1
  29. package/dist/esm/onchain/positions/PositionsService.js +1 -11
  30. package/dist/esm/onchain/utils/viem/simulateWithPriceUpdates.js +1 -1
  31. package/dist/esm/preview/simulate/simulatePoolOperation.js +1 -1
  32. package/dist/esm/preview/trace/extractTransfers.js +1 -1
  33. package/dist/esm/sdk/execute/ExecuteApi.js +4 -4
  34. package/dist/esm/sdk/index.js +2 -1
  35. package/dist/esm/sdk/prepare/PrepareApi.js +327 -94
  36. package/dist/esm/sdk/prepare/errors.js +86 -0
  37. package/dist/esm/sdk/prepare/index.js +2 -1
  38. package/dist/types/model/errors.d.ts +74 -0
  39. package/dist/types/model/index.d.ts +2 -1
  40. package/dist/types/onchain/accounts/intents/open-strategy.d.ts +3 -3
  41. package/dist/types/onchain/accounts/intents/types.d.ts +13 -14
  42. package/dist/types/onchain/positions/PositionsService.d.ts +0 -8
  43. package/dist/types/sdk/execute/types.d.ts +6 -6
  44. package/dist/types/sdk/index.d.ts +3 -2
  45. package/dist/types/sdk/prepare/PrepareApi.d.ts +11 -6
  46. package/dist/types/sdk/prepare/errors.d.ts +280 -0
  47. package/dist/types/sdk/prepare/index.d.ts +3 -2
  48. package/dist/types/sdk/prepare/types.d.ts +73 -46
  49. package/package.json +1 -1
@@ -0,0 +1,74 @@
1
+ //#region src/model/errors.d.ts
2
+ /**
3
+ * The failure vocabulary the SDK answers in.
4
+ *
5
+ * A request that the protocol, the market or the request's own numbers rule out
6
+ * is not an exception: it is an answer, and a screen shows it the way it shows
7
+ * any other. So a method that can be refused returns a {@link WithError}
8
+ * envelope rather than throwing, and what it puts in the failure half is one of
9
+ * these — never a bare string, never a boolean the caller has to interpret.
10
+ *
11
+ * A thrown exception still means what it always did: the SDK could not do its
12
+ * job (a read failed, a contract reverted unexpectedly, an argument is wrong).
13
+ * Those are bugs and outages, not verdicts on the request.
14
+ **/
15
+ /**
16
+ * What every error the SDK reports has.
17
+ *
18
+ * `code` is the discriminant: switch on it and the error narrows to the shape
19
+ * carrying that failure's own numbers, so a caller reads `available` and
20
+ * `required` off the error rather than re-deriving them from the request.
21
+ *
22
+ * The codes themselves are per namespace — there is no SDK-wide enumeration of
23
+ * them, because the set a method can answer with is part of that method's
24
+ * contract, see the `E` of {@link WithError}.
25
+ **/
26
+ interface IGearboxError {
27
+ /**
28
+ * Machine-readable identity of the failure, and the discriminant of the
29
+ * union a method returns.
30
+ **/
31
+ code: string;
32
+ /**
33
+ * One sentence naming what was refused, in English, safe to log. Not a
34
+ * message to show a user as-is: a screen renders the code and the numbers
35
+ * beside it in its own words and its own language.
36
+ **/
37
+ message: string;
38
+ /**
39
+ * The failure this one was raised for, where one error stands in front of
40
+ * another. Absent for a refusal that is its own reason, which is most of
41
+ * them.
42
+ **/
43
+ cause?: IGearboxError | Error;
44
+ }
45
+ /**
46
+ * What a method that can be refused answers with: the data it was asked for, or
47
+ * the reason there is none.
48
+ *
49
+ * `success` is the discriminant, and narrowing it settles which of the two
50
+ * fields is there — a caller cannot read `data` without having ruled the
51
+ * failure out first.
52
+ *
53
+ * ```ts
54
+ * const { data: result } = await sdk.prepare.depositStrategy(position, params);
55
+ * if (!result.success) {
56
+ * return showRefusal(result.error.code, result.error);
57
+ * }
58
+ * const tx = await sdk.execute.buildTx({ kind: "account", sim: result, ... });
59
+ * ```
60
+ *
61
+ * @typeParam D - What the method answers when it can.
62
+ * @typeParam E - The errors that method can refuse with, as a union of
63
+ * {@link IGearboxError}s. Naming them per method is the point: the union is the
64
+ * list of everything a caller has to handle, checked by the compiler.
65
+ **/
66
+ type WithError<D, E extends IGearboxError> = {
67
+ success: true;
68
+ data: D;
69
+ } | {
70
+ success: false;
71
+ error: E;
72
+ };
73
+ //#endregion
74
+ export { IGearboxError, WithError };
@@ -5,6 +5,7 @@ import { CompareTag, CompareTolerance, ToleranceCompareTag, backendPreferred, co
5
5
  import { Curator, CuratorName } from "./curators.js";
6
6
  import { curatorNameSchema, curatorSchema } from "./curators.schema.js";
7
7
  import { DelayedAddCollateralIntent, DelayedCloseAccountIntent, DelayedDecreaseLeverageIntent, DelayedDepositAndIncreaseLeverageIntent, DelayedDepositIntent, DelayedIncreaseLeverageIntent, DelayedIntent, DelayedWithdrawCollateralIntent } from "./delayed-intents.js";
8
+ import { IGearboxError, WithError } from "./errors.js";
8
9
  import { ChainScopedFilter, FILTER_ALL, FilterAll, Filterable, isFilterSet } from "./filters.js";
9
10
  import { booleanParamSchema, encodeFlag, filterAllSchema, filterable } from "./filters.schema.js";
10
11
  import { ApyBreakdown, Opportunity, OpportunityBase, OpportunityDetail, OpportunityFilter, OpportunityId, OpportunityKey, OpportunityKind, OpportunityTotals, PointRewards, PointsProgram, PoolOpportunity, PoolOpportunityDetail, PoolOpportunityKey, PoolOpportunityRef, PriceFeedData, PriceFeedSummary, QuotaAsset, RateCurve, RateCurvePoint, Rewards, StrategyOpportunity, StrategyOpportunityDetail, StrategyOpportunityKey, StrategyOpportunityRef, TokenRewards, matchesOpportunityFilter, opportunityId, poolOpportunityId, strategyOpportunityId } from "./opportunities.js";
@@ -21,4 +22,4 @@ import { ChainFailed, ChainMetadata, ChainScoped, ChainSucceeded, DataResponse,
21
22
  import { chainFailedSchema, chainMetadataSchema, chainSucceededSchema, dataSourceSchema, responseMetadataSchema, responseSchema } from "./response.schema.js";
22
23
  import { PositionClaimableWithdrawal, PositionPendingWithdrawal, PositionWithdrawals } from "./withdrawals.js";
23
24
  import { positionClaimableWithdrawalSchema, positionPendingWithdrawalSchema, positionWithdrawalsSchema } from "./withdrawals.schema.js";
24
- export { AccountHoldings, AccountMetrics, AccountProjection, AccountStateChange, AdjustStrategyPositionPreview, Amount, ApyBreakdown, Asset, AssetType, BorrowRateBreakdown, Bps, CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ChainFailed, ChainId, ChainMetadata, ChainScoped, ChainScopedFilter, ChainSucceeded, ChartBundle, ChartDenomination, ChartMetric, ChartQuery, ChartRange, ChartSeries, ChartSeriesOk, ChartSeriesUnavailable, ChartUnavailableCode, ChartUnit, ChartValue, ChartWindow, CompareTag, CompareTolerance, CreditOperationMarket, Curator, CuratorName, DataResponse, DataSource, DelayedAddCollateralIntent, DelayedCloseAccountIntent, DelayedDecreaseLeverageIntent, DelayedDepositAndIncreaseLeverageIntent, DelayedDepositIntent, DelayedIncreaseLeverageIntent, DelayedIntent, DelayedReceivedAsset, DelayedStrategyPositionOperationPreview, DelayedWithdrawCollateralIntent, ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPRICEABLE_TOKEN, ERROR_UNSUPPORTED_OUT_OF_BRACKET_CALL, Estimated, EstimatedProjection, ExitStrategyPositionPreview, FILTER_ALL, FilterAll, Filterable, GridSampling, InstantReceivedAsset, InstantStrategyPositionOperationPreview, Leverage, LiquidatableAccount, LiquidatableAccountFilter, LiquidationApproval, LiquidationDetails, LiquidationPosition, Notice, NoticeKind, NoticeSubject, OpenStrategyPositionPreview, OperationPreview, OperationPreviewError, Opportunity, OpportunityBase, OpportunityChartMetric, OpportunityDetail, OpportunityFilter, OpportunityId, OpportunityKey, OpportunityKind, OpportunityTotals, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PnlBreakdown, PointRewards, PointsProgram, PointsProgramPnL, PointsRewardsPnL, PoolOperationType, PoolOpportunity, PoolOpportunityChartMetric, PoolOpportunityDetail, PoolOpportunityKey, PoolOpportunityRef, PoolPosition, PoolPositionChartMetric, PoolPositionKey, PoolPositionOperationPreview, PoolPositionRef, Position, PositionChartMetric, PositionClaimableWithdrawal, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionPendingWithdrawal, PositionTransaction, PositionTransactionKind, PositionWithdrawals, PositionsTotals, PreviewOperationInput, PreviewOperationOptions, PriceFeedData, PriceFeedSummary, QuotaAsset, RateCurve, RateCurvePoint, ReceivedAsset, RepayStrategyPositionPreview, ResponseMetadata, Rewards, RewardsPnL, RoutedField, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, StrategyOpportunity, StrategyOpportunityChartMetric, StrategyOpportunityDetail, StrategyOpportunityKey, StrategyOpportunityRef, StrategyPosition, StrategyPositionChartMetric, StrategyPositionKey, StrategyPositionRef, Timestamp, Token, TokenAmount, TokenQuotaRate, TokenRewards, TokenRewardsPnL, ToleranceCompareTag, TxCall, UnderlyingToken, amountSchema, apyBreakdownSchema, asEstimated, assetTypeSchema, backendPreferred, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, compareTagOf, curatorNameSchema, curatorSchema, dataSourceSchema, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, instantReceivedAssetSchema, isFilterSet, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, positionClaimableWithdrawalSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionPendingWithdrawalSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionWithdrawalsSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema };
25
+ export { AccountHoldings, AccountMetrics, AccountProjection, AccountStateChange, AdjustStrategyPositionPreview, Amount, ApyBreakdown, Asset, AssetType, BorrowRateBreakdown, Bps, CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ChainFailed, ChainId, ChainMetadata, ChainScoped, ChainScopedFilter, ChainSucceeded, ChartBundle, ChartDenomination, ChartMetric, ChartQuery, ChartRange, ChartSeries, ChartSeriesOk, ChartSeriesUnavailable, ChartUnavailableCode, ChartUnit, ChartValue, ChartWindow, CompareTag, CompareTolerance, CreditOperationMarket, Curator, CuratorName, DataResponse, DataSource, DelayedAddCollateralIntent, DelayedCloseAccountIntent, DelayedDecreaseLeverageIntent, DelayedDepositAndIncreaseLeverageIntent, DelayedDepositIntent, DelayedIncreaseLeverageIntent, DelayedIntent, DelayedReceivedAsset, DelayedStrategyPositionOperationPreview, DelayedWithdrawCollateralIntent, ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPRICEABLE_TOKEN, ERROR_UNSUPPORTED_OUT_OF_BRACKET_CALL, Estimated, EstimatedProjection, ExitStrategyPositionPreview, FILTER_ALL, FilterAll, Filterable, GridSampling, IGearboxError, InstantReceivedAsset, InstantStrategyPositionOperationPreview, Leverage, LiquidatableAccount, LiquidatableAccountFilter, LiquidationApproval, LiquidationDetails, LiquidationPosition, Notice, NoticeKind, NoticeSubject, OpenStrategyPositionPreview, OperationPreview, OperationPreviewError, Opportunity, OpportunityBase, OpportunityChartMetric, OpportunityDetail, OpportunityFilter, OpportunityId, OpportunityKey, OpportunityKind, OpportunityTotals, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PnlBreakdown, PointRewards, PointsProgram, PointsProgramPnL, PointsRewardsPnL, PoolOperationType, PoolOpportunity, PoolOpportunityChartMetric, PoolOpportunityDetail, PoolOpportunityKey, PoolOpportunityRef, PoolPosition, PoolPositionChartMetric, PoolPositionKey, PoolPositionOperationPreview, PoolPositionRef, Position, PositionChartMetric, PositionClaimableWithdrawal, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionPendingWithdrawal, PositionTransaction, PositionTransactionKind, PositionWithdrawals, PositionsTotals, PreviewOperationInput, PreviewOperationOptions, PriceFeedData, PriceFeedSummary, QuotaAsset, RateCurve, RateCurvePoint, ReceivedAsset, RepayStrategyPositionPreview, ResponseMetadata, Rewards, RewardsPnL, RoutedField, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, StrategyOpportunity, StrategyOpportunityChartMetric, StrategyOpportunityDetail, StrategyOpportunityKey, StrategyOpportunityRef, StrategyPosition, StrategyPositionChartMetric, StrategyPositionKey, StrategyPositionRef, Timestamp, Token, TokenAmount, TokenQuotaRate, TokenRewards, TokenRewardsPnL, ToleranceCompareTag, TxCall, UnderlyingToken, WithError, amountSchema, apyBreakdownSchema, asEstimated, assetTypeSchema, backendPreferred, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, compareTagOf, curatorNameSchema, curatorSchema, dataSourceSchema, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, instantReceivedAssetSchema, isFilterSet, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, positionClaimableWithdrawalSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionPendingWithdrawalSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionWithdrawalsSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema };
@@ -4,7 +4,7 @@ import "../../../model/index.js";
4
4
  import { Asset } from "../../base/types.js";
5
5
  import { MultiCall } from "../../types/transactions.js";
6
6
  import { OnchainSDK } from "../../OnchainSDK.js";
7
- import { PreparedPrices } from "./types.js";
7
+ import { SimulationPrices } from "./types.js";
8
8
  import "../../index.js";
9
9
  import { Address } from "viem";
10
10
  //#region src/onchain/accounts/intents/open-strategy.d.ts
@@ -32,7 +32,7 @@ interface OpenStrategyProps {
32
32
  * hands back expected and floor balances from a single call, and `openCA` wants
33
33
  * both `minQuota` and `averageQuota`, so there is nothing to gain by dropping one.
34
34
  */
35
- interface OpenStrategyState extends Omit<AccountProjection, "assets" | "quotas">, PreparedPrices {
35
+ interface OpenStrategyState extends Omit<AccountProjection, "assets" | "quotas">, SimulationPrices {
36
36
  /** Expected post-open balances. */
37
37
  averageAssets: TokenAmount[];
38
38
  /** Floor post-open balances after slippage. */
@@ -52,7 +52,7 @@ interface OpenStrategyState extends Omit<AccountProjection, "assets" | "quotas">
52
52
  }
53
53
  /**
54
54
  * Builds the state opening a leveraged position out of wallet collateral would
55
- * land in.
55
+ * reach.
56
56
  *
57
57
  * Debt follows from the target leverage against the supplied margin
58
58
  * (`debt = margin * (L - 1)`, `totalValue = margin * L`); the collateral and the
@@ -31,14 +31,14 @@ interface PathLossRate {
31
31
  totalValuePriceImpact: bigint;
32
32
  }
33
33
  /**
34
- * The two prices only a planned walk can quote, carried by every `prepare`
34
+ * The two prices only a planned walk can quote, carried by every simulation
35
35
  * result beside its projection.
36
36
  *
37
37
  * A calldata preview is asked for neither: it reads a transaction that already
38
38
  * names its amounts, and it reports what that transaction does rather than what
39
39
  * the market charges while a form is open.
40
40
  */
41
- interface PreparedPrices {
41
+ interface SimulationPrices {
42
42
  /**
43
43
  * What the routed legs lost to market depth. `undefined` where nothing was
44
44
  * routed or nothing could be measured — never a manufactured zero.
@@ -60,10 +60,10 @@ interface PreparedPrices {
60
60
  * {@link AccountProjection} vocabulary, plus the prices only a routed walk can
61
61
  * report.
62
62
  */
63
- interface OperationState extends AccountProjection, PreparedPrices {}
63
+ interface OperationState extends AccountProjection, SimulationPrices {}
64
64
  /**
65
- * What a preview yields: the operation chain, the state it projects, and the
66
- * calldata that realises it — or the reason the request is not viable.
65
+ * What planning an intent yields: the operation chain, the state it projects,
66
+ * and the calldata that realises it — or the reason the request is not viable.
67
67
  */
68
68
  type IntentPreviewResult = {
69
69
  ok: true;
@@ -105,8 +105,8 @@ interface DelayedStart {
105
105
  * the phantom of the in-flight redemption in its place, the debt untouched.
106
106
  *
107
107
  * This is the state the facade judges when the transaction lands, so it is
108
- * the one the engine's guards are applied to — while the `state` beside it is
109
- * where the intent ends up, tail included, which is what a caller asking
108
+ * the one the engine's guards are applied to — while the `state` beside it
109
+ * is where the intent ends up, tail included, which is what a caller asking
110
110
  * "what does this do to my position" means.
111
111
  */
112
112
  afterRequest: OperationState;
@@ -116,10 +116,10 @@ interface DelayedStart {
116
116
  * plus what it recorded for the tail.
117
117
  *
118
118
  * `operations` and `calls` are the request and nothing else — that is the only
119
- * transaction there is to send now. `state`, though, is where the intent ends:
120
- * the account once the redemption matures, is claimed and the tail runs, since
121
- * that is what the caller asked for when they asked to withdraw. The half-way
122
- * state the request itself lands in is
119
+ * transaction there is to send now. `state`, though, is where the intent
120
+ * ends: the state the account reaches once the redemption matures, is claimed
121
+ * and the tail runs, since that is what the caller asked for when they asked
122
+ * to withdraw. The half-way state the request itself lands in is
123
123
  * {@link DelayedStart.afterRequest}, and both are validated before either is
124
124
  * reported.
125
125
  *
@@ -390,10 +390,9 @@ type FinishIntentProps = StartIntentProps & {
390
390
  intent: ResumableIntent;
391
391
  /**
392
392
  * The matured withdrawal, as reported by
393
- * `sdk.positions.getCurrentWithdrawals` (mapped back to the compressor
394
- * shape at `prepare.finalize`).
393
+ * `sdk.accounts.getPendingWithdrawals`.
395
394
  */
396
395
  claimable: ClaimableWithdrawal;
397
396
  };
398
397
  //#endregion
399
- export { AddCollateralIntent, AdjustLeverageIntent, CreditAccountSlice, DelayableIntent, DelayedRoute, DelayedStart, DelayedStartResult, DepositStrategyIntent, FinishIntentProps, InstantRoute, IntentPreviewResult, IntentRoutesResult, OperationState, PathLossRate, PreparedPrices, RepayStrategyIntent, ResumableIntent, RouteRefusals, StartIntent, StartIntentProps, WithdrawAssetIntent, WithdrawStrategyIntent };
398
+ export { AddCollateralIntent, AdjustLeverageIntent, CreditAccountSlice, DelayableIntent, DelayedRoute, DelayedStart, DelayedStartResult, DepositStrategyIntent, FinishIntentProps, InstantRoute, IntentPreviewResult, IntentRoutesResult, OperationState, PathLossRate, RepayStrategyIntent, ResumableIntent, RouteRefusals, SimulationPrices, StartIntent, StartIntentProps, WithdrawAssetIntent, WithdrawStrategyIntent };
@@ -44,14 +44,6 @@ declare class PositionsService extends SDKConstruct {
44
44
  listStrategyPositions(props: ListStrategyPositionsProps): Promise<StrategyPosition[]>;
45
45
  /**
46
46
  * Returns delayed withdrawals of a strategy position
47
- *
48
- * Empty when this chain has no withdrawal compressor, or when the account's
49
- * credit manager has no withdrawal config — no config, no withdrawal, and
50
- * nothing to ask the chain about.
51
- *
52
- * The manager comes from the caller. It used to be read off the account
53
- * here, which cost an uncached read of the whole account to learn one field
54
- * every caller already knows.
55
47
  **/
56
48
  getCurrentWithdrawals(props: GetCurrentWithdrawalsProps): Promise<PositionWithdrawals>;
57
49
  /**
@@ -22,7 +22,7 @@ interface PoolPrepareRequest {
22
22
  wallet: Address;
23
23
  op: "deposit" | "withdraw" | "redeem";
24
24
  sim: Extract<LpPrepare, {
25
- ok: true;
25
+ success: true;
26
26
  }>;
27
27
  }
28
28
  /**
@@ -37,7 +37,7 @@ interface OpenPrepareRequest {
37
37
  creditManager: Address;
38
38
  wallet: Address;
39
39
  sim: Extract<OpenStrategyPrepare, {
40
- ok: true;
40
+ success: true;
41
41
  }>;
42
42
  /** What leaves the wallet, token by token. */
43
43
  collateral: Asset[];
@@ -64,7 +64,7 @@ interface AccountPrepareRequest {
64
64
  creditAccount: Address;
65
65
  wallet: Address;
66
66
  sim: Extract<StrategyPrepare, {
67
- ok: true;
67
+ success: true;
68
68
  }>;
69
69
  }
70
70
  /**
@@ -86,9 +86,9 @@ interface IOpportunitiesExecute {
86
86
  * the state's router path and quotas to `openCA`, `pool` requests encode the
87
87
  * deposit / redeem the result priced.
88
88
  *
89
- * @throws on a `prepare` result that is not `ok`; when a `pool` request names a
90
- * route the pool has no metadata for, or one the pool does not accept a
91
- * transaction for (RWA on-demand deposits)
89
+ * @throws on a refused `prepare` result; when a `pool` request names a route
90
+ * the pool has no metadata for, or one the pool does not accept a transaction
91
+ * for (RWA on-demand deposits)
92
92
  **/
93
93
  buildTx(request: PrepareRequest): Promise<RawTx>;
94
94
  }
@@ -2,7 +2,8 @@ import { BorrowLimitBinding, IntentPreviewError, PreviewErrorDetails, PreviewErr
2
2
  import { LeverageBand } from "../onchain/accounts/intents/leverage-band.js";
3
3
  import { OperationState, PathLossRate } from "../onchain/accounts/intents/types.js";
4
4
  import { ILiquidations, ILiquidationsByMode } from "./liquidations/types.js";
5
- import { AddCollateralParams, AdjustLeverageParams, DelayedStrategyPrepare, DepositStrategyParams, FinalizeParams, IOpportunitiesPrepare, LpParams, LpPrepare, LpRedeemParams, OpenStrategyParams, OpenStrategyPrepare, PoolInput, PositionInput, PrepareOptions, RepayStrategyParams, StrategyInput, StrategyPrepare, StrategyRoutesPrepare, WithdrawCollateralParams, WithdrawStrategyParams } from "./prepare/types.js";
5
+ import { CreditAccountNotFoundError, DebtOutOfRangeError, ForbiddenTokenError, InsufficientCollateralError, InsufficientPoolLiquidityError, InsufficientSourceBalanceError, LeverageOutOfRangeError, MalformedTransactionError, MarketExpiredError, MarketPausedError, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, PoolSunsetError, PrepareError, QuotaCountExceededError, QuotaLimitReachedError, RoutesPrepareError, UnexpectedFailureError, UnsupportedCollateralTokenError, UnsupportedTokenPairError, WithdrawalInProgressError, creditAccountNotFound, noStrategyTargetCollateral, toPrepareError, unexpectedFailure } from "./prepare/errors.js";
6
+ import { AddCollateralParams, AdjustLeverageParams, AmountPrepare, DelayedStrategyPlan, DelayedStrategyPrepare, DepositStrategyParams, FinalizeParams, IOpportunitiesPrepare, LpParams, LpPlan, LpPrepare, LpRedeemParams, OpenStrategyParams, OpenStrategyPlan, OpenStrategyPrepare, PoolInput, PositionInput, PrepareOptions, RepayStrategyParams, StrategyInput, StrategyPlan, StrategyPrepare, StrategyRoutes, StrategyRoutesPrepare, WithdrawCollateralParams, WithdrawStrategyParams } from "./prepare/types.js";
6
7
  import { ChainOf, PrepareApi } from "./prepare/PrepareApi.js";
7
8
  import "./prepare/index.js";
8
9
  import { AccountPrepareRequest, IOpportunitiesExecute, OpenPrepareRequest, PoolPrepareRequest, PrepareRequest } from "./execute/types.js";
@@ -34,4 +35,4 @@ import { SourceUnavailableError } from "./errors/SourceUnavailableError.js";
34
35
  import { assertSameChains } from "./errors/assertSameChains.js";
35
36
  import { everyChainFailed } from "./errors/everyChainFailed.js";
36
37
  import "./errors/index.js";
37
- export { AbstractNamespace, AccountPrepareRequest, AddCollateralParams, AdjustLeverageParams, AllSourcesFailedError, BorrowLimitBinding, ChainOf, ChainRef, DEFAULT_MAX_OFFCHAIN_LAG, DEFAULT_MAX_STATE_AGE, DelayedStrategyPrepare, DepositStrategyParams, EnsureFreshChains, type EntityMerger, ExecuteApi, type FilterResult, FinalizeParams, GearboxSDK, GearboxSDKOptions, 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, IntentPreviewError, type LeverageBand, LiquidationsNamespace, type ListMerger, LpParams, LpPrepare, LpRedeemParams, type MergeListResult, MergedQuery, MissingSourceError, Mode, NamespaceOptions, NoSourceServedError, OffchainByMode, OffchainSource, OnchainByMode, OnchainSource, OpenPrepareRequest, OpenStrategyParams, OpenStrategyPrepare, type OperationState, OpportunitiesNamespace, type PathLossRate, PlainMultichainSDKOptions, PoolInput, PoolPrepareRequest, PositionInput, PositionsNamespace, PrepareApi, PrepareOptions, PrepareRequest, PreviewErrorDetails, PreviewErrorReason, PreviewIssue, PreviewNamespace, PreviewRefusal, RepayStrategyParams, SourceChainMismatchError, SourceUnavailableError, StrategyInput, StrategyPrepare, StrategyRoutesPrepare, WithdrawCollateralParams, WithdrawStrategyParams, assertSameChains, everyChainFailed, filterResponse, mergeChainList, mergeChainOne, raise, refuse };
38
+ export { AbstractNamespace, AccountPrepareRequest, AddCollateralParams, AdjustLeverageParams, AllSourcesFailedError, AmountPrepare, BorrowLimitBinding, ChainOf, ChainRef, CreditAccountNotFoundError, DEFAULT_MAX_OFFCHAIN_LAG, DEFAULT_MAX_STATE_AGE, DebtOutOfRangeError, DelayedStrategyPlan, DelayedStrategyPrepare, DepositStrategyParams, EnsureFreshChains, type EntityMerger, ExecuteApi, type FilterResult, FinalizeParams, ForbiddenTokenError, GearboxSDK, GearboxSDKOptions, 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, InsufficientCollateralError, InsufficientPoolLiquidityError, InsufficientSourceBalanceError, IntentPreviewError, type LeverageBand, LeverageOutOfRangeError, LiquidationsNamespace, type ListMerger, LpParams, LpPlan, LpPrepare, LpRedeemParams, MalformedTransactionError, MarketExpiredError, MarketPausedError, type MergeListResult, MergedQuery, MissingSourceError, Mode, MultipleDelayedWithdrawalsError, NamespaceOptions, NoDelayedRouteError, NoRecordedIntentError, NoSourceServedError, NoStrategyTargetCollateralError, OffchainByMode, OffchainSource, OnchainByMode, OnchainSource, OpenPrepareRequest, OpenStrategyParams, OpenStrategyPlan, OpenStrategyPrepare, type OperationState, OpportunitiesNamespace, type PathLossRate, PlainMultichainSDKOptions, PoolInput, PoolPrepareRequest, PoolSunsetError, PositionInput, PositionsNamespace, PrepareApi, PrepareError, PrepareOptions, PrepareRequest, PreviewErrorDetails, PreviewErrorReason, PreviewIssue, PreviewNamespace, PreviewRefusal, QuotaCountExceededError, QuotaLimitReachedError, RepayStrategyParams, RoutesPrepareError, SourceChainMismatchError, SourceUnavailableError, StrategyInput, StrategyPlan, StrategyPrepare, StrategyRoutes, StrategyRoutesPrepare, UnexpectedFailureError, UnsupportedCollateralTokenError, UnsupportedTokenPairError, WithdrawCollateralParams, WithdrawStrategyParams, WithdrawalInProgressError, assertSameChains, creditAccountNotFound, everyChainFailed, filterResponse, mergeChainList, mergeChainOne, noStrategyTargetCollateral, raise, refuse, toPrepareError, unexpectedFailure };
@@ -8,7 +8,7 @@ import { MultichainSDK } from "../../onchain/MultichainSDK.js";
8
8
  import { ChainQueryOneProps, MultichainConstruct } from "../../onchain/base/MultichainConstruct.js";
9
9
  import { LeverageBand } from "../../onchain/accounts/intents/leverage-band.js";
10
10
  import "../../onchain/index.js";
11
- import { AddCollateralParams, AdjustLeverageParams, DepositStrategyParams, FinalizeParams, IOpportunitiesPrepare, LpParams, LpPrepare, LpRedeemParams, OpenStrategyParams, OpenStrategyPrepare, PoolInput, PositionInput, RepayStrategyParams, StrategyInput, StrategyPrepare, StrategyRoutesPrepare, WithdrawCollateralParams, WithdrawStrategyParams } from "./types.js";
11
+ import { AddCollateralParams, AdjustLeverageParams, AmountPrepare, DepositStrategyParams, FinalizeParams, IOpportunitiesPrepare, LpParams, LpPrepare, LpRedeemParams, OpenStrategyParams, OpenStrategyPrepare, PoolInput, PositionInput, RepayStrategyParams, StrategyInput, StrategyPrepare, StrategyRoutesPrepare, WithdrawCollateralParams, WithdrawStrategyParams } from "./types.js";
12
12
  import { EnsureFreshChains } from "../types.js";
13
13
  import { Address } from "viem";
14
14
  //#region src/sdk/prepare/PrepareApi.d.ts
@@ -30,8 +30,13 @@ type ChainOf = (chainId: ChainId) => OnchainSDK;
30
30
  *
31
31
  * A prepared operation names one chain, so it reads through
32
32
  * {@link MultichainConstruct.queryChain}: there is no second source to fall back
33
- * to, hence a chain the SDK does not cover, or one that fails the read, throws
34
- * rather than answering with empty metadata.
33
+ * to, hence a chain the SDK does not cover, or one that fails the read, is a
34
+ * failure of the whole request rather than a thinner answer.
35
+ *
36
+ * No method here throws. Every way a preparation can fail — the market's own
37
+ * refusals, the two the namespace decides itself, and anything the chain or the
38
+ * engine raises — comes back described in the envelope, see {@link PrepareError}.
39
+ * A caller writes one branch, not a branch and a `try`.
35
40
  **/
36
41
  declare class PrepareApi extends MultichainConstruct implements IOpportunitiesPrepare {
37
42
  #private;
@@ -68,7 +73,7 @@ declare class PrepareApi extends MultichainConstruct implements IOpportunitiesPr
68
73
  /**
69
74
  * {@inheritDoc IOpportunitiesPrepare.maxWithdraw}
70
75
  **/
71
- maxWithdraw(position: PositionInput): Promise<DataResponse<bigint>>;
76
+ maxWithdraw(position: PositionInput): Promise<DataResponse<AmountPrepare>>;
72
77
  /**
73
78
  * {@inheritDoc IOpportunitiesPrepare.repayStrategy}
74
79
  **/
@@ -76,7 +81,7 @@ declare class PrepareApi extends MultichainConstruct implements IOpportunitiesPr
76
81
  /**
77
82
  * {@inheritDoc IOpportunitiesPrepare.maxRepay}
78
83
  **/
79
- maxRepay(position: PositionInput): Promise<DataResponse<bigint>>;
84
+ maxRepay(position: PositionInput): Promise<DataResponse<AmountPrepare>>;
80
85
  /**
81
86
  * {@inheritDoc IOpportunitiesPrepare.adjustLeverage}
82
87
  **/
@@ -100,7 +105,7 @@ declare class PrepareApi extends MultichainConstruct implements IOpportunitiesPr
100
105
  /**
101
106
  * {@inheritDoc IOpportunitiesPrepare.maxWithdrawCollateral}
102
107
  **/
103
- maxWithdrawCollateral(position: PositionInput, token: Address, targetHF?: bigint): Promise<DataResponse<bigint>>;
108
+ maxWithdrawCollateral(position: PositionInput, token: Address, targetHF?: bigint): Promise<DataResponse<AmountPrepare>>;
104
109
  }
105
110
  //#endregion
106
111
  export { ChainOf, PrepareApi };
@@ -0,0 +1,280 @@
1
+ import { Bps, Token, TokenAmount } from "../../model/primitives.js";
2
+ import { IGearboxError } from "../../model/errors.js";
3
+ import "../../model/index.js";
4
+ import { BorrowLimitBinding, PreviewIssue } from "../../onchain/validation/refusal.js";
5
+ import { RouteRefusals } from "../../onchain/accounts/intents/types.js";
6
+ import "../../onchain/index.js";
7
+ import { Address } from "viem";
8
+ //#region src/sdk/prepare/errors.d.ts
9
+ /**
10
+ * Why a preparation was refused.
11
+ *
12
+ * One interface per reason, discriminated by `code`, each carrying the numbers
13
+ * behind that reason — so a caller reads the limit that was missed off the
14
+ * error instead of re-deriving it. Switch on `code` and the fields narrow with
15
+ * it.
16
+ *
17
+ * Most codes are the engine's `PreviewErrorReason` members, which is what keeps
18
+ * `prepare` and `preview` refusing in one vocabulary; what differs is where the
19
+ * numbers sit. The engine keeps them one level down, in `detail`, because it
20
+ * distributes them over `reason`; here they are stated outright, so it is
21
+ * `error.maxDebt` rather than `error.detail.maxDebt`. The last three are the
22
+ * namespace's own, raised before or around the engine.
23
+ *
24
+ * Nothing else comes out of a `prepare` method: every failure on the way to an
25
+ * answer, the ones that used to be thrown included, is one of these.
26
+ **/
27
+ type PrepareError = DebtOutOfRangeError | LeverageOutOfRangeError | InsufficientSourceBalanceError | UnsupportedCollateralTokenError | UnsupportedTokenPairError | NoDelayedRouteError | MultipleDelayedWithdrawalsError | WithdrawalInProgressError | NoRecordedIntentError | MarketPausedError | MarketExpiredError | InsufficientPoolLiquidityError | QuotaLimitReachedError | ForbiddenTokenError | InsufficientCollateralError | PoolSunsetError | QuotaCountExceededError | MalformedTransactionError | NoStrategyTargetCollateralError | CreditAccountNotFoundError | UnexpectedFailureError;
28
+ /** The debt the request implies falls outside the facade's band. */
29
+ interface DebtOutOfRangeError extends IGearboxError {
30
+ code: "debtOutOfRange";
31
+ /** All three in the market's underlying. */
32
+ requested: TokenAmount;
33
+ minDebt: TokenAmount;
34
+ maxDebt: TokenAmount;
35
+ }
36
+ /** The leverage asked for cannot be expressed as a plan at all. */
37
+ interface LeverageOutOfRangeError extends IGearboxError {
38
+ code: "leverageOutOfRange";
39
+ /**
40
+ * Scaled by `LEVERAGE_DECIMALS` (`100n` = 1x), as the intent states it — not
41
+ * the read model's `Leverage`. Both are absent where the floor is not fixed:
42
+ * the deposit planner's is a function of the deposit.
43
+ **/
44
+ requested?: bigint;
45
+ min?: bigint;
46
+ }
47
+ /** Nothing on the account or in the wallet can fund what was asked. */
48
+ interface InsufficientSourceBalanceError extends IGearboxError {
49
+ code: "insufficientSourceBalance";
50
+ /**
51
+ * Both absent where the request never got as far as naming an amount, which
52
+ * is most of the sites that raise this.
53
+ **/
54
+ required?: TokenAmount;
55
+ held?: TokenAmount;
56
+ }
57
+ /** Input token is not accepted by the flow (e.g. deposit of a non-underlying). */
58
+ interface UnsupportedCollateralTokenError extends IGearboxError {
59
+ code: "unsupportedCollateralToken";
60
+ token: Token;
61
+ }
62
+ /**
63
+ * No route for the trade the plan needs: no pool pair between the tokens
64
+ * requested, several and none was picked, or the pathfinder itself found no
65
+ * path for the amounts involved.
66
+ **/
67
+ interface UnsupportedTokenPairError extends IGearboxError {
68
+ code: "unsupportedTokenPair";
69
+ /**
70
+ * `to` is absent where the market named no output for `from`; both are absent
71
+ * when the pathfinder reverted rather than answered.
72
+ **/
73
+ from?: Token;
74
+ to?: Token;
75
+ }
76
+ /**
77
+ * The intent cannot settle with a delay: the source has no redemption config,
78
+ * the chain has no compressor, or the payout is one the tail cannot serve.
79
+ **/
80
+ interface NoDelayedRouteError extends IGearboxError {
81
+ code: "noDelayedRoute";
82
+ /** Absent where the refusal is the intent's, not the token's. */
83
+ token?: Token;
84
+ }
85
+ /** Several redemption venues for the source, and nothing says which. */
86
+ interface MultipleDelayedWithdrawalsError extends IGearboxError {
87
+ code: "multipleDelayedWithdrawals";
88
+ token: Token;
89
+ venues: number;
90
+ }
91
+ /** A redemption of the same asset is already in flight. */
92
+ interface WithdrawalInProgressError extends IGearboxError {
93
+ code: "withdrawalInProgress";
94
+ /** The phantom token standing for the redemption already in flight. */
95
+ inFlight: TokenAmount;
96
+ }
97
+ /**
98
+ * The claim names no operation to resume: requested without an intent, or read
99
+ * through a compressor too old to report one.
100
+ **/
101
+ interface NoRecordedIntentError extends IGearboxError {
102
+ code: "noRecordedIntent";
103
+ }
104
+ /** The facade or the pool behind it is paused: nothing can be done at all. */
105
+ interface MarketPausedError extends IGearboxError {
106
+ code: "marketPaused";
107
+ /**
108
+ * Which contract is paused: a credit account operation names the manager, an
109
+ * LP operation the pool. Exactly one of the two is present.
110
+ **/
111
+ creditManager?: Address;
112
+ pool?: Address;
113
+ }
114
+ /** The facade is past its expiration date and takes no more multicalls. */
115
+ interface MarketExpiredError extends IGearboxError {
116
+ code: "marketExpired";
117
+ creditManager: Address;
118
+ /** Unix seconds, as the facade reports it. */
119
+ expirationDate: number;
120
+ }
121
+ /**
122
+ * The pool cannot lend what the plan draws right now — its free liquidity, the
123
+ * manager's debt limit or the per-block cap stands in the way.
124
+ **/
125
+ interface InsufficientPoolLiquidityError extends IGearboxError {
126
+ code: "insufficientPoolLiquidity";
127
+ /** Both in the market's underlying. */
128
+ requested: TokenAmount;
129
+ available: TokenAmount;
130
+ /**
131
+ * Which of the four ceilings ran out first, so a caller can say what would
132
+ * fix it — waiting for lenders and asking governance are opposite answers.
133
+ **/
134
+ binding: BorrowLimitBinding;
135
+ /**
136
+ * The largest position still openable, absent when even the minimum debt does
137
+ * not fit.
138
+ **/
139
+ solutionAmount?: TokenAmount;
140
+ }
141
+ /** The market takes no more quota for a token the plan wants to hold. */
142
+ interface QuotaLimitReachedError extends IGearboxError {
143
+ code: "quotaLimitReached";
144
+ /** The token whose quota is asked for. */
145
+ token: Token;
146
+ /**
147
+ * In the **underlying**, which is what a quota is measured in. `requested` is
148
+ * absent for a token the market opened no quota for at all — nothing was
149
+ * weighed against a limit.
150
+ **/
151
+ requested: TokenAmount | undefined;
152
+ available: TokenAmount;
153
+ }
154
+ /** The plan would increase the balance of a token the market forbids. */
155
+ interface ForbiddenTokenError extends IGearboxError {
156
+ code: "forbiddenToken";
157
+ token: Token;
158
+ }
159
+ /**
160
+ * The account would end the transaction owing more than its collateral is worth
161
+ * under liquidation thresholds, which the facade refuses to allow.
162
+ **/
163
+ interface InsufficientCollateralError extends IGearboxError {
164
+ code: "insufficientCollateral";
165
+ /**
166
+ * The factor that was compared, which for a call that hands funds over is the
167
+ * safe-price one; `safePrices` says which, since a projection always reports
168
+ * main prices.
169
+ **/
170
+ healthFactor: Bps;
171
+ /**
172
+ * The bar it was weighed against — the facade's own `1.0` for a check that
173
+ * asks whether the transaction lands, a form's higher bar for one that asks
174
+ * whether it is wise.
175
+ **/
176
+ required: Bps;
177
+ safePrices: boolean;
178
+ }
179
+ /** The pool is winding down: it still pays out, but takes no more deposits. */
180
+ interface PoolSunsetError extends IGearboxError {
181
+ code: "poolSunset";
182
+ pool: Address;
183
+ }
184
+ /**
185
+ * The account would end up with more quoted tokens than the facade enables at
186
+ * once. A count, not an amount — unlike {@link QuotaLimitReachedError}.
187
+ **/
188
+ interface QuotaCountExceededError extends IGearboxError {
189
+ code: "quotaCountExceeded";
190
+ count: number;
191
+ max: number;
192
+ }
193
+ /**
194
+ * The transaction could not be replayed: it is malformed, and every field
195
+ * derived from replayed balances is guesswork.
196
+ **/
197
+ interface MalformedTransactionError extends IGearboxError {
198
+ code: "malformedTransaction";
199
+ /**
200
+ * The SDK's own preview error code (the `ERROR_*` 1xxx constants). Named
201
+ * apart from `code`, which every error in the envelope spells the same way.
202
+ **/
203
+ previewCode: number;
204
+ /** What the replay reported, which is narrower than {@link message}. */
205
+ detail: string;
206
+ }
207
+ /**
208
+ * Opening asked for no target token and the market names none of its own, so
209
+ * there is nothing to put the position into.
210
+ *
211
+ * A market fact, not a bad argument: pass a `targetToken` to open against a
212
+ * manager that has no default one.
213
+ **/
214
+ interface NoStrategyTargetCollateralError extends IGearboxError {
215
+ code: "noStrategyTargetCollateral";
216
+ creditManager: Address;
217
+ }
218
+ /**
219
+ * No account at that address in the markets this SDK is connected to — closed
220
+ * since it was listed, or read on the wrong chain.
221
+ **/
222
+ interface CreditAccountNotFoundError extends IGearboxError {
223
+ code: "creditAccountNotFound";
224
+ creditAccount: Address;
225
+ }
226
+ /**
227
+ * The SDK could not answer at all: a read that failed, a chain it is not
228
+ * connected to, a market or token address it knows nothing about, a contract
229
+ * that reverted where nothing should, a bug of ours.
230
+ *
231
+ * The one code that is not a verdict on the request — everything above says
232
+ * "this cannot be done", this one says "we do not know". It exists so that a
233
+ * `prepare` method always answers: the failure that used to escape as an
234
+ * exception arrives here instead, whole, under `cause`. `meta.chains` marks the
235
+ * chain as failed alongside it.
236
+ **/
237
+ interface UnexpectedFailureError extends IGearboxError {
238
+ code: "unexpectedFailure";
239
+ /** What actually went wrong, for a log and a bug report. */
240
+ cause: Error;
241
+ }
242
+ /**
243
+ * The refusal of a request that has two routes to offer, see
244
+ * {@link StrategyRoutesPrepare}.
245
+ *
246
+ * `refused` says why each route is missing, which is the answer a form needs
247
+ * even when neither exists: the error itself is the instant route's refusal —
248
+ * the one a caller can usually act on — or the delayed route's when the instant
249
+ * one did not get far enough to have a reason of its own.
250
+ **/
251
+ type RoutesPrepareError = PrepareError & {
252
+ refused: RouteRefusals;
253
+ };
254
+ /**
255
+ * The engine's refusal, as the error the namespace answers with.
256
+ *
257
+ * One place does the lifting, so the two shapes cannot drift: `reason` becomes
258
+ * `code`, the detail is spread onto the error, and the sentence comes from
259
+ * {@link MESSAGES}. A malformed transaction is spelled out rather than spread,
260
+ * because its detail names a `code` and a `message` of its own and they are not
261
+ * the envelope's.
262
+ **/
263
+ declare function toPrepareError(issue: PreviewIssue): PrepareError;
264
+ /**
265
+ * {@inheritDoc NoStrategyTargetCollateralError}
266
+ **/
267
+ declare function noStrategyTargetCollateral(creditManager: Address): NoStrategyTargetCollateralError;
268
+ /**
269
+ * {@inheritDoc CreditAccountNotFoundError}
270
+ **/
271
+ declare function creditAccountNotFound(creditAccount: Address): CreditAccountNotFoundError;
272
+ /**
273
+ * {@inheritDoc UnexpectedFailureError}
274
+ *
275
+ * Takes what was thrown, whatever that is: a `throw` is not obliged to raise an
276
+ * `Error`, and `cause` promises one.
277
+ **/
278
+ declare function unexpectedFailure(thrown: unknown): UnexpectedFailureError;
279
+ //#endregion
280
+ export { CreditAccountNotFoundError, DebtOutOfRangeError, ForbiddenTokenError, InsufficientCollateralError, InsufficientPoolLiquidityError, InsufficientSourceBalanceError, LeverageOutOfRangeError, MalformedTransactionError, MarketExpiredError, MarketPausedError, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, PoolSunsetError, PrepareError, QuotaCountExceededError, QuotaLimitReachedError, RoutesPrepareError, UnexpectedFailureError, UnsupportedCollateralTokenError, UnsupportedTokenPairError, WithdrawalInProgressError, creditAccountNotFound, noStrategyTargetCollateral, toPrepareError, unexpectedFailure };
@@ -1,6 +1,7 @@
1
1
  import { BorrowLimitBinding, IntentPreviewError, PreviewErrorDetails, PreviewErrorReason, PreviewIssue, PreviewRefusal, raise, refuse } from "../../onchain/validation/refusal.js";
2
2
  import { LeverageBand } from "../../onchain/accounts/intents/leverage-band.js";
3
3
  import { OperationState, PathLossRate } from "../../onchain/accounts/intents/types.js";
4
- import { AddCollateralParams, AdjustLeverageParams, DelayedStrategyPrepare, DepositStrategyParams, FinalizeParams, IOpportunitiesPrepare, LpParams, LpPrepare, LpRedeemParams, OpenStrategyParams, OpenStrategyPrepare, PoolInput, PositionInput, PrepareOptions, RepayStrategyParams, StrategyInput, StrategyPrepare, StrategyRoutesPrepare, WithdrawCollateralParams, WithdrawStrategyParams } from "./types.js";
4
+ import { CreditAccountNotFoundError, DebtOutOfRangeError, ForbiddenTokenError, InsufficientCollateralError, InsufficientPoolLiquidityError, InsufficientSourceBalanceError, LeverageOutOfRangeError, MalformedTransactionError, MarketExpiredError, MarketPausedError, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, PoolSunsetError, PrepareError, QuotaCountExceededError, QuotaLimitReachedError, RoutesPrepareError, UnexpectedFailureError, UnsupportedCollateralTokenError, UnsupportedTokenPairError, WithdrawalInProgressError, creditAccountNotFound, noStrategyTargetCollateral, toPrepareError, unexpectedFailure } from "./errors.js";
5
+ import { AddCollateralParams, AdjustLeverageParams, AmountPrepare, DelayedStrategyPlan, DelayedStrategyPrepare, DepositStrategyParams, FinalizeParams, IOpportunitiesPrepare, LpParams, LpPlan, LpPrepare, LpRedeemParams, OpenStrategyParams, OpenStrategyPlan, OpenStrategyPrepare, PoolInput, PositionInput, PrepareOptions, RepayStrategyParams, StrategyInput, StrategyPlan, StrategyPrepare, StrategyRoutes, StrategyRoutesPrepare, WithdrawCollateralParams, WithdrawStrategyParams } from "./types.js";
5
6
  import { ChainOf, PrepareApi } from "./PrepareApi.js";
6
- export { AddCollateralParams, AdjustLeverageParams, BorrowLimitBinding, ChainOf, DelayedStrategyPrepare, DepositStrategyParams, FinalizeParams, IOpportunitiesPrepare, IntentPreviewError, type LeverageBand, LpParams, LpPrepare, LpRedeemParams, OpenStrategyParams, OpenStrategyPrepare, type OperationState, type PathLossRate, PoolInput, PositionInput, PrepareApi, PrepareOptions, PreviewErrorDetails, PreviewErrorReason, PreviewIssue, PreviewRefusal, RepayStrategyParams, StrategyInput, StrategyPrepare, StrategyRoutesPrepare, WithdrawCollateralParams, WithdrawStrategyParams, raise, refuse };
7
+ export { AddCollateralParams, AdjustLeverageParams, AmountPrepare, BorrowLimitBinding, ChainOf, CreditAccountNotFoundError, DebtOutOfRangeError, DelayedStrategyPlan, DelayedStrategyPrepare, DepositStrategyParams, FinalizeParams, ForbiddenTokenError, IOpportunitiesPrepare, InsufficientCollateralError, InsufficientPoolLiquidityError, InsufficientSourceBalanceError, IntentPreviewError, type LeverageBand, LeverageOutOfRangeError, LpParams, LpPlan, LpPrepare, LpRedeemParams, MalformedTransactionError, MarketExpiredError, MarketPausedError, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, OpenStrategyParams, OpenStrategyPlan, OpenStrategyPrepare, type OperationState, type PathLossRate, PoolInput, PoolSunsetError, PositionInput, PrepareApi, PrepareError, PrepareOptions, PreviewErrorDetails, PreviewErrorReason, PreviewIssue, PreviewRefusal, QuotaCountExceededError, QuotaLimitReachedError, RepayStrategyParams, RoutesPrepareError, StrategyInput, StrategyPlan, StrategyPrepare, StrategyRoutes, StrategyRoutesPrepare, UnexpectedFailureError, UnsupportedCollateralTokenError, UnsupportedTokenPairError, WithdrawCollateralParams, WithdrawStrategyParams, WithdrawalInProgressError, creditAccountNotFound, noStrategyTargetCollateral, raise, refuse, toPrepareError, unexpectedFailure };