elhajin
    • 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
    # Duration Vault Strategy — Audit Handbook --- | Table of Contents | |---| | [Scope](#Scope) | | [Context](#Context) | | [Core Changes](#Core-Changes) | | [How It Works](#How-It-Works) | | [Invariants](#Invariants) | | [Known Issues](#Known-Issues) | --- ## Scope ### New Contracts <!-- TODO: provide links --> | File | Description | |------|-------------| | `src/contracts/strategies/DurationVaultStrategy.sol` | Main implementation | | `script/releases/v1.11.0-duration-vault` | Deployment and upgrade script | :::spoiler :information_source: About upgradeScript : Our upgrade scripts use a deploy/metadata manager called "zeus" – however, this is not in scope. The purpose of including our upgrade script here is to get some input on the steps of the upgrade and if it can break anything in the already existing protocol. ::: ### Modified Contracts | File | Changes | |------|---------| | `src/contracts/core/StrategyManager.sol` | Added `beforeAddShares` / `beforeRemoveShares` hook calls | | `src/contracts/strategies/StrategyBase.sol` | Added virtual hook functions for strategies to override | | `src/contracts/strategies/StrategyFactory.sol` | Added `deployDurationVaultStrategy()`, duration vault beacon and some new related state variables | - **Commit** : [eb09ca46d0d8c6a9cb9bc74bfcd583d55a51c04c](https://github.com/Layr-Labs/eigenlayer-contracts/tree/release-dev/duration-vaults) For full diff check PRs : - main PR : [PR-1671](https://github.com/Layr-Labs/eigenlayer-contracts/commit/bcb070730cdb14cc5abab86e081c43ba210db80e) - arbitrator PR : [PR-1700](https://github.com/Layr-Labs/eigenlayer-contracts/pull/1700) --- ## Context The `DurationVaultStrategy` is a **time-bound, single-use EigenLayer strategy** designed for use cases requiring guaranteed stake commitments (e.g., insurance pools). ### High-Level Flow 1. *AVS creates vault* via `StrategyFactory` with duration, caps, operator set config, and arbitrator 2. *Vault self-registers as an operator* — stakers must delegate to the vault before depositing 3. *Stakers deposit* during the open window, subject to per-deposit and total caps 4. *Admin locks the vault* — deposits/withdrawal queuing blocked; full magnitude allocated to operator set 5. *AVS submits rewards* — stakers can claim rewards via normal EigenLayer reward flow 6. *Vault exits lock* — either: - **Normal**: duration elapses → anyone calls `markMatured()` - **Early**: arbitrator calls `advanceToWithdrawals()` before duration elapses 7. *Stakers withdraw* — receive principal minus any slashing that occurred ### Key Design Points | Concept | Description | |---------|-------------| | **Vault = Operator** | Vault registers as EigenLayer operator; all deposited shares are delegated to itself | | **Arbitrator** | Trusted address that can unlock the vault early via `advanceToWithdrawals()` if external terms are violated | | **Active Share Cap** | TVL cap uses `operatorShares` (excludes queued withdrawals) | | **Allocation Delay** | Set to `minWithdrawalDelayBlocks + 1` — ensures pre-lock queued withdrawals complete before allocation becomes slashable | | **Deallocation Delay** | After maturity, vault remains slashable for `DEALLOCATION_DELAY` blocks | | **Single-Use** | Vaults cannot be re-locked after maturity; deploy new vault for new commitment | ### Related Documentation <!-- TODO: add links --> - [DurationVaultStrategy docs](https://github.com/Layr-Labs/eigenlayer-contracts/blob/release-dev/duration-vaults/docs/core/DurationVaultStrategy.md) --- ## Core Changes ### Strategy Hooks **Problem**: Standard `StrategyBase` has no mechanism to enforce custom constraints on share movements after they are already deposited. Duration vaults need to block deposits after lock, require delegation to the vault, enforce caps, and block withdrawal queuing during the allocation period. **Solution**: Add hook functions that `StrategyManager` calls before any movement of shares. Strategies can override these to implement custom logic, like vetoing re-delegation or preventing withdrawal queuing. #### StrategyManager Integration In `_addShares()` — called when crediting shares after deposit or withdrawal completion as shares: ```solidity // allow the strategy to veto or enforce constraints on adding shares strategy.beforeAddShares(staker, shares); ``` In `_removeDepositShares()` — called when queuing a withdrawal or undelegating: ```solidity // allow the strategy to veto or enforce constraints on removing shares strategy.beforeRemoveShares(staker, depositSharesToRemove); ``` #### StrategyBase Virtual Hooks ```solidity // Default: no-op. Derived strategies override to add constraints. function beforeAddShares(address, uint256) external virtual onlyStrategyManager {} function beforeRemoveShares(address, uint256) external virtual onlyStrategyManager {} ``` **Why hooks instead of modifying StrategyManager directly?** - Keeps core contract minimal and generic - Allows per-strategy customization without forking `StrategyManager` - Existing strategies unaffected (default no-op) --- ### StrategyFactory — Deploying Duration Vaults Duration vaults are deployed via `StrategyFactory.deployDurationVaultStrategy(config)`. This mirrors how regular strategies use `deployNewStrategy(token)`, but with a separate beacon and different tracking. **Deployment flow:** 1. AVS provides a `VaultConfig` (token, admin, duration, caps, operator set, etc.) 2. Factory deploys a `BeaconProxy` pointing to `durationVaultBeacon`, calling `initialize(config)` 3. Factory registers the vault in `durationVaultsByToken[token]` — multiple vaults per token allowed (unlike regular strategies which are 1:1) 4. Factory whitelists the vault in `StrategyManager` for deposits 5. Vault's `initialize()` handles operator registration, operator set registration, and reward split config **Changes from main:** - Added `durationVaultBeacon` immutable — new beacon for duration vault implementations - Added `durationVaultsByToken` mapping — new state variable that tracks all duration vaults per token - Both beacons are now set in constructor (previously `strategyBeacon` was set in `initialize()`) --- ## How It Works ### Vault as Operator On initialization, the vault: 1. **Registers itself as operator** via `delegationManager.registerAsOperator()` 2. **Sets allocation delay** to `minWithdrawalDelayBlocks + 1` 3. **Registers for operator set** via `allocationManager.registerForOperatorSets()` 4. **Sets reward split to 0%** — 100% of rewards go to stakers --- ### Lifecycle & State Machine ``` ┌──────────────┐ lock() ┌──────────────┐ markMatured() ┌──────────────┐ │ DEPOSITS │ ──────────► │ ALLOCATIONS │ ──────────────► │ WITHDRAWALS │ └──────────────┘ └──────────────┘ │ └──────────────┘ │ │ │ │ ✓ Deposits ✗ Deposits │ ✗ Deposits ✓ Queue withdrawals ✗ Queue withdrawals │ ✓ Queue withdrawals ✗ Slashable ✓ Slashable* │ ✓ Slashable** │ advanceToWithdrawals() ─┘ (arbitrator, early exit) * After allocation delay passes ** Until deallocation delay passes ``` | Transition | Trigger | Who | Requirements | |------------|---------|-----|--------------| | `DEPOSITS → ALLOCATIONS` | `lock()` | `vaultAdmin` | State is `DEPOSITS` | | `ALLOCATIONS → WITHDRAWALS` | `markMatured()` | Anyone | `block.timestamp >= unlockAt` | | `ALLOCATIONS → WITHDRAWALS` | `advanceToWithdrawals()` | `arbitrator` | `block.timestamp < unlockAt` | --- ### Deposits (State: `DEPOSITS`) The `beforeAddShares()` hook enforces: 1. **Vault must be in DEPOSITS state** — deposits blocked after lock 2. **Token must not be blacklisted** — checked against `StrategyFactory.isBlacklisted()` 3. **Delegation check** — stakers must be delegated to the vault (since it's an operator) before depositing 4. **Deposit amount must not exceed per-deposit cap** — single deposit can't be larger than `maxPerDeposit` 5. **Post-deposit total must not exceed stake cap** — total active shares (in underlying) can't exceed `maxTotalDeposits` > The cap uses `operatorShares` which is the active shares of an operator for any given time. Queued withdrawals reduce `operatorShares`, so they don't count toward the cap. --- ### Lock (Transition to `ALLOCATIONS`) When `vaultAdmin` calls `lock()`: 1. Records the lock timestamp and calculates unlock time (`lockedAt + duration`) 2. Allocates full magnitude (100%) to the configured operator set :::spoiler Allocation delay protects pre-lock withdrawals The allocation doesn't become slashable immediately. It takes effect after `allocationDelay` blocks, which is set to `minWithdrawalDelayBlocks + 1`. This ensures any withdrawals queued before lock won't be slashed. ::: During `ALLOCATIONS`, new withdrawal queuing is blocked via `beforeRemoveShares()`. However, withdrawals that were already queued before `lock()` can still complete — the hook only prevents *new* queuing, not the completion of existing ones. This gives stakers an exit window. :::info *NOTE* that Withdrawals are allowed during `DEPOSITS` state so users can exit if the admin never locks the vault — they're not forced to wait indefinitely. ::: --- ### Mark Matured (Transition to `WITHDRAWALS`) Once the duration elapses (`block.timestamp >= unlockAt`), anyone can call `markMatured()` to transition the vault to `WITHDRAWALS` state. This function: 1. Records maturity timestamp and opens withdrawals 2. Attempts to deallocate magnitude to 0 (removes slashable stake) 3. Attempts to deregister from the operator set Both deallocation and deregistration are wrapped in `try/catch` — failures are silently ignored so the function always succeeds. This is intentional: external conditions (e.g., `AllocationManager` paused, AVS already deregistered the vault) should not prevent users from withdrawing their funds after maturity. :::info *NOTE* that even after `markMatured()`, the vault remains slashable for at least `DEALLOCATION_DELAY` blocks until the deallocation takes effect on the `AllocationManager`. ::: ### Early Exit via Arbitrator The `arbitrator` (set at deployment) can call `advanceToWithdrawals()` to unlock the vault **before** the duration elapses. This is intended for cases where external agreement terms are violated (e.g., insurance premiums not paid). Same effects as `markMatured()` — deallocates, deregisters, opens withdrawals. **Rewards:** Follow standard EigenLayer flow — AVS submits to `RewardsCoordinator`, stakers claim normally. Operator split is set to 0% at init, so 100% goes to stakers. Reward claims are not blocked by vault state. --- ## Invariants ***State Machine*** | # | Invariant | |---|-----------| | 1 | State only progresses forward: `DEPOSITS → ALLOCATIONS → WITHDRAWALS` | | 2 | `lockedAt > 0` ⟹ `state ≠ DEPOSITS` | | 3 | `maturedAt > 0` ⟹ `state == WITHDRAWALS` | | 4 | `unlockAt == lockedAt + duration` when locked | ***Deposits & Delegation*** | # | Invariant | |---|-----------| | 5 | Any successful deposit requires staker delegated to the vault strategy | | 6 | Any user with active shares in this strategy MUST always be delegated to this same strategy | | 7 | Vault shares cannot be delegated to any operator other than the vault itself | | 8 | Any normal deposit cannot exceed `maxPerDeposit` (see known issues)| | 9 | Post-deposit active shares (in underlying) cannot exceed `maxTotalDeposits` | | 10 | `maxPerDeposit <= maxTotalDeposits` always | ***Withdrawal & Slashing Protection*** | # | Invariant | |---|-----------| | 11 | Users should always be able to queue withdraw before lock or after maturity | | 12 | Vault delegated shares may only decrease due to slashing during the `ALLOCATIONS` state | | 13 | Any queued withdrawal created before `lockedAt` MUST NOT be subject to slashing (unless dealocation delay changed)| --- ## Known Issues ### 1. Cap Bypass via Direct Token Transfer **Issue**: Donations (direct token transfers) to the vault bypass `beforeAddShares()` and inflate the share value without triggering cap checks. - The `beforeAddShares` hook is only called through the `StrategyManager` deposit flow. Direct ERC20 transfers to the strategy contract increase the underlying balance without minting new shares, which inflates the exchange rate. - The attacker gains nothing —and they should be the first depositor or they'll be donating value to existing shareholders. While this can be used to exceed the TVL cap in underlying terms, the cap's primary purpose is to limit protocol risk exposure, and donations don't really increase that risk. --- ### 2. Best-Effort Cleanup State Inconsistency **Issue**: If `_deallocateAll()` or `_deregisterFromOperatorSet()` silently fails during `markMatured()`, the vault transitions to `WITHDRAWALS` state but may still have active allocation/registration on `AllocationManager`. - These calls are wrapped in `try/catch` to prevent external conditions (e.g., `AllocationManager` paused, AVS already deregistered the vault) from blocking user withdrawals after maturity. --- ### 3. Short Duration Edge Case **Issue**: The allocation delay is set to `minWithdrawalDelayBlocks + 1` to protect pre-lock withdrawals. If the vault's duration is shorter than this delay, the vault matures before the allocation becomes active. - AVSs deploying duration vaults should ensure the duration is meaningful for their use case, and stakers can always check the duration of each duration strategy vault. --- ### 4. Front-Run Lock **Issue**: A depositor can front-run the admin's `lock()` call to queue a withdrawal, causing the vault to lock with less capital than expected. - During `DEPOSITS` state, withdrawal queuing is allowed (so users aren't trapped if admin never locks). It's the admin's responsibility to avoid front-running and make sure that they lock the strategy with the desired capital. --- ### 5. Admin Can Set Cap Below Current **Issue**: The `vaultAdmin` or `unpauser` can set the TVL limit to a value less than currently invested funds. - This is intentional flexibility. Setting a lower cap doesn't affect existing deposits — it only blocks new deposits until withdrawals bring the balance below the new cap.

    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