Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Add Rebasable token to Optimism #58

Draft
wants to merge 65 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 42 commits
Commits
Show all changes
65 commits
Select commit Hold shift + click to select a range
3256d9f
create new contract that represents stETH on L2
kovalgek Oct 10, 2023
e4b2cbd
add wrap/unwrap functions
kovalgek Oct 11, 2023
82038ea
add shares to rebasable token
kovalgek Oct 13, 2023
380caaa
add unit tests
kovalgek Oct 17, 2023
eab8718
add deposit flow for new rebasable token
kovalgek Nov 4, 2023
c3bc0db
add withdraw flow for rebasable token on optimism
kovalgek Nov 5, 2023
eb98d0b
send rate in data and time during deposit flow
kovalgek Nov 9, 2023
800e33f
add possibility to depost 0 tokens
kovalgek Nov 9, 2023
d9ac556
init structs
kovalgek Nov 9, 2023
ddb9ca3
add comments
kovalgek Dec 11, 2023
a73bcf4
add gas test
kovalgek Dec 11, 2023
6d37edc
update gas test
kovalgek Dec 12, 2023
8098fe1
fix tests
kovalgek Dec 16, 2023
3335339
add token rate oracle
kovalgek Dec 20, 2023
86037dc
add tests for new token, renaming
kovalgek Dec 24, 2023
86788b2
simplify oracle, remove warnings
kovalgek Dec 27, 2023
ddffe1f
update unit tests for token rate oracle
kovalgek Dec 28, 2023
7c79d2d
fix integration tests for rebasable token
kovalgek Jan 9, 2024
6174943
Merge branch 'main' into feature/add_stETH_token_to_optimism
kovalgek Jan 9, 2024
f0b891a
add test for push token rate method
kovalgek Jan 9, 2024
e314bb1
unused return values fix
kovalgek Jan 9, 2024
4b56ccf
fix deployment scripts for new oracle and token
kovalgek Jan 9, 2024
3b82da7
add hearbeat to oracle
kovalgek Jan 10, 2024
171db5a
pr fixes from first rount review: apply unstructured storage in token…
kovalgek Jan 22, 2024
76b4ff3
PR fixes: fix comments, rename interface, abstract wst
kovalgek Jan 29, 2024
7abf60f
use real implemnations of non rebasable token and oracle contracts in…
kovalgek Feb 2, 2024
707da9b
update unit tests for bridges
kovalgek Feb 8, 2024
1cb344a
fix evetns + formating
kovalgek Feb 13, 2024
f9463f0
Merge branch 'main' into feature/add_stETH_token_to_optimism
kovalgek Feb 29, 2024
3fd1e94
move token rate to the base contract
kovalgek Mar 6, 2024
66b2501
use inheritance for token rate in l1 bridge, fix e2e tests
kovalgek Mar 6, 2024
7badd9e
add rebasable token e2e tests
kovalgek Mar 6, 2024
72bc8f3
add bridging-to e2e tests for rebasable token
kovalgek Mar 6, 2024
83e292b
add token rate observer
kovalgek Mar 7, 2024
dbf2f92
add observers array
kovalgek Mar 14, 2024
47c50c6
add factory and tests
kovalgek Mar 18, 2024
7e45410
add unit tests for notifier
kovalgek Mar 19, 2024
55111b8
add token rate pusher
kovalgek Mar 22, 2024
d99a52f
update unit tests for token rate oracle
kovalgek Mar 22, 2024
fb3eb40
remove observer array
kovalgek Mar 22, 2024
b167ebd
fix token rate publicher and notifier unit tests
kovalgek Mar 22, 2024
55d2e3f
fix small comments from PR review
kovalgek Mar 22, 2024
13712ca
feat(steth): intermediate work on adding ERC-2612/EIP-1271 permit
arwer13 Mar 27, 2024
6a46704
update optimism sdk version to fix integration tests
kovalgek Mar 29, 2024
b9d5e56
update addresses to run e2e tests
kovalgek Mar 29, 2024
a3f4544
fix integration test
kovalgek Mar 29, 2024
e2c29e0
deployment scripts
kovalgek Apr 1, 2024
d28d53d
Merge branch 'feature/add_stETH_token_to_optimism' into feat/steth-pe…
arwer13 Apr 1, 2024
0d2df1d
add token rate oracle integration tests
kovalgek Apr 1, 2024
8dc246e
fix happy path test for permit for rebasable
arwer13 Apr 2, 2024
ba0b41e
test(rebasable permit): move the rest tests from core stethpermit.tes…
arwer13 Apr 2, 2024
18a1dc5
add e2e tests for oracle
kovalgek Apr 2, 2024
624219c
Merge pull request #74 from lidofinance/feat/steth-permit
kovalgek Apr 2, 2024
5f86091
remove increaseAllowance and decreaseAllowance from tokens
kovalgek Apr 3, 2024
cc868ef
change function names
kovalgek Apr 3, 2024
06d00c7
rename stETH to rebasable token in env
kovalgek Apr 3, 2024
0b22b0f
deploy all script, refactor other deploy scripts
kovalgek Apr 8, 2024
f563fab
add permit to non-rebasable token
kovalgek Apr 9, 2024
3332e30
add unit tests for non-rebasable token
kovalgek Apr 10, 2024
0545e33
PR fixes: fix comments, readme, rename bridges, notifier refactoring
kovalgek Apr 10, 2024
a55b5f0
use mapping for tokens in bridges
kovalgek Apr 15, 2024
f54eecd
fix bridge unit and integration tests, remove mapping in storing toke…
kovalgek Apr 15, 2024
bc1c56f
fix scripts
kovalgek Apr 15, 2024
b62fbee
PR fixes: add comments, rename constracts, more interfaces to contrac…
kovalgek Apr 15, 2024
f387de6
PR fixes: rename tokens, add sanity check to oracle update, add unit …
kovalgek Apr 16, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
charset = utf-8
indent_style = space
indent_size = 4

