@gearbox-protocol/sdk 16.0.0-next.46 → 16.0.0-next.48

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/onchain/accounts/intents/testing/sdk-mock.js +2 -0
  2. package/dist/cjs/onchain/index.js +0 -2
  3. package/dist/cjs/onchain/market/MarketSuite.js +37 -1
  4. package/dist/cjs/onchain/market/credit/CreditSuite.js +1 -2
  5. package/dist/cjs/onchain/market/pool/PoolV310Contract.js +25 -0
  6. package/dist/cjs/onchain/pools/PoolService.js +5 -56
  7. package/dist/cjs/onchain/pools/index.js +0 -2
  8. package/dist/cjs/onchain/positions/PositionsService.js +4 -2
  9. package/dist/cjs/preview/index.js +2 -0
  10. package/dist/cjs/preview/preview/buildDelayedStrategyPositionOperationPreview.js +20 -20
  11. package/dist/cjs/preview/preview/errors.js +16 -0
  12. package/dist/cjs/preview/preview/index.js +2 -1
  13. package/dist/cjs/preview/preview/previewAdjustStrategyPosition.js +4 -12
  14. package/dist/cjs/preview/preview/previewExitOrRepayStrategyPosition.js +15 -5
  15. package/dist/cjs/preview/preview/previewPoolPositionOperation.js +31 -12
  16. package/dist/cjs/preview/simulate/index.js +1 -1
  17. package/dist/cjs/preview/simulate/simulateOperation.js +1 -1
  18. package/dist/cjs/preview/simulate/simulatePoolOperation.js +2 -0
  19. package/dist/cjs/sdk/prepare/PrepareApi.js +5 -6
  20. package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +2 -0
  21. package/dist/esm/onchain/index.js +2 -2
  22. package/dist/esm/onchain/market/MarketSuite.js +37 -1
  23. package/dist/esm/onchain/market/credit/CreditSuite.js +1 -2
  24. package/dist/esm/onchain/market/pool/PoolV310Contract.js +25 -0
  25. package/dist/esm/onchain/pools/PoolService.js +7 -56
  26. package/dist/esm/onchain/pools/index.js +2 -2
  27. package/dist/esm/onchain/positions/PositionsService.js +4 -2
  28. package/dist/esm/preview/index.js +2 -1
  29. package/dist/esm/preview/preview/buildDelayedStrategyPositionOperationPreview.js +21 -21
  30. package/dist/esm/preview/preview/errors.js +16 -1
  31. package/dist/esm/preview/preview/index.js +2 -2
  32. package/dist/esm/preview/preview/previewAdjustStrategyPosition.js +5 -13
  33. package/dist/esm/preview/preview/previewExitOrRepayStrategyPosition.js +15 -5
  34. package/dist/esm/preview/preview/previewPoolPositionOperation.js +33 -14
  35. package/dist/esm/preview/simulate/index.js +1 -1
  36. package/dist/esm/preview/simulate/simulateOperation.js +1 -1
  37. package/dist/esm/preview/simulate/simulatePoolOperation.js +1 -1
  38. package/dist/esm/sdk/prepare/PrepareApi.js +5 -6
  39. package/dist/types/model/positions.d.ts +4 -1
  40. package/dist/types/model/previews.d.ts +34 -23
  41. package/dist/types/onchain/index.d.ts +4 -4
  42. package/dist/types/onchain/market/MarketSuite.d.ts +35 -2
  43. package/dist/types/onchain/market/index.d.ts +2 -2
  44. package/dist/types/onchain/market/pool/PoolV310Contract.d.ts +12 -0
  45. package/dist/types/onchain/market/pool/types.d.ts +18 -0
  46. package/dist/types/onchain/pools/PoolService.d.ts +2 -29
  47. package/dist/types/onchain/pools/index.d.ts +3 -3
  48. package/dist/types/onchain/pools/types.d.ts +1 -40
  49. package/dist/types/preview/index.d.ts +2 -2
  50. package/dist/types/preview/preview/buildDelayedStrategyPositionOperationPreview.d.ts +3 -2
  51. package/dist/types/preview/preview/errors.d.ts +9 -1
  52. package/dist/types/preview/preview/index.d.ts +2 -2
  53. package/dist/types/preview/simulate/simulatePoolOperation.d.ts +18 -1
  54. package/dist/types/preview/simulate/types.d.ts +12 -4
  55. package/dist/types/sdk/prepare/types.d.ts +6 -4
  56. package/package.json +1 -1
@@ -224,7 +224,7 @@ import "./opportunities/index.js";
224
224
  import { BasePlugin } from "./plugins/BasePlugin.js";
225
225
  import { PluginStateVersionError } from "./plugins/errors.js";
226
226
  import "./plugins/index.js";
227
- import { PoolService, toShares, toSharesUp } from "./pools/PoolService.js";
227
+ import { PoolService } from "./pools/PoolService.js";
228
228
  import "./pools/index.js";
229
229
  import { calcBorrowRate } from "./positions/calcBorrowRate.js";
