> For the complete documentation index, see [llms.txt](https://calnix.gitbook.io/aave-book/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://calnix.gitbook.io/aave-book/functions/common-functions/.cache.md).

# .cache

## TLDR

The cache function creates a cached copy of struct `ReservesData` in memory, as `reserveCache` to avoid repeated calls to storage which are expensive.&#x20;

Essentially, `reserveCache` will serve as the working copy within which data will be modified and updated through the course of execution.

* Caches `ReserveData` into `ReserveCache` struct
* `ReserveData` exists in storage, `ReserveCache` exist in memory
* Read/Write calls to memory are cheaper than storage

<details>

<summary>ReserveData (DataTypes.sol)</summary>

```solidity
  struct ReserveData {
    //stores the reserve configuration
    ReserveConfigurationMap configuration;
    //the liquidity index. Expressed in ray
    uint128 liquidityIndex;
    //the current supply rate. Expressed in ray
    uint128 currentLiquidityRate;
    //variable borrow index. Expressed in ray
    uint128 variableBorrowIndex;
    //the current variable borrow rate. Expressed in ray
    uint128 currentVariableBorrowRate;
    //the current stable borrow rate. Expressed in ray
    uint128 currentStableBorrowRate;
    //timestamp of last update
    uint40 lastUpdateTimestamp;
    //the id of the reserve. Represents the position in the list of the active reserves
    uint16 id;
    //aToken address
    address aTokenAddress;
    //stableDebtToken address
    address stableDebtTokenAddress;
    //variableDebtToken address
    address variableDebtTokenAddress;
    //address of the interest rate strategy
    address interestRateStrategyAddress;
    //the current treasury balance, scaled
    uint128 accruedToTreasury;
    //the outstanding unbacked aTokens minted through the bridging feature
    uint128 unbacked;
    //the outstanding debt borrowed against this asset in isolation mode
    uint128 isolationModeTotalDebt;
  }
```

</details>

<details>

<summary>ReserveCache (DataTypes.sol)</summary>

![](https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2F4askqNcOYPj2M2g6WmA2%2Fimage.png?alt=media\&token=74f8a520-b606-40a8-bba1-0b9a36a67376)

</details>

* Each reserve (asset) in Aave has its own unique configuration, rates, indexes, and token contracts (aToken and other debt tokens).
* For each reserve, this data is captured within a struct `ReserveData`. These structs are accessed via the mapping  `_reserves`, which maps the asset address to its corresponding `ReserveData`.
* `_reserves` is defined on PoolStorage.sol which is inherited by Pool.sol

{% code title="PoolStorage.sol" %}

```solidity
// Map of reserves and their data (underlyingAssetOfReserve => reserveData)
  mapping(address => DataTypes.ReserveData) internal _reserves;
```

{% endcode %}

### Caching reserve into reserveCache

.cache serves to map the data held within `reserve` onto `reserveCache`, by unpacking and through some calculations.

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2FDX9UhlCLuAsdcg1rUoHx%2Fimage.png?alt=media&amp;token=b7f5b11b-db59-43cf-84f8-67284412f630" alt=""><figcaption><p>reserveData -> reserveCache</p></figcaption></figure>

```solidity
// reservesData is PoolStorage::_reserves
DataTypes.ReserveData storage reserve = reservesData[params.asset];
DataTypes.ReserveCache memory reserveCache = reserve.cache();
```

{% hint style="info" %}
ReserveData variables NOT cached:

* id&#x20;
* aTokenAddress&#x20;
* interestRateStrategyAddress&#x20;
* accruedToTreasury&#x20;
* unbacked&#x20;
* isolationModeTotalDebt
  {% endhint %}

## Code

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2Fkbl59bHw9Ad6Qh04u9Ke%2Fimage.png?alt=media&amp;token=99ef018b-25af-45be-88f1-2a7b137449da" alt=""><figcaption></figcaption></figure>

### 1. Get ReserveConfigurationMap reserveConfiguration&#x20;

```solidity
reserveCache.reserveConfiguration = reserve.configuration;
```

* simply copies `reserveConfigurationMap` from storage to memory &#x20;

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2FHkbZX2xtccTPDMgUz2eq%2Fimage.png?alt=media&amp;token=9f8334d9-6967-46eb-9906-38395770b3f2" alt=""><figcaption></figcaption></figure>

### 2. Get reserveFactor

The value of `reserveFactor` is obtained by passing `reserveConfiguration`, obtained earlier, into function `getReserveFactor`.&#x20;

```solidity
reserveCache.reserveFactor = reserveCache.reserveConfiguration.getReserveFactor();
```

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2Fnek2DnoTiwMhdp1WYMzQ%2Fimage.png?alt=media&amp;token=010e2343-ed12-4099-afe4-1473e1490926" alt=""><figcaption></figcaption></figure>

The `reserveFactor`, amongst other data, is stored within `ReserveConfigurationMap`, which is a bitmap. See [getReserveFactor](/aave-book/functions/common-functions/getreservefactor-getdecimals.md#getreservefactor) for in-depth explanation.

{% hint style="info" %}
The reserve factor is a percentage of protocol interest which goes to the Aave Ecosystem Reserve. The rest of the borrow interest goes to the suppliers.
{% endhint %}

### 3 - 4. Get indexes: current and next

3. `currLiquidityIndex` and `nextLiquidityIndex`

<pre class="language-solidity" data-overflow="wrap" data-full-width="false"><code class="lang-solidity"><strong>reserveCache.currLiquidityIndex = reserveCache.nextLiquidityIndex = reserve.liquidityIndex;
</strong></code></pre>

4. `currVariableBorrowIndex` and `nextVariableBorrowIndex`

```solidity
reserveCache.currVariableBorrowIndex = reserveCache.nextVariableBorrowIndex 
= reserve.variableBorrowIndex;
```

* reserve.liquidityIndex is the value of the supply index, as per the last time [updateState](/aave-book/functions/common-functions/.updatestate.md#_updateindexes) was ran previously. Similarly, reserve.variableBorrowIndex.&#x20;
* `nextLiquidityIndex and nextVariableBorrowIndex`  will be updated in [updateState](/aave-book/functions/common-functions/.updatestate.md#_updateindexes), to reflect interest accruel till current block.timestamp.

{% hint style="info" %}
Having both next and current indexes allows us to compare interest deltas and the like.&#x20;
{% endhint %}

### 5 - 6. Get rates: `currLiquidityRate` & `currVariableBorrowRate`

```solidity
reserveCache.currLiquidityRate = reserve.currentLiquidityRate;
reserveCache.currVariableBorrowRate = reserve.currentVariableBorrowRate;
```

* `currentLiquidityRate`: current supply rate
* `currentVariableBorrowRate`: current variable borrow rate

{% hint style="info" %}
Both reserve.currentLiquidityRate and reserve.currentVariableBorrowRate are updated each time [.updateInterestRates](/aave-book/functions/common-functions/.updateinterestrates.md) is executed.
{% endhint %}

### 7-10. Token Addresses

```solidity
    reserveCache.aTokenAddress = reserve.aTokenAddress;
    reserveCache.stableDebtTokenAddress = reserve.stableDebtTokenAddress;
    reserveCache.variableDebtTokenAddress = reserve.variableDebtTokenAddress;

    reserveCache.reserveLastUpdateTimestamp = reserve.lastUpdateTimestamp;
```

Values are obtained as follows:

| ReserveData              | ReserveCache               |
| ------------------------ | -------------------------- |
| aTokenAddress            | aTokenAddress              |
| stableDebtTokenAddress   | stableDebtTokenAddress     |
| variableDebtTokenAddress | variableDebtTokenAddress   |
| lastUpdateTimeStamp      | reserveLastUpdateTimeStamp |

{% hint style="info" %}
reserve.lastUpdateTimestamp is updated each time .[updateState](/aave-book/functions/common-functions/.updatestate.md) is executed.
{% endhint %}

### 11. Get `currScaledVariableDebt` & `nextScaledVariableDebt`

{% code overflow="wrap" %}

```solidity
reserveCache.currScaledVariableDebt = reserveCache.nextScaledVariableDebt = IVariableDebtToken(reserveCache.variableDebtTokenAddress).scaledTotalSupply();
```

{% endcode %}

* returns scaled variable debt
* actual variable debt can be obtained by: `scaledBalance * variableBorrowIndex`

### 12. Get `currPrincipalStableDebt`, `currAvgStableBorrowRate`, `currTotalStableDebt`

```solidity
    (
      reserveCache.currPrincipalStableDebt,
      reserveCache.currTotalStableDebt,
      reserveCache.currAvgStableBorrowRate,
      reserveCache.stableDebtLastUpdateTimestamp
    ) = IStableDebtToken(reserveCache.stableDebtTokenAddress).getSupplyData();
```

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2FXaMaSl4NxVRIecTQSeQH%2Fimage.png?alt=media&amp;token=f1fd5b61-234f-4db8-a7c2-9331a50fc2aa" alt=""><figcaption><p><code>getSupplyData()</code></p></figcaption></figure>

**`currPrincipalStableDebt = super.totalSupply() = _totalSupply`**

* Reflects total stable debt, accounting for interest accrued from inception till \_totalSupplyTimestamp.
* Does not account for interest accrued from \_totalSupplyTimestamp to now.

**`currTotalStableDebt = _calcTotalSupply(avgRate)`**

* Calculates total stable debt, accounting for interest accrued to date.

**`currAvgStableBorrowRate = _avgStableRate`**

* weighted global average rate, calculated across all stable borrows

**`stableDebtLastUpdateTimestamp = _totalSupplyTimestamp`**&#x20;

* Timestamp of the last update of \_totalSupply

{% hint style="info" %}
See [getSupplyData](/aave-book/contracts/stabledebttoken.md#getsupplydata) for detailed explanations
{% endhint %}

### 13. Get next`AvgStableBorrowRate, nextTotalStableDebt`

```solidity
reserveCache.nextTotalStableDebt = reserveCache.currTotalStableDebt;
reserveCache.nextAvgStableBorrowRate = reserveCache.currAvgStableBorrowRate;
```

* See [getSupplyData](/aave-book/contracts/stabledebttoken.md#getsupplydata) for detailed explanation
