Xiangan He
    • 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
    --- title: 'yAcademy code review' disqus: yAcademy --- yAcademy Morpho review === **Review Resources:** A protocol yellowpaper and documentation were provided **Residents:** - Peep (xiangan.eth) ## Table of Contents [TOC] ## Review Summary **Morpho** The Morpho protocol is a Pareto-improving interest-rate mechanism built on top of existing pool-based lending protocols. The dev branch of the Morpho [Repo](https://github.com/morpho-labs/morpho-contracts/tree/dev/contracts/compound) was reviewed over 8 days. 1 day was used to create a report of the findings. Only the compound contracts were covered. The contracts were reviewed from April 28 to May 9. The code was reviewed by 1 resident for a total of 42 man hours. The repository was under active development during the review, but the review was limited to [one specific commit](https://github.com/morpho-labs/morpho-contracts/tree/9123b34db1bfe39f91f619de61a69d34a9f339e5). ## Scope [Code Repo](https://github.com/morpho-labs/morpho-contracts/tree/dev/contracts/compound) [Commit](https://github.com/morpho-labs/morpho-contracts/tree/9123b34db1bfe39f91f619de61a69d34a9f339e5) The commit reviewed was 9123b34db1bfe39f91f619de61a69d34a9f339e5. The review covered the entire repository at this specific commit but focused on the contracts directory. After the findings were presented to the Morpho team, fixes were made and included up to [commit 17f2d91a8b4c43d5287ad85f9fc47d9449d61c13](https://github.com/morpho-labs/morpho-contracts/commit/17f2d91a8b4c43d5287ad85f9fc47d9449d61c13). Fixes were reviewed to confirm whether they remedied the original finding, but a new security review was not performed on the revised code (e.g. to determine whether new vulnerabilities were introduced by the fixes). The review is a code review to identify potential vulnerabilities in the code. The reviewers did not investigate security practices or operational security and assumed that privileged accounts could be trusted. The reviewers did not evaluate the security of the code relative to a standard or specification. The review may not have identified all potential attack vectors or areas of vulnerability. yAcademy and the residents make no warranties regarding the security of the code and do not warrant that the code is free from defects. yAcademy and the residents do not represent nor imply to third party users that the code has been audited nor that the code is free from defects. By deploying or using the code, Morpho and and users agree to use the code at their own risk. Code Evaluation Matrix --- | Category | Mark | Description | | ------------------------ | ---- | ----------- | | Access Control | Good | Access controls are applied where needed. Ownable is appropriately used to limit function calls to respective permissions, and view functions are made public for liquidation purposes. | Mathematics | Good | Solidity 0.8.13 is used, which provides overflow and underflow protect. Unchecked code was checked in this audit to yield no anomalies. No low-level bitwise operations are performed. There was no unusually complex math, except perhaps some of the calculations with current interest rates based on market growth factor. | | Complexity | Medium | The delegatecall structure and sometimes duplicate function names can make the code hard to follow at times. The core complexity also lies in the security implications of Compound itself and what happens in the event of market anomalies and manipulations in Compound. | | Libraries | Good | Only basic Open Zeppelin contracts such as SafeERC20, Ownable, ReentrancyGuard, and Math are imported, no other external libraries are used. Fewer and simpler external dependencies is always a plus for security. | | Decentralization | Poor | The governance contract is successfully implemented but needs work integrating with Zodiac. Additionally, further due diligence has to be done for that integration, along with the fact that little coverage on test for governance contracts exists at the moment. | | Code stability | Average | Changes were reviewed at a specific commit and the scope was not expanded after the review was started. However, development was ongoing when the review was performed so the code was not fully frozen, which means deployed code may vary from what was reviewed. | | Documentation | Good | Comments existed in many places, and mostly clarified what the code did. Some documentation had to be added to distinguish between functions with duplicate names, as well as fixing some typos. | Monitoring | Good | Events were added to all important functions that modified state variables. | | Testing and verification | Good | All tests were passing after a small fix to a typo, and test coverage was very expansive. | ## Findings Explanation Findings are broken down into sections by their respective impact: - Critical, High, Medium, Low impact - These are findings that range from attacks that may cause loss of funds, impact control/ownership of the contracts, or cause any unintended consequences/actions that are outside the scope of the requirements, - Gas savings - Findings that can improve the gas efficiency of the contracts - Informational - Findings including recommendations and best practices --- ## Critical Findings ### 1. Critical - P2P market can be drained if P2P gets toggled off after matching. #### Proof of concept The following code, which subtracts the supplyBalance of a user upon withdrawal, does not trigger if P2P gets turned off after a user has already supplied tokens to the pools. ```solidity if (vars.remainingToWithdraw > 0 && !marketsManager.noP2P(_poolTokenAddress)) { supplyBalanceInOf[_poolTokenAddress][_supplier].inP2P -= CompoundMath.min( supplyBalanceInOf[_poolTokenAddress][_supplier].inP2P, vars.remainingToWithdraw.div(supplyP2PExchangeRate) ); // In p2pUnit updateSuppliers(_poolTokenAddress, _supplier); ``` #### Impact This causes the entire pool to be drainable, since the attacker would then be able to continue calling withdraw on the maximum balance they had before their withdrawal. #### Recommendation It's possible to split the condition into two parts, such that the only check here is ```solidity if (vars.remainingToWithdraw > 0) { supplyBalanceInOf[_poolTokenAddress][_supplier].inP2P -= CompoundMath.min( supplyBalanceInOf[_poolTokenAddress][_supplier].inP2P, vars.remainingToWithdraw.div(supplyP2PExchangeRate) ); ``` and then implementing the other part of the logic for when governance is turned off some other way. #### Developer Response Fixed. ## High Findings ### 1. High - Delta manipulations in certain scenarios (notably flashloaning) #### Proof of concept In a scenario where some borrowers are matched P2P (earning a low borrow rate), many are still on the pool and therefore in the pool queue (earning a worse borrow rate from Comp/Aave). An attacker supplies a huge amount, creating a P2P credit line for every borrower. (They can repeat this step several times if the max iterations limit is reached.) The attacker immediately withdraws the supplied amount again. The protocol now attempts to demote the borrowers and reconnect them to the pool. But the algorithm performs a "hard withdraw" as the last step if it reaches the max iteration limit, creating a borrower delta. These are funds borrowed from the pool (at a higher borrow rate) that are still wrongly recorded to be in a P2P position for some borrowers. This increase in borrow rate is socialized equally among all P2P borrowers. (reflected in an updated p2pBorrowRate as the shareOfDelta increased.) The initial P2P borrowers earn a worse rate than before. If the borrower delta is large, it's close to the on-pool rate. If an attacker-controlled borrower account was newly matched P2P and not properly reconnected to the pool (in the "demote borrowers" step of the algorithm), they will earn the better P2P rate than the on-pool rate they earned before. #### Impact High, this can cause P2P borrowers to earn at a worse rate than before the attack. #### Recommendation In withdraw() of logic.sol, putting in an update for P2P delta immediately when hard-withdraw is triggered. ```solidity delta.borrowP2PAmount -= unmatched.div( marketsManager.borrowP2PExchangeRate(_poolTokenAddress) ); ``` #### Developer Response Acknowledged & working solutions. ## Medium Findings ### 1. Medium - Governance contract needs receive() Currently, the PositionManagerGovernance for compound does not have a receive() function to receive protocol fees, in addition to claimToTreasury sending the whole balance of PositionManagerGovernance.sol to the treasuryVault. #### Proof of concept No function in PositionManagerGovernance.sol is payable, nor is there a receive function to receive ETH. #### Impact Medium, transactions revert (also given no fallback function) when sending funds to governance contracts. #### Recommendation Implement `receive() external payable` in contract #### Developer Response Fixed since the contracts have been combined into Morpho.sol ## Low Findings ### 1. Low - MarketsManager.sol setReserveFactor does not require market as created Consider putting a modifier that requires the target pool token to already have a market that is created. Or perhaps even causing updateP2PExchangeRates to revert if the target market does not exist. #### Proof of concept See tests folder. #### Impact Varies, depending on additional due diligence with integration with Zodiac #### Recommendation Adding additional tests and performing edge-case testing after an integration with Zodiac. #### Developer Response Developers agreed and will perform additional tests. Fixed in a later commit. ### 2. Low - View function may be called on nonexistent pool address Consider putting a modifier that requires the target pool address to already have a market that is created. #### Proof of concept ```solidity function getUpdatedBorrowP2PExchangeRate(address _poolTokenAddress) external view returns (uint256) ``` May be called on `_poolTokenAddress` that does not exist as a pool yet. #### Impact Extra gas expenditures on view functions. #### Recommendation Put a modifier that checks for whether the target pool address exists on one or multiple of the functions referenced here. #### Developer Response Developers agreed and later removed the targeted function ## Gas Savings Findings ### 1. Gas - Double Linked List implementation #### Proof of concept With regards to gas and computational optimization, potentially using https://github.com/Dev43/heap-solidity instead of the current DoubleLinkedList implementation will drastically reduce average gas costs with larger amounts of matched suppliers and borrowers. This also helps prevent DOS attacks related to making the matching engine inefficient via. multiple small accounts. This can be implemented in the long run. #### Impact Gas savings #### Recommendation In the long term, switch to a different implementation of organizing users and pools instead of the DoubleLinkedList. #### Developer Response Unsure whether or not fixing this is possible due to needing the ability to remove someone within a bloc. Implementation needs to be tested first to avoid potential issues worse than just inefficiency (e.g. contract halting, etc.) ## Informational Findings ### 1. Informational - Aave contracts may require resizing, may require redeployment because it exceeds max memory size. #### Impact May cause extra gas to have to be consumed in redeploying the contract. #### Recommendation Reducing contract size on certain Aave contracts #### Developer Response Acknowledged & working. ### 2. Informational - Change "weth" to wEth: noncompiling gas report. A small typo on the tests are stopping gas reports from running in TestMarketsManager.t.sol:29:37. #### Developer Response Fixed in later version. ### 3. Informational - Typo in inline documentation L85 of Logic.sol has a typo: : "MatchingEngineForCompound", not Aave. #### Developer Response Fixed. ### 4. Informational - MarketsManager.sol L283 & L314 control flow decision made on block.timestamp. block.timestamp != block.number. Block.number is guaranteed by the protocol to increase by one compared to the previous block, while block.timestamp can be minimally gamed by a miner (if this matters). #### Proof of concept Several functions on MarketsManager.sol (e.g. getUpdatedSupplyP2PExchangeRates) rely on `block.timestamp == lastUpdateBlockNumber` to return updated exchange rates for a certain poolTokenAddress. Switching over to using block.number may yield more stable and secure exchange rate updating results. #### Impact Informational. #### Recommendation Choose to use block.number if miner gaming matters. #### Developer Response Recognized and fixed in later version. ## Final remarks With a focus on how contracts interact with each other and vulnerabilities with any delegate-call mechanics to the main Logic.sol contract, I found nothing particularly worthy of note that was a critical exploit. The protocol has immense coverage on tests with potential fluctuations and edge cases that can occur with Compound markets. Some additional tests on governance (by extension, the integration with Zodiac) can be added along with limited potential for heavy gas optimizations (viz. DoubleLinkedList setup). ## Appendix and FAQ ###### tags: `Review` `yAcademy`

    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