import { assetAmountInEth, assetAmountInWei, getAssetInfo } from '@defisaver/tokens'; import { Client } from 'viem'; import Dec from 'decimal.js'; import { getAaveLikeBalances } from '../helpers/aaveBalances'; import { AaveIncentiveDataProviderV3ContractViem, AaveIncentivesControllerViem, AaveV3ViewContractViem, createViemContractFromConfigFunc, getConfigContractAbi, StkAAVEViem, } from '../contracts'; import { aaveAnyGetAggregatedPositionData, aaveV3IsInIsolationMode, aaveV3IsInSiloedMode } from '../helpers/aaveHelpers'; import { AAVE_V3 } from '../markets/aave'; import { aprToApy, calculateBorrowingAssetLimit } from '../moneymarket'; import { getWrappedNativeAssetFromUnwrapped, isEnabledOnBitmap, isLayer2Network, wethToEth, } from '../services/utils'; import { getStakingApy, STAKING_ASSETS } from '../staking'; import { AaveMarketInfo, AaveV3AssetData, AaveV3AssetsData, AaveV3MarketData, AaveV3PositionData, AaveV3UsedAsset, AaveV3UsedAssets, EModeCategoriesData, EModeCategoryData, EModeCategoryDataMapping, StakeAaveData, } from '../types'; import { Blockish, EthAddress, EthereumProvider, IncentiveEligibilityId, IncentiveKind, NetworkNumber, PositionBalances, HexString, } from '../types/common'; import { getViemProvider, setViemBlockNumber } from '../services/viem'; import { getMeritCampaigns } from './merit'; import { getAaveUnderlyingSymbol, getMerkleCampaigns } from './merkl'; import { getSghoData } from './sgho'; import { SECONDS_PER_YEAR } from '../constants'; export const aaveV3EmodeCategoriesMapping = (extractedState: any, usedAssets: AaveV3UsedAssets) => { const { eModeCategoriesData }: { assetsData: AaveV3AssetsData, eModeCategoriesData: EModeCategoriesData } = extractedState; const usedAssetsValues = Object.values(usedAssets); const categoriesMapping: { [key: number]: EModeCategoryDataMapping } = {}; Object.values(eModeCategoriesData).forEach((e: EModeCategoryData) => { const borrowingOnlyFromCategory = e.id === 0 ? true : !usedAssetsValues.filter(u => u.isBorrowed && !e.borrowAssets.includes(u.symbol)).length; const afterEnteringCategory = aaveAnyGetAggregatedPositionData({ ...extractedState, usedAssets, eModeCategory: e.id, }); const willStayOverCollateralized = new Dec(afterEnteringCategory.ratio === 'NaN' ? '0' : afterEnteringCategory.ratio).eq(0) || new Dec(afterEnteringCategory.ratio).gt(afterEnteringCategory.liqPercent); const collateralOnlyFromCategory = e.id === 0 || !e.isolated ? true : !usedAssetsValues.filter(u => u.isSupplied && u.collateral && !e.collateralAssets.includes(u.symbol)).length; const enteringTerms = [borrowingOnlyFromCategory, willStayOverCollateralized, collateralOnlyFromCategory]; categoriesMapping[e.id] = { enteringTerms, canEnterCategory: !enteringTerms.includes(false), id: e.id, enabledData: { ratio: afterEnteringCategory.ratio, liqRatio: afterEnteringCategory.liqRatio, liqPercent: afterEnteringCategory.liqPercent, collRatio: afterEnteringCategory.collRatio, }, }; }); return categoriesMapping; }; export async function _getAaveV3MarketData(provider: Client, network: NetworkNumber, market: AaveMarketInfo, blockNumber: 'latest' | number = 'latest'): Promise { const _addresses = market.assets.map(a => getAssetInfo(getWrappedNativeAssetFromUnwrapped(a), network).address); const loanInfoContract = AaveV3ViewContractViem(provider, network); const aaveIncentivesContract = AaveIncentiveDataProviderV3ContractViem(provider, network); const marketAddress = market.providerAddress; const networksWithIncentives = [NetworkNumber.Eth, NetworkNumber.Arb, NetworkNumber.Opt, NetworkNumber.Linea, NetworkNumber.Plasma]; // Limit each view call to 10 tokens, run chunks concurrently, then combine their results into loanInfo. const addressesPerRequest = 10; const addressChunks: EthAddress[][] = _addresses.length > addressesPerRequest ? Array.from( { length: Math.ceil(_addresses.length / addressesPerRequest) }, (_, index) => _addresses.slice(index * addressesPerRequest, (index + 1) * addressesPerRequest) as EthAddress[], ) : [_addresses as EthAddress[]]; const loanInfoPromise = Promise.all(addressChunks.map((addresses) => loanInfoContract.read.getFullTokensInfo( [marketAddress, addresses], setViemBlockNumber(blockNumber), ))).then((loanInfoChunks) => loanInfoChunks.flat()); // eslint-disable-next-line prefer-const let [loanInfo, eModesInfo, rewardInfo, merkleRewardsMap, meritRewardsMap] = await Promise.all([ loanInfoPromise, loanInfoContract.read.getAllEmodes([marketAddress], setViemBlockNumber(blockNumber)), networksWithIncentives.includes(network) ? aaveIncentivesContract.read.getReservesIncentivesData([marketAddress], setViemBlockNumber(blockNumber)) : null, getMerkleCampaigns(network), getMeritCampaigns(network, market.value), ]); // same break logic as view contract let missCounter = 0; const eModeCategoriesData: EModeCategoriesData = {}; for (let i = 0; i < eModesInfo.length; i++) { if (eModesInfo[i].liquidationThreshold !== 0) { eModeCategoriesData[i + 1] = { label: eModesInfo[i].label, id: i + 1, liquidationBonus: new Dec(eModesInfo[i].liquidationBonus).div(10000).toString(), liquidationRatio: new Dec(eModesInfo[i].liquidationThreshold).div(10000).toString(), collateralFactor: new Dec(eModesInfo[i].ltv).div(10000).toString(), borrowableBitmap: eModesInfo[i].borrowableBitmap.toString(), collateralBitmap: eModesInfo[i].collateralBitmap.toString(), ltvzeroBitmap: eModesInfo[i].ltvzeroBitmap.toString(), isolated: eModesInfo[i].isolated ?? false, borrowAssets: [], collateralAssets: [], ltvZeroAssets: [], }; missCounter = 0; } else { ++missCounter; if (missCounter > 2) break; } } if (networksWithIncentives.includes(network) && rewardInfo) { rewardInfo = rewardInfo.reduce((all: any, _market: any) => { // eslint-disable-next-line no-param-reassign all[_market.underlyingAsset] = _market; return all; }, {}); } const assetsData: AaveV3AssetData[] = await Promise.all(loanInfo .map(async (tokenMarket, i) => { const symbol = market.assets[i]; // eslint-disable-next-line guard-for-in for (const eModeIndex in eModeCategoriesData) { if (isEnabledOnBitmap(eModeCategoriesData[eModeIndex].collateralBitmap!, Number(tokenMarket.assetId))) eModeCategoriesData[eModeIndex].collateralAssets.push(symbol); if (isEnabledOnBitmap(eModeCategoriesData[eModeIndex].borrowableBitmap!, Number(tokenMarket.assetId))) eModeCategoriesData[eModeIndex].borrowAssets.push(symbol); if (isEnabledOnBitmap(eModeCategoriesData[eModeIndex].ltvzeroBitmap!, Number(tokenMarket.assetId))) eModeCategoriesData[eModeIndex].ltvZeroAssets.push(symbol); } const borrowCap = tokenMarket.borrowCap.toString(); const borrowCapInWei = new Dec(assetAmountInWei(borrowCap, symbol)); let marketLiquidity = borrowCapInWei.lt(new Dec(tokenMarket.totalSupply.toString())) ? assetAmountInEth(borrowCapInWei .sub(tokenMarket.totalBorrow.toString()) .toString(), symbol) : assetAmountInEth(new Dec(tokenMarket.totalSupply.toString()) .sub(tokenMarket.totalBorrow.toString()) .toString(), symbol); if (new Dec(marketLiquidity).lt(0)) { marketLiquidity = '0'; } return ({ symbol, isIsolated: new Dec(tokenMarket.debtCeilingForIsolationMode.toString()).gt(0), debtCeilingForIsolationMode: new Dec(tokenMarket.debtCeilingForIsolationMode.toString()).div(100).toString(), isSiloed: tokenMarket.isSiloedForBorrowing, isolationModeTotalDebt: new Dec(tokenMarket.isolationModeTotalDebt.toString()).div(100).toString(), assetId: Number(tokenMarket.assetId), underlyingTokenAddress: tokenMarket.underlyingTokenAddress, supplyRate: aprToApy(new Dec(tokenMarket.supplyRate.toString()).div(1e25).toString()), borrowRate: aprToApy(new Dec(tokenMarket.borrowRateVariable.toString()).div(1e25).toString()), borrowRateStable: aprToApy(new Dec(tokenMarket.borrowRateStable.toString()).div(1e25).toString()), collateralFactor: new Dec(tokenMarket.collateralFactor.toString()).div(10000).toString(), liquidationBonus: new Dec(tokenMarket.liquidationBonus.toString()).div(10000).toString(), liquidationRatio: new Dec(tokenMarket.liquidationRatio.toString()).div(10000).toString(), marketLiquidity, utilization: new Dec(tokenMarket.totalBorrow.toString()).times(100).div(new Dec(tokenMarket.totalSupply.toString())).toString(), usageAsCollateralEnabled: tokenMarket.usageAsCollateralEnabled, supplyCap: tokenMarket.supplyCap.toString(), borrowCap, totalSupply: assetAmountInEth(tokenMarket.totalSupply.toString(), symbol), isInactive: !tokenMarket.isActive, isFrozen: tokenMarket.isFrozen, isPaused: tokenMarket.isPaused, canBeBorrowed: tokenMarket.isActive && !tokenMarket.isPaused && !tokenMarket.isFrozen && tokenMarket.borrowingEnabled, canBeSupplied: tokenMarket.isActive && !tokenMarket.isPaused && !tokenMarket.isFrozen, canBeWithdrawn: tokenMarket.isActive && !tokenMarket.isPaused, canBePayBacked: tokenMarket.isActive && !tokenMarket.isPaused, disabledStableBorrowing: !tokenMarket.stableBorrowRateEnabled, totalBorrow: assetAmountInEth(tokenMarket.totalBorrow.toString(), symbol), totalBorrowVar: assetAmountInEth(tokenMarket.totalBorrowVar.toString(), symbol), price: new Dec(tokenMarket.price.toString()).div(1e8).toString(), // is actually price in USD isolationModeBorrowingEnabled: tokenMarket.isolationModeBorrowingEnabled, isFlashLoanEnabled: tokenMarket.isFlashLoanEnabled, aTokenAddress: tokenMarket.aTokenAddress, vTokenAddress: tokenMarket.debtTokenAddress, supplyIncentives: [], borrowIncentives: [], }); }), ); // Get incentives data await Promise.all(assetsData.map(async (_market: AaveV3AssetData, index) => { /* eslint-disable no-param-reassign */ // @ts-ignore const rewardForMarket = rewardInfo?.[_market.underlyingTokenAddress]; const isStakingAsset = STAKING_ASSETS.includes(_market.symbol); if (isStakingAsset) { const yieldApy = await getStakingApy(_market.symbol, network as NetworkNumber); _market.supplyIncentives.push({ apy: yieldApy, token: _market.symbol, incentiveKind: IncentiveKind.Staking, description: `Native ${_market.symbol} yield.`, }); if (_market.canBeBorrowed) { // when borrowing assets whose value increases over time _market.borrowIncentives.push({ apy: new Dec(yieldApy).mul(-1).toString(), token: _market.symbol, incentiveKind: IncentiveKind.Reward, description: `Due to the native yield of ${_market.symbol}, the value of the debt would increase over time.`, }); } } const aTokenAddress = (_market as any).aTokenAddress.toLowerCase(); // DEV: Should aTokenAddress be in AaveV3AssetData type? if (merkleRewardsMap[aTokenAddress]?.supply) { const { apy, rewardTokenSymbol, description, identifier, } = merkleRewardsMap[aTokenAddress].supply; _market.supplyIncentives.push({ apy, token: rewardTokenSymbol, incentiveKind: IncentiveKind.Reward, description, eligibilityId: identifier as IncentiveEligibilityId, }); } const vTokenAddress = (_market as any).vTokenAddress.toLowerCase(); // DEV: Should vTokenAddress be in AaveV3AssetData type? if (merkleRewardsMap[vTokenAddress]?.borrow) { const { apy, rewardTokenSymbol, description, identifier, } = merkleRewardsMap[vTokenAddress].borrow; _market.borrowIncentives.push({ apy, token: rewardTokenSymbol, incentiveKind: IncentiveKind.Reward, description, eligibilityId: identifier as IncentiveEligibilityId, }); } if (meritRewardsMap.supply[_market.symbol]) { const { apy, rewardTokenSymbol, description } = meritRewardsMap.supply[_market.symbol]; _market.supplyIncentives.push({ apy, token: rewardTokenSymbol, incentiveKind: IncentiveKind.Reward, description, }); } if (meritRewardsMap.borrow[_market.symbol]) { const { apy, rewardTokenSymbol, description } = meritRewardsMap.borrow[_market.symbol]; _market.borrowIncentives.push({ apy, token: rewardTokenSymbol, incentiveKind: IncentiveKind.Reward, description, }); } if (!rewardForMarket) return; // @ts-ignore rewardForMarket.aIncentiveData.rewardsTokenInformation.forEach(supplyRewardData => { if (supplyRewardData) { if (+(supplyRewardData.emissionEndTimestamp.toString()) * 1000 < Date.now()) return; // reward token is aave asset const supplyEmissionPerSecond = supplyRewardData.emissionPerSecond; const supplyRewardPrice = new Dec(supplyRewardData.rewardPriceFeed).div(10 ** +supplyRewardData.priceFeedDecimals) .toString(); const rewardApy = new Dec(supplyEmissionPerSecond).div((10 ** +supplyRewardData.rewardTokenDecimals) / 100) .mul(365 * 24 * 3600) .mul(supplyRewardPrice) .div(_market.price) .div(_market.totalSupply) .toString(); _market.supplyIncentives.push({ token: getAaveUnderlyingSymbol(supplyRewardData.rewardTokenSymbol), apy: rewardApy, incentiveKind: IncentiveKind.Reward, description: 'Eligible for protocol-level incentives.', }); } }); // @ts-ignore rewardForMarket.vIncentiveData.rewardsTokenInformation.forEach(borrowRewardData => { if (borrowRewardData) { if (+(borrowRewardData.emissionEndTimestamp.toString()) * 1000 < Date.now()) return; const supplyEmissionPerSecond = borrowRewardData.emissionPerSecond; const supplyRewardPrice = new Dec(borrowRewardData.rewardPriceFeed).div(10 ** +borrowRewardData.priceFeedDecimals) .toString(); const rewardApy = new Dec(supplyEmissionPerSecond).div((10 ** +borrowRewardData.rewardTokenDecimals) / 100) .mul(365 * 24 * 3600) .mul(supplyRewardPrice) .div(_market.price) .div(_market.totalBorrowVar) .toString(); _market.borrowIncentives.push({ token: getAaveUnderlyingSymbol(borrowRewardData.rewardTokenSymbol), apy: rewardApy, incentiveKind: IncentiveKind.Reward, description: 'Eligible for protocol-level incentives.', }); } }); })); const payload: AaveV3AssetsData = {}; // Sort by market size assetsData .sort((a, b) => { const aMarket = new Dec(a.price).times(a.totalSupply).toString(); const bMarket = new Dec(b.price).times(b.totalSupply).toString(); return new Dec(bMarket).minus(aMarket).toNumber(); }) .forEach((assetData: AaveV3AssetData, i) => { payload[assetData.symbol] = { ...assetData, sortIndex: i }; }); eModeCategoriesData[0] = { id: 0, label: '', liquidationBonus: '0', liquidationRatio: '0', collateralFactor: '0', collateralAssets: assetsData.map((a) => a.symbol), borrowAssets: assetsData.map((a) => a.symbol), ltvZeroAssets: [], isolated: false, }; return { assetsData: payload, eModeCategoriesData }; } export async function getAaveV3MarketData(provider: EthereumProvider, network: NetworkNumber, market: AaveMarketInfo, blockNumber: 'latest' | number = 'latest'): Promise { return _getAaveV3MarketData(getViemProvider(provider, network), network, market, blockNumber); } export const EMPTY_AAVE_DATA = { usedAssets: {}, suppliedUsd: '0', borrowedUsd: '0', borrowLimitUsd: '0', leftToBorrowUsd: '0', ratio: '0', minRatio: '0', netApy: '0', incentiveUsd: '0', totalInterestUsd: '0', isSubscribedToAutomation: false, automationResubscribeRequired: false, eModeCategory: 0, isInIsolationMode: false, isInSiloedMode: false, totalSupplied: '0', eModeCategories: [], collRatio: '0', suppliedCollateralUsd: '0', exposure: 'N/A', }; export const _getAaveV3AccountBalances = async (provider: Client, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress): Promise => { const balances = await getAaveLikeBalances(provider, network, block, addressMapping, address, AAVE_V3(network), 'AaveV3View'); return balances; }; export const getAaveV3AccountBalances = async (provider: EthereumProvider, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress): Promise => _getAaveV3AccountBalances(getViemProvider(provider, network), network, block, addressMapping, address); /** * Historical net-balance helpers that bypass the AaveV3View contract. * * The View contract (and therefore `getAaveV3AccountData` / `getAaveV3AccountBalances`) can only be * queried from its deployment block onwards, so it cannot read balances for positions older than that. * The aTokens/debt tokens, the ProtocolDataProvider and the Aave price oracle all exist from Aave v3 * launch, so reading `balanceOf` on those tokens + the oracle price directly reaches much further back * and costs ~1 multicall per point. Used to build a position balance-history chart. */ // matches morphoVaults' batchSize; stays under the 500k portfolio discovery allows on simulation fork RPCs const HISTORICAL_MULTICALL_BATCH_SIZE = 250_000; // Minimal Aave price oracle ABI (getAssetPrice returns the asset price in the market base currency). const AAVE_ORACLE_ABI = [ { inputs: [{ internalType: 'address', name: 'asset', type: 'address' }], name: 'getAssetPrice', outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }], stateMutability: 'view', type: 'function', }, ] as const; export interface AaveV3ReserveTokenAddresses { [symbol: string]: { symbol: string, underlyingAddress: EthAddress, aTokenAddress: EthAddress, stableDebtTokenAddress: EthAddress, variableDebtTokenAddress: EthAddress, }; } export interface AaveV3HistoricalBalance { block: number, suppliedUsd: string, borrowedUsd: string, netUsd: string, } /** * Fetches the aToken / stable-debt / variable-debt token addresses for every asset in the market. * These are effectively immutable per reserve, so fetch once and reuse across all history points. */ export const _getAaveV3ReserveTokenAddresses = async (provider: Client, network: NetworkNumber, market: AaveMarketInfo): Promise => { const symbols = market.assets; const underlyingAddresses = symbols.map((a: string) => getAssetInfo(getWrappedNativeAssetFromUnwrapped(a), network).address as EthAddress); // @ts-ignore market.protocolData is a valid config key at runtime const dataProviderAbi = getConfigContractAbi(market.protocolData, network); const contracts = underlyingAddresses.map((underlying) => ({ address: market.protocolDataAddress as EthAddress, abi: dataProviderAbi, functionName: 'getReserveTokensAddresses', args: [underlying], })); // @ts-ignore const results = await provider.multicall({ contracts, allowFailure: true, batchSize: HISTORICAL_MULTICALL_BATCH_SIZE }); const mapping: AaveV3ReserveTokenAddresses = {}; results.forEach((res: any, i: number) => { if (res.status !== 'success' || !res.result) return; // outputs order: [aTokenAddress, stableDebtTokenAddress, variableDebtTokenAddress] const [aTokenAddress, stableDebtTokenAddress, variableDebtTokenAddress] = res.result as [EthAddress, EthAddress, EthAddress]; mapping[symbols[i]] = { symbol: symbols[i], underlyingAddress: underlyingAddresses[i], aTokenAddress, stableDebtTokenAddress, variableDebtTokenAddress, }; }); return mapping; }; export const getAaveV3ReserveTokenAddresses = async (provider: EthereumProvider, network: NetworkNumber, market: AaveMarketInfo): Promise => _getAaveV3ReserveTokenAddresses(getViemProvider(provider, network, { batch: { multicall: true } }), network, market); /** * Resolves the price oracle the market's addresses provider points at (at `block`, or latest). * Aave can rotate the oracle over time, so a caller hoisting one address across many historical * points must resolve it at both ends of its block range and only reuse it when the two agree — * otherwise leave `oracleAddress` unset on _getAaveV3HistoricalBalance and it resolves per block. */ export const _getAaveV3OracleAddress = async (provider: Client, network: NetworkNumber, market: AaveMarketInfo, block: Blockish = 'latest'): Promise => { // @ts-ignore market.provider is a valid config key at runtime const providerAbi = getConfigContractAbi(market.provider, network); // @ts-ignore readContract exists on the public client returned by getViemProvider const oracleAddress = await provider.readContract({ address: market.providerAddress as EthAddress, abi: providerAbi as any, functionName: 'getPriceOracle', ...setViemBlockNumber(block), }); if (!oracleAddress) throw new Error(`AaveV3 oracle unavailable at block ${block}`); return oracleAddress as EthAddress; }; export const getAaveV3OracleAddress = async (provider: EthereumProvider, network: NetworkNumber, market: AaveMarketInfo, block: Blockish = 'latest'): Promise => _getAaveV3OracleAddress(getViemProvider(provider, network, { batch: { multicall: true } }), network, market, block); type AaveV3ReserveTokenEntry = AaveV3ReserveTokenAddresses[string]; type AaveV3ActiveHistoricalAsset = AaveV3ReserveTokenEntry & { supplied: string, debt: string }; // raw getAssetPrice multicall result per asset symbol type AaveV3PriceResultsBySymbol = Record; // supply = aToken.balanceOf, debt = variableDebtToken.balanceOf + stableDebtToken.balanceOf — three reads per reserve const getHistoricalBalanceContracts = (entries: AaveV3ReserveTokenEntry[], address: EthAddress) => { const erc20Abi = getConfigContractAbi('Erc20'); return entries.flatMap((e) => ([ { address: e.aTokenAddress, abi: erc20Abi, functionName: 'balanceOf', args: [address], }, { address: e.variableDebtTokenAddress, abi: erc20Abi, functionName: 'balanceOf', args: [address], }, { address: e.stableDebtTokenAddress, abi: erc20Abi, functionName: 'balanceOf', args: [address], }, ])); }; const getAssetPriceContract = (oracle: EthAddress, underlyingAddress: EthAddress) => ({ address: oracle, abi: AAVE_ORACLE_ABI, functionName: 'getAssetPrice', args: [underlyingAddress], }); /** * Pairs each reserve with its three balance reads and keeps the assets the wallet actually held. * Throws when every read failed — a totally failed fetch must not masquerade as a real $0 balance, * so the caller can distinguish "fetch failed" (gap) from "position was empty" (genuine 0). */ const toActiveHistoricalAssets = (entries: AaveV3ReserveTokenEntry[], balanceResults: any[], block: number): AaveV3ActiveHistoricalAsset[] => { const anyBalanceRead = balanceResults.some((r) => r?.status === 'success'); if (!anyBalanceRead) throw new Error(`AaveV3 historical balance: all balance reads failed at block ${block}`); return entries.map((e, i) => { const supplyRes = balanceResults[i * 3]; const varDebtRes = balanceResults[(i * 3) + 1]; const stableDebtRes = balanceResults[(i * 3) + 2]; const supplied = supplyRes?.status === 'success' ? (supplyRes.result as bigint).toString() : '0'; const varDebt = varDebtRes?.status === 'success' ? (varDebtRes.result as bigint).toString() : '0'; const stableDebt = stableDebtRes?.status === 'success' ? (stableDebtRes.result as bigint).toString() : '0'; const debt = new Dec(varDebt).add(stableDebt).toString(); return { ...e, supplied, debt }; }).filter((a) => a.supplied !== '0' || a.debt !== '0'); }; /** * Sums the active assets into the point's USD totals. Throws when every price read failed — the * oracle couldn't serve this block (pruned state, or a hoisted oracle that wasn't deployed yet back * then), and totalling it up anyway would return a fake near-$0 balance. A single asset's price * failure still just skips that asset, matching the live data path. */ const sumHistoricalUsd = (activeAssets: AaveV3ActiveHistoricalAsset[], priceResBySymbol: AaveV3PriceResultsBySymbol, block: number): AaveV3HistoricalBalance => { const anyPriceRead = activeAssets.some((a) => priceResBySymbol[a.symbol]?.status === 'success'); if (!anyPriceRead) throw new Error(`AaveV3 historical balance: all price reads failed at block ${block}`); let suppliedUsd = new Dec(0); let borrowedUsd = new Dec(0); activeAssets.forEach((a) => { const priceRes = priceResBySymbol[a.symbol]; if (priceRes?.status !== 'success') return; const priceUsd = new Dec((priceRes.result as bigint).toString()).div(1e8); // Aave v3 base currency is USD with 8 decimals if (a.supplied !== '0') suppliedUsd = suppliedUsd.add(new Dec(assetAmountInEth(a.supplied, a.symbol)).mul(priceUsd)); if (a.debt !== '0') borrowedUsd = borrowedUsd.add(new Dec(assetAmountInEth(a.debt, a.symbol)).mul(priceUsd)); }); return { block, suppliedUsd: suppliedUsd.toString(), borrowedUsd: borrowedUsd.toString(), netUsd: suppliedUsd.minus(borrowedUsd).toString(), }; }; /** * Fast path, ONE multicall: balances plus a price read for every reserve through the caller-hoisted * oracle. Prices are read for all reserves because which assets are active isn't known until the * balances come back — extra reads inside an already-paid multicall are nearly free. */ const fetchHistoricalPointWithOracle = async (provider: Client, entries: AaveV3ReserveTokenEntry[], address: EthAddress, block: number, oracleAddress: EthAddress) => { const balanceContracts = getHistoricalBalanceContracts(entries, address); const priceContracts = entries.map((e) => getAssetPriceContract(oracleAddress, e.underlyingAddress)); // @ts-ignore const results = await provider.multicall({ contracts: [...balanceContracts, ...priceContracts], allowFailure: true, blockNumber: BigInt(block), batchSize: HISTORICAL_MULTICALL_BATCH_SIZE, }); const activeAssets = toActiveHistoricalAssets(entries, results.slice(0, balanceContracts.length), block); const priceResBySymbol: AaveV3PriceResultsBySymbol = {}; results.slice(balanceContracts.length).forEach((res: any, i: number) => { priceResBySymbol[entries[i].symbol] = res; }); return { activeAssets, priceResBySymbol }; }; /** * Fallback path, TWO multicalls: balances plus getPriceOracle (resolving the oracle that was active * AT the block — Aave can rotate it over time), then prices for just the active assets. The oracle * read has no fallback: if it fails (bad archive node, rate limit, ...) the failure must surface * rather than silently returning $0 — the caller renders a gap instead of a misleading zero. */ const fetchHistoricalPointResolvingOracle = async (provider: Client, network: NetworkNumber, market: AaveMarketInfo, entries: AaveV3ReserveTokenEntry[], address: EthAddress, block: number) => { const balanceContracts = getHistoricalBalanceContracts(entries, address); // @ts-ignore market.provider is a valid config key at runtime const providerAbi = getConfigContractAbi(market.provider, network); const oracleContract = { address: market.providerAddress as EthAddress, abi: providerAbi, functionName: 'getPriceOracle', }; const blockNumber = BigInt(block); // @ts-ignore const results = await provider.multicall({ contracts: [...balanceContracts, oracleContract], allowFailure: true, blockNumber, batchSize: HISTORICAL_MULTICALL_BATCH_SIZE, }); const oracleRes = results[balanceContracts.length]; if (oracleRes?.status !== 'success' || !oracleRes.result) throw new Error(`AaveV3 historical balance: oracle unavailable at block ${block}`); const activeAssets = toActiveHistoricalAssets(entries, results.slice(0, balanceContracts.length), block); if (!activeAssets.length) return { activeAssets, priceResBySymbol: {} }; const priceContracts = activeAssets.map((a) => getAssetPriceContract(oracleRes.result as EthAddress, a.underlyingAddress)); // @ts-ignore const priceResults = await provider.multicall({ contracts: priceContracts, allowFailure: true, blockNumber, batchSize: HISTORICAL_MULTICALL_BATCH_SIZE, }); const priceResBySymbol: AaveV3PriceResultsBySymbol = {}; priceResults.forEach((res: any, i: number) => { priceResBySymbol[activeAssets[i].symbol] = res; }); return { activeAssets, priceResBySymbol }; }; /** * Computes a user's Aave v3 net USD balance (supplied collateral - borrowed debt) at a historical block, * without touching the AaveV3View contract. Pass `reserveTokens` (from getAaveV3ReserveTokenAddresses) * to avoid refetching token addresses for every point, and `oracleAddress` (from getAaveV3OracleAddress, * verified identical at both ends of the sampled range) to collapse the point into a single multicall — * with it the balances and all prices ride one request; without it the oracle is resolved at the block * inside the balance multicall and the active assets are priced in a second one. */ export const _getAaveV3HistoricalBalance = async ( provider: Client, network: NetworkNumber, market: AaveMarketInfo, address: EthAddress, block: number, reserveTokens?: AaveV3ReserveTokenAddresses, oracleAddress?: EthAddress, ): Promise => { const empty: AaveV3HistoricalBalance = { block, suppliedUsd: '0', borrowedUsd: '0', netUsd: '0', }; if (!address) return empty; const tokens = reserveTokens || await _getAaveV3ReserveTokenAddresses(provider, network, market); const entries = Object.values(tokens); if (!entries.length) return empty; const { activeAssets, priceResBySymbol } = oracleAddress ? await fetchHistoricalPointWithOracle(provider, entries, address, block, oracleAddress) : await fetchHistoricalPointResolvingOracle(provider, network, market, entries, address, block); if (!activeAssets.length) return empty; return sumHistoricalUsd(activeAssets, priceResBySymbol, block); }; export const getAaveV3HistoricalBalance = async ( provider: EthereumProvider, network: NetworkNumber, market: AaveMarketInfo, address: EthAddress, block: number, reserveTokens?: AaveV3ReserveTokenAddresses, oracleAddress?: EthAddress, ): Promise => _getAaveV3HistoricalBalance(getViemProvider(provider, network, { batch: { multicall: true } }), network, market, address, block, reserveTokens, oracleAddress); export const _getAaveV3AccountData = async (provider: Client, network: NetworkNumber, address: EthAddress, extractedState: any, blockNumber: 'latest' | number = 'latest'): Promise => { const { selectedMarket: market, assetsData, eModeCategoriesData, } = extractedState; let payload: AaveV3PositionData = { ...EMPTY_AAVE_DATA, lastUpdated: Date.now(), }; if (!address) { return payload; } const loanInfoContract = AaveV3ViewContractViem(provider, network); const lendingPoolContract = createViemContractFromConfigFunc(market.lendingPool, market.lendingPoolAddress)(provider, network); const marketAddress = market.providerAddress; const _addresses = market.assets.map((a: string) => getAssetInfo(getWrappedNativeAssetFromUnwrapped(a), network).address); const middleAddressIndex = Math.floor(_addresses.length / 2); // split addresses in half to avoid gas limit by multicall const [eModeCategory, tokenBalances1, tokenBalances2] = await Promise.all([ lendingPoolContract.read.getUserEMode([address], setViemBlockNumber(blockNumber)), loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(0, middleAddressIndex) as EthAddress[]], setViemBlockNumber(blockNumber)), loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length) as EthAddress[]], setViemBlockNumber(blockNumber)), ]); const loanInfo = [...tokenBalances1, ...tokenBalances2]; const usedAssets = {} as AaveV3UsedAssets; loanInfo.map(async (tokenInfo, i) => { const asset = market.assets[i]; const isSupplied = tokenInfo.balance.toString() !== '0'; const isBorrowed = tokenInfo.borrowsStable.toString() !== '0' || tokenInfo.borrowsVariable.toString() !== '0'; if (!isSupplied && !isBorrowed) return; const supplied = assetAmountInEth(tokenInfo.balance.toString(), asset); const borrowedStable = assetAmountInEth(tokenInfo.borrowsStable.toString(), asset); const borrowedVariable = assetAmountInEth(tokenInfo.borrowsVariable.toString(), asset); const eModeCategoryData = eModeCategoriesData[+(eModeCategory as BigInt).toString()]; const usageAsCollateralIsEnabledInEmode = eModeCategoryData?.collateralAssets.includes(asset); const enabledAsCollateral = (assetsData[asset].usageAsCollateralEnabled || usageAsCollateralIsEnabledInEmode) ? tokenInfo.enabledAsCollateral : false; let interestMode; if (borrowedVariable === '0' && borrowedStable !== '0') { interestMode = '1'; } else if (borrowedVariable !== '0' && borrowedStable === '0') { interestMode = '2'; } else { interestMode = 'both'; } if (!usedAssets[asset]) usedAssets[asset] = {} as AaveV3UsedAsset; const borrowed = new Dec(borrowedStable).add(borrowedVariable).toString(); usedAssets[asset] = { ...usedAssets[asset], symbol: asset, supplied, suppliedUsd: new Dec(supplied).mul(assetsData[asset].price).toString(), isSupplied, collateral: enabledAsCollateral, stableBorrowRate: aprToApy(new Dec(tokenInfo.stableBorrowRate.toString()).div(1e25).toString()), borrowedStable, borrowedVariable, borrowedUsdStable: new Dec(borrowedStable).mul(assetsData[asset].price).toString(), borrowedUsdVariable: new Dec(borrowedVariable).mul(assetsData[asset].price).toString(), borrowed, borrowedUsd: new Dec(new Dec(borrowedVariable).add(borrowedStable)).mul(assetsData[asset].price).toString(), isBorrowed, interestMode, }; }); payload.eModeCategory = +(eModeCategory as BigInt).toString(); payload = { ...payload, usedAssets, ...aaveAnyGetAggregatedPositionData({ ...extractedState, usedAssets, eModeCategory: payload.eModeCategory, }), }; payload.eModeCategories = aaveV3EmodeCategoriesMapping(extractedState, usedAssets); payload.isInIsolationMode = aaveV3IsInIsolationMode({ usedAssets, assetsData }); payload.isInSiloedMode = aaveV3IsInSiloedMode({ usedAssets, assetsData }); payload.ratio = payload.borrowedUsd && payload.borrowedUsd !== '0' ? new Dec(payload.borrowLimitUsd).div(payload.borrowedUsd).mul(100).toString() : '0'; payload.minRatio = '100'; payload.collRatio = payload.borrowedUsd && payload.borrowedUsd !== '0' ? new Dec(payload.suppliedCollateralUsd).div(payload.borrowedUsd).mul(100).toString() : '0'; // Calculate borrow limits per asset Object.values(payload.usedAssets).forEach((item) => { if (item.isBorrowed) { // eslint-disable-next-line no-param-reassign item.stableLimit = calculateBorrowingAssetLimit(item.borrowedUsdStable, payload.borrowLimitUsd); // eslint-disable-next-line no-param-reassign item.variableLimit = calculateBorrowingAssetLimit(item.borrowedUsdVariable, payload.borrowLimitUsd); // eslint-disable-next-line no-param-reassign item.limit = calculateBorrowingAssetLimit(item.borrowedUsd, payload.borrowLimitUsd); } }); payload.isSubscribedToAutomation = false; payload.automationResubscribeRequired = false; return payload; }; export const getAaveV3AccountData = async (provider: EthereumProvider, network: NetworkNumber, address: EthAddress, extractedState: any, blockNumber: 'latest' | number = 'latest'): Promise => _getAaveV3AccountData(getViemProvider(provider, network), network, address, extractedState, blockNumber); export const getAaveV3FullPositionData = async (provider: EthereumProvider, network: NetworkNumber, address: EthAddress, market: AaveMarketInfo): Promise => { const marketData = await getAaveV3MarketData(provider, network, market); const positionData = await getAaveV3AccountData(provider, network, address, { assetsData: marketData.assetsData, selectedMarket: market, eModeCategoriesData: marketData.eModeCategoriesData }); return positionData; }; // aTokens eligible for AAVE rewards export const REWARDABLE_ASSETS = [ '0x028171bCA77440897B824Ca71D1c56caC55b68A3', // DAI '0x6C3c78838c761c6Ac7bE9F59fe808ea2A6E4379d', '0xD37EE7e4f452C6638c96536e68090De8cBcdb583', // GUSD '0x279AF5b99540c1A3A7E3CDd326e19659401eF99e', '0xBcca60bB61934080951369a648Fb03DF4F96263C', // USDC '0x619beb58998eD2278e08620f97007e1116D5D25b', '0x3Ed3B47Dd13EC9a98b44e6204A523E766B225811', // USDT '0x531842cEbbdD378f8ee36D171d6cC9C4fcf475Ec', '0x9ff58f4fFB29fA2266Ab25e75e2A8b3503311656', // WBTC '0x9c39809Dec7F95F5e0713634a4D0701329B3b4d2', '0x030bA81f1c18d280636F32af80b9AAd02Cf0854e', // WETH '0xF63B34710400CAd3e044cFfDcAb00a0f32E33eCf', '0xa06bC25B5805d5F8d82847D191Cb4Af5A3e873E0', // LINK '0x0b8f12b1788BFdE65Aa1ca52E3e9F3Ba401be16D', '0x6C5024Cd4F8A59110119C56f8933403A539555EB', // SUSD '0xdC6a3Ab17299D9C2A412B0e0a4C1f55446AE0817', '0x5165d24277cD063F5ac44Efd447B27025e888f37', // YFI '0x7EbD09022Be45AD993BAA1CEc61166Fcc8644d97', '0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a', // xSUSHI '0xfAFEDF95E21184E3d880bd56D4806c4b8d31c69A', '0xB9D7CB55f463405CDfBe4E90a6D2Df01C2B92BF1', // UNI '0x5BdB050A92CADcCfCDcCCBFC17204a1C9cC0Ab73', '0xc713e5E149D5D0715DcD1c156a020976e7E56B88', // MKR '0xba728eAd5e496BE00DCF66F650b6d7758eCB50f8', '0x101cc05f4A51C0319f570d5E146a8C625198e636', // TUSD '0x01C0eb1f8c6F1C1bF74ae028697ce7AA2a8b0E92', '0xc9BC48c72154ef3e5425641a3c747242112a46AF', // RAI '0xB5385132EE8321977FfF44b60cDE9fE9AB0B4e6b', '0x272F97b7a56a387aE942350bBC7Df5700f8a4576', // BAL '0x13210D4Fe0d5402bd7Ecbc4B5bC5cFcA3b71adB0', '0x2e8f4bdbe3d47d7d7de490437aea9915d930f1a3', // USDP '0xfdb93b3b10936cf81fa59a02a7523b6e2149b2b7', '0xA361718326c15715591c299427c62086F69923D9', // BUSD '0xbA429f7011c9fa04cDd46a2Da24dc0FF0aC6099c', '0xd4937682df3C8aEF4FE912A96A74121C0829E664', // FRAX '0xfE8F19B17fFeF0fDbfe2671F248903055AFAA8Ca', '0x683923dB55Fead99A79Fa01A27EeC3cB19679cC3', // FEI '0xC2e10006AccAb7B45D9184FcF5b7EC7763f5BaAe', '0x8dAE6Cb04688C62d939ed9B68d32Bc62e49970b1', // CRV '0x00ad8eBF64F141f1C81e9f8f792d3d1631c6c684', '0x6F634c6135D2EBD550000ac92F494F9CB8183dAe', // DPI '0x4dDff5885a67E4EffeC55875a3977D7E60F82ae0', ] as const; export const fetchYearlyMeritApyForStakingGho = async () => { try { const response = await fetch('https://apps.aavechan.com/api/merit/aprs', { signal: AbortSignal.timeout(5000) }); const data = await response.json(); const apr = data?.currentAPR?.actionsAPR?.['ethereum-stkgho'] || '0' as string; const apy = aprToApy(apr); const apyWithDFSBonus = new Dec(apy).mul(1.05).toString(); // 5% bonus for DFS users return apyWithDFSBonus; } catch (e) { const message = 'External API Failure: Failed to fetch yearly merit APY for staking GHO'; console.error(message, e); return '0'; } }; export const getStakeAaveData = async (provider: Client, network: NetworkNumber, address: EthAddress): Promise => { const stkGhoAddress = getAssetInfo('stkGHO').address as HexString; const stkAaveAddress = getAssetInfo('stkAAVE').address as HexString; const AaveIncentivesController = AaveIncentivesControllerViem(provider, network); const stkAAVE = StkAAVEViem(provider, network); const stkGHO = createViemContractFromConfigFunc('Erc20', stkGhoAddress as HexString)(provider, network); const [aaveRewardsBalance, emissionsPerSecond, stkAAVEBalance, stkAAVETotalSupply, stkGHOBalance, ghoMeritApy, sgho] = await Promise.all([ AaveIncentivesController.read.getRewardsBalance([REWARDABLE_ASSETS, address]), stkAAVE.read.assets([stkAaveAddress]), stkAAVE.read.balanceOf([address]), stkAAVE.read.totalSupply(), stkGHO.read.balanceOf([address]), fetchYearlyMeritApyForStakingGho(), getSghoData(network, address), ]); const stkAaveApy = new Dec(assetAmountInEth(emissionsPerSecond[0].toString(), 'GHO') || 0).mul(SECONDS_PER_YEAR).mul(100).div(assetAmountInEth(stkAAVETotalSupply.toString(), 'stkAAVE')) .toString(); return { activatedCooldown: '0', activatedCooldownAmount: '0', stkAaveRewardsBalance: '0', aaveRewardsBalance: assetAmountInEth(aaveRewardsBalance.toString(), 'AAVE'), stkAaveBalance: assetAmountInEth(stkAAVEBalance.toString(), 'stkAAVE'), stkGhoBalance: assetAmountInEth(stkGHOBalance.toString(), 'GHO'), ghoMeritApy, stkAaveApy, sgho, }; }; export { getMeritCampaigns, getMerkleCampaigns, }; export { getSghoData } from './sgho'; export type { SghoData, SghoUserData } from './sgho';