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

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 (56) hide show
  1. package/dist/cjs/model/index.js +4 -0
  2. package/dist/cjs/model/result.js +27 -0
  3. package/dist/cjs/onchain/accounts/intents/tail.js +1 -1
  4. package/dist/cjs/onchain/accounts/withdrawal-compressor/errors.js +14 -14
  5. package/dist/cjs/onchain/index.js +0 -1
  6. package/dist/cjs/onchain/market/zapper/errors.js +13 -12
  7. package/dist/cjs/onchain/validation/index.js +0 -1
  8. package/dist/cjs/preview/index.js +4 -1
  9. package/dist/cjs/preview/parse/errors.js +25 -22
  10. package/dist/cjs/preview/preview/errors.js +12 -11
  11. package/dist/cjs/preview/preview/previewOperation.js +41 -10
  12. package/dist/cjs/preview/simulate/errors.js +18 -17
  13. package/dist/cjs/sdk/execute/ExecuteApi.js +1 -1
  14. package/dist/cjs/sdk/index.js +1 -1
  15. package/dist/cjs/sdk/prepare/PrepareApi.js +198 -278
  16. package/dist/cjs/sdk/prepare/errors.js +5 -2
  17. package/dist/cjs/sdk/prepare/index.js +1 -1
  18. package/dist/esm/model/index.js +2 -1
  19. package/dist/esm/model/result.js +24 -0
  20. package/dist/esm/onchain/accounts/intents/tail.js +1 -1
  21. package/dist/esm/onchain/accounts/withdrawal-compressor/errors.js +14 -14
  22. package/dist/esm/onchain/index.js +2 -2
  23. package/dist/esm/onchain/market/zapper/errors.js +13 -12
  24. package/dist/esm/onchain/validation/index.js +2 -2
  25. package/dist/esm/preview/index.js +4 -2
  26. package/dist/esm/preview/parse/errors.js +25 -22
  27. package/dist/esm/preview/preview/errors.js +12 -11
  28. package/dist/esm/preview/preview/previewOperation.js +41 -10
  29. package/dist/esm/preview/simulate/errors.js +18 -17
  30. package/dist/esm/sdk/execute/ExecuteApi.js +1 -1
  31. package/dist/esm/sdk/index.js +2 -2
  32. package/dist/esm/sdk/prepare/PrepareApi.js +199 -279
  33. package/dist/esm/sdk/prepare/errors.js +5 -2
  34. package/dist/esm/sdk/prepare/index.js +2 -2
  35. package/dist/types/model/errors.d.ts +3 -31
  36. package/dist/types/model/index.d.ts +3 -2
  37. package/dist/types/model/result.d.ts +48 -0
  38. package/dist/types/onchain/accounts/withdrawal-compressor/errors.d.ts +18 -5
  39. package/dist/types/onchain/index.d.ts +2 -2
  40. package/dist/types/onchain/market/zapper/errors.d.ts +20 -6
  41. package/dist/types/onchain/validation/index.d.ts +2 -2
  42. package/dist/types/preview/index.d.ts +5 -3
  43. package/dist/types/preview/parse/errors.d.ts +36 -11
  44. package/dist/types/preview/preview/errors.d.ts +17 -5
  45. package/dist/types/preview/preview/index.d.ts +2 -2
  46. package/dist/types/preview/preview/previewOperation.d.ts +21 -2
  47. package/dist/types/preview/simulate/errors.d.ts +21 -8
  48. package/dist/types/sdk/execute/types.d.ts +6 -11
  49. package/dist/types/sdk/index.d.ts +3 -3
  50. package/dist/types/sdk/prepare/PrepareApi.d.ts +29 -26
  51. package/dist/types/sdk/prepare/errors.d.ts +56 -19
  52. package/dist/types/sdk/prepare/index.d.ts +3 -3
  53. package/dist/types/sdk/prepare/types.d.ts +73 -74
  54. package/dist/types/sdk/preview/PreviewNamespace.d.ts +4 -1
  55. package/dist/types/sdk/preview/types.d.ts +7 -3
  56. package/package.json +11 -2