[*.{js,yml,json,cjs}]
indent_size = 2
max_line_length = 120
6 changes: 6 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ ETHERSCAN_API_KEY_OPT=
# Address of the token to deploy the bridge/gateway for
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
TOKEN=

# Address of the rebasable token to deploy the bridge/gateway for
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
STETH_TOKEN=

# Name of the network environments used by deployment scripts.
# Might be one of: "mainnet", "goerli".
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
NETWORK=mainnet
Expand Down Expand Up @@ -74,6 +77,9 @@ TESTING_ARB_L2_GATEWAY_ROUTER=0x57f54f87C44d816f60b92864e23b8c0897D4d81D
TESTING_OPT_NETWORK=
TESTING_OPT_L1_TOKEN=0xaF8a2F0aE374b03376155BF745A3421Dac711C12
TESTING_OPT_L2_TOKEN=0xAED5F9aaF167923D34174b8E636aaF040A11f6F7
TESTING_OPT_L1_REBASABLE_TOKEN=0xB82381A3fBD3FaFA77B3a7bE693342618240067b
TESTING_OPT_L2_REBASABLE_TOKEN=0x6696Cb7bb602FC744254Ad9E07EfC474FBF78857
TESTING_OPT_L2_TOKEN_RATE_ORACLE=0x8ea513d1e5Be31fb5FC2f2971897594720de9E70
TESTING_OPT_L1_ERC20_TOKEN_BRIDGE=0x243b661276670bD17399C488E7287ea4D416115b
TESTING_OPT_L2_ERC20_TOKEN_BRIDGE=0x447CD1794d209Ac4E6B4097B34658bc00C4d0a51

Expand Down
3 changes: 3 additions & 0 deletions .env.wsteth.opt_mainnet
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ ETHERSCAN_API_KEY_OPT=
# Address of the token to deploy the bridge/gateway for
TOKEN=0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0

# Address of the rebasable token to deploy the bridge/gateway for
STETH_TOKEN=

