/ src / utils / getMaxAmountAvailableToSupply.ts
getMaxAmountAvailableToSupply.ts
 1  import { API_ETH_MOCK_ADDRESS } from '@aave/contract-helpers';
 2  import { valueToBigNumber } from '@aave/math-utils';
 3  import { BigNumber } from 'bignumber.js';
 4  
 5  import { roundToTokenDecimals } from './utils';
 6  
 7  // Subset of ComputedReserveData
 8  interface PoolReserveSupplySubset {
 9    supplyCap: string;
10    debtCeiling: string;
11    isolationModeTotalDebt: string;
12    totalLiquidity: string;
13    isFrozen: boolean;
14    decimals: number;
15  }
16  
17  export function remainingCap(cap: string, total: string) {
18    return cap === '0' ? new BigNumber(-1) : new BigNumber(cap).minus(total);
19  }
20  
21  export function getMaxAmountAvailableToSupply(
22    walletBalance: string,
23    poolReserve: PoolReserveSupplySubset,
24    underlyingAsset: string,
25    minRemainingBaseToken: string
26  ): string {
27    if (poolReserve.isFrozen) {
28      return '0';
29    }
30  
31    // Calculate max amount to supply
32    let maxAmountToSupply = valueToBigNumber(walletBalance);
33  
34    // keep a bit for other transactions
35    if (
36      maxAmountToSupply.gt(0) &&
37      underlyingAsset.toLowerCase() === API_ETH_MOCK_ADDRESS.toLowerCase()
38    ) {
39      maxAmountToSupply = maxAmountToSupply.minus(minRemainingBaseToken);
40    }
41  
42    // make sure we don't try to supply more then maximum supply cap
43    if (poolReserve.supplyCap !== '0') {
44      maxAmountToSupply = BigNumber.min(
45        maxAmountToSupply,
46        remainingCap(poolReserve.supplyCap, poolReserve.totalLiquidity)
47      );
48    }
49  
50    if (maxAmountToSupply.lte(0)) {
51      return '0';
52    }
53  
54    // Convert amount to smallest allowed precision based on token decimals
55    return roundToTokenDecimals(maxAmountToSupply.toString(10), poolReserve.decimals);
56  }