Alexander Biryukov
    • 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
    --- tags: ADR author: Alexander Biryukov, Eugene Mamin, Artyom Veremeenko blockchain: Gnosis Chain, Gnosis Beacon Chain, Ethereum discussions-to: TBA --- # ADR ##: Lido on Gnosis * Status: RFC * Deciders: Lido dev team, Lido DAO <!-- optional --> * Date: 2022-07-06 ## Context and Problem Statement Gnosis follows the Ethereum 2.0 roadmap closely. [Gnosis Chain (GC)](https://docs.gnosischain.com/) execution layer is very similar to ETH1, while Gnosis Beacon Chain (GBC) is similar to Ethereum 2.0 Beacon Chain (EBC). Much like Ethereum, GC will continue to run in its current form until the merge with the GBC. This merge will follow a similar trajectory to the Ethereum merge. After the merge, validators (stakers) on the GBC will begin validating transactions on the GC; the GC will become a shard within the larger GBC infrastructure. However, [Lido (StETH) contracts](https://github.com/lidofinance/lido-dao) cannot be reused directly because staking on Gnosis is implemented with an ERC-20 compatible asset ([mGNO](https://github.com/gnosischain/deposit-contract/blob/develop/contracts/SBCToken.sol)) instead of the native currency (xDAI). In Lido, user funds (ETH only) are accepted via - payable fallback function - dedicated external payable function called `submit` Since on Gnosis staking is based on mGNO, its [Deposit Contract](https://github.com/gnosischain/deposit-contract/blob/develop/contracts/SBCDepositContract.sol) accepts mGNO. To be consistent with Ethereum, it's 32 mGNO as well. mGNO is a [wrapped](https://github.com/gnosischain/deposit-contract/blob/develop/contracts/SBCWrapper.sol) version of [GNO](https://blockscout.com/xdai/mainnet/token/0x9C58BAcC331c9aa871AFD802DB6379a98e80CEdb), another ERC-20 token. 1 GNO = 32 mGNO. [GBC](https://docs.gnosischain.com/contracts-addresses-parameters#initial-parameters-subject-to-change) also differs from [EBC](https://kb.beaconcha.in/glossary) in the following paramaters: | | GBC | EBC | |---------------------------|:-------------:|:-------------------:| | Staking amount | 32 mGNO | 32 ETH | | Block time | 5 seconds | 12 seconds | | Validator slots per epoch | 16 (with further reduction possible) | 32| | Epoch time | 80 seconds | 384 seconds | | Slashing | Reductions to 16 mGNO, then removal | ≥ 1/32 of balance at stake | GBC mechanics seems NOT to be fully resembling EBC. The Oracle code should be revised carefully. ### Execution Layer rewards Execution Layer (EL) rewards, such as transaction priority fees and [MEV](https://ethereum.org/en/developers/docs/mev/) are [paid in the native currency - xDAI](https://developers.gnosischain.com/for-developers/developer-resources/mev-and-flashbots). Another possible source of xDAI can be user deposits. Since staking is performed with mGNO, mGNO effectively replaces the role of ETH in all the Lido logic (like BufferedEther, PooledEther, etc.). xDAI does not fit into the staking logic. We might consider converting xDAI into mGNO. ### Reacting to user token transfers Native currency transfers usually trigger some function inside the receiver contract (custom payable function, `receive`, or `fallback`). ERC-20 transfers, by default, lack this ability. They can happen by calling `transfer` on the ERC-20 token's contract without the receiver contract's knowing about it. Lido needs to know about incoming transfers to be able to mint corresponding `stETH` shares. The solution can be utilizing ERC-677 callback functionality. Both GNO and mGNO support ERC-677. ```solidity= /** * @dev Implements the ERC677 transferAndCall standard. * Executes a regular transfer, but calls the receiver's function to handle them in the same transaction. * @param _to tokens receiver. * @param _amount amount of sent tokens. * @param _data extra data to pass to the callback function. */ function transferAndCall( address _to, uint256 _amount, bytes calldata _data ) external override { address sender = _msgSender(); _transfer(sender, _to, _amount); require(IERC677Receiver(_to).onTokenTransfer(sender, _amount, _data), "SBCToken: ERC677 callback failed"); } ``` Right after the transfer, `onTokenTransfer` callback is called. ## Decision Drivers - **Contract size limit.** [The main Lido contract](https://github.com/lidofinance/lido-dao/blob/master/contracts/0.4.24/Lido.sol) size is already 24241 bytes. ["It seems xdai (GC) doesn't currently impose the contract size limit of 24576 bytes"](https://github.com/1Hive/uniswap-v2-core/blob/master/README.md#in-the-uniswap-v2-periphery-repo). [Here](https://blockscout.com/xdai/mainnet/tx/0xfcc495cdb313b48bbb0cd0a25cb2e8fd512eb8fb0b15f75947a9d5668e47a918) is an example of such a transaction having succeeded. However, GC has a block gas limit of [30M Gas](https://developers.gnosischain.com/for-developers/developer-resources#general-information), which means the effective contract size limit still exists, even though it is much higher than on Ethereum. The implication is that we are free to add functionality if the only targeted chain is GC, but we should be cautious if compatibility with other chains is required. The idea is to write new code in a separate abstract contract or a library. In the future, the deployment can be split. - **Code reuse for other chains.** - **Gas efficiency.** - **Transparency and predictability for the users.** - **Ease of use.** If Lido contracts are used outside our own frontend, the public interface should be as simple as possible. - **Security.** Resistance to attacks (e.g. front-running). ## Considered Options ### 1. Accepting user funds The proposed solution can accept: 1. _mGNO_ - sent directly to GBC deposit contract. 2. _GNO_ Pros: - _GNO_ is the first class citizen in the Gnosis ecosystem. It's tradable on exchanges and can be moved from the Ethereum mainnet via a bridge. Many users already have _GNO_, but not _mGNO_. - Wrapping _GNO_ into _mGNO_ is straightforward. Cons: - Increases the contract size. - Consumes more gas than _mGNO_ deposit. But gas is cheap on GC and the user will have to do the wrapping anyway if they have _GNO_. 3. _xDAI_ - will not accept Pros: - Can be useful for backwards compatibility with the existing interfaces, including the payable fallback function. - Execution Layer rewards are also paid in _xDAI_. Cons: - Cannot be converted into _mGNO_ easily. Possible approaches to conversion are discussed [later](#converting-xdai-into-mgno). ### 2. Reacting to user token transfers 1. Lido can implement `IERC677Receiver`'s `onTokenTransfer` with its `_submit` logic (minting stmGNO etc.). Unfortunately, [the wrapper contract](https://github.com/gnosischain/deposit-contract/blob/develop/contracts/SBCWrapper.sol) is tightly coupled to the deposit contract. There is no way to set our contract as ERC677Receiver for the wrapper. So, accepting GNO this way is impossible. But it's still possible to accept mGNO. For the same `sumbit` logic: - `approve` +`transferFrom` takes _246,093_ gas. - `transferAndCall` + `onTokenTransfer` takes _192,574_ gas. That's _53,519_ gas savings. Pros: - Saves an additional `approve` transaction for mGNO. - Delegates mGNO transfer logic to the mGNO contract itself, thus slightly reducing Lido's `submit` code. - Eliminates the need for checking the status of the transfer. Cons: - Harder to reason about callbacks. 2. Simply call `transferFrom` on mGNO directly inside Lido's `submit` function. Pros: - Easier to reason about and more standard. Cons: - Requires an additional `approve` transaction for mGNO. - Slightly more gas expensive. - Requires more code. ### 3. Leveraging EIP-2612: permit – 712-signed approvals [GNO](https://github.com/poanetwork/tokenbridge-contracts/blob/master/contracts/PermittableToken.sol) is also an [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612) token. This allows the user to avoid sending 2 separate transactions (1 for `approve`, 1 for `sumbit` or `transferAndCall`, both of which will call `transferFrom` inside them). Instead, the user can pre-sign their approval off-chain and then pass the signature (v, r, s) into the Lido contract. Lido will call `permit` and `transferFrom` on GNO in 1 transaction. ```solidity= /// @dev Allows to spend holder's unlimited amount by the specified spender. /// The function can be called by anyone, but requires having allowance parameters /// signed by the holder according to EIP712. /// @param _holder The holder's address. /// @param _spender The spender's address. /// @param _nonce The nonce taken from `nonces(_holder)` public getter. /// @param _expiry The allowance expiration date (unix timestamp in UTC). /// Can be zero for no expiration. Forced to zero if `_allowed` is `false`. /// Note that timestamps are not precise, malicious miner/validator can manipulate them to some extend. /// Assume that there can be a 900 seconds time delta between the desired timestamp and the actual expiration. /// @param _allowed True to enable unlimited allowance for the spender by the holder. False to disable. /// @param _v A final byte of signature (ECDSA component). /// @param _r The first 32 bytes of signature (ECDSA component). /// @param _s The second 32 bytes of signature (ECDSA component). function permit( address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, uint8 _v, bytes32 _r, bytes32 _s ) external; ``` Pros: - Allows the user to avoid sending 2 separate transactions. Cons: - Can only work with GNO, not mGNO, since mGNO does not implement EIP-2612 `permit`. - Requires a separate function from the regular approved transfer. ### 4. Converting xDAI into mGNO Possible approaches are: 1. Use an aggregator (Cowswap). Pros: - Faster and better guaranteed conversion compared to auctions. - More standard solution. Cons: - Slippage can be high. 2. Implement some kind of an auction (e.g. a Dutch auction). The oracle price is provided by an oracle. The initial price is oracle price with a premium. The current price in each next block decreases by a certain percentage. Pros: - Can get better prices. - Avoid dependence on a 3rd party (DEX). - Can be useful for restaking. Cons: - Longer wait, less guaranteed conversion. - Potentially more complex and non-standard code. - Not so convenient for user deposits. ### 5. Generalized approach for Lido to work with the native currency and ERC20-compatible tokens Pros: - 1 universal codebase, which is easier to maintain and reuse across different chains. Cons: - Contract size limit, as discussed in [Decision Drivers](#decision-drivers). - Added complexity to the original codebase (`if (isERC20)` checks). - Variations in implementations between different ERC-20 tokens and their corresponding deposit contracts. For example, GNO to mGNO wrapping is probably unique to GC. EIP-2612's `permit` optimization is not standard for any ERC-20, etc. ### 6. Naming for external functions Possible approaches are: 1. Leave the existing names of functions and variables Ether-specific. Pros: - Backwards-compatibility with the existing interfaces. - Gas efficiency since there are no external calls forwarded to libraries. Cons: - Confusing naming for ERC20 stake based contracts. - Direct usage of base Lido contract for the majority of the external functions. Asset-specific contracts (LidoEth, LidoGnosis) are only used for the submit logic. 2. Put common state (storage slot names) and functions into a linkable library. Pros: - Natural namings for both native currency and ERC20 stake based contracts. - Single entry point for all external functions (only LidoEth, LidoGnosis, etc.; no direct calls to the base Lido contract). Cons: - Breaking backwards-compatibility with the existing interfaces. - More gas expensive because of external calls forwarded to libraries. - More refactoring since base Lido contract no longer exists. ## Proposed solution ### 1. Accepting user funds Considering the difficulties preserving the exchange rate between xDAI and GNO, we decided not to support user deposits in xDAI. So, the only accepted assets will be mGNO and GNO. ### 2. Reacting to user token transfers The only acceptable use case for `transferAndCall` is the initial user mGNO transfer. It will allow to avoid `approve` as a separate transaction. Place in a separate contract. ### 3. Leveraging EIP-2612: permit – 712-signed approvals Use for GNO. Place in a separate contract. ### 4. Converting xDAI into mGNO Try using an aggregator (CowSwap) first. If not successful, an auction can be used for restaking. Do not accept user deposits in xDAI. #### CowSwap CowSwap orders are [placed off-chain](https://github.com/cowprotocol/cow-sdk/blob/e086d9edeb24b25bb873a11c462019fa1ea4c021/docs/post-order-example.ts). There needs to be a dedicated service (can be combined with oracle) that interacts with the CoW Protocol, e.g. using [cow-sdk](https://github.com/cowprotocol/cow-sdk). For the signature, we can use [Pre-signing the order with an onchain transaction from the owner of the order](https://docs.cow.fi/smart-contracts/settlement-contract/signature-schemes). The `orderUid` will be submitted into our `LidoExecutionLayerRewardsVaultGnosis` contract: ```solidity= /** * Initiate sell of XDAI for GNO * @param _orderUid The unique identifier of the order to pre-sign. */ function initiateSellOfNativeCurrencyForStakeToken(bytes calldata _orderUid) override external { uint256 balance = address(this).balance; require(balance > 0, "ZERO_BALANCE"); WXDAI.deposit{ value: balance }(); WXDAI.approve(GP_V2_VAULT_RELAYER, balance); GP_V2_SETTLEMENT.setPreSignature(_orderUid, false); } ``` Here we take EL vault's xDAI balance, convert it into WxDAI (wrapped xDAI, similar to WETH), approve our WxDAI tokens for CoW's [Vault relayer](https://docs.cow.fi/smart-contracts/vault-relayer), and pre-sign the `orderUid`. The signature in this scheme is simply `LidoExecutionLayerRewardsVaultGnosis` contract's address. Since an approval is already made, there is no need for a secure signature. > ##### Note: > A potentially more secure approach is to generate all the order data fields on-chain directly inside the `initiateSellOfNativeCurrencyForStakeToken` function instead of generating the order off-chain and passing the orderUid. This will guarantee that the pre-signed orderUid actually belongs to the order. Then, the actual order for WxDAI to GNO swap is submitted off-chain. Eventually, the order will get filled. (If not, it can be canceled and submitted a new order based on some schedule, e.g. the same schedule as for oracle reports). With the next oracle report, `Lido`'s `handleOracleReport` function will call `LidoExecutionLayerRewardsVaultGnosis`'s `withdrawRewards` function: ```solidity= /** * @notice Withdraw all accumulated rewards to Lido contract * @dev Can be called only by the Lido contract * @return amount of funds received as execution layer rewards (in stake tokens) */ function withdrawRewards(uint256) override external returns (uint256 amount) { require(msg.sender == LIDO, "ONLY_LIDO_CAN_WITHDRAW"); _beforeStakeTokenTransfer(); amount = _getStakeTokenBalance(); if (amount > 0) { _transferStakeToken(LIDO, amount); } return amount; } ``` In the general `LidoExecutionLayerRewardsVaultErc20`, `_beforeStakeTokenTransfer` function is abstract. In the concrete implementations it's overridden. For example, in `LidoExecutionLayerRewardsVaultGnosis` it converts GNO (received from CowSwap) into mGNO: ```solidity= /** * Wrap GNO into mGNO */ function _beforeStakeTokenTransfer() override internal { uint256 gnoBalance = _getGnoBalance(); _convertGnoToMgno(gnoBalance); } ``` In the end, the `_transferStakeToken` function transfers the resulting mGNO to the `Lido` contract, where this mGNO is added to the pooled mGNO available for staking. ### 5. Generalized approach for Lido to work with the native currency and ERC20-compatible tokens #### First design (old): <figure> <img src="https://i.imgur.com/WXE2bA5.png" alt="The proposed Lido generalized for ETH and ERC20"> <figcaption> <center> The proposed Lido generalized for ETH and ERC20 </center> </figcaption> </figure> For `submit` logic, add helper contracts `LidoEth`, `LidoErc20` (abstract), and `LidoGnosis` (concrete implementation with Gnosis-specific features). For EL rewards, extract the common logic into an abstract `LidoExecutionLayerRewardsVaultBase` and put the specific features into deriving dedicated contracts `LidoExecutionLayerRewardsVaultEth`, `LidoExecutionLayerRewardsVaultErc20` (abstract), and `LidoExecutionLayerRewardsVaultGnosis` (Gnosis-specific). Deploy only ETH or only ERC20 versions separately, depending on the chain staking requirements. In the initial implementation, only submit logic was moved to asset-specific contracts (LidoEth, LidoErc20, LidoGnosis). The rest was kept in the existing Lido contract. However, after further discussions, we decided to propose the approach with linked libraries. #### Second design: <figure> <img src="https://i.imgur.com/jw47c8h.png" alt="The proposed Lido with a linked library LidoLib"> <figcaption> <center> The proposed Lido with a linked library LidoLib </center> </figcaption> </figure> Leave the base Lido contract. Derive asset-specific contracts from it. Extract code-heavy functions and functions containing the word "ether" in their names into a linked library (LidoLib). Make all the functions in the library that are called direcly from contracts public or external so that they would not get inlined. ### 6. Naming for external functions Put common state (storage slot names) and functions into a linkable library as described above in the **Second design**.

    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