@@ -20,6 +20,7 @@ import { ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ER
20
20
  import "./primitives.js";
21
21
  import "./response.js";
22
22
  import { chainFailedSchema, chainMetadataSchema, chainSucceededSchema, dataSourceSchema, responseMetadataSchema, responseSchema } from "./response.schema.js";
23
+ import { isSDKError, sdkErr, sdkOk } from "./result.js";
23
24
  import "./withdrawals.js";
24
25
  import { positionClaimableWithdrawalSchema, positionPendingWithdrawalSchema, positionWithdrawalsSchema } from "./withdrawals.schema.js";
25
- export { CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, 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, FILTER_ALL, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, 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 };
26
+ export { CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, 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, FILTER_ALL, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, 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, isSDKError, 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, sdkErr, sdkOk, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema };
@@ -0,0 +1,24 @@
1
+ //#region src/model/result.ts
2
+ /** The success half, built. */
3
+ function sdkOk(data) {
4
+ return {
5
+ ok: true,
6
+ data
7
+ };
8
+ }
9
+ /** The failure half, built. */
10
+ function sdkErr(error) {
11
+ return {
12
+ ok: false,
13
+ error
14
+ };
15
+ }
16
+ /**
17
+ * Narrows a {@link SDKReturn} to its failure half. Trivial over `ok`, but it
18
+ * names the intent at call sites that would otherwise read `!r.ok`.
19
+ **/
20
+ function isSDKError(answer) {
21
+ return !answer.ok;
22
+ }
23
+ //#endregion
24
+ export { isSDKError, sdkErr, sdkOk };
@@ -53,7 +53,7 @@ async function projectTail(args) {
53
53
  const { request, delayed, creditAccount, sdk, quotaReserve } = args;
54
54
  const { claim } = delayed;
55
55
  const queued = request.outputs.find((o) => o.isDelayed);
56
- if (!queued || !claim) throw new Error("projectTail: the request queued nothing to claim");
56
+ if (!queued || !claim) throw new IntentPreviewError("noRecordedIntent", void 0, "projectTail: the request queued nothing to claim");
57
57
  const next = sliceAfter(creditAccount, delayed.afterRequest);
58
58
  const steps = planTail({
59
59
  intent: delayed.record,
@@ -1,19 +1,19 @@
1
1
  //#region src/onchain/accounts/withdrawal-compressor/errors.ts
2
+ function invalidDelayedIntent(extraData, cause) {
3
+ const verdict = {
4
+ code: "invalidDelayedIntent",
5
+ message: `cannot decode delayed intent from extraData ${extraData}`,
6
+ extraData
7
+ };
8
+ if (cause !== void 0) verdict.cause = cause instanceof Error ? cause : new Error(String(cause));
9
+ return verdict;
10
+ }
11
+ Object.defineProperty(invalidDelayedIntent, Symbol.hasInstance, { value: (value) => typeof value === "object" && value !== null && value.code === "invalidDelayedIntent" });
2
12
  /**
3
- * Thrown when a delayed-withdrawal request or redemption log carries
4
- * non-empty `extraData` that cannot be decoded as a `DelayedIntent`.
5
- * Requests produced by our stack always encode a valid intent, so garbage
6
- * here means a malformed/foreign transaction that must not be previewed as
7
- * if it were fine.
13
+ * Builds the verdict. Callable with or without `new`, so pre-declassing raise
14
+ * sites keep compiling; `instanceof` matches on the `code` discriminant, and
15
+ * the answer is never an `Error`.
8
16
  */
9
- var InvalidDelayedIntentError = class extends Error {
10
- /** Raw `extraData` that failed to decode. */
11
- extraData;
12
- constructor(extraData, cause) {
13
- super(`cannot decode delayed intent from extraData ${extraData}`, { cause });
14
- this.name = "InvalidDelayedIntentError";
15
- this.extraData = extraData;
16
- }
17
- };
17
+ const InvalidDelayedIntentError = invalidDelayedIntent;
18
18
  //#endregion
19
19
  export { InvalidDelayedIntentError };
@@ -195,7 +195,7 @@ import { CreditAccountCompressorV310Contract } from "./accounts/credit-account-c
195
195
  import { CreditAccountCompressor } from "./accounts/credit-account-compressor/CreditAccountCompressor.js";
196
196
  import { CreditAccountsServiceV310 } from "./accounts/CreditAccountsServiceV310.js";
197
197
  import { MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_SAFE_HEALTH_FACTOR_FORM, amountOf, checkBorrowLimit, checkCollateralised, checkCreditManagerPaused, checkDebtInBand, checkForbiddenToken, checkFunding, checkLeverageAtLeastOne, checkMarketExpired, checkPoolPaused, checkPoolPayout, checkPoolSunset, checkPreviewError, checkQuotaCount, checkQuotaLimit, isMalformedPreviewError } from "./validation/checks.js";
198
- import { IntentPreviewError, raise, refuse } from "./validation/refusal.js";
198
+ import { raise, refuse } from "./validation/refusal.js";
199
199
  import { toToken, toTokenAmount } from "./validation/token.js";
200
200
  import { isPhantomToken } from "./accounts/intents/utils/pick-token.js";
201
201
  import { borrowable } from "./accounts/intents/guards.js";
@@ -246,4 +246,4 @@ import { MultichainSDK } from "./MultichainSDK.js";
246
246
  import { attachOptionsSchema, onchainSDKOptionsSchema } from "./options.js";
247
247
  import "./types/index.js";
248
248
  import "./validation/index.js";
249
- export { ADDRESS_0X0, ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, AbstractAdapterContract, AbstractLPPriceFeedContract, AbstractPriceFeedContract, AbstractWithdrawalCompressorContract, AccountBotsService, AccountMigratorAdapterContract, AdapterType, AddressMap, AddressProviderV310Contract, AddressSet, AssetsMap, BLOCKS_PER_WEEK_BY_NETWORK, BalancerStablePriceFeedContract, BalancerV3PoolStatus, BalancerV3RouterAdapterContract, BalancerV3WrapperAdapterContract, BalancerWeightedPriceFeedContract, BaseContract, BasePlugin, BigIntMath, BotPermissions, BoundedPriceFeedContract, CamelotV3AdapterContract, ChainContractsRegister, ChainNotConfiguredError, CompositePriceFeedContract, Construct, ContractParseError, ConvexV1BaseRewardPoolAdapterContract, ConvexV1BoosterAdapterContract, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, Curve2AssetsAdapterContract, Curve3AssetsAdapterContract, Curve4AssetsAdapterContract, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, CurveV1AdapterStETHContract, CurveV1StableNGAdapterContract, DEFAULT_QUOTA_BUFFER_BPS, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, DUST_THRESHOLD, DaiUsdsAdapterContract, ERC4626AdapterContract, ERC4626ReferralAdapterContract, EXECUTE_BYTES_SELECTOR, Erc4626PriceFeedContract, ExternalPriceFeedContract, FluidDexAdapterContract, GaugeContract, IERC20ZapperContract, IETHZapperContract, InfinifiGatewayAdapterContract, InfinifiUnwindingGatewayAdapterContract, IntentPreviewError, InvalidDelayedIntentError, KelpLRTDepositPoolAdapterContract, KelpLRTWithdrawalManagerAdapterContract, LEVERAGE_DECIMALS, LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, LidoV1AdapterContract, LinearInterestRateModelContract, LiquidationsService, MAX_INT, MAX_LEVERAGE_BUFFER_BPS, MAX_UINT16, MAX_UINT256, MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_INT96, MIN_SAFE_HEALTH_FACTOR_FORM, MULTICALL_ADDRESS, MarketRegister, MarketSuite, MellowClaimerAdapterContract, MellowDVVAdapterContract, MellowERC4626VaultAdapterContract, MellowLRTPriceFeedContract, MellowWrapperAdapterContract, MidasGatewayAdapterContract, MidasIssuanceVaultAdapterContract, MidasLiquidatorContract, MidasRedemptionVaultAdapterContract, MissingSerializedParamsError, MultichainConstruct, MultichainLiquidationsService, MultichainOpportunitiesService, MultichainPositionsService, MultichainSDK, NATIVE_ADDRESS, NON_STRATEGY_PHANTOM_TOKEN_TYPES, NOT_DEPLOYED, NO_VERSION, NetworkType, OnchainSDK, OpportunitiesService, PARTIAL_LIQUIDATION_BUFFER_BPS, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PERIPHERY_CONTRACTS, PHANTOM_TOKEN_CONTRACT_TYPES, PHANTOM_TOKEN_MIDAS_REDEMPTION, PHANTOM_TOKEN_SECURITIZE_REDEMPTION, PRICE_DECIMALS, PRICE_DECIMALS_POW, PartialPriceFeedInitError, PendlePairStatus, PendleRouterAdapterContract, PendleTWAPPTPriceFeed, PendleTokenType, PeripheryCompressorV310Contract, PluginStateVersionError, PoolService, PoolSuite, PoolV310Contract, PositionsService, PriceFeedRef, PriceFeedRegister, PriceOracleV310Contract, PythPriceFeed, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, RWARegistry, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_LIQUIDATOR_MIDAS, RWA_LIQUIDATOR_SECURITIZE, RWA_ON_DEMAND_LP_MONOPOLIZED, RWA_UNDERLYING_DEFAULT, RWA_UNDERLYING_ON_DEMAND, RedemptionLoggerV310Contract, RedstonePriceFeedContract, RouterV310Contract, SDKConstruct, SECONDS_PER_YEAR, SECURITIZE_REGISTER_VAULT_TYPES, SLIPPAGE_DECIMALS, STATE_VERSION, SUPPORTED_NETWORKS, SdkAlreadyAttachedError, SdkChainMismatchError, SdkMissingChainStateError, SdkNotAttachedError, SdkRWADataNotLoadedError, SdkStateVersionMismatchError, SdkSyncFailedError, SecuritizeLiquidatorContract, SecuritizeOnRampAdapterContract, SecuritizeRWAFactory, SecuritizeRedemptionGatewayAdapterContract, SimulateWithPriceUpdatesError, SimulationError, StakingRewardsAdapterContract, TokensMeta, TraderJoePoolVersion, TraderJoeRouterAdapterContract, TypedObjectUtils, UniswapV2AdapterContract, UniswapV3AdapterContract, UniswapV4AdapterContract, UnsupportedZapperFunctionError, UpshiftVaultAdapterContract, VERSION_RANGE_310, VelodromeV2RouterAdapterContract, VotingContractStatus, WAD, WAD_DECIMALS_POW, WithdrawalCompressorV310Contract, WithdrawalCompressorV311Contract, WithdrawalCompressorV313Contract, WstETHPriceFeedContract, WstETHV1AdapterContract, YearnPriceFeedContract, ZapperContract, ZeroPriceFeedContract, ZodAddress, ZodBigInt, ZodHex, accountSnapshotFromCreditAccountData, adapterActionAbi, adapterActionSelectors, adapterActionSignatures, adapterConstructorAbi, allTransfersAsTokenAmounts, amountOf, assetsMap, attachOptionsSchema, borrowable, botPermissionsToString, bpsToRay, bytes32ToString, calcBorrowApy, calcBorrowRate, calcDefaultQuota, calcEffectiveBorrowApy, calcHealthFactor, calcLiquidationPrice, calcLiquidationPriceForTarget, calcMaxLeverage, calcNetStrategyApy, calcPositionLeverage, calcQuotaRate, calcQuotaUpdate, calcRecommendedQuota, calcTimeToLiquidationMs, calcUtilization, calcUtilizationRaw, chains, checkBorrowLimit, checkCollateralised, checkCreditManagerPaused, checkDebtInBand, checkForbiddenToken, checkFunding, checkLeverageAtLeastOne, checkMarketExpired, checkPoolPaused, checkPoolPayout, checkPoolSunset, checkPreviewError, checkQuotaCount, checkQuotaLimit, childLogger, classifyCurveOperation, collateralPriceInUnderlying, collectTraces, createAdapter, createAddressProvider, createPriceOracle, createRawTx, createRedemptionLogger, createRouter, createWithdrawalCompressor, createZapper, abi as creditFacadeV310Abi, curveAddLiquidityFromTransfers, curveRemoveLiquidityFromTransfers, decodeDelayedIntent, detectNetwork, dominantCollateral, encodeDelayedIntent, erc4626ReferralAdapterAbi, estimateRawTxGas, etherscanApiUrl, etherscanUrl, executeDelegatedMulticalls, executeMulticallBatches, expectedBalanceDeltas, fetchCreditAccountSlice, fetchRedstonePayloads, filterDust, filterDustUSD, findCallTo, findCallWithInput, findCuratorMarketConfigurator, findExecuteBytes, fmtBinaryMask, fnSigToName, formatBN, formatBNvalue, formatDuration, formatLeverage, formatNumberToString_, formatPercentage, formatTimestamp, functionArgsToMap, functionArgsToRecord, generateCastTraceCall, getAccountTargetCollateral, getAdapterActionAbi, getAdapterDeployParamsAbi, getAdapterType, getAssetType, getCastTraceArgs, getChain, getCuratorName, getFunctionSignature, getLegacyStrategyTarget, getNetworkType, getRawPriceUpdates, getSimulateWithPriceUpdatesError, getWithdrawalCompressorAddress, halfRAY, hasAdapterDeployParamsAbi, healthFactorBps, hexEq, hydrateAddressProvider, iBalancerV3RouterAbi, iBalancerV3RouterAdapterAbi, iBalancerV3WrapperAbi, iBalancerV3WrapperAdapterAbi, iBaseOnRampAbi, iBaseRewardPoolAbi, iBoosterAbi, iCamelotV3AdapterAbi, iCamelotV3RouterAbi, iConvexV1BaseRewardPoolAdapterAbi, iConvexV1BoosterAdapterAbi, iCreditAccountAbi, iCurvePoolAbi, iCurvePoolStableNGAbi, iCurvePool_2Abi, iCurvePool_3Abi, iCurvePool_4Abi, iCurveV1StableNgAdapterAbi, iCurveV1_2AssetsAdapterAbi, iCurveV1_3AssetsAdapterAbi, iCurveV1_4AssetsAdapterAbi, iDaiUsdsAbi, iDaiUsdsAdapterAbi, iERC4626Abi, iERC4626ReferralAbi, iFluidDexAbi, iFluidDexAdapterAbi, iInfinifiGatewayAbi, iInfinifiGatewayAdapterAbi, iInfinifiUnwindingGatewayAbi, iInfinifiUnwindingGatewayAdapterAbi, iKelpLRTDepositPoolGatewayAbi, iKelpLRTWithdrawalManagerGatewayAbi, iKelpLrtDepositPoolAdapterAbi, iKelpLrtDepositPoolGatewayAbi, iKelpLrtWithdrawalManagerAdapterAbi, iKelpLrtWithdrawalManagerGatewayAbi, iLidoV1AdapterAbi, iMellow4626VaultAdapterAbi, iMellowClaimerAbi, iMellowClaimerAdapterAbi, iMellowWrapperAbi, iMellowWrapperAdapterAbi, iMidasGatewayAdapterV311Abi, iMidasGatewayV311Abi, iMidasIssuanceVaultAdapterV310Abi, iMidasIssuanceVaultV310Abi, iMidasRedemptionVaultAdapterV310Abi, iMidasRedemptionVaultGatewayV310Abi, iPendleRouterAbi, iPendleRouterAdapterAbi, iSecuritizeOnRampAbi, iSecuritizeOnRampAdapterV310Abi, iSecuritizeRedemptionGatewayAdapterV311Abi, iSecuritizeRedemptionGatewayV311Abi, iStakingRewardsAbi, iStakingRewardsAdapterAbi, iTraderJoeRouterAbi, iTraderJoeRouterAdapterAbi, iUniswapV2AdapterAbi, iUniswapV2Router02Abi, iUniswapV3Abi, iUniswapV3AdapterAbi, iUniswapV4AdapterAbi, iUniswapV4GatewayAbi, iUpshiftVaultAdapterAbi, iUpshiftVaultGatewayAbi, iVelodromeV2RouterAbi, iVelodromeV2RouterAdapterAbi, isDust, isLPPriceFeed, isMalformedPreviewError, isPhantomToken, isPublicNetwork, isRWAFactory, isRWAToken, isStrategyCollateral, isSunsetPool, isSunsetStrategy, isSupportedNetwork, isUpdatablePriceFeed, isV310, isVersionRange, isZeroBalance, iwstETHAbi, iwstEthv1AdapterAbi, json_parse, json_stringify, lidoV1_WETHGatewayAbi, mellowDvvAdapterAbi, minSeizedAmount, numberWithCommas, onchainSDKOptionsSchema, optimalHFForPartialLiquidation, optimalRepaidAmount, parseAdapterAction, parseAdapterDeployParams, parsePosNegAmount, percentFmt, pickStrategyTargetCollateral, raise, rayToBps, rayToNumber, refuse, resolveProtocolCall, retry, rewardsFromTransfers, roundUpQuota, sendRawTx, shortAddress, shortHash, simulateCall, simulateMulticall, simulateWithPriceUpdates, soleNonUnderlyingCollateral, strategyName, swapFromTransfers, toAddress, toBN, toBigInt, toChainIds, toClaimableWithdrawal, toCreditAccountSlice, toNetTransfers, toPendingWithdrawal, toRequestableWithdrawal, toShares, toSharesUp, toSignificant, toToken, toTokenAmount, toWithdrawalStatus, usdToNumber, watchBlocksAsync };
249
+ export { ADDRESS_0X0, ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, AbstractAdapterContract, AbstractLPPriceFeedContract, AbstractPriceFeedContract, AbstractWithdrawalCompressorContract, AccountBotsService, AccountMigratorAdapterContract, AdapterType, AddressMap, AddressProviderV310Contract, AddressSet, AssetsMap, BLOCKS_PER_WEEK_BY_NETWORK, BalancerStablePriceFeedContract, BalancerV3PoolStatus, BalancerV3RouterAdapterContract, BalancerV3WrapperAdapterContract, BalancerWeightedPriceFeedContract, BaseContract, BasePlugin, BigIntMath, BotPermissions, BoundedPriceFeedContract, CamelotV3AdapterContract, ChainContractsRegister, ChainNotConfiguredError, CompositePriceFeedContract, Construct, ContractParseError, ConvexV1BaseRewardPoolAdapterContract, ConvexV1BoosterAdapterContract, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, Curve2AssetsAdapterContract, Curve3AssetsAdapterContract, Curve4AssetsAdapterContract, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, CurveV1AdapterStETHContract, CurveV1StableNGAdapterContract, DEFAULT_QUOTA_BUFFER_BPS, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, DUST_THRESHOLD, DaiUsdsAdapterContract, ERC4626AdapterContract, ERC4626ReferralAdapterContract, EXECUTE_BYTES_SELECTOR, Erc4626PriceFeedContract, ExternalPriceFeedContract, FluidDexAdapterContract, GaugeContract, IERC20ZapperContract, IETHZapperContract, InfinifiGatewayAdapterContract, InfinifiUnwindingGatewayAdapterContract, InvalidDelayedIntentError, KelpLRTDepositPoolAdapterContract, KelpLRTWithdrawalManagerAdapterContract, LEVERAGE_DECIMALS, LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, LidoV1AdapterContract, LinearInterestRateModelContract, LiquidationsService, MAX_INT, MAX_LEVERAGE_BUFFER_BPS, MAX_UINT16, MAX_UINT256, MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_INT96, MIN_SAFE_HEALTH_FACTOR_FORM, MULTICALL_ADDRESS, MarketRegister, MarketSuite, MellowClaimerAdapterContract, MellowDVVAdapterContract, MellowERC4626VaultAdapterContract, MellowLRTPriceFeedContract, MellowWrapperAdapterContract, MidasGatewayAdapterContract, MidasIssuanceVaultAdapterContract, MidasLiquidatorContract, MidasRedemptionVaultAdapterContract, MissingSerializedParamsError, MultichainConstruct, MultichainLiquidationsService, MultichainOpportunitiesService, MultichainPositionsService, MultichainSDK, NATIVE_ADDRESS, NON_STRATEGY_PHANTOM_TOKEN_TYPES, NOT_DEPLOYED, NO_VERSION, NetworkType, OnchainSDK, OpportunitiesService, PARTIAL_LIQUIDATION_BUFFER_BPS, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PERIPHERY_CONTRACTS, PHANTOM_TOKEN_CONTRACT_TYPES, PHANTOM_TOKEN_MIDAS_REDEMPTION, PHANTOM_TOKEN_SECURITIZE_REDEMPTION, PRICE_DECIMALS, PRICE_DECIMALS_POW, PartialPriceFeedInitError, PendlePairStatus, PendleRouterAdapterContract, PendleTWAPPTPriceFeed, PendleTokenType, PeripheryCompressorV310Contract, PluginStateVersionError, PoolService, PoolSuite, PoolV310Contract, PositionsService, PriceFeedRef, PriceFeedRegister, PriceOracleV310Contract, PythPriceFeed, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, RWARegistry, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_LIQUIDATOR_MIDAS, RWA_LIQUIDATOR_SECURITIZE, RWA_ON_DEMAND_LP_MONOPOLIZED, RWA_UNDERLYING_DEFAULT, RWA_UNDERLYING_ON_DEMAND, RedemptionLoggerV310Contract, RedstonePriceFeedContract, RouterV310Contract, SDKConstruct, SECONDS_PER_YEAR, SECURITIZE_REGISTER_VAULT_TYPES, SLIPPAGE_DECIMALS, STATE_VERSION, SUPPORTED_NETWORKS, SdkAlreadyAttachedError, SdkChainMismatchError, SdkMissingChainStateError, SdkNotAttachedError, SdkRWADataNotLoadedError, SdkStateVersionMismatchError, SdkSyncFailedError, SecuritizeLiquidatorContract, SecuritizeOnRampAdapterContract, SecuritizeRWAFactory, SecuritizeRedemptionGatewayAdapterContract, SimulateWithPriceUpdatesError, SimulationError, StakingRewardsAdapterContract, TokensMeta, TraderJoePoolVersion, TraderJoeRouterAdapterContract, TypedObjectUtils, UniswapV2AdapterContract, UniswapV3AdapterContract, UniswapV4AdapterContract, UnsupportedZapperFunctionError, UpshiftVaultAdapterContract, VERSION_RANGE_310, VelodromeV2RouterAdapterContract, VotingContractStatus, WAD, WAD_DECIMALS_POW, WithdrawalCompressorV310Contract, WithdrawalCompressorV311Contract, WithdrawalCompressorV313Contract, WstETHPriceFeedContract, WstETHV1AdapterContract, YearnPriceFeedContract, ZapperContract, ZeroPriceFeedContract, ZodAddress, ZodBigInt, ZodHex, accountSnapshotFromCreditAccountData, adapterActionAbi, adapterActionSelectors, adapterActionSignatures, adapterConstructorAbi, allTransfersAsTokenAmounts, amountOf, assetsMap, attachOptionsSchema, borrowable, botPermissionsToString, bpsToRay, bytes32ToString, calcBorrowApy, calcBorrowRate, calcDefaultQuota, calcEffectiveBorrowApy, calcHealthFactor, calcLiquidationPrice, calcLiquidationPriceForTarget, calcMaxLeverage, calcNetStrategyApy, calcPositionLeverage, calcQuotaRate, calcQuotaUpdate, calcRecommendedQuota, calcTimeToLiquidationMs, calcUtilization, calcUtilizationRaw, chains, checkBorrowLimit, checkCollateralised, checkCreditManagerPaused, checkDebtInBand, checkForbiddenToken, checkFunding, checkLeverageAtLeastOne, checkMarketExpired, checkPoolPaused, checkPoolPayout, checkPoolSunset, checkPreviewError, checkQuotaCount, checkQuotaLimit, childLogger, classifyCurveOperation, collateralPriceInUnderlying, collectTraces, createAdapter, createAddressProvider, createPriceOracle, createRawTx, createRedemptionLogger, createRouter, createWithdrawalCompressor, createZapper, abi as creditFacadeV310Abi, curveAddLiquidityFromTransfers, curveRemoveLiquidityFromTransfers, decodeDelayedIntent, detectNetwork, dominantCollateral, encodeDelayedIntent, erc4626ReferralAdapterAbi, estimateRawTxGas, etherscanApiUrl, etherscanUrl, executeDelegatedMulticalls, executeMulticallBatches, expectedBalanceDeltas, fetchCreditAccountSlice, fetchRedstonePayloads, filterDust, filterDustUSD, findCallTo, findCallWithInput, findCuratorMarketConfigurator, findExecuteBytes, fmtBinaryMask, fnSigToName, formatBN, formatBNvalue, formatDuration, formatLeverage, formatNumberToString_, formatPercentage, formatTimestamp, functionArgsToMap, functionArgsToRecord, generateCastTraceCall, getAccountTargetCollateral, getAdapterActionAbi, getAdapterDeployParamsAbi, getAdapterType, getAssetType, getCastTraceArgs, getChain, getCuratorName, getFunctionSignature, getLegacyStrategyTarget, getNetworkType, getRawPriceUpdates, getSimulateWithPriceUpdatesError, getWithdrawalCompressorAddress, halfRAY, hasAdapterDeployParamsAbi, healthFactorBps, hexEq, hydrateAddressProvider, iBalancerV3RouterAbi, iBalancerV3RouterAdapterAbi, iBalancerV3WrapperAbi, iBalancerV3WrapperAdapterAbi, iBaseOnRampAbi, iBaseRewardPoolAbi, iBoosterAbi, iCamelotV3AdapterAbi, iCamelotV3RouterAbi, iConvexV1BaseRewardPoolAdapterAbi, iConvexV1BoosterAdapterAbi, iCreditAccountAbi, iCurvePoolAbi, iCurvePoolStableNGAbi, iCurvePool_2Abi, iCurvePool_3Abi, iCurvePool_4Abi, iCurveV1StableNgAdapterAbi, iCurveV1_2AssetsAdapterAbi, iCurveV1_3AssetsAdapterAbi, iCurveV1_4AssetsAdapterAbi, iDaiUsdsAbi, iDaiUsdsAdapterAbi, iERC4626Abi, iERC4626ReferralAbi, iFluidDexAbi, iFluidDexAdapterAbi, iInfinifiGatewayAbi, iInfinifiGatewayAdapterAbi, iInfinifiUnwindingGatewayAbi, iInfinifiUnwindingGatewayAdapterAbi, iKelpLRTDepositPoolGatewayAbi, iKelpLRTWithdrawalManagerGatewayAbi, iKelpLrtDepositPoolAdapterAbi, iKelpLrtDepositPoolGatewayAbi, iKelpLrtWithdrawalManagerAdapterAbi, iKelpLrtWithdrawalManagerGatewayAbi, iLidoV1AdapterAbi, iMellow4626VaultAdapterAbi, iMellowClaimerAbi, iMellowClaimerAdapterAbi, iMellowWrapperAbi, iMellowWrapperAdapterAbi, iMidasGatewayAdapterV311Abi, iMidasGatewayV311Abi, iMidasIssuanceVaultAdapterV310Abi, iMidasIssuanceVaultV310Abi, iMidasRedemptionVaultAdapterV310Abi, iMidasRedemptionVaultGatewayV310Abi, iPendleRouterAbi, iPendleRouterAdapterAbi, iSecuritizeOnRampAbi, iSecuritizeOnRampAdapterV310Abi, iSecuritizeRedemptionGatewayAdapterV311Abi, iSecuritizeRedemptionGatewayV311Abi, iStakingRewardsAbi, iStakingRewardsAdapterAbi, iTraderJoeRouterAbi, iTraderJoeRouterAdapterAbi, iUniswapV2AdapterAbi, iUniswapV2Router02Abi, iUniswapV3Abi, iUniswapV3AdapterAbi, iUniswapV4AdapterAbi, iUniswapV4GatewayAbi, iUpshiftVaultAdapterAbi, iUpshiftVaultGatewayAbi, iVelodromeV2RouterAbi, iVelodromeV2RouterAdapterAbi, isDust, isLPPriceFeed, isMalformedPreviewError, isPhantomToken, isPublicNetwork, isRWAFactory, isRWAToken, isStrategyCollateral, isSunsetPool, isSunsetStrategy, isSupportedNetwork, isUpdatablePriceFeed, isV310, isVersionRange, isZeroBalance, iwstETHAbi, iwstEthv1AdapterAbi, json_parse, json_stringify, lidoV1_WETHGatewayAbi, mellowDvvAdapterAbi, minSeizedAmount, numberWithCommas, onchainSDKOptionsSchema, optimalHFForPartialLiquidation, optimalRepaidAmount, parseAdapterAction, parseAdapterDeployParams, parsePosNegAmount, percentFmt, pickStrategyTargetCollateral, raise, rayToBps, rayToNumber, refuse, resolveProtocolCall, retry, rewardsFromTransfers, roundUpQuota, sendRawTx, shortAddress, shortHash, simulateCall, simulateMulticall, simulateWithPriceUpdates, soleNonUnderlyingCollateral, strategyName, swapFromTransfers, toAddress, toBN, toBigInt, toChainIds, toClaimableWithdrawal, toCreditAccountSlice, toNetTransfers, toPendingWithdrawal, toRequestableWithdrawal, toShares, toSharesUp, toSignificant, toToken, toTokenAmount, toWithdrawalStatus, usdToNumber, watchBlocksAsync };
@@ -1,17 +1,18 @@
1
1
  //#region src/onchain/market/zapper/errors.ts
2
+ function unsupportedZapperFunction(zapper, functionName) {
3
+ return {
4
+ code: "unsupportedZapperFunction",
5
+ message: `unsupported zapper function "${functionName}" on ${zapper}`,
6
+ zapper,
7
+ functionName
8
+ };
9
+ }
10
+ Object.defineProperty(unsupportedZapperFunction, Symbol.hasInstance, { value: (value) => typeof value === "object" && value !== null && value.code === "unsupportedZapperFunction" });
2
11
  /**
3
- * Thrown when a zapper call uses a function other than a known
4
- * `deposit`/`redeem` variant.
12
+ * Builds the verdict. Callable with or without `new`, so pre-declassing raise
13
+ * sites keep compiling; `instanceof` matches on the `code` discriminant, and
14
+ * the answer is never an `Error`.
5
15
  */
6
- var UnsupportedZapperFunctionError = class extends Error {
7
- zapper;
8
- functionName;
9
- constructor(zapper, functionName) {
10
- super(`unsupported zapper function "${functionName}" on ${zapper}`);
11
- this.name = "UnsupportedZapperFunctionError";
12
- this.zapper = zapper;
13
- this.functionName = functionName;
14
- }
15
- };
16
+ const UnsupportedZapperFunctionError = unsupportedZapperFunction;
16
17
  //#endregion
17
18
  export { UnsupportedZapperFunctionError };
@@ -1,4 +1,4 @@
1
1
  import { MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_SAFE_HEALTH_FACTOR_FORM, amountOf, checkBorrowLimit, checkCollateralised, checkCreditManagerPaused, checkDebtInBand, checkForbiddenToken, checkFunding, checkLeverageAtLeastOne, checkMarketExpired, checkPoolPaused, checkPoolPayout, checkPoolSunset, checkPreviewError, checkQuotaCount, checkQuotaLimit, isMalformedPreviewError } from "./checks.js";
2
- import { IntentPreviewError, raise, refuse } from "./refusal.js";
2
+ import { raise, refuse } from "./refusal.js";
3
3
  import { toToken, toTokenAmount } from "./token.js";
4
- export { IntentPreviewError, MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_SAFE_HEALTH_FACTOR_FORM, amountOf, checkBorrowLimit, checkCollateralised, checkCreditManagerPaused, checkDebtInBand, checkForbiddenToken, checkFunding, checkLeverageAtLeastOne, checkMarketExpired, checkPoolPaused, checkPoolPayout, checkPoolSunset, checkPreviewError, checkQuotaCount, checkQuotaLimit, isMalformedPreviewError, raise, refuse, toToken, toTokenAmount };
4
+ export { MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_SAFE_HEALTH_FACTOR_FORM, amountOf, checkBorrowLimit, checkCollateralised, checkCreditManagerPaused, checkDebtInBand, checkForbiddenToken, checkFunding, checkLeverageAtLeastOne, checkMarketExpired, checkPoolPaused, checkPoolPayout, checkPoolSunset, checkPreviewError, checkQuotaCount, checkQuotaLimit, isMalformedPreviewError, raise, refuse, toToken, toTokenAmount };
@@ -1,5 +1,6 @@
1
1
  import { UnsupportedZapperFunctionError } from "../onchain/market/zapper/errors.js";
2
- import { IntentPreviewError, raise, refuse } from "../onchain/validation/refusal.js";
2
+ import { raise, refuse } from "../onchain/validation/refusal.js";
3
+ import { InvalidDelayedIntentError } from "../onchain/accounts/withdrawal-compressor/errors.js";
3
4
  import { TransferAlignmentError, UnexpectedFacadeEventOrderError, UnknownAdapterError, UnknownFacadeCallError, WithdrawCollateralAlignmentError } from "./trace/errors.js";
4
5
  import { extractAdapterCallTraces } from "./trace/extractAdapterCallTraces.js";
5
6
  import { extractTransfers } from "./trace/extractTransfers.js";
@@ -30,10 +31,11 @@ import { makeReplayState, replayInnerOperations } from "./preview/replayInnerOpe
30
31
  import { replayMulticall } from "./preview/replayMulticall.js";
31
32
  import { previewAdjustStrategyPosition } from "./preview/previewAdjustStrategyPosition.js";
32
33
  import { previewExitOrRepayStrategyPosition } from "./preview/previewExitOrRepayStrategyPosition.js";
34
+ import { PreviewSimulationError } from "./simulate/errors.js";
33
35
  import { previewOperation } from "./preview/previewOperation.js";
34
36
  import "./preview/index.js";
35
37
  import "./types.js";
36
38
  import { checkOperation, collateralIssue, marketIssues, quotaCountIssue } from "./validate/checkOperation.js";
37
39
  import { checkSimulation } from "./validate/checkSimulation.js";
38
40
  import "./validate/index.js";
39
- export { AllowancePrerequisite, BalancePrerequisite, CreditAccountState, IntentPreviewError, Prerequisite, RWAOpenRequirementsPrerequisite, TransferAlignmentError, UnexpectedFacadeEventOrderError, UnknownAdapterError, UnknownFacadeCallError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedZapperFunctionError, WithdrawCollateralAlignmentError, buildDelayedStrategyPositionOperationPreview, checkOperation, checkPrerequisites, checkSimulation, classifyCloseOrRepay, classifyInnerOperations, collateralIssue, detectDelayedClaim, detectDelayedOperation, estimateClaimableAt, extractAdapterCallTraces, extractTransfers, findFacadeCalls, isCloseOrRepay, isPoolOperation, isRWAOperation, makeReplayState, marketIssues, parseFacadeOperationCalldata, parseOperationCalldata, parsePoolOperationCalldata, parseRWAFactoryOperationCalldata, previewAdjustStrategyPosition, previewExitOrRepayStrategyPosition, previewOperation, quotaCountIssue, raise, refuse, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
41
+ export { AllowancePrerequisite, BalancePrerequisite, CreditAccountState, InvalidDelayedIntentError, Prerequisite, PreviewSimulationError, RWAOpenRequirementsPrerequisite, TransferAlignmentError, UnexpectedFacadeEventOrderError, UnknownAdapterError, UnknownFacadeCallError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedZapperFunctionError, WithdrawCollateralAlignmentError, buildDelayedStrategyPositionOperationPreview, checkOperation, checkPrerequisites, checkSimulation, classifyCloseOrRepay, classifyInnerOperations, collateralIssue, detectDelayedClaim, detectDelayedOperation, estimateClaimableAt, extractAdapterCallTraces, extractTransfers, findFacadeCalls, isCloseOrRepay, isPoolOperation, isRWAOperation, makeReplayState, marketIssues, parseFacadeOperationCalldata, parseOperationCalldata, parsePoolOperationCalldata, parseRWAFactoryOperationCalldata, previewAdjustStrategyPosition, previewExitOrRepayStrategyPosition, previewOperation, quotaCountIssue, raise, refuse, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
@@ -1,30 +1,33 @@
1
1
  import { UnsupportedZapperFunctionError } from "../../onchain/market/zapper/errors.js";
2
- import "../../onchain/index.js";
3
2
  //#region src/preview/parse/errors.ts
3
+ function unsupportedTarget(target) {
4
+ return {
5
+ code: "unsupportedTarget",
6
+ message: `unsupported transaction target: ${target}`,
7
+ target
8
+ };
9
+ }
10
+ Object.defineProperty(unsupportedTarget, Symbol.hasInstance, { value: (value) => typeof value === "object" && value !== null && value.code === "unsupportedTarget" });
4
11
  /**
5
- * Thrown when the target of a transaction is neither a known Gearbox pool nor a
6
- * credit facade.
12
+ * Builds the verdict. Callable with or without `new`, so pre-declassing raise
13
+ * sites keep compiling; `instanceof` matches on the `code` discriminant, and
14
+ * the answer is never an `Error`.
7
15
  */
8
- var UnsupportedTargetError = class extends Error {
9
- target;
10
- constructor(target) {
11
- super(`unsupported transaction target: ${target}`);
12
- this.name = "UnsupportedTargetError";
13
- this.target = target;
14
- }
15
- };
16
+ const UnsupportedTargetError = unsupportedTarget;
17
+ function unsupportedPoolFunction(pool, functionName) {
18
+ return {
19
+ code: "unsupportedPoolFunction",
20
+ message: `unsupported pool function "${functionName}" on ${pool}`,
21
+ pool,
22
+ functionName
23
+ };
24
+ }
25
+ Object.defineProperty(unsupportedPoolFunction, Symbol.hasInstance, { value: (value) => typeof value === "object" && value !== null && value.code === "unsupportedPoolFunction" });
16
26
  /**
17
- * Thrown when a pool call uses a function other than ERC4626 `deposit`/`redeem`.
27
+ * Builds the verdict. Callable with or without `new`, so pre-declassing raise
28
+ * sites keep compiling; `instanceof` matches on the `code` discriminant, and
29
+ * the answer is never an `Error`.
18
30
  */
19
- var UnsupportedPoolFunctionError = class extends Error {
20
- pool;
21
- functionName;
22
- constructor(pool, functionName) {
23
- super(`unsupported pool function "${functionName}" on ${pool}`);
24
- this.name = "UnsupportedPoolFunctionError";
25
- this.pool = pool;
26
- this.functionName = functionName;
27
- }
28
- };
31
+ const UnsupportedPoolFunctionError = unsupportedPoolFunction;
29
32
  //#endregion
30
33
  export { UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedZapperFunctionError };
@@ -1,16 +1,17 @@
1
1
  //#region src/preview/preview/errors.ts
2
+ function unsupportedOperation(operation) {
3
+ return {
4
+ code: "unsupportedOperation",
5
+ message: `operation "${operation}" is not supported by previewOperation`,
6
+ operation
7
+ };
8
+ }
9
+ Object.defineProperty(unsupportedOperation, Symbol.hasInstance, { value: (value) => typeof value === "object" && value !== null && value.code === "unsupportedOperation" });
2
10
  /**
3
- * Thrown by `previewOperation` for parsed operations it cannot preview yet.
4
- * Currently only pool operations and credit account opening are supported.
11
+ * Builds the verdict. Callable with or without `new`, so pre-declassing raise
12
+ * sites keep compiling; `instanceof` matches on the `code` discriminant, and
13
+ * the answer is never an `Error`.
5
14
  */
6
- var UnsupportedOperationError = class extends Error {
7
- /** The parsed operation kind (the `operation` discriminant). */
8
- operation;
9
- constructor(operation) {
10
- super(`operation "${operation}" is not supported by previewOperation`);
11
- this.name = "UnsupportedOperationError";
12
- this.operation = operation;
13
- }
14
- };
15
+ const UnsupportedOperationError = unsupportedOperation;
15
16
  //#endregion
16
17
  export { UnsupportedOperationError };
@@ -1,3 +1,9 @@
1
+ import { sdkErr, sdkOk } from "../../model/result.js";
2
+ import "../../model/index.js";
3
+ import { UnsupportedZapperFunctionError } from "../../onchain/market/zapper/errors.js";
4
+ import { InvalidDelayedIntentError } from "../../onchain/accounts/withdrawal-compressor/errors.js";
5
+ import "../../onchain/index.js";
6
+ import { UnsupportedPoolFunctionError, UnsupportedTargetError } from "../parse/errors.js";
1
7
  import { parseOperationCalldata } from "../parse/parseOperationCalldata.js";
2
8
  import { isPoolOperation } from "../parse/types.js";
3
9
  import "../parse/index.js";
@@ -10,25 +16,50 @@ import { estimateClaimableAt } from "./estimateClaimableAt.js";
10
16
  import { replayMulticall } from "./replayMulticall.js";
11
17
  import { previewAdjustStrategyPosition } from "./previewAdjustStrategyPosition.js";
12
18
  import { previewExitOrRepayStrategyPosition } from "./previewExitOrRepayStrategyPosition.js";
19
+ import { PreviewSimulationError } from "../simulate/errors.js";
13
20
  import { previewOpenStrategyPosition } from "./previewOpenStrategyPosition.js";
14
21
  import { previewPoolPositionOperation } from "./previewPoolPositionOperation.js";
15
22
  //#region src/preview/preview/previewOperation.ts
16
23
  /**
24
+ * Narrows a raised value to the verdict vocabulary: a plain non-`Error`
25
+ * object whose `code` is one of the preview verdicts. Genuine exceptions —
26
+ * bugs, outages, calldata the parser cannot read at all — fail the check and
27
+ * keep propagating as throws.
28
+ */
29
+ function isPreviewVerdict(raised) {
30
+ if (typeof raised !== "object" || raised === null || raised instanceof Error) return false;
31
+ return raised instanceof UnsupportedTargetError || raised instanceof UnsupportedPoolFunctionError || raised instanceof UnsupportedZapperFunctionError || raised instanceof UnsupportedOperationError || raised instanceof InvalidDelayedIntentError || raised instanceof PreviewSimulationError;
32
+ }
33
+ /**
17
34
  * Previews a raw operation calldata: decodes it into a typed operation and
18
35
  * assembles an operation-specific, human-displayable preview.
36
+ *
37
+ * Answers an {@link SDKReturn} envelope: the preview behind `ok: true`, or —
38
+ * when the transaction is one the previewer refuses to read — a
39
+ * {@link PreviewVerdictError} behind `ok: false`. A thrown exception still
40
+ * means the SDK could not do its job (a read failed, the targeted credit
41
+ * account could not be resolved), not a verdict on the transaction.
19
42
  */
20
43
  async function previewOperation(input, options) {
21
- const operation = parseOperationCalldata(input);
22
- if (isPoolOperation(operation)) return previewPoolPositionOperation(input, operation, options);
23
- if (operation.operation === "OpenCreditAccount" || operation.operation === "RWAOpenCreditAccount") return previewOpenStrategyPosition(input, operation);
24
- if (operation.operation === "CloseCreditAccount") {
25
- const resolved = await resolveCreditAccount(input, operation, options);
26
- const preview = previewExitOrRepayStrategyPosition(input, operation, true, resolved);
27
- preview.intent = await resolveDelayedClaimIntent(input.sdk, operation.multicall, options?.blockNumber);
28
- return preview;
44
+ try {
45
+ const operation = parseOperationCalldata(input);
46
+ if (isPoolOperation(operation)) return sdkOk(await previewPoolPositionOperation(input, operation, options));
47
+ if (operation.operation === "OpenCreditAccount" || operation.operation === "RWAOpenCreditAccount") return sdkOk(await previewOpenStrategyPosition(input, operation));
48
+ if (operation.operation === "CloseCreditAccount") {
49
+ const resolved = await resolveCreditAccount(input, operation, options);
50
+ const preview = previewExitOrRepayStrategyPosition(input, operation, true, resolved);
51
+ preview.intent = await resolveDelayedClaimIntent(input.sdk, operation.multicall, options?.blockNumber);
52
+ return sdkOk(preview);
53
+ }
54
+ if (operation.operation === "MultiCall" || operation.operation === "BotMulticall" || operation.operation === "RWAMulticall") {
55
+ const resolved = await resolveCreditAccount(input, operation, options);
56
+ return sdkOk(await previewMulticallOperation(input, operation, resolved));
57
+ }
58
+ return sdkErr(UnsupportedOperationError(operation.operation));
59
+ } catch (raised) {
60
+ if (isPreviewVerdict(raised)) return sdkErr(raised);
61
+ throw raised;
29
62
  }
30
- if (operation.operation === "MultiCall" || operation.operation === "BotMulticall" || operation.operation === "RWAMulticall") return previewMulticallOperation(input, operation, await resolveCreditAccount(input, operation, options));
31
- throw new UnsupportedOperationError(operation.operation);
32
63
  }
33
64
  /**
34
65
  * Resolves the pre-state of the credit account an operation targets: uses the
@@ -1,33 +1,34 @@
1
1
  import { errorAbis } from "../../abi/errors.js";
2
2
  import { BaseError, ContractFunctionRevertedError, decodeErrorResult } from "viem";
3
3
  //#region src/preview/simulate/errors.ts
4
+ function previewSimulationFailed(failures) {
5
+ const message = failures.length <= 1 ? failures[0]?.detail.reason ?? "simulation failed" : "all simulation flows failed";
6
+ const cause = failures.find((f) => f.detail.cause instanceof Error)?.detail.cause;
7
+ const verdict = {
8
+ code: "previewSimulationFailed",
9
+ message,
10
+ failures
11
+ };
12
+ if (cause) verdict.cause = cause;
13
+ return verdict;
14
+ }
15
+ Object.defineProperty(previewSimulationFailed, Symbol.hasInstance, { value: (value) => typeof value === "object" && value !== null && value.code === "previewSimulationFailed" });
4
16
  /**
5
- * Error returned by the pool simulation when it fails. It wraps the flow's
6
- * decoded revert reason (see {@link failures}).
17
+ * Builds the verdict. Callable with or without `new`, so pre-declassing raise
18
+ * sites keep compiling; `instanceof` matches on the `code` discriminant, and
19
+ * the answer is never an `Error`.
7
20
  */
8
- var PreviewSimulationError = class extends BaseError {
9
- name = "PreviewSimulationError";
10
- /** Per-flow decoded failures behind this error. */
11
- failures;
12
- constructor(failures) {
13
- const shortMessage = failures.length <= 1 ? failures[0]?.detail.reason ?? "simulation failed" : "all simulation flows failed";
14
- const cause = failures.find((f) => f.detail.cause instanceof Error)?.detail.cause;
15
- super(shortMessage, {
16
- metaMessages: failures.map((f) => `[${f.source}] ${f.detail.reason}`),
17
- cause
18
- });
19
- this.failures = failures;
20
- }
21
- };
21
+ const PreviewSimulationError = previewSimulationFailed;
22
22
  /**
23
23
  * Normalises an unknown rejection reason into a {@link PreviewSimulationError}.
24
24
  * Pass-through when it already is one; otherwise decodes it under `source`.
25
25
  */
26
26
  function asPreviewSimulationError(reason, source) {
27
27
  if (reason instanceof PreviewSimulationError) return reason;
28
+ const error = reason instanceof Error ? reason : new Error(String(reason));
28
29
  return new PreviewSimulationError([{
29
30
  source,
30
- detail: decodeSimulationError({ error: reason instanceof Error ? reason : new Error(String(reason)) })
31
+ detail: decodeSimulationError({ error })
31
32
  }]);
32
33
  }
33
34
  /**
@@ -11,7 +11,7 @@ var ExecuteApi = class {
11
11
  * {@inheritDoc IOpportunitiesExecute.buildTx}
12
12
  **/
13
13
  async buildTx(request) {
14
- if (!request.sim.success) throw new Error(`cannot build a transaction from a failed ${request.kind} preparation`);
14
+ if (!request.sim.ok) throw new Error(`cannot build a transaction from a failed ${request.kind} preparation`);
15
15
  const sdk = this.#chainOf(request.chainId);
16
16
  switch (request.kind) {
17
17
  case "pool": return poolTx(sdk, request);
@@ -12,7 +12,7 @@ import { LiquidationsNamespace } from "./liquidations/LiquidationsNamespace.js";
12
12
  import "./liquidations/index.js";
13
13
  import { ExecuteApi } from "./execute/ExecuteApi.js";
14
14
  import "./execute/index.js";
15
- import { creditAccountNotFound, noStrategyTargetCollateral, toPrepareError, unexpectedFailure } from "./prepare/errors.js";
15
+ import { creditAccountNotFound, noStrategyTargetCollateral, toRefusalError, unexpectedFailure } from "./prepare/errors.js";
16
16
  import { PrepareApi } from "./prepare/PrepareApi.js";
17
17
  import "./prepare/index.js";
18
18
  import { filterResponse } from "./utils/filterResponse.js";
@@ -26,4 +26,4 @@ import { PreviewNamespace } from "./preview/PreviewNamespace.js";
26
26
  import "./preview/index.js";
27
27
  import { DEFAULT_MAX_STATE_AGE, GearboxSDK } from "./GearboxSDK.js";
28
28
  import "./types.js";
29
- export { AbstractNamespace, AllSourcesFailedError, DEFAULT_MAX_OFFCHAIN_LAG, DEFAULT_MAX_STATE_AGE, ExecuteApi, GearboxSDK, IntentPreviewError, LiquidationsNamespace, MissingSourceError, NoSourceServedError, OpportunitiesNamespace, PositionsNamespace, PrepareApi, PreviewNamespace, SourceChainMismatchError, SourceUnavailableError, assertSameChains, creditAccountNotFound, everyChainFailed, filterResponse, mergeChainList, mergeChainOne, noStrategyTargetCollateral, raise, refuse, toPrepareError, unexpectedFailure };
29
+ export { AbstractNamespace, AllSourcesFailedError, DEFAULT_MAX_OFFCHAIN_LAG, DEFAULT_MAX_STATE_AGE, ExecuteApi, GearboxSDK, IntentPreviewError, LiquidationsNamespace, MissingSourceError, NoSourceServedError, OpportunitiesNamespace, PositionsNamespace, PrepareApi, PreviewNamespace, SourceChainMismatchError, SourceUnavailableError, assertSameChains, creditAccountNotFound, everyChainFailed, filterResponse, mergeChainList, mergeChainOne, noStrategyTargetCollateral, raise, refuse, toRefusalError, unexpectedFailure };