230
230
  import { calcHealthFactor } from "./positions/calcHealthFactor.js";
@@ -244,4 +244,4 @@ import { MultichainSDK } from "./MultichainSDK.js";
244
244
  import { attachOptionsSchema, onchainSDKOptionsSchema } from "./options.js";
245
245
  import "./types/index.js";
246
246
  import "./validation/index.js";
247
- 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, 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, 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 };
247
+ 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, 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, 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, toSignificant, toToken, toTokenAmount, toWithdrawalStatus, usdToNumber, watchBlocksAsync };
@@ -1,5 +1,7 @@
1
1
  import { AddressMap } from "../utils/AddressMap.js";
2
2
  import { isRWAToken, isSunsetPool } from "../chain/chains.js";
3
+ import { DUST_THRESHOLD } from "../constants/math.js";
4
+ import "../constants/index.js";
3
5
  import "../utils/index.js";
4
6
  import { SDKConstruct } from "../base/SDKConstruct.js";
5
7
  import "../base/index.js";
@@ -127,6 +129,14 @@ var MarketSuite = class extends SDKConstruct {
127
129
  };
128
130
  }
129
131
  /**
132
+ * Whether `token` is this market's pool underlying or the asset it wraps
133
+ * (dcUSDC or USDC on an RWA pool). Amounts in either unit are 1:1 with the
134
+ * figure {@link toUnderlyingAmount} reports.
135
+ */
136
+ isUnderlyingLike(token) {
137
+ return isAddressEqual(token, this.underlying) || isAddressEqual(token, this.unwrappedUnderlying);
138
+ }
139
+ /**
130
140
  * Prices a figure already denominated in this market's underlying — a debt,
131
141
  * a TVL, a payout — as the read model reports one.
132
142
  *
@@ -142,6 +152,32 @@ var MarketSuite = class extends SDKConstruct {
142
152
  ...this.priceOracle.toAmount(this.underlying, value)
143
153
  });
144
154
  /**
155
+ * Sums `assets` in this market's underlying at latest oracle prices.
156
+ *
157
+ * Balances at or below `minBalance` are ignored. A token the oracle cannot
158
+ * price contributes nothing; the first such token is {@link ValueInUnderlying.unpriceable}.
159
+ *
160
+ * The counterpart of {@link toUnderlyingAmount}: that method labels a figure
161
+ * already in underlying, this one produces the figure from mixed holdings.
162
+ **/
163
+ valueInUnderlying(assets, minBalance = DUST_THRESHOLD) {
164
+ let unpriceable;
165
+ let value = 0n;
166
+ for (const { token, balance } of assets) {
167
+ if (balance <= minBalance) continue;
168
+ const converted = this.priceOracle.safeConvert(token, this.underlying, balance);
169
+ if (converted === null) {
170
+ unpriceable ??= token;
171
+ continue;
172
+ }
173
+ value += converted;
174
+ }
175
+ return unpriceable === void 0 ? { value } : {
176
+ value,
177
+ unpriceable
178
+ };
179
+ }
180
+ /**
145
181
  * Display name of this market's pool, e.g. `"USDC Pool"`.
146
182
  */
