---
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**.