# Name of the network environments used by deployment scripts.
# Might be one of: "mainnet", "goerli".
NETWORK=mainnet
Expand Down
9 changes: 7 additions & 2 deletions README.md
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ Fill the newly created `.env` file with the required variables. See the [Project

The configuration of the deployment scripts happens via the ENV variables. The following variables are required:

- [`TOKEN`](#TOKEN) - address of the token to deploy a new bridge on the Ethereum chain.
- [`TOKEN`](#TOKEN) - address of the non-rebasable token to deploy a new bridge on the Ethereum chain.
- [`STETH_TOKEN`] (#STETH_TOKEN) - address of the rebasable token to deploy new bridge on the Ethereum chain.
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
- [`NETWORK`](#NETWORK) - name of the network environments used by deployment scripts. Allowed values: `mainnet`, `goerli`.
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
- [`FORKING`](#FORKING) - run deployment in the forking network instead of real ones
- [`ETH_DEPLOYER_PRIVATE_KEY`](#ETH_DEPLOYER_PRIVATE_KEY) - The private key of the deployer account in the Ethereum network is used during the deployment process.
Expand Down Expand Up @@ -314,7 +315,11 @@ Below variables used in the Arbitrum/Optimism bridge deployment process.

#### `TOKEN`

Address of the token to deploy a new bridge on the Ethereum chain.
Address of the non-rebasable token to deploy a new bridge on the Ethereum chain.
kovalgek marked this conversation as resolved.
Show resolved Hide resolved

#### `STETH_TOKEN`

Address of the rebasable token to deploy new bridge on the Ethereum chain.
kovalgek marked this conversation as resolved.
Show resolved Hide resolved

#### `NETWORK`

Expand Down
120 changes: 120 additions & 0 deletions contracts/lido/TokenRateNotifier.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// SPDX-FileCopyrightText: 2024 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.10;

import {IPostTokenRebaseReceiver} from "./interfaces/IPostTokenRebaseReceiver.sol";
import {ITokenRatePusher} from "./interfaces/ITokenRatePusher.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ERC165Checker} from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";

/// @author kovalgek
/// @notice Notifies all observers when rebase event occures.
contract TokenRateNotifier is Ownable, IPostTokenRebaseReceiver {
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
using ERC165Checker for address;

/// @notice Maximum amount of observers to be supported.
uint256 public constant MAX_OBSERVERS_COUNT = 16;
kovalgek marked this conversation as resolved.
Show resolved Hide resolved

/// @notice Invalid interface id.
bytes4 public constant INVALID_INTERFACE_ID = 0xffffffff;
kovalgek marked this conversation as resolved.
Show resolved Hide resolved

/// @notice A value that indicates that value was not found.
uint256 public constant INDEX_NOT_FOUND = type(uint256).max;

/// @notice An interface that each observer should support.
bytes4 public constant REQUIRED_INTERFACE = type(ITokenRatePusher).interfaceId;

/// @notice All observers.
address[] public observers;

/// @notice Add a `observer_` to the back of array
/// @param observer_ observer address
function addObserver(address observer_) external onlyOwner {
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
if (observer_ == address(0)) {
revert ErrorZeroAddressObserver();
}
if (!observer_.supportsInterface(REQUIRED_INTERFACE)) {
revert ErrorBadObserverInterface();
}
if (observers.length >= MAX_OBSERVERS_COUNT) {
revert ErrorMaxObserversCountExceeded();
}

observers.push(observer_);
emit ObserverAdded(observer_);
}

/// @notice Remove a observer at the given `observer_` position
/// @param observer_ observer remove position
function removeObserver(address observer_) external onlyOwner {
kovalgek marked this conversation as resolved.
Show resolved Hide resolved

uint256 observerIndexToRemove = _observerIndex(observer_);

if (observerIndexToRemove == INDEX_NOT_FOUND) {
revert ErrorNoObserverToRemove();
}

for (uint256 obIndex = observerIndexToRemove; obIndex < observers.length - 1; obIndex++) {
observers[obIndex] = observers[obIndex + 1];
}

observers.pop();

emit ObserverRemoved(observer_);
}

/// @inheritdoc IPostTokenRebaseReceiver
function handlePostTokenRebase(
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
) external {
for (uint256 obIndex = 0; obIndex < observers.length; obIndex++) {
try ITokenRatePusher(observers[obIndex]).pushTokenRate() {}

Check warning on line 78 in contracts/lido/TokenRateNotifier.sol

View workflow job for this annotation

GitHub Actions / solhint

Code contains empty blocks
catch (bytes memory lowLevelRevertData) {

Check warning

Code scanning / Slither

Uninitialized local variables Medium

/// @dev This check is required to prevent incorrect gas estimation of the method.
/// Without it, Ethereum nodes that use binary search for gas estimation may
/// return an invalid value when the pushTokenRate() reverts because of the
/// "out of gas" error. Here we assume that the pushTokenRate() method doesn't
/// have reverts with empty error data except "out of gas".
if (lowLevelRevertData.length == 0) revert ErrorTokenRateNotifierRevertedWithNoData();
emit PushTokenRateFailed(
observers[obIndex],
lowLevelRevertData
);
}
}
}

/// @notice Observer length
/// @return Added observers count
function observersLength() public view returns (uint256) {
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
return observers.length;
}

Check warning

Code scanning / Slither

Public function that could be declared external Warning

observersLength() should be declared external:
- TokenRateNotifier.observersLength()

/// @notice `observer_` index in `observers` array.
/// @return An index of `observer_` or `INDEX_NOT_FOUND` if it wasn't found.
function _observerIndex(address observer_) internal view returns (uint256) {
for (uint256 obIndex = 0; obIndex < observers.length; obIndex++) {
if (observers[obIndex] == observer_) {
return obIndex;
}
}
return INDEX_NOT_FOUND;
}

event PushTokenRateFailed(address indexed observer, bytes lowLevelRevertData);
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
event ObserverAdded(address indexed observer);
event ObserverRemoved(address indexed observer);

error ErrorTokenRateNotifierRevertedWithNoData();
error ErrorZeroAddressObserver();
error ErrorBadObserverInterface();
error ErrorMaxObserversCountExceeded();
error ErrorNoObserverToRemove();
}
20 changes: 20 additions & 0 deletions contracts/lido/interfaces/IPostTokenRebaseReceiver.sol
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// SPDX-FileCopyrightText: 2024 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.10;

/// @author kovalgek
/// @notice An interface to subscribe on the `stETH` token rebases (defined in the `Lido` core contract)
interface IPostTokenRebaseReceiver {

/// @notice Is called in the context of `Lido.handleOracleReport` to notify the subscribers about each token rebase
function handlePostTokenRebase(
uint256 _reportTimestamp,
uint256 _timeElapsed,
uint256 _preTotalShares,
uint256 _preTotalEther,
uint256 _postTotalShares,
uint256 _postTotalEther,
uint256 _sharesMintedAsFees
) external;
}
11 changes: 11 additions & 0 deletions contracts/lido/interfaces/ITokenRatePusher.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// SPDX-FileCopyrightText: 2024 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.10;

/// @author kovalgek
/// @notice An interface for entity that pushes rate.
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
interface ITokenRatePusher {
/// @notice Pushes token rate to L2 by depositing zero tokens.
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
function pushTokenRate() external;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// SPDX-FileCopyrightText: 2024 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

kovalgek marked this conversation as resolved.
Show resolved Hide resolved
pragma solidity 0.8.10;

import {ITokenRatePusher} from "../interfaces/ITokenRatePusher.sol";
import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";

contract OpStackTokenRatePusherWithOutOfGasErrorStub is ERC165, ITokenRatePusher {

mapping (uint256 => uint256) data;

function pushTokenRate() external {
for (uint256 i = 0; i < 1000000000000; ++i) {
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
data[i] = i;
}
}

/// @inheritdoc ERC165
function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) {
return (
_interfaceId == type(ITokenRatePusher).interfaceId
|| super.supportsInterface(_interfaceId)
);
}
}
24 changes: 24 additions & 0 deletions contracts/lido/stubs/OpStackTokenRatePusherWithSomeErrorStub.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// SPDX-FileCopyrightText: 2024 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.10;

import {ITokenRatePusher} from "../interfaces/ITokenRatePusher.sol";
import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";

contract OpStackTokenRatePusherWithSomeErrorStub is ERC165, ITokenRatePusher {

error SomeError();

function pushTokenRate() external {
revert SomeError();
}

/// @inheritdoc ERC165
function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) {
return (
_interfaceId == type(ITokenRatePusher).interfaceId
|| super.supportsInterface(_interfaceId)
);
}
}
10 changes: 5 additions & 5 deletions contracts/optimism/CrossDomainEnabled.sol
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ import {ICrossDomainMessenger} from "./interfaces/ICrossDomainMessenger.sol";
/// @dev Helper contract for contracts performing cross-domain communications
contract CrossDomainEnabled {
/// @notice Messenger contract used to send and receive messages from the other domain
ICrossDomainMessenger public immutable messenger;
ICrossDomainMessenger public immutable MESSENGER;

/// @param messenger_ Address of the CrossDomainMessenger on the current layer
constructor(address messenger_) {
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
messenger = ICrossDomainMessenger(messenger_);
MESSENGER = ICrossDomainMessenger(messenger_);
}

/// @dev Sends a message to an account on another domain
Expand All @@ -25,17 +25,17 @@ contract CrossDomainEnabled {
uint32 gasLimit_,
bytes memory message_
) internal {
messenger.sendMessage(crossDomainTarget_, message_, gasLimit_);
MESSENGER.sendMessage(crossDomainTarget_, message_, gasLimit_);
}

/// @dev Enforces that the modified function is only callable by a specific cross-domain account
/// @param sourceDomainAccount_ The only account on the originating domain which is
/// authenticated to call this function
modifier onlyFromCrossDomainAccount(address sourceDomainAccount_) {
if (msg.sender != address(messenger)) {
if (msg.sender != address(MESSENGER)) {
revert ErrorUnauthorizedMessenger();
}
if (messenger.xDomainMessageSender() != sourceDomainAccount_) {
if (MESSENGER.xDomainMessageSender() != sourceDomainAccount_) {
revert ErrorWrongCrossDomainSender();
}
_;
Expand Down
44 changes: 44 additions & 0 deletions contracts/optimism/DepositDataCodec.sol
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is an attack vector of asynchronous bridge upgrades

E.g., suppose L2 has been updated while L1 hasn't been yet
This case anyone would be able to pass arbitrary tokenRate and timestamp disrupting operations and breaking the protocol's invariants on L2.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Vise versa, if L1 upgraded and L2 is not, then stETH deposits would lead to funds being stuck on the L1 bridge

Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// SPDX-FileCopyrightText: 2023 Lido <[email protected]>
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.10;

/// @author kovalgek
/// @notice encodes and decodes DepositData for crosschain transfering.
contract DepositDataCodec {
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
folkyatina marked this conversation as resolved.
Show resolved Hide resolved
kovalgek marked this conversation as resolved.
Show resolved Hide resolved

uint8 internal constant RATE_FIELD_SIZE = 12;
uint8 internal constant TIMESTAMP_FIELD_SIZE = 5;

struct DepositData {
uint96 rate;
uint40 timestamp;
bytes data;
}

function encodeDepositData(DepositData memory depositData) internal pure returns (bytes memory) {
bytes memory data = bytes.concat(
abi.encodePacked(depositData.rate),
abi.encodePacked(depositData.timestamp),
abi.encodePacked(depositData.data)
);
return data;
}

function decodeDepositData(bytes calldata buffer) internal pure returns (DepositData memory) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

later on would be great to fuzz these methods


if (buffer.length < RATE_FIELD_SIZE + TIMESTAMP_FIELD_SIZE) {
revert ErrorDepositDataLength();
}

DepositData memory depositData = DepositData({
rate: uint96(bytes12(buffer[0:RATE_FIELD_SIZE])),
kovalgek marked this conversation as resolved.
Show resolved Hide resolved
timestamp: uint40(bytes5(buffer[RATE_FIELD_SIZE:RATE_FIELD_SIZE + TIMESTAMP_FIELD_SIZE])),
data: buffer[RATE_FIELD_SIZE + TIMESTAMP_FIELD_SIZE:]
});

return depositData;
}

error ErrorDepositDataLength();
}
Loading
Loading