@gearbox-protocol/sdk 17.2.1 → 17.3.0
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.
- package/dist/cjs/onchain/accounts/intents/leverage-band.js +1 -1
- package/dist/cjs/onchain/accounts/intents/maxBorrow.js +15 -11
- package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +5 -2
- package/dist/cjs/onchain/chain/chains.js +1 -2
- package/dist/cjs/onchain/index.js +2 -0
- package/dist/cjs/onchain/market/MarketSuite.js +11 -4
- package/dist/cjs/onchain/market/credit/CreditSuite.js +25 -138
- package/dist/cjs/onchain/market/credit/CreditSuiteStrategy.js +179 -0
- package/dist/cjs/onchain/market/credit/index.js +2 -0
- package/dist/cjs/onchain/market/index.js +2 -0
- package/dist/cjs/onchain/market/pool/PoolQuotaKeeperV310Contract.js +4 -1
- package/dist/cjs/onchain/opportunities/OpportunitiesService.js +7 -9
- package/dist/cjs/sdk/prepare/PrepareApi.js +1 -1
- package/dist/esm/onchain/accounts/intents/leverage-band.js +1 -1
- package/dist/esm/onchain/accounts/intents/maxBorrow.js +15 -11
- package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +5 -2
- package/dist/esm/onchain/chain/chains.js +1 -2
- package/dist/esm/onchain/index.js +2 -1
- package/dist/esm/onchain/market/MarketSuite.js +11 -4
- package/dist/esm/onchain/market/credit/CreditSuite.js +27 -140
- package/dist/esm/onchain/market/credit/CreditSuiteStrategy.js +178 -0
- package/dist/esm/onchain/market/credit/index.js +2 -1
- package/dist/esm/onchain/market/index.js +2 -1
- package/dist/esm/onchain/market/pool/PoolQuotaKeeperV310Contract.js +4 -1
- package/dist/esm/onchain/opportunities/OpportunitiesService.js +7 -9
- package/dist/esm/sdk/prepare/PrepareApi.js +1 -1
- package/dist/types/model/errors/operation-errors.d.ts +6 -1
- package/dist/types/onchain/accounts/intents/maxBorrow.d.ts +12 -10
- package/dist/types/onchain/index.d.ts +2 -1
- package/dist/types/onchain/market/MarketSuite.d.ts +6 -0
- package/dist/types/onchain/market/credit/CreditSuite.d.ts +18 -52
- package/dist/types/onchain/market/credit/CreditSuiteStrategy.d.ts +78 -0
- package/dist/types/onchain/market/credit/index.d.ts +2 -1
- package/dist/types/onchain/market/credit/types.d.ts +3 -1
- package/dist/types/onchain/market/index.d.ts +2 -1
- package/dist/types/onchain/market/pool/PoolQuotaKeeperV310Contract.d.ts +2 -0
- package/package.json +1 -1
|
@@ -231,7 +231,7 @@ var PrepareApi = class extends require_onchain_base_MultichainConstruct.Multicha
|
|
|
231
231
|
const sdk = await this.#chain(strategy.chainId);
|
|
232
232
|
const at = stateBlock(sdk);
|
|
233
233
|
Object.assign(state, marketOf(sdk, strategy.creditManager));
|
|
234
|
-
const targetToken = params.targetToken ?? sdk.marketRegister.findCreditManager(strategy.creditManager).
|
|
234
|
+
const targetToken = params.targetToken ?? sdk.marketRegister.findCreditManager(strategy.creditManager).strategy?.targetCollateral;
|
|
235
235
|
if (!targetToken) return refused(require_model_errors_prepare_errors.noStrategyTargetCollateral(strategy.creditManager), state);
|
|
236
236
|
const reused = await reusable(sdk, strategy, params.creditAccount);
|
|
237
237
|
if (reused && "error" in reused) return refused(reused.error, state);
|
|
@@ -33,7 +33,7 @@ function calcLeverageBand({ sdk, creditManager, collateral, targetHF }) {
|
|
|
33
33
|
const found = resolveCreditManager(sdk, creditManager);
|
|
34
34
|
if (!found) return;
|
|
35
35
|
const { suite, market } = found;
|
|
36
|
-
const target = suite.
|
|
36
|
+
const target = suite.strategy?.targetCollateral;
|
|
37
37
|
if (!target) return;
|
|
38
38
|
const ceiling = suite.creditManager.maxLeverage(target, targetHF);
|
|
39
39
|
const underlying = market.pool.underlying;
|
|
@@ -19,17 +19,19 @@ import { collateralValuation } from "./collateral-valuation.js";
|
|
|
19
19
|
* Collateral is valued the way the transaction will be judged — at safe
|
|
20
20
|
* prices, under its liquidation threshold, capped by the quota the borrow
|
|
21
21
|
* buys for it, all of which is {@link collateralValuation}'s business. The ceiling
|
|
22
|
-
* is then held to what the market will actually lend
|
|
23
|
-
*
|
|
24
|
-
* binds first.
|
|
22
|
+
* is then held to what the market will actually lend,
|
|
23
|
+
* {@link CreditSuite.maxBorrowAmount}: the pool's free liquidity, the
|
|
24
|
+
* manager's own allowance and the facade's `maxDebt`, whichever binds first.
|
|
25
25
|
*
|
|
26
|
-
* The facade's `minDebt` is
|
|
27
|
-
* ceiling answered as `0n` because the collateral is too
|
|
28
|
-
* would tell a form nothing about what it is holding —
|
|
29
|
-
* to see is the one they are short of. Collateral
|
|
30
|
-
* therefore answers with it, whether or not the market
|
|
31
|
-
* a loan under the floor is refused by `borrow`
|
|
32
|
-
* naming both ends.
|
|
26
|
+
* The facade's `minDebt` is not applied to the collateral's own ceiling. It
|
|
27
|
+
* is a floor, and a ceiling answered as `0n` because the collateral is too
|
|
28
|
+
* small for this market would tell a form nothing about what it is holding —
|
|
29
|
+
* the number a user needs to see is the one they are short of. Collateral
|
|
30
|
+
* that carries something therefore answers with it, whether or not the market
|
|
31
|
+
* would lend that little; a loan under the floor is refused by `borrow`
|
|
32
|
+
* itself, with `debtOutOfRange` naming both ends. A market whose own capacity
|
|
33
|
+
* is under `minDebt` is different: the answer is `0n`, because no loan of any
|
|
34
|
+
* size exists there.
|
|
33
35
|
*
|
|
34
36
|
* Nothing is fetched or simulated — the account does not exist yet and every
|
|
35
37
|
* input is loaded market state, so a form can call this on each keystroke.
|
|
@@ -79,7 +81,9 @@ function maxBorrow(props) {
|
|
|
79
81
|
const weighted = valuation.checkedUsd(holding) * valuation.lt(collateralToken);
|
|
80
82
|
const backed = quotas.some((q) => eq(q.token, collateralToken)) ? BigIntMath.min(valuation.quotaValue(holding), weighted) : weighted;
|
|
81
83
|
if (backed <= 0n) return 0n;
|
|
82
|
-
const
|
|
84
|
+
const lends = suite.maxBorrowAmount().amount.value;
|
|
85
|
+
if (lends < suite.creditFacade.minDebt) return 0n;
|
|
86
|
+
const ceiling = BigIntMath.min(priceOracle.safeConvertFromUSD(underlying, backed / targetHF).value, lends);
|
|
83
87
|
const unwrapsPayout = !!rwaAsset && eq(borrowToken, rwaAsset);
|
|
84
88
|
return eq(borrowToken, underlying) ? ceiling : unwrapsPayout ? toTargetDecimals(ceiling, underlying, borrowToken, sdk) : priceOracle.safeConvert(underlying, borrowToken, ceiling).value;
|
|
85
89
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import "../../../constants/math.js";
|
|
2
2
|
import "../../../constants/index.js";
|
|
3
3
|
import { calcMaxLeverage } from "../../../market/math.js";
|
|
4
|
+
import { CreditSuiteStrategy } from "../../../market/credit/CreditSuiteStrategy.js";
|
|
4
5
|
import { CreditSuite } from "../../../market/credit/CreditSuite.js";
|
|
5
6
|
import { PositionsService } from "../../../positions/PositionsService.js";
|
|
6
7
|
import { TestPriceOracle } from "../../../market/oracle/TestPriceOracle.mock.js";
|
|
@@ -189,8 +190,10 @@ function buildMockSdk(args) {
|
|
|
189
190
|
const strategyName = strategyTargetCollateral ? `${tokenOf(strategyTargetCollateral).symbol} / ${underlyingToken.symbol}` : void 0;
|
|
190
191
|
const creditManagerSuite = {
|
|
191
192
|
name: "TestCreditManager",
|
|
192
|
-
strategyName,
|
|
193
193
|
underlyingToken,
|
|
194
|
+
get strategy() {
|
|
195
|
+
return strategyTargetCollateral ? new CreditSuiteStrategy(creditManagerSuite, strategyTargetCollateral) : void 0;
|
|
196
|
+
},
|
|
194
197
|
accountTargetCollateral: () => strategyTargetCollateral ? tokenOf(strategyTargetCollateral) : null,
|
|
195
198
|
accountStrategyName: () => strategyName ?? underlyingToken.symbol,
|
|
196
199
|
liquidationFees: () => MOCK_LIQUIDATION_FEES,
|
|
@@ -219,7 +222,6 @@ function buildMockSdk(args) {
|
|
|
219
222
|
market,
|
|
220
223
|
isPaused: facadePaused || poolPaused,
|
|
221
224
|
forbiddenTokens: [...forbidden],
|
|
222
|
-
strategyTargetCollateral,
|
|
223
225
|
isExpired: expirationDate > 0 && expirationDate < (args.timestamp ?? 0)
|
|
224
226
|
};
|
|
225
227
|
const routeCalls = (tokenIn, tokenOut) => {
|
|
@@ -356,6 +358,7 @@ function buildMockSdk(args) {
|
|
|
356
358
|
}
|
|
357
359
|
};
|
|
358
360
|
Object.assign(sdk, { positions: new PositionsService(sdk) });
|
|
361
|
+
Object.assign(creditManagerSuite, { sdk });
|
|
359
362
|
return sdk;
|
|
360
363
|
}
|
|
361
364
|
/** A full account payload carrying exactly what the slice builder reads back. */
|
|
@@ -96,8 +96,7 @@ const chains = {
|
|
|
96
96
|
"0x89014edc549ffa5c5b6e859b1496731bd035c247": "0x31454faa1daa04cacf59a6bd37681da9160d092a",
|
|
97
97
|
"0x3b7ab1f4fee570933b24b202de90ffda82f6cae0": "0x31454faa1daa04cacf59a6bd37681da9160d092a",
|
|
98
98
|
"0x721798d8ccf31ae75c12db82fa72b3806759cbc9": "0x31454faa1daa04cacf59a6bd37681da9160d092a",
|
|
99
|
-
"0xd7273d9594ac88f993eda9773041e621633acea0": "0x1a711a5bc48b5c1352c1882fa65dc14b5b9e829d"
|
|
100
|
-
"0x34442ca47435e90b80d835aab9737166e76d9962": "0x403cc0d2694ec2639101f32b146b90d766461ce9"
|
|
99
|
+
"0xd7273d9594ac88f993eda9773041e621633acea0": "0x1a711a5bc48b5c1352c1882fa65dc14b5b9e829d"
|
|
101
100
|
}),
|
|
102
101
|
sunsetPools: new AddressSet([
|
|
103
102
|
"0xF791Ecc5F2472637eac9DFe3f7894C0B32C32bDf",
|
|
@@ -139,6 +139,7 @@ import { DEGEN_NFT_MIDAS, PHANTOM_TOKEN_MIDAS_REDEMPTION, RWA_LIQUIDATOR_MIDAS }
|
|
|
139
139
|
import { MidasDegenNFT } from "./market/rwa/midas/MidasDegenNFT.js";
|
|
140
140
|
import { DEGEN_NFT_SECURITIZE, PHANTOM_TOKEN_SECURITIZE_REDEMPTION, RWA_LIQUIDATOR_SECURITIZE } from "./market/rwa/securitize/constants.js";
|
|
141
141
|
import { strategyName } from "./market/strategyName.js";
|
|
142
|
+
import { CreditSuiteStrategy } from "./market/credit/CreditSuiteStrategy.js";
|
|
142
143
|
import { dominantCollateral, isStrategyCollateral, pickStrategyTargetCollateral } from "./market/credit/collateralUtils.js";
|
|
143
144
|
import { CreditSuite } from "./market/credit/CreditSuite.js";
|
|
144
145
|
import { expectedBalanceDeltas } from "./market/credit/expectedBalanceDeltas.js";
|
|
@@ -304,4 +305,4 @@ import { replayMulticall } from "./preview/preview/replayMulticall.js";
|
|
|
304
305
|
import { previewOperation } from "./preview/preview/previewOperation.js";
|
|
305
306
|
import "./preview/index.js";
|
|
306
307
|
import "./types/index.js";
|
|
307
|
-
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_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, ConstantPriceFeedContract, Construct, ContractParseError, ConvexV1BaseRewardPoolAdapterContract, ConvexV1BoosterAdapterContract, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountState, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, Curve2AssetsAdapterContract, Curve3AssetsAdapterContract, Curve4AssetsAdapterContract, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, CurveV1AdapterStETHContract, CurveV1StableNGAdapterContract, DEFAULT_QUOTA_BUFFER_BPS, DEGEN_NFT_MIDAS, DEGEN_NFT_SECURITIZE, 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, MidasDegenNFT, 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, PriceFeedRegistry, PriceOracleV310Contract, PriceUpdatesCache, PythPriceFeed, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, RWARegistry, RWA_COMPRESSOR_ADDRESS, 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, SLIPPAGE_DECIMALS, STATE_VERSION, SUPPORTED_NETWORKS, SdkAlreadyAttachedError, SdkChainMismatchError, SdkMissingChainStateError, SdkNotAttachedError, SdkRWADataNotLoadedError, SdkStateVersionMismatchError, SdkSyncFailedError, SecuritizeDegenNFT, SecuritizeLiquidatorContract, SecuritizeOnRampAdapterContract, SecuritizeRWAFactory, SecuritizeRedemptionGatewayAdapterContract, SimulateWithPriceUpdatesError, SimulationError, StakingRewardsAdapterContract, TokensMeta, TraderJoePoolVersion, TraderJoeRouterAdapterContract, TypedObjectUtils, UniswapV2AdapterContract, UniswapV3AdapterContract, UniswapV4AdapterContract, UpdatablePriceFeedRegistry, 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, botPermissionsToString, bpsToRay, buildDelayedStrategyPositionOperationPreview, bytes32ToString, calcBorrowApy, calcBorrowRate, calcDefaultQuota, calcEffectiveBorrowApy, calcHealthFactor, calcLiquidationPrice, calcLiquidationPriceForTarget, calcMaxLeverage, calcNetStrategyApy, calcPositionLeverage, calcQuotaRate, calcQuotaUpdate, calcRecommendedQuota, calcTimeToLiquidationMs, calcUtilization, calcUtilizationRaw, chains, checkAccountQuotas, checkBorrowLimit, checkCollateralFunding, checkCollateralised, checkCreditAccountFrozen, checkCreditManagerPaused, checkCreditOperation, checkDebtLimits, checkEmergencyLiquidator, checkForbiddenToken, checkHealthFactors, checkIncreaseDebt, checkIncreaseQuota, checkLeverage, checkLiquidation, checkLiquidationEligibility, checkLiquidationFunding, checkLiquidatorEligible, checkMarket, checkMarketExpired, checkMidasAccountGreenlist, checkObtained, checkOperation, checkPoolFunding, checkPoolLiquidity, checkPoolOperation, checkPoolPaused, checkPoolSunset, checkQuotaCount, checkQuotaLimit, checkRWAOpenRequirements, checkRWAOpening, checkReservePriceLimited, checkSimulation, checkWallet, checkWalletAllowance, checkWalletBalance, childLogger, classifyCloseOrRepay, classifyCurveOperation, classifyInnerOperations, collateralPriceInUnderlying, collectTraces, createAdapter, createAddressProvider, createPriceOracle, createRawTx, createRedemptionLogger, createRouter, createWithdrawalCompressor, createZapper, abi as creditFacadeV310Abi, curveAddLiquidityFromTransfers, curveRemoveLiquidityFromTransfers, decodeDelayedIntent, detectDelayedClaim, detectDelayedOperation, detectNetwork, dominantCollateral, encodeDelayedIntent, erc4626ReferralAdapterAbi, estimateClaimableAt, estimateRawTxGas, etherscanApiUrl, etherscanUrl, executeDelegatedMulticalls, executeMulticallBatches, expectedBalanceDeltas, fetchCreditAccountSlice, 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, isCloseOrRepay, isDust, isLPPriceFeed, isPhantomToken, isPoolOperation, isPublicNetwork, isRWAFactory, isRWAOperation, isRWAToken, isStrategyCollateral, isSunsetPool, isSunsetStrategy, isSupportedNetwork, isUpdatablePriceFeed, isV310, isVersionRange, isZeroBalance, iwstETHAbi, iwstEthv1AdapterAbi, json_parse, json_stringify, lidoV1_WETHGatewayAbi, makeReplayState, mellowDvvAdapterAbi, midasGreenlistsAccount, minSeizedAmount, numberWithCommas, onchainSDKOptionsSchema, optimalHFForPartialLiquidation, optimalRepaidAmount, parseAdapterAction, parseAdapterDeployParams, parseFacadeOperationCalldata, parseOperationCalldata, parsePoolOperationCalldata, parsePosNegAmount, parseRWAFactoryOperationCalldata, percentFmt, pickStrategyTargetCollateral, previewAdjustStrategyPosition, previewExitOrRepayStrategyPosition, previewOperation, raise, rayToBps, rayToNumber, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent, 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, updatableDependencies, usdToNumber, watchBlocksAsync };
|
|
308
|
+
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_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, ConstantPriceFeedContract, Construct, ContractParseError, ConvexV1BaseRewardPoolAdapterContract, ConvexV1BoosterAdapterContract, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountState, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, CreditSuiteStrategy, Curve2AssetsAdapterContract, Curve3AssetsAdapterContract, Curve4AssetsAdapterContract, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, CurveV1AdapterStETHContract, CurveV1StableNGAdapterContract, DEFAULT_QUOTA_BUFFER_BPS, DEGEN_NFT_MIDAS, DEGEN_NFT_SECURITIZE, 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, MidasDegenNFT, 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, PriceFeedRegistry, PriceOracleV310Contract, PriceUpdatesCache, PythPriceFeed, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, RWARegistry, RWA_COMPRESSOR_ADDRESS, 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, SLIPPAGE_DECIMALS, STATE_VERSION, SUPPORTED_NETWORKS, SdkAlreadyAttachedError, SdkChainMismatchError, SdkMissingChainStateError, SdkNotAttachedError, SdkRWADataNotLoadedError, SdkStateVersionMismatchError, SdkSyncFailedError, SecuritizeDegenNFT, SecuritizeLiquidatorContract, SecuritizeOnRampAdapterContract, SecuritizeRWAFactory, SecuritizeRedemptionGatewayAdapterContract, SimulateWithPriceUpdatesError, SimulationError, StakingRewardsAdapterContract, TokensMeta, TraderJoePoolVersion, TraderJoeRouterAdapterContract, TypedObjectUtils, UniswapV2AdapterContract, UniswapV3AdapterContract, UniswapV4AdapterContract, UpdatablePriceFeedRegistry, 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, botPermissionsToString, bpsToRay, buildDelayedStrategyPositionOperationPreview, bytes32ToString, calcBorrowApy, calcBorrowRate, calcDefaultQuota, calcEffectiveBorrowApy, calcHealthFactor, calcLiquidationPrice, calcLiquidationPriceForTarget, calcMaxLeverage, calcNetStrategyApy, calcPositionLeverage, calcQuotaRate, calcQuotaUpdate, calcRecommendedQuota, calcTimeToLiquidationMs, calcUtilization, calcUtilizationRaw, chains, checkAccountQuotas, checkBorrowLimit, checkCollateralFunding, checkCollateralised, checkCreditAccountFrozen, checkCreditManagerPaused, checkCreditOperation, checkDebtLimits, checkEmergencyLiquidator, checkForbiddenToken, checkHealthFactors, checkIncreaseDebt, checkIncreaseQuota, checkLeverage, checkLiquidation, checkLiquidationEligibility, checkLiquidationFunding, checkLiquidatorEligible, checkMarket, checkMarketExpired, checkMidasAccountGreenlist, checkObtained, checkOperation, checkPoolFunding, checkPoolLiquidity, checkPoolOperation, checkPoolPaused, checkPoolSunset, checkQuotaCount, checkQuotaLimit, checkRWAOpenRequirements, checkRWAOpening, checkReservePriceLimited, checkSimulation, checkWallet, checkWalletAllowance, checkWalletBalance, childLogger, classifyCloseOrRepay, classifyCurveOperation, classifyInnerOperations, collateralPriceInUnderlying, collectTraces, createAdapter, createAddressProvider, createPriceOracle, createRawTx, createRedemptionLogger, createRouter, createWithdrawalCompressor, createZapper, abi as creditFacadeV310Abi, curveAddLiquidityFromTransfers, curveRemoveLiquidityFromTransfers, decodeDelayedIntent, detectDelayedClaim, detectDelayedOperation, detectNetwork, dominantCollateral, encodeDelayedIntent, erc4626ReferralAdapterAbi, estimateClaimableAt, estimateRawTxGas, etherscanApiUrl, etherscanUrl, executeDelegatedMulticalls, executeMulticallBatches, expectedBalanceDeltas, fetchCreditAccountSlice, 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, isCloseOrRepay, isDust, isLPPriceFeed, isPhantomToken, isPoolOperation, isPublicNetwork, isRWAFactory, isRWAOperation, isRWAToken, isStrategyCollateral, isSunsetPool, isSunsetStrategy, isSupportedNetwork, isUpdatablePriceFeed, isV310, isVersionRange, isZeroBalance, iwstETHAbi, iwstEthv1AdapterAbi, json_parse, json_stringify, lidoV1_WETHGatewayAbi, makeReplayState, mellowDvvAdapterAbi, midasGreenlistsAccount, minSeizedAmount, numberWithCommas, onchainSDKOptionsSchema, optimalHFForPartialLiquidation, optimalRepaidAmount, parseAdapterAction, parseAdapterDeployParams, parseFacadeOperationCalldata, parseOperationCalldata, parsePoolOperationCalldata, parsePosNegAmount, parseRWAFactoryOperationCalldata, percentFmt, pickStrategyTargetCollateral, previewAdjustStrategyPosition, previewExitOrRepayStrategyPosition, previewOperation, raise, rayToBps, rayToNumber, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent, 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, updatableDependencies, usdToNumber, watchBlocksAsync };
|
|
@@ -236,13 +236,20 @@ var MarketSuite = class extends SDKConstruct {
|
|
|
236
236
|
const rows = [];
|
|
237
237
|
const kind = filter?.kind;
|
|
238
238
|
if (!isFilterSet(kind) || kind === "pool") rows.push(this.poolOpportunity());
|
|
239
|
-
if (!isFilterSet(kind) || kind === "strategy")
|
|
240
|
-
const opportunity = suite.strategyOpportunity();
|
|
241
|
-
if (opportunity) rows.push(opportunity);
|
|
242
|
-
}
|
|
239
|
+
if (!isFilterSet(kind) || kind === "strategy") rows.push(...this.strategies().map((s) => s.opportunity()));
|
|
243
240
|
return rows.filter((row) => matchesOpportunityFilter(row, filter));
|
|
244
241
|
}
|
|
245
242
|
/**
|
|
243
|
+
* Strategies this market lists as opportunities; see
|
|
244
|
+
* {@link CreditSuiteStrategy.isListed}.
|
|
245
|
+
*/
|
|
246
|
+
strategies() {
|
|
247
|
+
return this.creditManagers.flatMap((suite) => {
|
|
248
|
+
const strategy = suite.strategy;
|
|
249
|
+
return strategy?.isListed ? [strategy] : [];
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
246
253
|
* Passive lending into this market's pool, as the shared read model
|
|
247
254
|
* describes it.
|
|
248
255
|
*/
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { AddressMap } from "../../utils/AddressMap.js";
|
|
2
|
-
import { getAccountTargetCollateral, getLegacyStrategyTarget
|
|
2
|
+
import { getAccountTargetCollateral, getLegacyStrategyTarget } from "../../chain/chains.js";
|
|
3
3
|
import "../../constants/addresses.js";
|
|
4
4
|
import { PERCENTAGE_FACTOR, RAY } from "../../constants/math.js";
|
|
5
5
|
import "../../constants/index.js";
|
|
6
6
|
import "../../utils/index.js";
|
|
7
7
|
import { SDKConstruct } from "../../base/SDKConstruct.js";
|
|
8
8
|
import "../../base/index.js";
|
|
9
|
-
import {
|
|
9
|
+
import { minSeizedAmount, optimalHFForPartialLiquidation, optimalRepaidAmount } from "../math.js";
|
|
10
10
|
import { createDegenNFT } from "../rwa/createDegenNFT.js";
|
|
11
11
|
import { strategyName } from "../strategyName.js";
|
|
12
|
+
import { CreditSuiteStrategy } from "./CreditSuiteStrategy.js";
|
|
12
13
|
import { dominantCollateral, isStrategyCollateral, pickStrategyTargetCollateral } from "./collateralUtils.js";
|
|
13
14
|
import createCreditConfigurator from "./createCreditConfigurator.js";
|
|
14
15
|
import createCreditFacade from "./createCreditFacade.js";
|
|
@@ -16,13 +17,6 @@ import createCreditManager from "./createCreditManager.js";
|
|
|
16
17
|
import { isAddressEqual } from "viem";
|
|
17
18
|
//#region src/onchain/market/credit/CreditSuite.ts
|
|
18
19
|
/**
|
|
19
|
-
* Amount of underlying seeded into each pool at market creation to protect
|
|
20
|
-
* from inflation attacks, in raw token units. A suite whose
|
|
21
|
-
* {@link CreditSuite.maxBorrowAmount} is at or below this is treated as
|
|
22
|
-
* having nothing left to lend.
|
|
23
|
-
**/
|
|
24
|
-
const MIN_STRATEGY_BORROW_AMOUNT = 100000n;
|
|
25
|
-
/**
|
|
26
20
|
* SDK aggregate for one credit-manager branch inside a market.
|
|
27
21
|
*
|
|
28
22
|
* @remarks
|
|
@@ -129,31 +123,6 @@ var CreditSuite = class extends SDKConstruct {
|
|
|
129
123
|
return this.#degenNFT;
|
|
130
124
|
}
|
|
131
125
|
/**
|
|
132
|
-
* The KYC gate of this suite's strategy; `null` when there is none.
|
|
133
|
-
* Wallet-independent.
|
|
134
|
-
*/
|
|
135
|
-
async kycRequirement(targetCollateral) {
|
|
136
|
-
const nft = await this.degenNFT();
|
|
137
|
-
if (!nft) return null;
|
|
138
|
-
const tokens = await nft.getTokens();
|
|
139
|
-
const token = tokens.find((t) => isAddressEqual(t, targetCollateral)) ?? tokens[0];
|
|
140
|
-
return {
|
|
141
|
-
protocol: nft.protocol,
|
|
142
|
-
token: token ? this.tokensMeta.getToken(token) : void 0,
|
|
143
|
-
registrationLink: nft.registrationLink
|
|
144
|
-
};
|
|
145
|
-
}
|
|
146
|
-
/**
|
|
147
|
-
* Whether `wallet` may open this suite's strategy today; `true` when there
|
|
148
|
-
* is no KYC gate.
|
|
149
|
-
*/
|
|
150
|
-
async isEligibleForStrategy(wallet, targetCollateral) {
|
|
151
|
-
const nft = await this.degenNFT();
|
|
152
|
-
if (!nft) return true;
|
|
153
|
-
const requirements = await nft.getOpenAccountRequirements(wallet, { tokenOutAddress: targetCollateral });
|
|
154
|
-
return nft.isRegistered(requirements);
|
|
155
|
-
}
|
|
156
|
-
/**
|
|
157
126
|
* Builds a transaction that executes a multicall on one of this suite's
|
|
158
127
|
* credit accounts.
|
|
159
128
|
*
|
|
@@ -246,13 +215,14 @@ var CreditSuite = class extends SDKConstruct {
|
|
|
246
215
|
* row all spread it, so the five fields are filled in one place and cannot
|
|
247
216
|
* drift apart between the halves of the SDK.
|
|
248
217
|
*
|
|
249
|
-
* The curator comes from the same getter
|
|
218
|
+
* The curator comes from the same getter
|
|
219
|
+
* {@link CreditSuiteStrategy.opportunity} reads, so
|
|
250
220
|
* a result and the opportunity beside it name one entity.
|
|
251
221
|
*/
|
|
252
222
|
creditOperationMarket() {
|
|
253
223
|
return {
|
|
254
224
|
creditManager: this.creditManager.address,
|
|
255
|
-
name: this.
|
|
225
|
+
name: this.strategy?.name ?? this.underlyingToken.symbol,
|
|
256
226
|
underlyingToken: this.underlyingToken,
|
|
257
227
|
curator: this.market.curator,
|
|
258
228
|
liquidationDiscount: this.totalLiquidationDiscount()
|
|
@@ -281,15 +251,14 @@ var CreditSuite = class extends SDKConstruct {
|
|
|
281
251
|
return this.forbiddenTokens.some((f) => isAddressEqual(f, token));
|
|
282
252
|
}
|
|
283
253
|
/**
|
|
284
|
-
* Largest debt
|
|
285
|
-
* and which limit set that number.
|
|
254
|
+
* Largest debt this credit manager allows to borrow, and which limit set that number.
|
|
286
255
|
*
|
|
287
256
|
* Minimum of:
|
|
288
257
|
* - the pool's available liquidity,
|
|
289
258
|
* - this manager's remaining debt allowance, and
|
|
290
259
|
* - the facade's per-account `maxDebt`.
|
|
291
|
-
*
|
|
292
|
-
*
|
|
260
|
+
*
|
|
261
|
+
* If the credit manager allows no debt at all, the answer is `0`.
|
|
293
262
|
*/
|
|
294
263
|
maxBorrowAmount() {
|
|
295
264
|
const { pool } = this.market.pool;
|
|
@@ -319,32 +288,25 @@ var CreditSuite = class extends SDKConstruct {
|
|
|
319
288
|
};
|
|
320
289
|
}
|
|
321
290
|
/**
|
|
322
|
-
*
|
|
323
|
-
*
|
|
291
|
+
* This suite's leveraged strategy, or `undefined` when no target collateral
|
|
292
|
+
* can be resolved.
|
|
324
293
|
*
|
|
325
|
-
*
|
|
326
|
-
*
|
|
327
|
-
*
|
|
328
|
-
*
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
* {@link isStrategyCollateral} accepts with quota required;
|
|
332
|
-
* 3. the biggest-index collateral that {@link isStrategyCollateral} accepts
|
|
333
|
-
* without quota.
|
|
334
|
-
*/
|
|
335
|
-
get strategyTargetCollateral() {
|
|
294
|
+
* The strategy exists whether or not it is offered today, because its
|
|
295
|
+
* target also names existing positions; see
|
|
296
|
+
* {@link CreditSuiteStrategy.isListed} for whether it is listed as an
|
|
297
|
+
* opportunity.
|
|
298
|
+
*/
|
|
299
|
+
get strategy() {
|
|
336
300
|
const legacy = getLegacyStrategyTarget(this.creditManager.address, this.chainId);
|
|
337
|
-
|
|
338
|
-
return
|
|
301
|
+
const target = legacy && this.creditManager.liquidationThresholds.has(legacy) ? legacy : pickStrategyTargetCollateral(this.creditManager.collateralTokens.map((token) => this.#strategyCollateralProps(token)));
|
|
302
|
+
return target ? new CreditSuiteStrategy(this, target) : void 0;
|
|
339
303
|
}
|
|
340
304
|
/**
|
|
341
|
-
*
|
|
342
|
-
*
|
|
305
|
+
* Whether `token` can be this suite's strategy target; see
|
|
306
|
+
* {@link isStrategyCollateral}.
|
|
343
307
|
*/
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
if (!collateral) return;
|
|
347
|
-
return strategyName(this.tokensMeta.mustGetToken(collateral), this.underlyingToken);
|
|
308
|
+
isStrategyCollateral(token, requireQuota = false) {
|
|
309
|
+
return isStrategyCollateral(this.#strategyCollateralProps(token), requireQuota);
|
|
348
310
|
}
|
|
349
311
|
/**
|
|
350
312
|
* Collateral token an existing credit account in this suite is a strategy
|
|
@@ -352,12 +314,13 @@ var CreditSuite = class extends SDKConstruct {
|
|
|
352
314
|
*
|
|
353
315
|
* Resolution, in order:
|
|
354
316
|
* 1. a hardcoded per-account override, when present;
|
|
355
|
-
* 2. {@link
|
|
317
|
+
* 2. the target of {@link strategy};
|
|
356
318
|
* 3. `null` when neither can be resolved.
|
|
357
319
|
*/
|
|
358
320
|
accountTargetCollateral(creditAccount) {
|
|
359
|
-
const
|
|
360
|
-
|
|
321
|
+
const override = getAccountTargetCollateral(creditAccount, this.chainId);
|
|
322
|
+
if (override) return this.tokensMeta.mustGetToken(override);
|
|
323
|
+
return this.strategy?.token ?? null;
|
|
361
324
|
}
|
|
362
325
|
/**
|
|
363
326
|
* Display name of an existing credit account in this suite, e.g.
|
|
@@ -371,61 +334,6 @@ var CreditSuite = class extends SDKConstruct {
|
|
|
371
334
|
return target ? strategyName(target, this.underlyingToken) : this.underlyingToken.symbol;
|
|
372
335
|
}
|
|
373
336
|
/**
|
|
374
|
-
* Describes this suite's leveraged strategy as the shared read model does,
|
|
375
|
-
* or `undefined` when credit suite does not offer a strategy opportunity.
|
|
376
|
-
*/
|
|
377
|
-
strategyOpportunity() {
|
|
378
|
-
const maxBorrowAmount = this.maxBorrowAmount().amount.value;
|
|
379
|
-
if (maxBorrowAmount <= MIN_STRATEGY_BORROW_AMOUNT) return;
|
|
380
|
-
const collateral = this.strategyTargetCollateral;
|
|
381
|
-
if (!collateral) return;
|
|
382
|
-
if (!isStrategyCollateral(this.#strategyCollateralProps(collateral), true)) return;
|
|
383
|
-
const { market, creditManager: cm } = this;
|
|
384
|
-
const { pool } = market.pool;
|
|
385
|
-
const oracle = market.priceOracle;
|
|
386
|
-
const liquidationThreshold = cm.liquidationThresholds.mustGet(collateral);
|
|
387
|
-
const maxLeverage = cm.maxLeverage(collateral);
|
|
388
|
-
const debtParams = pool.creditManagerDebtParams.get(cm.address);
|
|
389
|
-
const borrowed = debtParams?.borrowed ?? 0n;
|
|
390
|
-
return {
|
|
391
|
-
kind: "strategy",
|
|
392
|
-
chainId: this.chainId,
|
|
393
|
-
creditManager: cm.address,
|
|
394
|
-
targetCollateral: this.tokensMeta.mustGetToken(collateral),
|
|
395
|
-
name: this.strategyName ?? this.underlyingToken.symbol,
|
|
396
|
-
curator: market.curator,
|
|
397
|
-
underlyingToken: this.underlyingToken,
|
|
398
|
-
totalBorrowed: oracle.toAmount(pool.underlying, borrowed),
|
|
399
|
-
allowedDepositTokens: this.allowedDepositTokens(collateral),
|
|
400
|
-
paused: this.isPaused,
|
|
401
|
-
rwa: market.rwa,
|
|
402
|
-
sunset: market.sunset || isSunsetStrategy(cm.address, this.sdk.networkType),
|
|
403
|
-
liquidationThreshold,
|
|
404
|
-
liquidationPremium: cm.liquidationPremium,
|
|
405
|
-
liquidationFee: cm.feeLiquidation,
|
|
406
|
-
expirationDate: this.expirationDate,
|
|
407
|
-
borrowApy: calcBorrowApy(pool.baseInterestRate, cm.feeInterest),
|
|
408
|
-
quotaRate: calcQuotaRate(market.pool.pqk.quotaRate(collateral), cm.feeInterest),
|
|
409
|
-
availableLiquidity: oracle.toAmount(pool.underlying, pool.availableLiquidity),
|
|
410
|
-
minDebt: oracle.toAmount(pool.underlying, this.creditFacade.minDebt),
|
|
411
|
-
totalDebtLimit: oracle.toAmount(pool.underlying, debtParams?.limit ?? 0n),
|
|
412
|
-
maxBorrowAmount: oracle.toAmount(pool.underlying, maxBorrowAmount),
|
|
413
|
-
maxLeverage
|
|
414
|
-
};
|
|
415
|
-
}
|
|
416
|
-
/**
|
|
417
|
-
* {@link strategyOpportunity} plus the data only its detail screen needs.
|
|
418
|
-
*/
|
|
419
|
-
strategyOpportunityDetail() {
|
|
420
|
-
const opportunity = this.strategyOpportunity();
|
|
421
|
-
if (!opportunity) return;
|
|
422
|
-
return {
|
|
423
|
-
...opportunity,
|
|
424
|
-
rateCurve: this.market.pool.rateCurve,
|
|
425
|
-
priceFeeds: this.market.priceFeedSummary(opportunity.targetCollateral.address)
|
|
426
|
-
};
|
|
427
|
-
}
|
|
428
|
-
/**
|
|
429
337
|
* Everything a partial liquidation of credit account needs, with any parameter the
|
|
430
338
|
* caller pinned down taken as given and the rest derived from current state.
|
|
431
339
|
*
|
|
@@ -465,27 +373,6 @@ var CreditSuite = class extends SDKConstruct {
|
|
|
465
373
|
return collateral;
|
|
466
374
|
}
|
|
467
375
|
/**
|
|
468
|
-
* Tokens a user can transfer from their wallet when opening an account in
|
|
469
|
-
* this suite:
|
|
470
|
-
*
|
|
471
|
-
* 1. unwrapped underlying (USDC, never dcUSDC)
|
|
472
|
-
* 2. target collateral
|
|
473
|
-
* 3. remaining CM collaterals in manager order, excluding phantom tokens
|
|
474
|
-
* and tokens without price
|
|
475
|
-
*/
|
|
476
|
-
allowedDepositTokens(targetCollateral) {
|
|
477
|
-
const unwrappedUnderlying = this.market.unwrappedUnderlying;
|
|
478
|
-
const { mainPrices, reservePrices } = this.market.priceOracle;
|
|
479
|
-
return [
|
|
480
|
-
unwrappedUnderlying,
|
|
481
|
-
targetCollateral,
|
|
482
|
-
...this.creditManager.collateralTokens.filter((token) => {
|
|
483
|
-
const contractType = this.tokensMeta.mustGet(token).contractType;
|
|
484
|
-
return !this.market.isUnderlyingLike(token) && !isAddressEqual(token, targetCollateral) && !contractType?.startsWith("PHANTOM_TOKEN::") && (!!mainPrices.get(token)?.price || !!reservePrices.get(token)?.price);
|
|
485
|
-
})
|
|
486
|
-
].map((token) => this.tokensMeta.mustGetToken(token));
|
|
487
|
-
}
|
|
488
|
-
/**
|
|
489
376
|
* Shared inputs of {@link isStrategyCollateral} for one of this suite's
|
|
490
377
|
* collateral tokens.
|
|
491
378
|
*/
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { isSunsetStrategy } from "../../chain/chains.js";
|
|
2
|
+
import { calcBorrowApy, calcQuotaRate } from "../math.js";
|
|
3
|
+
import { strategyName } from "../strategyName.js";
|
|
4
|
+
import { isAddressEqual } from "viem";
|
|
5
|
+
//#region src/onchain/market/credit/CreditSuiteStrategy.ts
|
|
6
|
+
/**
|
|
7
|
+
* Amount of underlying seeded into each pool at market creation to protect
|
|
8
|
+
* from inflation attacks, in raw token units. A strategy whose
|
|
9
|
+
* {@link CreditSuiteStrategy.maxBorrowAmount} is at or below this is treated
|
|
10
|
+
* as having nothing left to lend.
|
|
11
|
+
**/
|
|
12
|
+
const MIN_STRATEGY_BORROW_AMOUNT = 100000n;
|
|
13
|
+
/**
|
|
14
|
+
* The leveraged strategy a credit suite runs: one target collateral bought
|
|
15
|
+
* with underlying borrowed from the pool.
|
|
16
|
+
*
|
|
17
|
+
* A view over live suite state, see {@link CreditSuite.strategy}.
|
|
18
|
+
*/
|
|
19
|
+
var CreditSuiteStrategy = class {
|
|
20
|
+
/**
|
|
21
|
+
* Credit suite this strategy borrows through.
|
|
22
|
+
*/
|
|
23
|
+
suite;
|
|
24
|
+
/**
|
|
25
|
+
* Collateral token a position in this strategy is built to hold.
|
|
26
|
+
*/
|
|
27
|
+
targetCollateral;
|
|
28
|
+
constructor(suite, targetCollateral) {
|
|
29
|
+
this.suite = suite;
|
|
30
|
+
this.targetCollateral = targetCollateral;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* {@link targetCollateral} as the shared read model describes it.
|
|
34
|
+
*/
|
|
35
|
+
get token() {
|
|
36
|
+
return this.suite.sdk.tokensMeta.mustGetToken(this.targetCollateral);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Display name of this strategy, e.g. `"wstETH / WETH"`.
|
|
40
|
+
*/
|
|
41
|
+
get name() {
|
|
42
|
+
return strategyName(this.token, this.suite.underlyingToken);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Tokens a user can transfer from their wallet when opening a position in
|
|
46
|
+
* this strategy:
|
|
47
|
+
*
|
|
48
|
+
* 1. unwrapped underlying (USDC, never dcUSDC)
|
|
49
|
+
* 2. target collateral
|
|
50
|
+
* 3. remaining CM collaterals in manager order, excluding phantom tokens
|
|
51
|
+
* and tokens without price
|
|
52
|
+
*/
|
|
53
|
+
get allowedDepositTokens() {
|
|
54
|
+
const { market, creditManager, sdk } = this.suite;
|
|
55
|
+
const { tokensMeta } = sdk;
|
|
56
|
+
const { targetCollateral } = this;
|
|
57
|
+
const { mainPrices, reservePrices } = market.priceOracle;
|
|
58
|
+
const rest = creditManager.collateralTokens.filter((token) => {
|
|
59
|
+
const contractType = tokensMeta.mustGet(token).contractType;
|
|
60
|
+
return !market.isUnderlyingLike(token) && !isAddressEqual(token, targetCollateral) && !contractType?.startsWith("PHANTOM_TOKEN::") && (!!mainPrices.get(token)?.price || !!reservePrices.get(token)?.price);
|
|
61
|
+
});
|
|
62
|
+
return [
|
|
63
|
+
market.unwrappedUnderlying,
|
|
64
|
+
targetCollateral,
|
|
65
|
+
...rest
|
|
66
|
+
].map((token) => tokensMeta.mustGetToken(token));
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Largest debt one new position can take right now, and which limit set
|
|
70
|
+
* that number.
|
|
71
|
+
*
|
|
72
|
+
* `amount` is `0` whenever no position can be opened right now,
|
|
73
|
+
* and `limit` explains why.
|
|
74
|
+
*
|
|
75
|
+
*/
|
|
76
|
+
maxBorrowAmount() {
|
|
77
|
+
const { suite } = this;
|
|
78
|
+
const lends = suite.maxBorrowAmount();
|
|
79
|
+
if (lends.limit === "debtPerBlockLimit") return lends;
|
|
80
|
+
let value = lends.amount.value;
|
|
81
|
+
let limit = lends.limit;
|
|
82
|
+
const quota = suite.market.pool.pqk.quotaAvailable(this.targetCollateral);
|
|
83
|
+
if (quota < value) {
|
|
84
|
+
value = quota;
|
|
85
|
+
limit = "quotaAvailable";
|
|
86
|
+
}
|
|
87
|
+
if (value < suite.creditFacade.minDebt) return {
|
|
88
|
+
amount: suite.market.toUnderlyingAmount(0n),
|
|
89
|
+
limit: "minDebt"
|
|
90
|
+
};
|
|
91
|
+
return {
|
|
92
|
+
amount: suite.market.toUnderlyingAmount(value),
|
|
93
|
+
limit
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Whether this strategy is offered as an opportunity right now: it lends
|
|
98
|
+
* more than the pool's seed amount, and its target can be opened today.
|
|
99
|
+
*/
|
|
100
|
+
get isListed() {
|
|
101
|
+
return this.maxBorrowAmount().amount.value > MIN_STRATEGY_BORROW_AMOUNT && this.suite.isStrategyCollateral(this.targetCollateral, true);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Describes this strategy as the shared read model does. Whether it is
|
|
105
|
+
* listed at all is {@link isListed}.
|
|
106
|
+
*/
|
|
107
|
+
opportunity() {
|
|
108
|
+
const { suite, targetCollateral } = this;
|
|
109
|
+
const { market, creditManager: cm } = suite;
|
|
110
|
+
const { pool } = market.pool;
|
|
111
|
+
const oracle = market.priceOracle;
|
|
112
|
+
const debtParams = pool.creditManagerDebtParams.get(cm.address);
|
|
113
|
+
const borrowed = debtParams?.borrowed ?? 0n;
|
|
114
|
+
return {
|
|
115
|
+
kind: "strategy",
|
|
116
|
+
chainId: suite.chainId,
|
|
117
|
+
creditManager: cm.address,
|
|
118
|
+
targetCollateral: this.token,
|
|
119
|
+
name: this.name,
|
|
120
|
+
curator: market.curator,
|
|
121
|
+
underlyingToken: suite.underlyingToken,
|
|
122
|
+
totalBorrowed: oracle.toAmount(pool.underlying, borrowed),
|
|
123
|
+
allowedDepositTokens: this.allowedDepositTokens,
|
|
124
|
+
paused: suite.isPaused,
|
|
125
|
+
rwa: market.rwa,
|
|
126
|
+
sunset: market.sunset || isSunsetStrategy(cm.address, suite.sdk.networkType),
|
|
127
|
+
liquidationThreshold: cm.liquidationThresholds.mustGet(targetCollateral),
|
|
128
|
+
liquidationPremium: cm.liquidationPremium,
|
|
129
|
+
liquidationFee: cm.feeLiquidation,
|
|
130
|
+
expirationDate: suite.expirationDate,
|
|
131
|
+
borrowApy: calcBorrowApy(pool.baseInterestRate, cm.feeInterest),
|
|
132
|
+
quotaRate: calcQuotaRate(market.pool.pqk.quotaRate(targetCollateral), cm.feeInterest),
|
|
133
|
+
availableLiquidity: oracle.toAmount(pool.underlying, pool.availableLiquidity),
|
|
134
|
+
minDebt: oracle.toAmount(pool.underlying, suite.creditFacade.minDebt),
|
|
135
|
+
totalDebtLimit: oracle.toAmount(pool.underlying, debtParams?.limit ?? 0n),
|
|
136
|
+
maxBorrowAmount: oracle.toAmount(pool.underlying, this.maxBorrowAmount().amount.value),
|
|
137
|
+
maxLeverage: cm.maxLeverage(targetCollateral)
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* {@link opportunity} plus the data only its detail screen needs.
|
|
142
|
+
*/
|
|
143
|
+
opportunityDetail() {
|
|
144
|
+
const { market } = this.suite;
|
|
145
|
+
return {
|
|
146
|
+
...this.opportunity(),
|
|
147
|
+
rateCurve: market.pool.rateCurve,
|
|
148
|
+
priceFeeds: market.priceFeedSummary(this.targetCollateral)
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* The KYC gate of this strategy; `null` when there is none.
|
|
153
|
+
* Wallet-independent.
|
|
154
|
+
*/
|
|
155
|
+
async kycRequirement() {
|
|
156
|
+
const nft = await this.suite.degenNFT();
|
|
157
|
+
if (!nft) return null;
|
|
158
|
+
const tokens = await nft.getTokens();
|
|
159
|
+
const token = tokens.find((t) => isAddressEqual(t, this.targetCollateral)) ?? tokens[0];
|
|
160
|
+
return {
|
|
161
|
+
protocol: nft.protocol,
|
|
162
|
+
token: token ? this.suite.sdk.tokensMeta.getToken(token) : void 0,
|
|
163
|
+
registrationLink: nft.registrationLink
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Whether `wallet` may open this strategy today; `true` when there is no
|
|
168
|
+
* KYC gate.
|
|
169
|
+
*/
|
|
170
|
+
async isEligible(wallet) {
|
|
171
|
+
const nft = await this.suite.degenNFT();
|
|
172
|
+
if (!nft) return true;
|
|
173
|
+
const requirements = await nft.getOpenAccountRequirements(wallet, { tokenOutAddress: this.targetCollateral });
|
|
174
|
+
return nft.isRegistered(requirements);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
//#endregion
|
|
178
|
+
export { CreditSuiteStrategy };
|
|
@@ -2,8 +2,9 @@ import { CreditConfiguratorV310Contract } from "./CreditConfiguratorV310Contract
|
|
|
2
2
|
import { CreditFacadeV310BaseContract, creditFacadeV310Abi as abi } from "./CreditFacadeV310BaseContract.js";
|
|
3
3
|
import { CreditFacadeV310Contract } from "./CreditFacadeV310Contract.js";
|
|
4
4
|
import { CreditManagerV310Contract } from "./CreditManagerV310Contract.js";
|
|
5
|
+
import { CreditSuiteStrategy } from "./CreditSuiteStrategy.js";
|
|
5
6
|
import { dominantCollateral, isStrategyCollateral, pickStrategyTargetCollateral } from "./collateralUtils.js";
|
|
6
7
|
import { CreditSuite } from "./CreditSuite.js";
|
|
7
8
|
import { expectedBalanceDeltas } from "./expectedBalanceDeltas.js";
|
|
8
9
|
import "./types.js";
|
|
9
|
-
export { CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, abi as creditFacadeV310Abi, dominantCollateral, expectedBalanceDeltas, isStrategyCollateral, pickStrategyTargetCollateral };
|
|
10
|
+
export { CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, CreditSuiteStrategy, abi as creditFacadeV310Abi, dominantCollateral, expectedBalanceDeltas, isStrategyCollateral, pickStrategyTargetCollateral };
|