147
183
  get poolName() {
@@ -165,7 +201,7 @@ var MarketSuite = class extends SDKConstruct {
165
201
  seen.upsert(this.unwrappedUnderlying, this.underlyingToken);
166
202
  for (const zapper of this.sdk.marketRegister.poolZappers(this.pool.pool.address)) {
167
203
  const tokenIn = zapper.tokenIn.addr;
168
- if (isAddressEqual(tokenIn, this.pool.underlying) || isAddressEqual(tokenIn, this.unwrappedUnderlying)) continue;
204
+ if (this.isUnderlyingLike(tokenIn)) continue;
169
205
  seen.upsert(tokenIn, this.tokensMeta.mustGetToken(tokenIn));
170
206
  }
171
207
  return seen.values();
@@ -391,8 +391,7 @@ var CreditSuite = class extends SDKConstruct {
391
391
  */
392
392
  #allowedDepositTokens(targetCollateral) {
393
393
  const unwrappedUnderlying = this.market.unwrappedUnderlying;
394
- const contractUnderlying = this.underlying;
395
- const skip = (token) => isAddressEqual(token, unwrappedUnderlying) || isAddressEqual(token, contractUnderlying) || isAddressEqual(token, targetCollateral);
394
+ const skip = (token) => this.market.isUnderlyingLike(token) || isAddressEqual(token, targetCollateral);
396
395
  return [
397
396
  unwrappedUnderlying,
398
397
  targetCollateral,
@@ -50,6 +50,31 @@ var PoolV310Contract = class extends BaseContract {
50
50
  return this.totalSupply * this.dieselRate / RAY;
51
51
  }
52
52
  /**
53
+ * {@inheritDoc IPoolContract.getShareBalance}
54
+ */
55
+ async getShareBalance(wallet, blockNumber) {
56
+ return this.client.readContract({
57
+ address: this.address,
58
+ abi: this.abi,
59
+ functionName: "balanceOf",
60
+ args: [wallet],
61
+ blockNumber
62
+ });
63
+ }
64
+ /**
65
+ * {@inheritDoc IPoolContract.sharesToUnderlying}
66
+ */
67
+ sharesToUnderlying(shares) {
68
+ return this.dieselRate === 0n ? shares : shares * this.dieselRate / RAY;
69
+ }
70
+ /**
71
+ * {@inheritDoc IPoolContract.underlyingToShares}
72
+ */
73
+ underlyingToShares(underlying, roundUp = false) {
74
+ if (this.dieselRate === 0n) return underlying;
75
+ return roundUp ? (underlying * RAY + this.dieselRate - 1n) / this.dieselRate : underlying * RAY / this.dieselRate;
76
+ }
77
+ /**
53
78
  * {@inheritDoc IPoolContract.unwrappedUnderlying}
54
79
  */
55
80
  get unwrappedUnderlying() {
@@ -1,7 +1,7 @@
1
1
  import { ierc20Abi } from "../../abi/iERC20.js";
2
2
  import { AddressSet } from "../utils/AddressSet.js";
3
3
  import "../constants/addresses.js";
4
- import { PERCENTAGE_FACTOR, RAY } from "../constants/math.js";
4
+ import { PERCENTAGE_FACTOR } from "../constants/math.js";
5
5
  import "../constants/index.js";
6
6
  import { hexEq } from "../utils/hex.js";
7
7
  import "../utils/index.js";
@@ -29,25 +29,6 @@ function payoutCeiling(market) {
29
29
  return market.priceOracle.toAmount(pool.underlying, pool.pool.availableLiquidity * LIQUIDITY_SAFETY_NUM / LIQUIDITY_SAFETY_DENOM);
30
30
  }
31
31
  var PoolService = class extends SDKConstruct {
32
- /**
33
- * {@inheritDoc IPoolsService.getShareBalance}
34
- */
35
- async getShareBalance(props) {
36
- return this.client.readContract({
37
- address: this.sdk.marketRegister.findByPool(props.pool).pool.pool.address,
38
- abi: ierc20Abi,
39
- functionName: "balanceOf",
40
- args: [props.wallet],
41
- blockNumber: props.blockNumber
42
- });
43
- }
44
- /**
45
- * {@inheritDoc IPoolsService.sharesToUnderlying}
46
- */
47
- sharesToUnderlying(pool, shares) {
48
- const market = this.sdk.marketRegister.findByPool(pool);
49
- return market.toUnderlyingAmount(shares * market.pool.pool.dieselRate / RAY);
50
- }
51
32
  /**
52
33
  * {@inheritDoc IPoolsService.getDepositTokensIn}
53
34
  */
@@ -164,7 +145,7 @@ var PoolService = class extends SDKConstruct {
164
145
  const { zapper } = this.getDepositMetadata(poolAddr, tokenIn, tokenOut);
165
146
  return {
166
147
  tokenIn: toTokenAmount(tokenIn, amount),
167
- tokenOut: toTokenAmount(tokenOut, toShares(pool.pool, amount)),
148
+ tokenOut: toTokenAmount(tokenOut, pool.pool.underlyingToShares(amount)),
168
149
  zapper: zapper?.baseParams.addr
169
150
  };
170
151
  }
@@ -184,7 +165,7 @@ var PoolService = class extends SDKConstruct {
184
165
  });
185
166
  const { zapper } = this.getWithdrawalMetadata(poolAddr, tokenIn, tokenOut);
186
167
  return {
187
- tokenIn: toTokenAmount(tokenIn, toSharesUp(pool.pool, amount)),
168
+ tokenIn: toTokenAmount(tokenIn, pool.pool.underlyingToShares(amount * PERCENTAGE_FACTOR / (PERCENTAGE_FACTOR - pool.pool.withdrawFee), true)),
188
169
  tokenOut: toTokenAmount(tokenOut, amount),
189
170
  zapper: zapper?.baseParams.addr,
190
171
  availableLiquidity: payoutCeiling(market)
@@ -207,7 +188,7 @@ var PoolService = class extends SDKConstruct {
207
188
  const { zapper } = this.getWithdrawalMetadata(poolAddr, tokenIn, tokenOut);
208
189
  return {
209
190
  tokenIn: toTokenAmount(tokenIn, amount),
210
- tokenOut: toTokenAmount(tokenOut, toAssets(pool.pool, amount)),
191
+ tokenOut: toTokenAmount(tokenOut, pool.pool.sharesToUnderlying(amount) * (PERCENTAGE_FACTOR - pool.pool.withdrawFee) / PERCENTAGE_FACTOR),
211
192
  zapper: zapper?.baseParams.addr,
212
193
  availableLiquidity: payoutCeiling(market)
213
194
  };
@@ -239,7 +220,7 @@ var PoolService = class extends SDKConstruct {
239
220
  }
240
221
  const poolContract = this.sdk.marketRegister.findByPool(pool).pool.pool;
241
222
  if (meta.zapper instanceof IETHZapperContract || meta.zapper instanceof IERC20ZapperContract) {
242
- const shares = mode === "withdraw" ? toSharesUp(poolContract, amount) : amount;
223
+ const shares = mode === "withdraw" ? poolContract.underlyingToShares(amount * PERCENTAGE_FACTOR / (PERCENTAGE_FACTOR - poolContract.withdrawFee), true) : amount;
243
224
  const tx = permit ? meta.zapper.redeemWithPermit(shares, wallet, permit.deadline, permit.v, permit.r, permit.s) : meta.zapper.redeem(shares, wallet);
244
225
  return {
245
226
  tx,
@@ -433,40 +414,10 @@ var PoolService = class extends SDKConstruct {
433
414
  chainId: this.chainId,
434
415
  pool: pool.address,
435
416
  underlyingToken: market.underlyingToken,
436
- netValue: this.sharesToUnderlying(pool.address, shares),
417
+ netValue: market.toUnderlyingAmount(pool.sharesToUnderlying(shares)),
437
418
  apy: { organicApy: rayToBps(pool.supplyRate) }
438
419
  };
439
420
  }
440
421
  };
441
- /**
442
- * Shares minted for `assets`, as `previewDeposit` would report them.
443
- *
444
- * Both directions convert through the diesel rate — underlying per RAY of
445
- * shares — because that is the rate the pool itself divides by, and the only
446
- * exact one the SDK holds: `totalAssets` is this rate multiplied out, so
447
- * converting back through it costs a wei on large amounts. Rounds down, as
448
- * minting does.
449
- */
450
- function toShares(pool, assets) {
451
- const { dieselRate } = pool;
452
- return dieselRate === 0n ? assets : assets * RAY / dieselRate;
453
- }
454
- /**
455
- * Shares a withdrawal of `assets` burns, as `previewWithdraw` would report
456
- * them: {@link toShares} rounded the other way, since the burn has to cover
457
- * the payout the caller asked for.
458
- */
459
- function toSharesUp(pool, assets) {
460
- const { dieselRate } = pool;
461
- return dieselRate === 0n ? assets : (assets * RAY + dieselRate - 1n) / dieselRate;
462
- }
463
- /**
464
- * Underlying paid out for `shares`, as `previewRedeem` would report it:
465
- * {@link toShares} run backwards, less the pool's withdrawal fee.
466
- */
467
- function toAssets(pool, shares) {
468
- const { dieselRate, withdrawFee } = pool;
469
- return (dieselRate === 0n ? shares : shares * dieselRate / RAY) * (PERCENTAGE_FACTOR - withdrawFee) / PERCENTAGE_FACTOR;
470
- }
471
422
  //#endregion
472
- export { PoolService, toShares, toSharesUp };
423
+ export { PoolService };
@@ -1,3 +1,3 @@
1
- import { PoolService, toShares, toSharesUp } from "./PoolService.js";
1
+ import { PoolService } from "./PoolService.js";
2
2
  import "./types.js";
3
- export { PoolService, toShares, toSharesUp };
3
+ export { PoolService };
@@ -293,12 +293,14 @@ var PositionsService = class extends SDKConstruct {
293
293
  withdrawals: withdrawals.get(t.token) ?? []
294
294
  });
295
295
  if (recomputeTotals) {
296
- const value = priceOracle.safeConvert(t.token, market.underlying, t.balance) || 0n;
297
- totalValue += value;
298
296
  const usd = priceOracle.safeConvertToUSD(t.token, t.balance) || 0n;
299
297
  totalValueUSD += usd;
300
298
  }
301
299
  }
300
+ if (recomputeTotals) totalValue = market.valueInUnderlying(ca.tokens.map((t) => ({
301
+ token: t.token,
302
+ balance: t.balance
303
+ }))).value;
302
304
  const snapshot = {
303
305
  ...accountSnapshotFromCreditAccountData(ca),
304
306
  totalValue
@@ -17,6 +17,7 @@ import { BalancePrerequisite } from "./prerequisites/BalancePrerequisite.js";
17
17
  import { RWAOpenRequirementsPrerequisite } from "./prerequisites/RWAOpenRequirementsPrerequisite.js";
18
18
  import { checkPrerequisites } from "./prerequisites/checkPrerequisites.js";
19
19
  import "./prerequisites/index.js";
20
+ import { unpriceableTokenError } from "./preview/errors.js";
20
21
  import { buildDelayedStrategyPositionOperationPreview } from "./preview/buildDelayedStrategyPositionOperationPreview.js";
21
22
  import { CreditAccountState } from "./preview/CreditAccountState.js";
22
23
  import { classifyCloseOrRepay, isCloseOrRepay } from "./preview/detectCloseOrRepay.js";
@@ -34,4 +35,4 @@ import "./types.js";
34
35
  import { checkOperation, collateralIssue, marketIssues, quotaCountIssue } from "./validate/checkOperation.js";
35
36
  import { checkSimulation } from "./validate/checkSimulation.js";
36
37
  import "./validate/index.js";
37
- export { AllowancePrerequisite, BalancePrerequisite, CreditAccountState, Prerequisite, RWAOpenRequirementsPrerequisite, TransferAlignmentError, UnexpectedFacadeEventOrderError, UnknownAdapterError, UnknownFacadeCallError, WithdrawCollateralAlignmentError, asPreviewSimulationError, 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 };
38
+ export { AllowancePrerequisite, BalancePrerequisite, CreditAccountState, Prerequisite, RWAOpenRequirementsPrerequisite, TransferAlignmentError, UnexpectedFacadeEventOrderError, UnknownAdapterError, UnknownFacadeCallError, WithdrawCollateralAlignmentError, asPreviewSimulationError, 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, unpriceableTokenError };
@@ -1,9 +1,10 @@
1
1
  import { AssetsMap } from "../../onchain/utils/AssetsMap.js";
2
2
  import { BigIntMath } from "../../onchain/utils/bigint-math.js";
3
3
  import { DUST_THRESHOLD } from "../../onchain/constants/math.js";
4
- import { ERROR_UNPRICEABLE_TOKEN, asEstimated } from "../../model/previews.js";
4
+ import { asEstimated } from "../../model/previews.js";
5
5
  import "../../model/index.js";
6
6
  import "../../onchain/index.js";
7
+ import { unpriceableTokenError } from "./errors.js";
7
8
  import { isAddressEqual } from "viem";
8
9
  //#region src/preview/preview/buildDelayedStrategyPositionOperationPreview.ts
9
10
  /**
@@ -12,8 +13,9 @@ import { isAddressEqual } from "viem";
12
13
  * the claim itself followed by the intent-specific tail
13
14
  *
14
15
  * Pure function: the input states are never mutated and no network access is performed.
15
- * Swaps are estimated with the injected conversion; tokens it cannot price contribute
16
- * nothing and set a non-fatal `ERROR_UNPRICEABLE_TOKEN` error on the
16
+ * Swaps are estimated with the injected conversion; remaining holdings are
17
+ * priced by `MarketSuite.valueInUnderlying`. Tokens that cannot be priced
18
+ * contribute nothing and set a non-fatal `ERROR_UNPRICEABLE_TOKEN` error on the
17
19
  * preview.
18
20
  *
19
21
  * The changes (e.g. `totalDebtChange`) are reported relative to the account
@@ -50,10 +52,7 @@ function makeSafeConverter(convert) {
50
52
  try {
51
53
  return convert(token, to, amount);
52
54
  } catch {
53
- error ??= {
54
- code: ERROR_UNPRICEABLE_TOKEN,
55
- message: `cannot price token ${token}`
56
- };
55
+ error ??= unpriceableTokenError(token);
57
56
  return 0n;
58
57
  }
59
58
  },
@@ -148,35 +147,36 @@ function repayFromClaim(post, claimToken, convert, amount) {
148
147
  post.repay(received);
149
148
  }
150
149
  /**
151
- * Oracle estimate of the account's total value in the underlying, ignoring
152
- * balances at or below `dust`.
153
- */
154
- function totalValueInUnderlying(post, convert, dust) {
155
- return post.balances.sum((token, balance) => balance > dust ? convert(token, post.underlying, balance) : 0n);
156
- }
157
- /**
158
150
  * `CLOSE_ACCOUNT` operation tail: everything is swapped into the
159
151
  * underlying, the debt is repaid in full and the remainder is withdrawn to
160
152
  * the user as `receivedToken`.
161
153
  */
162
154
  function buildClosePreview(post, converter, receivedToken, sdk) {
163
- const totalValue = totalValueInUnderlying(post, converter.convert, 0n);
164
- const oracle = sdk.marketRegister.findByCreditManager(post.creditManager).priceOracle;
155
+ const market = sdk.marketRegister.findByCreditManager(post.creditManager);
156
+ const priced = market.valueInUnderlying(post.balances.toAssets(), 0n);
157
+ const oracle = market.priceOracle;
165
158
  const suite = sdk.marketRegister.findCreditManager(post.creditManager);
166
159
  return {
167
160
  operation: "CloseCreditAccount",
168
161
  permanent: false,
169
- ...suite.creditOperationMarket(),
162
+ ...asEstimated(sdk.positions.projection({
163
+ creditManager: post.creditManager,
164
+ assets: [],
165
+ quotas: [],
166
+ totalDebt: 0n,
167
+ totalValue: 0n
168
+ }, { availableLiquidityChange: post.totalDebt })),
170
169
  creditAccount: post.creditAccount,
171
170
  name: suite.accountStrategyName(post.creditAccount),
172
171
  targetCollateral: suite.accountTargetCollateral(post.creditAccount),
173
- receivedAmount: oracle.toTokenAmount(receivedToken, BigIntMath.max(totalValue - post.totalDebt, 0n)),
174
- error: converter.error
172
+ receivedAmount: oracle.toTokenAmount(receivedToken, BigIntMath.max(priced.value - post.totalDebt, 0n)),
173
+ error: converter.error ?? (priced.unpriceable ? unpriceableTokenError(priced.unpriceable) : void 0)
175
174
  };
176
175
  }
177
176
  function buildAdjustPreview(post, before, collateralWithdrawn, converter, sdk) {
178
- const snap = post.toSnapshot(totalValueInUnderlying(post, converter.convert, DUST_THRESHOLD));
179
177
  const market = sdk.marketRegister.findByCreditManager(post.creditManager);
178
+ const priced = market.valueInUnderlying(post.balances.toAssets());
179
+ const snap = post.toSnapshot(priced.value);
180
180
  const suite = sdk.marketRegister.findCreditManager(post.creditManager);
181
181
  const oracle = market.priceOracle;
182
182
  return {
@@ -193,7 +193,7 @@ function buildAdjustPreview(post, before, collateralWithdrawn, converter, sdk) {
193
193
  ...oracle.toAmount(market.underlying, q.balance)
194
194
  })),
195
195
  assetsChange: post.balances.difference(before.balances).toAssets(DUST_THRESHOLD).map((a) => oracle.toTokenAmount(a.token, a.balance)),
196
- error: converter.error
196
+ error: converter.error ?? (priced.unpriceable ? unpriceableTokenError(priced.unpriceable) : void 0)
197
197
  };
198
198
  }
199
199
  //#endregion
@@ -1 +1,16 @@
1
- export {};
1
+ import { ERROR_UNPRICEABLE_TOKEN } from "../../model/previews.js";
2
+ import "../../model/index.js";
3
+ //#region src/preview/preview/errors.ts
4
+ /**
5
+ * Preview limitation (2xxx): the oracle could not price `token`. Callers
6
+ * attach this with `error ??=` so a malformed-transaction (1xxx) error
7
+ * already recorded keeps precedence.
8
+ **/
9
+ function unpriceableTokenError(token) {
10
+ return {
11
+ code: ERROR_UNPRICEABLE_TOKEN,
12
+ message: `cannot price token ${token}`
13
+ };
14
+ }
15
+ //#endregion
16
+ export { unpriceableTokenError };
@@ -1,13 +1,13 @@
1
+ import { unpriceableTokenError } from "./errors.js";
1
2
  import { buildDelayedStrategyPositionOperationPreview } from "./buildDelayedStrategyPositionOperationPreview.js";
2
3
  import { CreditAccountState } from "./CreditAccountState.js";
3
4
  import { classifyCloseOrRepay, isCloseOrRepay } from "./detectCloseOrRepay.js";
4
5
  import { detectDelayedClaim, resolveDelayedClaimIntent } from "./detectDelayedClaim.js";
5
6
  import { detectDelayedOperation } from "./detectDelayedOperation.js";
6
- import "./errors.js";
7
7
  import { estimateClaimableAt } from "./estimateClaimableAt.js";
8
8
  import { makeReplayState, replayInnerOperations } from "./replayInnerOperations.js";
9
9
  import { replayMulticall } from "./replayMulticall.js";
10
10
  import { previewAdjustStrategyPosition } from "./previewAdjustStrategyPosition.js";
11
11
  import { previewExitOrRepayStrategyPosition } from "./previewExitOrRepayStrategyPosition.js";
12
12
  import { previewOperation } from "./previewOperation.js";
13
- export { CreditAccountState, buildDelayedStrategyPositionOperationPreview, classifyCloseOrRepay, detectDelayedClaim, detectDelayedOperation, estimateClaimableAt, isCloseOrRepay, makeReplayState, previewAdjustStrategyPosition, previewExitOrRepayStrategyPosition, previewOperation, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
13
+ export { CreditAccountState, buildDelayedStrategyPositionOperationPreview, classifyCloseOrRepay, detectDelayedClaim, detectDelayedOperation, estimateClaimableAt, isCloseOrRepay, makeReplayState, previewAdjustStrategyPosition, previewExitOrRepayStrategyPosition, previewOperation, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent, unpriceableTokenError };
@@ -1,8 +1,9 @@
1
1
  import { AP_WETH_TOKEN } from "../../onchain/constants/address-provider.js";
2
2
  import { DUST_THRESHOLD } from "../../onchain/constants/math.js";
3
- import { ERROR_UNPRICEABLE_TOKEN, asEstimated } from "../../model/previews.js";
3
+ import { asEstimated } from "../../model/previews.js";
4
4
  import "../../model/index.js";
5
5
  import "../../onchain/index.js";
6
+ import { unpriceableTokenError } from "./errors.js";
6
7
  import { replayMulticall } from "./replayMulticall.js";
7
8
  import { unwrapNativeCollateral } from "./unwrapNativeCollateral.js";
8
9
  //#region src/preview/preview/previewAdjustStrategyPosition.ts
@@ -24,18 +25,9 @@ function previewAdjustStrategyPosition(input, operation, options) {
24
25
  const { assets: collateralAdded, error: unwrapError } = unwrapNativeCollateral(after.collateralAdded.toAssets(), value, sdk.addressProvider.getAddress(AP_WETH_TOKEN, 0));
25
26
  error ??= unwrapError;
26
27
  const assetsChange = account.balances.difference(before.balances).toAssets(DUST_THRESHOLD);
27
- const totalValue = account.balances.toAssets(DUST_THRESHOLD).reduce((acc, { token, balance }) => {
28
- try {
29
- return acc + oracle.convert(token, market.underlying, balance);
30
- } catch {
31
- error ??= {
32
- code: ERROR_UNPRICEABLE_TOKEN,
33
- message: `cannot price token ${token}`
34
- };
35
- return acc;
36
- }
37
- }, 0n);
38
- const snap = account.toSnapshot(totalValue);
28
+ const priced = market.valueInUnderlying(account.balances.toAssets());
29
+ if (priced.unpriceable) error ??= unpriceableTokenError(priced.unpriceable);
30
+ const snap = account.toSnapshot(priced.value);
39
31
  return {
40
32
  operation: "AdjustCreditAccount",
41
33
  ...asEstimated(sdk.positions.projection(snap, { availableLiquidityChange: before.totalDebt - account.totalDebt })),
@@ -1,6 +1,9 @@
1
1
  import { AP_WETH_TOKEN } from "../../onchain/constants/address-provider.js";
2
2
  import "../../onchain/constants/math.js";
3
+ import { asEstimated } from "../../model/previews.js";
4
+ import "../../model/index.js";
3
5
  import "../../onchain/index.js";
6
+ import { unpriceableTokenError } from "./errors.js";
4
7
  import { classifyCloseOrRepay } from "./detectCloseOrRepay.js";
5
8
  import { replayMulticall } from "./replayMulticall.js";
6
9
  import { unwrapNativeCollateral } from "./unwrapNativeCollateral.js";
@@ -22,7 +25,11 @@ function previewExitOrRepayStrategyPosition(input, operation, permanent, options
22
25
  function previewCloseCreditAccount(input, operation, permanent, replay) {
23
26
  const { sdk } = input;
24
27
  const market = sdk.marketRegister.findByCreditManager(operation.creditManager);
25
- const { after, error } = replay;
28
+ const { before, after, error: replayError } = replay;
29
+ const account = after.account;
30
+ let error = replayError;
31
+ const priced = market.valueInUnderlying(account.balances.toAssets());
32
+ if (priced.unpriceable) error ??= unpriceableTokenError(priced.unpriceable);
26
33
  const suite = sdk.marketRegister.findCreditManager(operation.creditManager);
27
34
  let receivedToken = market.underlying;
28
35
  for (const m of operation.multicall) if (m.operation === "WithdrawCollateral" && m.amount === 115792089237316195423570985008687907853269984665640564039457584007913129639935n) {
@@ -32,7 +39,7 @@ function previewCloseCreditAccount(input, operation, permanent, replay) {
32
39
  return {
33
40
  operation: "CloseCreditAccount",
34
41
  permanent,
35
- ...suite.creditOperationMarket(),
42
+ ...asEstimated(sdk.positions.projection(account.toSnapshot(priced.value), { availableLiquidityChange: before.totalDebt - account.totalDebt })),
36
43
  creditAccount: operation.creditAccount,
37
44
  name: suite.accountStrategyName(operation.creditAccount),
38
45
  targetCollateral: suite.accountTargetCollateral(operation.creditAccount),
@@ -49,18 +56,21 @@ function previewRepayCreditAccount(input, operation, permanent, replay) {
49
56
  const { sdk, value = 0n } = input;
50
57
  const market = sdk.marketRegister.findByCreditManager(operation.creditManager);
51
58
  const { before, after, error: replayError } = replay;
59
+ const account = after.account;
52
60
  const { assets: collateralAdded, error: unwrapError } = unwrapNativeCollateral(after.collateralAdded.toAssets(), value, sdk.addressProvider.getAddress(AP_WETH_TOKEN, 0));
53
- const error = replayError ?? unwrapError;
61
+ let error = replayError ?? unwrapError;
62
+ const priced = market.valueInUnderlying(account.balances.toAssets());
63
+ if (priced.unpriceable) error ??= unpriceableTokenError(priced.unpriceable);
54
64
  const suite = sdk.marketRegister.findCreditManager(operation.creditManager);
55
65
  return {
56
66
  operation: "RepayCreditAccount",
57
67
  permanent,
58
- ...suite.creditOperationMarket(),
68
+ ...asEstimated(sdk.positions.projection(account.toSnapshot(priced.value), { availableLiquidityChange: before.totalDebt - account.totalDebt })),
59
69
  creditAccount: operation.creditAccount,
60
70
  name: suite.accountStrategyName(operation.creditAccount),
61
71
  targetCollateral: suite.accountTargetCollateral(operation.creditAccount),
62
72
  collateralAdded: collateralAdded.map((a) => market.priceOracle.toTokenAmount(a.token, a.balance)),
63
- debtRepaid: market.toUnderlyingAmount(before.totalDebt - after.account.totalDebt),
73
+ debtRepaid: market.toUnderlyingAmount(before.totalDebt - account.totalDebt),
64
74
  collateralWithdrawn: after.collateralWithdrawn.toAssets().map((a) => market.priceOracle.toTokenAmount(a.token, a.balance)),
65
75
  error
66
76
  };
@@ -1,28 +1,47 @@
1
- import { isSDKError, sdkOk } from "../../model/result.js";
1
+ import { ierc20Abi } from "../../abi/iERC20.js";
2
+ import { sdkErr, sdkOk } from "../../model/result.js";
2
3
  import "../../model/index.js";
3
- import { simulatePoolOperation } from "../simulate/simulatePoolOperation.js";
4
- import "../simulate/index.js";
4
+ import { asPreviewSimulationError } from "../simulate/errors.js";
5
+ import { amountsInOut, previewContract } from "../simulate/simulatePoolOperation.js";
5
6
  //#region src/preview/preview/previewPoolPositionOperation.ts
6
7
  async function previewPoolPositionOperation(input, operation, options) {
7
- const { sdk, to, calldata } = input;
8
+ const { sdk } = input;
8
9
  const { tokenIn, tokenOut } = operation;
9
10
  const market = sdk.marketRegister.findByPool(operation.pool);
10
- const answer = await simulatePoolOperation({
11
- sdk,
12
- operation,
13
- to,
14
- calldata
15
- }, options);
16
- if (isSDKError(answer)) return answer;
17
- const sim = answer.data;
11
+ const pool = market.pool.pool;
12
+ const holder = "owner" in operation ? operation.owner : operation.receiver;
13
+ let previewAmount;
14
+ let shares;
15
+ try {
16
+ [previewAmount, shares] = await sdk.client.multicall({
17
+ contracts: [previewContract(operation), {
18
+ address: operation.pool,
19
+ abi: ierc20Abi,
20
+ functionName: "balanceOf",
21
+ args: [holder]
22
+ }],
23
+ allowFailure: false,
24
+ batchSize: 0,
25
+ blockNumber: options?.blockNumber
26
+ });
27
+ } catch (cause) {
28
+ const error = asPreviewSimulationError(cause, "multicall");
29
+ options?.logger?.error(error, "pool operation simulation failed");
30
+ return sdkErr(error);
31
+ }
32
+ const sim = amountsInOut(operation, previewAmount);
33
+ const inflow = operation.operation === "Deposit" || operation.operation === "Mint";
34
+ const after = shares + (inflow ? sim.amountOut : -sim.amountIn);
18
35
  return sdkOk({
19
36
  operation: operation.operation,
20
37
  pool: operation.pool,
21
38
  name: sdk.tokensMeta.mustGetToken(operation.pool).name,
22
39
  underlyingToken: market.underlyingToken,
23
- shareRate: market.pool.pool.dieselRate,
40
+ shareRate: pool.dieselRate,
24
41
  tokenIn: market.priceOracle.toTokenAmount(tokenIn, sim.amountIn),
25
- tokenOut: market.priceOracle.toTokenAmount(tokenOut, sim.amountOut)
42
+ tokenOut: market.priceOracle.toTokenAmount(tokenOut, sim.amountOut),
43
+ curator: market.curator,
44
+ netValue: market.toUnderlyingAmount(pool.sharesToUnderlying(after > 0n ? after : 0n))
26
45
  });
27
46
  }
28
47
  //#endregion
@@ -1,6 +1,6 @@
1
1
  import { asPreviewSimulationError } from "./errors.js";
2
- import { simulateFacadeOperation } from "./simulateFacadeOperation.js";
3
2
  import { simulatePoolOperation } from "./simulatePoolOperation.js";
3
+ import { simulateFacadeOperation } from "./simulateFacadeOperation.js";
4
4
  import { simulateRWAOperation } from "./simulateRWAOperation.js";
5
5
  import { simulateOperation } from "./simulateOperation.js";
6
6
  export { asPreviewSimulationError, simulateFacadeOperation, simulateOperation, simulatePoolOperation, simulateRWAOperation };
@@ -2,8 +2,8 @@ import { sdkOk } from "../../model/result.js";
2
2
  import "../../model/index.js";
3
3
  import { isPoolOperation, isRWAOperation } from "../parse/types.js";
4
4
  import "../parse/index.js";
5
- import { simulateFacadeOperation } from "./simulateFacadeOperation.js";
6
5
  import { simulatePoolOperation } from "./simulatePoolOperation.js";
6
+ import { simulateFacadeOperation } from "./simulateFacadeOperation.js";
7
7
  import { simulateRWAOperation } from "./simulateRWAOperation.js";
8
8
  //#region src/preview/simulate/simulateOperation.ts
9
9
  /**
@@ -103,4 +103,4 @@ async function simulatePoolOperation(input, options = {}) {
103
103
  }
104
104
  }
105
105
  //#endregion
106
- export { simulatePoolOperation };
106
+ export { amountsInOut, previewContract, simulatePoolOperation };