---
# System prepended metadata

title: '*Survey of use of step-wise and continuous state updates*'

---

# *Survey of use of step-wise and continuous state updates*

Mechanically, state updates are the clockwork scaffolding of all Defi protocols. They are the cogs which turn the great wheel that moves billions of dollars of capital in the few seconds that each block is mined. So, it may be useful to disect and analyze how some of the largest protocols designed their cogs. 


## **Fuse**
<ins>*TLDR: Continuous Calculation Continous Distribution*</ins>
* Each Fule pool is essentially a fork of Compound. Uses *Comptroller* as its risk management layer to arbiter tx approval for interaction with fToken (instead of cToken).

### **Interest Calculations**:

On a per block basis, each function call updates the money market’s ***floating*** interest rates. 

Each time a transaction occurs, both the supply and borrow Interest Rate Index for the asset are updated to compound the interest since the prior index, using the interest for the period, denominated by r * t, calculated using a ***per-block*** interest rate.

$$
\text { Index }_{a, n}=\text { Index }_{a,(n-1)} *(1+r * t)
$$



Interest rates for each market update ***on any block*** in which the ***ratio*** of borrowed assets to supplied assets in the market has changed. 

Interest accrues to all suppliers and borrowers in a market when ***any Ethereum address*** interacts with the market’s ```fToken``` contract, calling one of these functions: ```mint```, ```redeem```, ```borrow```, or ```repay```. Successful execution of one of these functions triggers the ```accrueInterest``` method, which causes interest to be added to the underlying balance of ***every supplier and borrower*** in the market.

## State

Interest accrues for the ***current block***, as well as ***each prior block*** in which the ```accrueInterest``` method was not triggered (no user interacted with the fToken contract).

Interest compounds ***only*** during blocks in which the fToken contract has one of the aforementioned methods invoked.

*Example of supply interest accrual:*

Alice supplies 1 ETH to the Fuse protocol. At the time of supply, the ```supplyRatePerBlock``` is 37893605 Wei, or 0.000000000037893605 ETH per block. No one interacts with the fETHer contract for 3 Ethereum blocks. On the subsequent 4th block, Bob borrows some ETH. Alice’s underlying balance is now 1.000000000151574420 ETH (which is 37893605 Wei times 4 blocks, plus the original 1 ETH). Alice’s underlying ETH balance in subsequent blocks will have interest accrued based on the new value of 1.000000000151574420 ETH instead of the initial 1 ETH. 

```supplyRatePerBlock``` is used to project APY, although it is not constant.
#

```js
const onefTokenInUnderlying =
  exchangeRateCurrent / ((1 * 10) ^ (18 + underlyingDecimals - fTokenDecimals));
```

# **MIM**

<ins>*TLDR: Continuous Calculation Step-Wise Distribution*</ins>

Uses isolated lending markets with their own contracts (Kashi):

The main difference between Comp and Aave vs. Kashi, is that Kashi uses lending markets, and isolated risk markets, while Aave and Compound both **calculate risks globally**, such that the solvency of any token can affect the solvency of the whole platform. One important consequence of using isolated risk markets is that Kashi is able to allow any token to be listed. Another important consequence is that an elastic interest rate is used to incentivize liquidity in a certain range. Yet another consequence of lending markets and isolated risk markets is that Kashi’s oracles need to be **customizable** to provide price feeds for infinitely many tokens.

# **AAVEv**

<ins>*TLDR: Continuous Calculation Continous Distribution*</ins>

```aTokens``` are yield-generating tokens that are **minted** and **burnt** upon supply and withdraw of assets to Aave pool. 

The aTokens’ value is pegged to the value of the corresponding supplied asset at a 1:1 ratio and can be safely stored, transferred or traded. All yield collected by the aTokens’ reserves are distributed to aTokens’ holders directly by **continuously** increasing their wallet balance.

## State

LendingPool methods (deposit, withdraw, borrow, repay, liquidationCall) **updates the state** and cumulated liquidity index of the reserve once every block. AToken's balanceOf method returns the balance computed based on ```block.timestamp``` and ```liquidityIndex``` of the underlying reserve and hence, returns the most up to date balance of account, which includes principal + interest.


Liquidity rewards earned prior to the transfer of aToken are accrued by the user/address holding the aTokens originally. Though, all future liquidity rewards will be earned by the new recepient.

### Example:

Bob supplies 1,000 DAI to the Aave LendingPool, he will receive 1,000 aDAI (at 1:1 exchange rate).
Bob can see gis aDAI balance increasing right away.
Now, say a month later gis aDAI balance is 1,050. Bob could withdraw 1,050 DAI from LendingPool by burning 1050 aDAI.

# Compound

<ins>*TLDR: Continuous Calculation Continuous Distribution*</ins>

### Comptroller :

```compRate```  is an unsigned integer equal to the rate at which COMP is distrubted to suppliers or borrowers each block for all markets. 

```compSpeeds``` is a mapping of cToken addresses to an integer representing the rate of distribution per block (of COMP) based on a single market. 

### Claiming comp: 

Users may call ```claimComp``` at any moment to claim their accured COMP (can vary on condition):

``` 
// Claim all the COMP accrued by specific holders in specific markets for their supplies and/or borrows

function claimComp(address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers) public 
```

## Minting
 By minting cTokens, users (1) earn interest through the cToken's exchange rate, which increases in value relative to the underlying asset, and (2) gain the ability to use cTokens as collateral.
 
 Each cToken is convertible into an ever increasing quantity of the underlying asset, as interest accrues in the market. The exchange rate between a cToken and the underlying asset is equal to:

```exchangeRate = (getCash() + totalBorrows() - totalReserves()) / totalSupply()```

## State

*Compound.js (JavaScript SDK for Ethereum and the Compound Protocol):*

**Get Comp Accrued**
Gets the amount of COMP tokens accrued but not yet claimed by an address.
```async function () {
async function () {
  const acc = await Compound.comp.getCompAccrued('0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5');
  console.log('Accrued', acc);
})().catch(console.error);
```
**Claim Comp**
Creates a tx to claim accrued COMP for each user.
```const compound = new Compound(window.ethereum);
const compound = new Compound(window.ethereum);

(async function() {

  console.log('Claiming COMP...');
  const trx = await compound.claimComp();
  console.log('Ethers.js transaction object', trx);

})().catch(console.error);
```


https://github.com/compound-finance/compound-protocol/blob/4a8648ec0364d24c4ecfc7d6cae254f55030d65f/contracts/CToken.sol#L384

[compound protocol breakdown (updated recently)](https://docs.google.com/spreadsheets/d/1KTw1SM7dlEziW22PwOc69Vj7y8t-a108-pu_7Kbagxk/edit#gid=167502)

([compound speed calculation](https://docs.google.com/spreadsheets/d/1Meyl5eyU-Td6NfyL_jWSADR6etDRQc5-lCTmbnVg6eo/edit#gid=579891306))



A cToken's collateral factor can range from 0-90%, and represents the proportionate increase in liquidity (borrow limit) that an account receives by minting the cToken. 

There is also an interest rate, algorithmically calculated and determined by supply vs demand (borrowing vs. lending), but the weighting factors are determined by governance. e.g https://compound.comradery.io/post/1758


# KeeperDAO

<ins>*TLDR: Step-Wise Calculation Step-Wise Distribution*</ins>

In order to maximize throughput and minimize gas costs, Keepers transact with the Coordinator off-chain using payment channels. They will open this payment channel by staking Rook into a contract and then pass signed commitments and forth with the Coordinator. 

## Claiming rewards
All rewards (users and market makers) are claimable via the Coordination Game staking contract.  The Coordinator collects bids from keepers and opens up a payment channel to the user who can claim anytime they'd like. 

```
// The user receives ROOK porportional
// to the amount of MEV they contribute for a given epoch


user_ROOK_Reward = (user_MEV_created / all_MEV_created) 
* ROOK_emitted_for_epoch
 ```

![](https://i.imgur.com/1biqr1n.png)


## State

Retrieving latest state has staleness risk.

On-chain payment channel state will more often than not be **stale** since transacting using the payment channel occurs **off-chain**. 

There will only be on-chain payment channel interactions in certain circumstances: when a keeper stakes Rook to the payment channel, when a coordinator performs a partial settlement of spent Rook to accrue claimable Rook, and when a keeper performs a withdrawal. The Coordinator is the source of truth for the most up to date payment channel state and this state should be retrieved using the ```/keeperStakeChannel``` endpoint

The Coordination Game HTTP API is used by keepers to communicate with the Coordinator for general communications.

## Claiming rewards
All rewards (users and market makers) are claimable via the Coordination Game staking contract.  The Coordinator collects bids from keepers and opens up a payment channel to the user who can claim anytime they'd like.  
