mevbandit
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # *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.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully