tapir
    • 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
    # Yearn V3 Strategies Review checklist and Gotchas ## Functions to override ### **_deployFunds(uint256 _amount)** - `_amount` parameter is `S.totalIdle + assets` , where `S.totalIdle` is supposedly the idle balance of the contract and `assets` is the fresh taken user funds. - **Check assumptions on trying to deploy the `_amount`. If in some cases strategy doesnt want to fully deploy the `_amount`, then override `availableDepositLimit` function such that `_amount` is always deployable** - **IMPORTANT** Some strategies may not be suited for force `_deployFunds` on deposits since this could be an attack vector in some cases. e.g single siding into an LP pool that can be unbalanced or MEV'd, etc. *Careful* consideration must be employed and tests on these cases for strategies that deposit directly to a protocol and on what cases it can become dangerous to do so. Flags or other mechanism to limit rate of funds deployed may be reasonable in some cases. ### **_freeFunds(uint256 _amount)** As stated in the natspec of the original code: ``` Any difference between `_amount` and what is actually freed will be counted as a loss and passed on to the withdrawer. This means care should be taken in times of illiquidity. It may be better to revert if withdraws are simply illiquid so not to realize incorrect losses. ``` - `Math.min(_amount, asset.balanceOf(address(this)))` should be safe to use - On normal operations it should ONLY free the `_amount` of funds - **ALWAYS FREE THE `_amount` worth of position NOTHING MORE. If let's say there is a withdrawal fee, do not account it.** ### availableWithdrawLimit ### This function defaults to MAX uint 256, also by default there is no check wheter the vault is in emergency mode or not for withdrawals. Since this function overrides the maximum amounts of withdrawals users can make [here](https://github.com/yearn/tokenized-strategy/blob/8f6992d566a0c62a212beba93d593c1641ad3913/src/TokenizedStrategy.sol#L671) , is prudent to request an override of the function to allow for pause mechanisms by management or governance on extreme scenarios where we may need time before enabling withdrawals again. Also a limit may be set for withdrawals with cooldown in case of an emergencyShutdown to allow for response time on an incident but still be permissionless to enable withdrawals after a set time. This may be done with a new method `startCoolDown()` in `BasedTokenizedstrategy` that is open to any holder of the vault and sets a time configurable setting to allow withdrawals again after a period of time that is prudent. The intention is to mimic some of v2 safe guards around queue management to repair strategies while pausing withdrawals, this may not be an option in all cases but its prudent to leave the door open for emergency scenarios. Something to evaluate as option in a case by case basis based on strategy risk profile and projected TVL. ### **_emergencyWithdraw(uint256 _amount)** - `_amount` parameter needs to be uint256.MAX amount to fully exit This method is important to override in strategies that are intended for production in yearn vaults. Ideally regardless of the amount it should default to total balance and exit once. The method needs to try to exit all funds from the protocol yield source if possible without even getting rewards, this must assume the protocol is in the worst state possible. This method requires that the strategy method `shutdownStrategy` is called before calling emergencyWithdraw. ***So emergency exit is a two step process and it cannot be undone.*** 1. `strategy.shutdownStrategy()` 2. `strategy.emergencyWithdraw(2**256-1)` **TESTS should be require in reviews to ensure the strategy can exit position in emergency entirely.** ### **updateDebt** It's important to check the `deposit` logic on tokenized strategies actually mints the correct shares since vault when updating debt to increase it, it doesnt check the final shares number increased only the asset balances side effects. https://github.com/yearn/yearn-vaults-v3/blob/05fbd377a7778c660034f17c11b32e3767ff9166/contracts/VaultV3.vy#L799 Note: this case may apply more for external to yearn contracts that are erc4626 compliant but have different logic for minting shares or edge cases. ### **_mint** The `_mint` function https://github.com/yearn/tokenized-strategy/blob/ba8e6e1ca74b21e566f81b92618bcf39fe354ca2/src/TokenizedStrategy.sol#L1707 is not meant to be called directly by Contracts inheriting BaseTokenizedStrategy, a strategy should **NEVER** need to be calling the `_mint` method directly since minting to `self or address(this)` breaks an important invariant of the tokenized strategies regarding profit unlocking. ### set_open_role open in v3 vyper vault here there's an open role setter https://github.com/yearn/yearn-vaults-v3/blob/1e6bc67cf70352e9567e67404d73856cc343b634/contracts/VaultV3.vy#L1286 to allow a specific role to be called by any msg.sender, careful checks need to be considered in security reviews around expectations and consequencies of opening this role up for certain operations and considering the overall use case flow for security implications. ### **availableDepositLimit** - If limit is calculated as how much strategy can deploy up to, count the `S.totalIdle` too. - **Deposit check is only applied to "assets" user puts to the strategy. However, actual amount deployed is S.totalIdle + assets. So consider this !** ### **harvestAndReport** - V2 Harvest alike function. - NO NEED TO UNWIND THE PROFIT FROM THE STRATEGY. Just report what strategy has, no need to free profit or anything. - Sell rewards, deploy them to strategy, account the final balance, report loss or profit and REDEPOSIT. Even report loss, redeposit. **IMPORTANT SECURITY CONSIDERATIONS of `harvestAndReport`** * If the implemented method relies on protocol oracles, spot price, etc and the totalAssets return value can be manipulated or is badly calculated it could incorrectly report a profit or loss and leave the strategy in bad accounting state. Important checks of tests and logic are needed here. * If the `asset.balanceOf(this)` is by some error not reported or incorrectly reported, the strategy will assume is idle by default and may revert here if newTotalAssets < newIdle. https://github.com/yearn/tokenized-strategy/blob/8f6992d566a0c62a212beba93d593c1641ad3913/src/TokenizedStrategy.sol#L1059 * Because of reasons above it may be important to require healthcheck on `_harvestAndReport` implementations to avoid any miscalculations in reports. ## Linked Libraries on Contracts that extend BasedTokenizedStrategy `The only time the onlySelf may be used is if you add a Linked Library to your strategy` `which i would say should be discouraged` Quote from Schlag ## GENERAL - Any airdrop to strategy is not accounted as IDLE funds. It won't be accounted in `S.totalIdle`!! - If yTrades sends `asset` token to strategy, the profit accounting will be held inside the `harvestAndReport` strategy. Untill then strategy has no idea of the airdropped amount. - Strategy mints shares according to how much user provided "asset" tokens to strategy. Strategy doesn't care how much of it put into position. When withdrawing account for this too. Do not over withdraw if there is a withdrawal fee. Let the user incur losses. - Example: Let's imagine we have a bridge strategy, which includes both a 10% deposit and a 10% withdrawal fee. Now, let's say a user decides to deposit 100 DAI into the strategy. At this point, the strategy issues the user 100 shares. The strategy doesn't care about the deposit fee at this point. What's important is that the user has provided 100 DAI. Next, the same user decides to withdraw, and they want to take out 50 DAI. This is where the _freeFunds function comes into play. It's set up to withdraw exactly 50 DAI. Of course, because of the 10% withdrawal fee, the user actually ends up with 45 DAI, and there's a loss of 5 DAI. But here's the thing: the _freeFunds function doesn't try to pull out 55 DAI to cover the withdrawal fee. It just reports the loss. And that's totally okay. ## Direct Storage updates with assembly Note @storm0x : this is my impression from reading the code, it may be a general assumption to look out for and have very few exceptions if any. Tokenized strategies have a specific storage pointer slot to update important data, careful review should be done if there are any direct storage updates in assembly from a specific implementation of BaseTokenizedStrategy since most if not all strategies shouldn't be writing directly to slots in storage pointer. https://github.com/yearn/tokenized-strategy/blob/ba8e6e1ca74b21e566f81b92618bcf39fe354ca2/src/TokenizedStrategy.sol#L342 Most implementations should not need to directly update storages if at all, direct usage of assembly writing to storage location `keccak256("yearn.base.strategy.storage") - 1` should be disallowed.

    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