# .updateState

## TLDR

The updateState function serves to update the interest and indexes within the system for a specific asset.

### Code

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2FQtY53vuJMkDqRVSHqBr4%2Fimage.png?alt=media&#x26;token=1d0e8109-c159-43af-86ec-a83d19c0f98f" alt=""><figcaption></figcaption></figure>

If state has been updated within the same block in a previous transaction, do nothing. \
Else this function does two things:

1. **\_updateIndexes** => updates Indexes: `nextLiquidityIndex`, `nextVariableBorrowIndex`
2. **\_accrueToTreasury** => updates Treasury accrual&#x20;
3. updates **`reserve.lastUpdateTimestamp`** to current block.timestamp

{% hint style="info" %}
On time

* `.cache` assigns **`reserveCache.reserveLastUpdateTimestamp`** = `reserve.lastUpdateTimestamp`
* `.updateState` updates **`reserve.lastUpdateTimestamp`** to latest
  {% endhint %}

## &#x20;`_updateIndexes`&#x20;

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2FkLYf2XtaFhWHobSBsC7J%2Fimage.png?alt=media&#x26;token=c77da090-a546-4648-ab6d-4ff3eeba1eca" alt=""><figcaption></figcaption></figure>

Updates `nextliquidityIndex` by the way of `calculateLinearInterest`, and updates `nextVariableBorrowIndex` by the way of `calculateCompoundInterest`.

* supply interest is accrued via linear interest (simple interest)
* borrow interest is accrued via compound interest&#x20;

### `calculateLinearInterest`

Calculates linear interest accrued from `lastUpdateTimeStamp` till current `block.timestamp`.

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2FI0ZgTzVoeipBHlq8Pes1%2Fimage.png?alt=media&#x26;token=1228bbaa-fbe4-4106-a342-114f53d430e8" alt=""><figcaption></figcaption></figure>

* serves to update deposit interest and liquidity index
* explanation: [deposit-interest](https://calnix.gitbook.io/aave-book/deposit-and-borrow-interest#deposit-interest)

### `calculateCompoundInterest`

Calculates interest accrued from `lastUpdateTimeStamp` till current `block.timestamp`.&#x20;

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2FGro0d9WgWSdIUPnnv7M5%2Fimage.png?alt=media&#x26;token=4f4460c3-a363-499b-993d-ca3a6237c381" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2FTTFXZ0VNa9VqGrcymEVq%2Fimage.png?alt=media&#x26;token=d0eea838-5343-43a7-843c-31fe2f2ebbba" alt=""><figcaption></figcaption></figure>

* interest is compounded every second&#x20;
* serves to update variable borrow interest and variable borrow index
* explanation: [borrow-interest](https://calnix.gitbook.io/aave-book/deposit-and-borrow-interest#borrow-interest)

## **\_accrueToTreasury**&#x20;

A portion of repaid borrow interest goes to Aave's treasury; the rest is paid out to suppliers. This portion is determined by the reserve factor: : % of borrow rate that goes to Treasury.

* `reserve.accruedToTreasury` represents the treasury's cut of repaid interest to date.
* `_accrueToTreasury` serves to increment this value, by accounting for unbooked interest.
* Unbooked interest: interest accrued from the last update till now.
* Last update: `reserveCache.reserveLastUpdateTimestamp`&#x20;

{% hint style="info" %}

* Treasury accrues funds in aTokens.
* While `accruedToTreasury` is incremented, the tokens are not minted; that happens when `mintToTreasury` is called.
  {% endhint %}

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2FpI40BPZj9GbUeS3gymYW%2Fimage.png?alt=media&#x26;token=00abcc4a-e152-4a5c-b6f4-1ba116125ccf" alt=""><figcaption></figcaption></figure>

In a nutshell, the function calculates the "new debt" accumulated from `lastUpdateTimestamp`  till now, and applies the reserve factor upon - accounting for the treasury's portion.&#x20;

* "new debt" comprises of both variable and stable components&#x20;

### Unbooked variable debt&#x20;

For variable debt, the increase is accounted for by the delta between curr and next indexes:

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2FUVnQ89ulHMVlprSbFY6j%2Fimage.png?alt=media&#x26;token=4251e9a0-5650-4f52-9e25-5e6ee0bed01e" alt=""><figcaption></figcaption></figure>

* `nextVariableBorrowIndex` will account for interest accrued up till now
* `currVariableBorrowIndex` will account for interest accrued up till `lastUpdateTimestamp` &#x20;

Essentially,

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2FmMHom7uLRjnqBfxjIV46%2Fimage.png?alt=media&#x26;token=286caaad-a2d8-45cb-b2d1-fa5d557b655a" alt=""><figcaption></figcaption></figure>

**The difference gives us the delta of variable debt since `lastUpdateTimestamp`.**

### Unbooked stable debt&#x20;

The approach here has to be different simply because there is no index for stable debt.

First, let's isolate the sections of code for calculating unbooked stable debt.&#x20;

{% code title="calculated in .cache:" %}

```solidity
// from getSupplyData():
reserveCache.currTotalStableDebt = _calcTotalSupply(avgRate)
reserveCache.stableDebtLastUpdateTimestamp = _totalSupplyTimestamp
```

{% endcode %}

{% code title="from \_accrueToTreasury:" %}

```solidity
//calculate the stable debt from stableDebtLastUpdateTimestamp 
//until reserveLastUpdateTimestamp
vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest(
  reserveCache.currAvgStableBorrowRate,
  reserveCache.stableDebtLastUpdateTimestamp,
  reserveCache.reserveLastUpdateTimestamp
);

//prevTotalStableDebt = currPrincipalStableDebt * cumulatedStableInterest
vars.prevTotalStableDebt = 
reserveCache.currPrincipalStableDebt.rayMul(vars.cumulatedStableInterest);

// to find unbooked component
currTotalStableDebt - prevTotalStableDebt
```

{% endcode %}

**`currTotalStableDebt`** - **`prevTotalStableDebt`** gives us interest accrued from `reserveLastUpdateTimestamp` till now.

* **`currTotalStableDebt:`** accounts for interest from `_totalSupplyTimestamp` till now
* **`prevTotalStableDebt:`** accounts for interest from `stableDebtLastUpdateTimestamp` to `reserveLastUpdateTimestamp`

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2Fyi0EH5FXUUvaRs62zVMw%2Fimage.png?alt=media&#x26;token=f29bc801-a48e-459d-b2fd-8eddc0f6df39" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
`stableDebtLastUpdateTimestamp == _totalSupplyTimestamp`

* assigned via [`getSupplyData`](https://calnix.gitbook.io/aave-book/contracts/stabledebttoken#getsupplydata) in [`.cache`](https://calnix.gitbook.io/aave-book/functions/common-functions/.cache)
* `_totalSupplyTimestamp is updated during` [`mint`](https://calnix.gitbook.io/aave-book/contracts/stabledebttoken#mint)`/burn`
  {% endhint %}

**Why can't we simply calculate interest from `reserveLastUpdateTimestamp`, similar to variable debt?**

* `reserveLastUpdateTimestamp` **>=** `_totalSupplyTimestamp`
* **`_totalSupplyTimestamp`** is only updated when mint/burn of the stableDebtToken is called.&#x20;
* **`reserveLastUpdateTimestamp`** is updated in `.updateState`, which is called in every state-changing function.

Given how often that that happens,**`reserveLastUpdateTimestamp`** is updated far more frequently, while **`_totalSupplyTimestamp`** is likely to be 'stale'.&#x20;

{% hint style="warning" %}
Why ignore stable debt accrued from **`_totalSupplyTimestamp`**` ``to`` `**`reserveLastUpdateTimestamp` ?**
{% endhint %}

### **Putting it together**&#x20;

* Paid to treasury = `amountToMint` =`totalDebtAccrued * reserveFactor`

If `amountToMint` is a non-zero value, `reserve.accruedToTreasury` is incremented by: `amountToMint / nextLiquidityIndex`&#x20;

This scales against the most recent index; similar to how deposits are scaled.

## Visual Aid

<img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2Ffm95u90BbdzR3f7FNM7W%2Ffile.excalidraw.svg?alt=media&#x26;token=345712a5-a507-436a-9a2a-08c2af1ae5ee" alt="" class="gitbook-drawing">
