Commit efc5337e authored by Maurelian's avatar Maurelian Committed by Kelvin Fichter

style(contracts): Rewrite solidity files with prettier

parent f77c5edd
...@@ -2,16 +2,15 @@ ...@@ -2,16 +2,15 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import {Lib_OVMCodec} from "../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */ /* Interface Imports */
import { ICrossDomainMessenger } from "../../libraries/bridge/ICrossDomainMessenger.sol"; import {ICrossDomainMessenger} from "../../libraries/bridge/ICrossDomainMessenger.sol";
/** /**
* @title IL1CrossDomainMessenger * @title IL1CrossDomainMessenger
*/ */
interface IL1CrossDomainMessenger is ICrossDomainMessenger { interface IL1CrossDomainMessenger is ICrossDomainMessenger {
/******************* /*******************
* Data Structures * * Data Structures *
*******************/ *******************/
...@@ -24,7 +23,6 @@ interface IL1CrossDomainMessenger is ICrossDomainMessenger { ...@@ -24,7 +23,6 @@ interface IL1CrossDomainMessenger is ICrossDomainMessenger {
bytes storageTrieWitness; bytes storageTrieWitness;
} }
/******************** /********************
* Public Functions * * Public Functions *
********************/ ********************/
......
...@@ -5,12 +5,11 @@ pragma solidity >0.5.0 <0.9.0; ...@@ -5,12 +5,11 @@ pragma solidity >0.5.0 <0.9.0;
* @title IL1ERC20Bridge * @title IL1ERC20Bridge
*/ */
interface IL1ERC20Bridge { interface IL1ERC20Bridge {
/********** /**********
* Events * * Events *
**********/ **********/
event ERC20DepositInitiated ( event ERC20DepositInitiated(
address indexed _l1Token, address indexed _l1Token,
address indexed _l2Token, address indexed _l2Token,
address indexed _from, address indexed _from,
...@@ -19,7 +18,7 @@ interface IL1ERC20Bridge { ...@@ -19,7 +18,7 @@ interface IL1ERC20Bridge {
bytes _data bytes _data
); );
event ERC20WithdrawalFinalized ( event ERC20WithdrawalFinalized(
address indexed _l1Token, address indexed _l1Token,
address indexed _l2Token, address indexed _l2Token,
address indexed _from, address indexed _from,
...@@ -36,7 +35,7 @@ interface IL1ERC20Bridge { ...@@ -36,7 +35,7 @@ interface IL1ERC20Bridge {
* @dev get the address of the corresponding L2 bridge contract. * @dev get the address of the corresponding L2 bridge contract.
* @return Address of the corresponding L2 bridge contract. * @return Address of the corresponding L2 bridge contract.
*/ */
function l2TokenBridge() external returns(address); function l2TokenBridge() external returns (address);
/** /**
* @dev deposit an amount of the ERC20 to the caller's balance on L2. * @dev deposit an amount of the ERC20 to the caller's balance on L2.
...@@ -48,14 +47,13 @@ interface IL1ERC20Bridge { ...@@ -48,14 +47,13 @@ interface IL1ERC20Bridge {
* solely as a convenience for external contracts. Aside from enforcing a maximum * solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content. * length, these contracts provide no guarantees about its content.
*/ */
function depositERC20 ( function depositERC20(
address _l1Token, address _l1Token,
address _l2Token, address _l2Token,
uint _amount, uint256 _amount,
uint32 _l2Gas, uint32 _l2Gas,
bytes calldata _data bytes calldata _data
) ) external;
external;
/** /**
* @dev deposit an amount of ERC20 to a recipient's balance on L2. * @dev deposit an amount of ERC20 to a recipient's balance on L2.
...@@ -68,16 +66,14 @@ interface IL1ERC20Bridge { ...@@ -68,16 +66,14 @@ interface IL1ERC20Bridge {
* solely as a convenience for external contracts. Aside from enforcing a maximum * solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content. * length, these contracts provide no guarantees about its content.
*/ */
function depositERC20To ( function depositERC20To(
address _l1Token, address _l1Token,
address _l2Token, address _l2Token,
address _to, address _to,
uint _amount, uint256 _amount,
uint32 _l2Gas, uint32 _l2Gas,
bytes calldata _data bytes calldata _data
) ) external;
external;
/************************* /*************************
* Cross-chain Functions * * Cross-chain Functions *
...@@ -97,13 +93,12 @@ interface IL1ERC20Bridge { ...@@ -97,13 +93,12 @@ interface IL1ERC20Bridge {
* solely as a convenience for external contracts. Aside from enforcing a maximum * solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content. * length, these contracts provide no guarantees about its content.
*/ */
function finalizeERC20Withdrawal ( function finalizeERC20Withdrawal(
address _l1Token, address _l1Token,
address _l2Token, address _l2Token,
address _from, address _from,
address _to, address _to,
uint _amount, uint256 _amount,
bytes calldata _data bytes calldata _data
) ) external;
external;
} }
...@@ -7,18 +7,17 @@ import "./IL1ERC20Bridge.sol"; ...@@ -7,18 +7,17 @@ import "./IL1ERC20Bridge.sol";
* @title IL1StandardBridge * @title IL1StandardBridge
*/ */
interface IL1StandardBridge is IL1ERC20Bridge { interface IL1StandardBridge is IL1ERC20Bridge {
/********** /**********
* Events * * Events *
**********/ **********/
event ETHDepositInitiated ( event ETHDepositInitiated(
address indexed _from, address indexed _from,
address indexed _to, address indexed _to,
uint256 _amount, uint256 _amount,
bytes _data bytes _data
); );
event ETHWithdrawalFinalized ( event ETHWithdrawalFinalized(
address indexed _from, address indexed _from,
address indexed _to, address indexed _to,
uint256 _amount, uint256 _amount,
...@@ -36,12 +35,7 @@ interface IL1StandardBridge is IL1ERC20Bridge { ...@@ -36,12 +35,7 @@ interface IL1StandardBridge is IL1ERC20Bridge {
* solely as a convenience for external contracts. Aside from enforcing a maximum * solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content. * length, these contracts provide no guarantees about its content.
*/ */
function depositETH ( function depositETH(uint32 _l2Gas, bytes calldata _data) external payable;
uint32 _l2Gas,
bytes calldata _data
)
external
payable;
/** /**
* @dev Deposit an amount of ETH to a recipient's balance on L2. * @dev Deposit an amount of ETH to a recipient's balance on L2.
...@@ -51,13 +45,11 @@ interface IL1StandardBridge is IL1ERC20Bridge { ...@@ -51,13 +45,11 @@ interface IL1StandardBridge is IL1ERC20Bridge {
* solely as a convenience for external contracts. Aside from enforcing a maximum * solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content. * length, these contracts provide no guarantees about its content.
*/ */
function depositETHTo ( function depositETHTo(
address _to, address _to,
uint32 _l2Gas, uint32 _l2Gas,
bytes calldata _data bytes calldata _data
) ) external payable;
external
payable;
/************************* /*************************
* Cross-chain Functions * * Cross-chain Functions *
...@@ -74,11 +66,10 @@ interface IL1StandardBridge is IL1ERC20Bridge { ...@@ -74,11 +66,10 @@ interface IL1StandardBridge is IL1ERC20Bridge {
* solely as a convenience for external contracts. Aside from enforcing a maximum * solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content. * length, these contracts provide no guarantees about its content.
*/ */
function finalizeETHWithdrawal ( function finalizeETHWithdrawal(
address _from, address _from,
address _to, address _to,
uint _amount, uint256 _amount,
bytes calldata _data bytes calldata _data
) ) external;
external;
} }
...@@ -2,27 +2,30 @@ ...@@ -2,27 +2,30 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { AddressAliasHelper } from "../../standards/AddressAliasHelper.sol"; import {AddressAliasHelper} from "../../standards/AddressAliasHelper.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import {Lib_AddressResolver} from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import {Lib_OVMCodec} from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressManager } from "../../libraries/resolver/Lib_AddressManager.sol"; import {Lib_AddressManager} from "../../libraries/resolver/Lib_AddressManager.sol";
import { Lib_SecureMerkleTrie } from "../../libraries/trie/Lib_SecureMerkleTrie.sol"; import {Lib_SecureMerkleTrie} from "../../libraries/trie/Lib_SecureMerkleTrie.sol";
import { Lib_DefaultValues } from "../../libraries/constants/Lib_DefaultValues.sol"; import {Lib_DefaultValues} from "../../libraries/constants/Lib_DefaultValues.sol";
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; import {Lib_PredeployAddresses} from "../../libraries/constants/Lib_PredeployAddresses.sol";
import { Lib_CrossDomainUtils } from "../../libraries/bridge/Lib_CrossDomainUtils.sol"; import {Lib_CrossDomainUtils} from "../../libraries/bridge/Lib_CrossDomainUtils.sol";
/* Interface Imports */ /* Interface Imports */
import { IL1CrossDomainMessenger } from "./IL1CrossDomainMessenger.sol"; import {IL1CrossDomainMessenger} from "./IL1CrossDomainMessenger.sol";
import { ICanonicalTransactionChain } from "../rollup/ICanonicalTransactionChain.sol"; import {ICanonicalTransactionChain} from "../rollup/ICanonicalTransactionChain.sol";
import { IStateCommitmentChain } from "../rollup/IStateCommitmentChain.sol"; import {IStateCommitmentChain} from "../rollup/IStateCommitmentChain.sol";
/* External Imports */ /* External Imports */
import { OwnableUpgradeable } from import {
"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; OwnableUpgradeable
import { PausableUpgradeable } from } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import {
import { ReentrancyGuardUpgradeable } from PausableUpgradeable
"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; } from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import {
ReentrancyGuardUpgradeable
} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
/** /**
* @title L1CrossDomainMessenger * @title L1CrossDomainMessenger
...@@ -39,31 +42,24 @@ contract L1CrossDomainMessenger is ...@@ -39,31 +42,24 @@ contract L1CrossDomainMessenger is
PausableUpgradeable, PausableUpgradeable,
ReentrancyGuardUpgradeable ReentrancyGuardUpgradeable
{ {
/********** /**********
* Events * * Events *
**********/ **********/
event MessageBlocked( event MessageBlocked(bytes32 indexed _xDomainCalldataHash);
bytes32 indexed _xDomainCalldataHash
);
event MessageAllowed(
bytes32 indexed _xDomainCalldataHash
);
event MessageAllowed(bytes32 indexed _xDomainCalldataHash);
/********************** /**********************
* Contract Variables * * Contract Variables *
**********************/ **********************/
mapping (bytes32 => bool) public blockedMessages; mapping(bytes32 => bool) public blockedMessages;
mapping (bytes32 => bool) public relayedMessages; mapping(bytes32 => bool) public relayedMessages;
mapping (bytes32 => bool) public successfulMessages; mapping(bytes32 => bool) public successfulMessages;
address internal xDomainMsgSender = Lib_DefaultValues.DEFAULT_XDOMAIN_SENDER; address internal xDomainMsgSender = Lib_DefaultValues.DEFAULT_XDOMAIN_SENDER;
/*************** /***************
* Constructor * * Constructor *
***************/ ***************/
...@@ -73,10 +69,7 @@ contract L1CrossDomainMessenger is ...@@ -73,10 +69,7 @@ contract L1CrossDomainMessenger is
* We pass the zero address to the address resolver just to satisfy the constructor. * We pass the zero address to the address resolver just to satisfy the constructor.
* We still need to set this value in initialize(). * We still need to set this value in initialize().
*/ */
constructor() constructor() Lib_AddressResolver(address(0)) {}
Lib_AddressResolver(address(0))
{}
/******************** /********************
* Public Functions * * Public Functions *
...@@ -85,12 +78,7 @@ contract L1CrossDomainMessenger is ...@@ -85,12 +78,7 @@ contract L1CrossDomainMessenger is
/** /**
* @param _libAddressManager Address of the Address Manager. * @param _libAddressManager Address of the Address Manager.
*/ */
function initialize( function initialize(address _libAddressManager) public initializer {
address _libAddressManager
)
public
initializer
{
require( require(
address(libAddressManager) == address(0), address(libAddressManager) == address(0),
"L1CrossDomainMessenger already intialized." "L1CrossDomainMessenger already intialized."
...@@ -108,10 +96,7 @@ contract L1CrossDomainMessenger is ...@@ -108,10 +96,7 @@ contract L1CrossDomainMessenger is
/** /**
* Pause relaying. * Pause relaying.
*/ */
function pause() function pause() external onlyOwner {
external
onlyOwner
{
_pause(); _pause();
} }
...@@ -119,12 +104,7 @@ contract L1CrossDomainMessenger is ...@@ -119,12 +104,7 @@ contract L1CrossDomainMessenger is
* Block a message. * Block a message.
* @param _xDomainCalldataHash Hash of the message to block. * @param _xDomainCalldataHash Hash of the message to block.
*/ */
function blockMessage( function blockMessage(bytes32 _xDomainCalldataHash) external onlyOwner {
bytes32 _xDomainCalldataHash
)
external
onlyOwner
{
blockedMessages[_xDomainCalldataHash] = true; blockedMessages[_xDomainCalldataHash] = true;
emit MessageBlocked(_xDomainCalldataHash); emit MessageBlocked(_xDomainCalldataHash);
} }
...@@ -133,24 +113,16 @@ contract L1CrossDomainMessenger is ...@@ -133,24 +113,16 @@ contract L1CrossDomainMessenger is
* Allow a message. * Allow a message.
* @param _xDomainCalldataHash Hash of the message to block. * @param _xDomainCalldataHash Hash of the message to block.
*/ */
function allowMessage( function allowMessage(bytes32 _xDomainCalldataHash) external onlyOwner {
bytes32 _xDomainCalldataHash
)
external
onlyOwner
{
blockedMessages[_xDomainCalldataHash] = false; blockedMessages[_xDomainCalldataHash] = false;
emit MessageAllowed(_xDomainCalldataHash); emit MessageAllowed(_xDomainCalldataHash);
} }
function xDomainMessageSender() function xDomainMessageSender() public view returns (address) {
public require(
view xDomainMsgSender != Lib_DefaultValues.DEFAULT_XDOMAIN_SENDER,
returns ( "xDomainMessageSender is not set"
address );
)
{
require(xDomainMsgSender != Lib_DefaultValues.DEFAULT_XDOMAIN_SENDER, "xDomainMessageSender is not set");
return xDomainMsgSender; return xDomainMsgSender;
} }
...@@ -164,13 +136,10 @@ contract L1CrossDomainMessenger is ...@@ -164,13 +136,10 @@ contract L1CrossDomainMessenger is
address _target, address _target,
bytes memory _message, bytes memory _message,
uint32 _gasLimit uint32 _gasLimit
) ) public {
public
{
address ovmCanonicalTransactionChain = resolve("CanonicalTransactionChain"); address ovmCanonicalTransactionChain = resolve("CanonicalTransactionChain");
// Use the CTC queue length as nonce // Use the CTC queue length as nonce
uint40 nonce = uint40 nonce = ICanonicalTransactionChain(ovmCanonicalTransactionChain).getQueueLength();
ICanonicalTransactionChain(ovmCanonicalTransactionChain).getQueueLength();
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target, _target,
...@@ -179,11 +148,7 @@ contract L1CrossDomainMessenger is ...@@ -179,11 +148,7 @@ contract L1CrossDomainMessenger is
nonce nonce
); );
_sendXDomainMessage( _sendXDomainMessage(ovmCanonicalTransactionChain, xDomainCalldata, _gasLimit);
ovmCanonicalTransactionChain,
xDomainCalldata,
_gasLimit
);
emit SentMessage(_target, msg.sender, _message, nonce, _gasLimit); emit SentMessage(_target, msg.sender, _message, nonce, _gasLimit);
} }
...@@ -198,11 +163,7 @@ contract L1CrossDomainMessenger is ...@@ -198,11 +163,7 @@ contract L1CrossDomainMessenger is
bytes memory _message, bytes memory _message,
uint256 _messageNonce, uint256 _messageNonce,
L2MessageInclusionProof memory _proof L2MessageInclusionProof memory _proof
) ) public nonReentrant whenNotPaused {
public
nonReentrant
whenNotPaused
{
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target, _target,
_sender, _sender,
...@@ -211,10 +172,7 @@ contract L1CrossDomainMessenger is ...@@ -211,10 +172,7 @@ contract L1CrossDomainMessenger is
); );
require( require(
_verifyXDomainMessage( _verifyXDomainMessage(xDomainCalldata, _proof) == true,
xDomainCalldata,
_proof
) == true,
"Provided message could not be verified." "Provided message could not be verified."
); );
...@@ -250,13 +208,7 @@ contract L1CrossDomainMessenger is ...@@ -250,13 +208,7 @@ contract L1CrossDomainMessenger is
// Store an identifier that can be used to prove that the given message was relayed by some // Store an identifier that can be used to prove that the given message was relayed by some
// user. Gives us an easy way to pay relayers for their work. // user. Gives us an easy way to pay relayers for their work.
bytes32 relayId = keccak256( bytes32 relayId = keccak256(abi.encodePacked(xDomainCalldata, msg.sender, block.number));
abi.encodePacked(
xDomainCalldata,
msg.sender,
block.number
)
);
relayedMessages[relayId] = true; relayedMessages[relayId] = true;
} }
...@@ -271,13 +223,12 @@ contract L1CrossDomainMessenger is ...@@ -271,13 +223,12 @@ contract L1CrossDomainMessenger is
uint256 _queueIndex, uint256 _queueIndex,
uint32 _oldGasLimit, uint32 _oldGasLimit,
uint32 _newGasLimit uint32 _newGasLimit
) ) public {
public
{
// Verify that the message is in the queue: // Verify that the message is in the queue:
address canonicalTransactionChain = resolve("CanonicalTransactionChain"); address canonicalTransactionChain = resolve("CanonicalTransactionChain");
Lib_OVMCodec.QueueElement memory element = Lib_OVMCodec.QueueElement memory element = ICanonicalTransactionChain(
ICanonicalTransactionChain(canonicalTransactionChain).getQueueElement(_queueIndex); canonicalTransactionChain
).getQueueElement(_queueIndex);
// Compute the calldata that was originally used to send the message. // Compute the calldata that was originally used to send the message.
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
...@@ -304,14 +255,9 @@ contract L1CrossDomainMessenger is ...@@ -304,14 +255,9 @@ contract L1CrossDomainMessenger is
); );
// Send the same message but with the new gas limit. // Send the same message but with the new gas limit.
_sendXDomainMessage( _sendXDomainMessage(canonicalTransactionChain, xDomainCalldata, _newGasLimit);
canonicalTransactionChain,
xDomainCalldata,
_newGasLimit
);
} }
/********************** /**********************
* Internal Functions * * Internal Functions *
**********************/ **********************/
...@@ -325,17 +271,8 @@ contract L1CrossDomainMessenger is ...@@ -325,17 +271,8 @@ contract L1CrossDomainMessenger is
function _verifyXDomainMessage( function _verifyXDomainMessage(
bytes memory _xDomainCalldata, bytes memory _xDomainCalldata,
L2MessageInclusionProof memory _proof L2MessageInclusionProof memory _proof
) ) internal view returns (bool) {
internal return (_verifyStateRootProof(_proof) && _verifyStorageProof(_xDomainCalldata, _proof));
view
returns (
bool
)
{
return (
_verifyStateRootProof(_proof)
&& _verifyStorageProof(_xDomainCalldata, _proof)
);
} }
/** /**
...@@ -343,27 +280,22 @@ contract L1CrossDomainMessenger is ...@@ -343,27 +280,22 @@ contract L1CrossDomainMessenger is
* @param _proof Message inclusion proof. * @param _proof Message inclusion proof.
* @return Whether or not the provided proof is valid. * @return Whether or not the provided proof is valid.
*/ */
function _verifyStateRootProof( function _verifyStateRootProof(L2MessageInclusionProof memory _proof)
L2MessageInclusionProof memory _proof
)
internal internal
view view
returns ( returns (bool)
bool
)
{ {
IStateCommitmentChain ovmStateCommitmentChain = IStateCommitmentChain( IStateCommitmentChain ovmStateCommitmentChain = IStateCommitmentChain(
resolve("StateCommitmentChain") resolve("StateCommitmentChain")
); );
return ( return (ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) ==
ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false false &&
&& ovmStateCommitmentChain.verifyStateCommitment( ovmStateCommitmentChain.verifyStateCommitment(
_proof.stateRoot, _proof.stateRoot,
_proof.stateRootBatchHeader, _proof.stateRootBatchHeader,
_proof.stateRootProof _proof.stateRootProof
) ));
);
} }
/** /**
...@@ -375,13 +307,7 @@ contract L1CrossDomainMessenger is ...@@ -375,13 +307,7 @@ contract L1CrossDomainMessenger is
function _verifyStorageProof( function _verifyStorageProof(
bytes memory _xDomainCalldata, bytes memory _xDomainCalldata,
L2MessageInclusionProof memory _proof L2MessageInclusionProof memory _proof
) ) internal view returns (bool) {
internal
view
returns (
bool
)
{
bytes32 storageKey = keccak256( bytes32 storageKey = keccak256(
abi.encodePacked( abi.encodePacked(
keccak256( keccak256(
...@@ -394,10 +320,7 @@ contract L1CrossDomainMessenger is ...@@ -394,10 +320,7 @@ contract L1CrossDomainMessenger is
) )
); );
( (bool exists, bytes memory encodedMessagePassingAccount) = Lib_SecureMerkleTrie.get(
bool exists,
bytes memory encodedMessagePassingAccount
) = Lib_SecureMerkleTrie.get(
abi.encodePacked(Lib_PredeployAddresses.L2_TO_L1_MESSAGE_PASSER), abi.encodePacked(Lib_PredeployAddresses.L2_TO_L1_MESSAGE_PASSER),
_proof.stateTrieWitness, _proof.stateTrieWitness,
_proof.stateRoot _proof.stateRoot
...@@ -412,12 +335,13 @@ contract L1CrossDomainMessenger is ...@@ -412,12 +335,13 @@ contract L1CrossDomainMessenger is
encodedMessagePassingAccount encodedMessagePassingAccount
); );
return Lib_SecureMerkleTrie.verifyInclusionProof( return
abi.encodePacked(storageKey), Lib_SecureMerkleTrie.verifyInclusionProof(
abi.encodePacked(uint8(1)), abi.encodePacked(storageKey),
_proof.storageTrieWitness, abi.encodePacked(uint8(1)),
account.storageRoot _proof.storageTrieWitness,
); account.storageRoot
);
} }
/** /**
...@@ -430,9 +354,7 @@ contract L1CrossDomainMessenger is ...@@ -430,9 +354,7 @@ contract L1CrossDomainMessenger is
address _canonicalTransactionChain, address _canonicalTransactionChain,
bytes memory _message, bytes memory _message,
uint256 _gasLimit uint256 _gasLimit
) ) internal {
internal
{
ICanonicalTransactionChain(_canonicalTransactionChain).enqueue( ICanonicalTransactionChain(_canonicalTransactionChain).enqueue(
Lib_PredeployAddresses.L2_CROSS_DOMAIN_MESSENGER, Lib_PredeployAddresses.L2_CROSS_DOMAIN_MESSENGER,
_gasLimit, _gasLimit,
......
...@@ -2,16 +2,16 @@ ...@@ -2,16 +2,16 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Interface Imports */ /* Interface Imports */
import { IL1StandardBridge } from "./IL1StandardBridge.sol"; import {IL1StandardBridge} from "./IL1StandardBridge.sol";
import { IL1ERC20Bridge } from "./IL1ERC20Bridge.sol"; import {IL1ERC20Bridge} from "./IL1ERC20Bridge.sol";
import { IL2ERC20Bridge } from "../../L2/messaging/IL2ERC20Bridge.sol"; import {IL2ERC20Bridge} from "../../L2/messaging/IL2ERC20Bridge.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/* Library Imports */ /* Library Imports */
import { CrossDomainEnabled } from "../../libraries/bridge/CrossDomainEnabled.sol"; import {CrossDomainEnabled} from "../../libraries/bridge/CrossDomainEnabled.sol";
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; import {Lib_PredeployAddresses} from "../../libraries/constants/Lib_PredeployAddresses.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/** /**
* @title L1StandardBridge * @title L1StandardBridge
...@@ -31,16 +31,14 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled { ...@@ -31,16 +31,14 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled {
address public l2TokenBridge; address public l2TokenBridge;
// Maps L1 token to L2 token to balance of the L1 token deposited // Maps L1 token to L2 token to balance of the L1 token deposited
mapping(address => mapping (address => uint256)) public deposits; mapping(address => mapping(address => uint256)) public deposits;
/*************** /***************
* Constructor * * Constructor *
***************/ ***************/
// This contract lives behind a proxy, so the constructor parameters will go unused. // This contract lives behind a proxy, so the constructor parameters will go unused.
constructor() constructor() CrossDomainEnabled(address(0)) {}
CrossDomainEnabled(address(0))
{}
/****************** /******************
* Initialization * * Initialization *
...@@ -50,12 +48,7 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled { ...@@ -50,12 +48,7 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled {
* @param _l1messenger L1 Messenger address being used for cross-chain communications. * @param _l1messenger L1 Messenger address being used for cross-chain communications.
* @param _l2TokenBridge L2 standard bridge address. * @param _l2TokenBridge L2 standard bridge address.
*/ */
function initialize( function initialize(address _l1messenger, address _l2TokenBridge) public {
address _l1messenger,
address _l2TokenBridge
)
public
{
require(messenger == address(0), "Contract has already been initialized."); require(messenger == address(0), "Contract has already been initialized.");
messenger = _l1messenger; messenger = _l1messenger;
l2TokenBridge = _l2TokenBridge; l2TokenBridge = _l2TokenBridge;
...@@ -80,36 +73,15 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled { ...@@ -80,36 +73,15 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled {
* Since the receive function doesn't take data, a conservative * Since the receive function doesn't take data, a conservative
* default amount is forwarded to L2. * default amount is forwarded to L2.
*/ */
receive() receive() external payable onlyEOA {
external _initiateETHDeposit(msg.sender, msg.sender, 1_300_000, bytes(""));
payable
onlyEOA()
{
_initiateETHDeposit(
msg.sender,
msg.sender,
1_300_000,
bytes("")
);
} }
/** /**
* @inheritdoc IL1StandardBridge * @inheritdoc IL1StandardBridge
*/ */
function depositETH( function depositETH(uint32 _l2Gas, bytes calldata _data) external payable onlyEOA {
uint32 _l2Gas, _initiateETHDeposit(msg.sender, msg.sender, _l2Gas, _data);
bytes calldata _data
)
external
payable
onlyEOA()
{
_initiateETHDeposit(
msg.sender,
msg.sender,
_l2Gas,
_data
);
} }
/** /**
...@@ -119,16 +91,8 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled { ...@@ -119,16 +91,8 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled {
address _to, address _to,
uint32 _l2Gas, uint32 _l2Gas,
bytes calldata _data bytes calldata _data
) ) external payable {
external _initiateETHDeposit(msg.sender, _to, _l2Gas, _data);
payable
{
_initiateETHDeposit(
msg.sender,
_to,
_l2Gas,
_data
);
} }
/** /**
...@@ -146,27 +110,20 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled { ...@@ -146,27 +110,20 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled {
address _to, address _to,
uint32 _l2Gas, uint32 _l2Gas,
bytes memory _data bytes memory _data
) ) internal {
internal
{
// Construct calldata for finalizeDeposit call // Construct calldata for finalizeDeposit call
bytes memory message = bytes memory message = abi.encodeWithSelector(
abi.encodeWithSelector( IL2ERC20Bridge.finalizeDeposit.selector,
IL2ERC20Bridge.finalizeDeposit.selector, address(0),
address(0), Lib_PredeployAddresses.OVM_ETH,
Lib_PredeployAddresses.OVM_ETH, _from,
_from, _to,
_to, msg.value,
msg.value, _data
_data );
);
// Send calldata into L2 // Send calldata into L2
sendCrossDomainMessage( sendCrossDomainMessage(l2TokenBridge, _l2Gas, message);
l2TokenBridge,
_l2Gas,
message
);
emit ETHDepositInitiated(_from, _to, msg.value, _data); emit ETHDepositInitiated(_from, _to, msg.value, _data);
} }
...@@ -180,15 +137,11 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled { ...@@ -180,15 +137,11 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled {
uint256 _amount, uint256 _amount,
uint32 _l2Gas, uint32 _l2Gas,
bytes calldata _data bytes calldata _data
) ) external virtual onlyEOA {
external
virtual
onlyEOA()
{
_initiateERC20Deposit(_l1Token, _l2Token, msg.sender, msg.sender, _amount, _l2Gas, _data); _initiateERC20Deposit(_l1Token, _l2Token, msg.sender, msg.sender, _amount, _l2Gas, _data);
} }
/** /**
* @inheritdoc IL1ERC20Bridge * @inheritdoc IL1ERC20Bridge
*/ */
function depositERC20To( function depositERC20To(
...@@ -198,10 +151,7 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled { ...@@ -198,10 +151,7 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled {
uint256 _amount, uint256 _amount,
uint32 _l2Gas, uint32 _l2Gas,
bytes calldata _data bytes calldata _data
) ) external virtual {
external
virtual
{
_initiateERC20Deposit(_l1Token, _l2Token, msg.sender, _to, _amount, _l2Gas, _data); _initiateERC20Deposit(_l1Token, _l2Token, msg.sender, _to, _amount, _l2Gas, _data);
} }
...@@ -227,17 +177,11 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled { ...@@ -227,17 +177,11 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled {
uint256 _amount, uint256 _amount,
uint32 _l2Gas, uint32 _l2Gas,
bytes calldata _data bytes calldata _data
) ) internal {
internal
{
// When a deposit is initiated on L1, the L1 Bridge transfers the funds to itself for future // When a deposit is initiated on L1, the L1 Bridge transfers the funds to itself for future
// withdrawals. safeTransferFrom also checks if the contract has code, so this will fail if // withdrawals. safeTransferFrom also checks if the contract has code, so this will fail if
// _from is an EOA or address(0). // _from is an EOA or address(0).
IERC20(_l1Token).safeTransferFrom( IERC20(_l1Token).safeTransferFrom(_from, address(this), _amount);
_from,
address(this),
_amount
);
// Construct calldata for _l2Token.finalizeDeposit(_to, _amount) // Construct calldata for _l2Token.finalizeDeposit(_to, _amount)
bytes memory message = abi.encodeWithSelector( bytes memory message = abi.encodeWithSelector(
...@@ -251,11 +195,7 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled { ...@@ -251,11 +195,7 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled {
); );
// Send calldata into L2 // Send calldata into L2
sendCrossDomainMessage( sendCrossDomainMessage(l2TokenBridge, _l2Gas, message);
l2TokenBridge,
_l2Gas,
message
);
deposits[_l1Token][_l2Token] = deposits[_l1Token][_l2Token] + _amount; deposits[_l1Token][_l2Token] = deposits[_l1Token][_l2Token] + _amount;
...@@ -266,7 +206,7 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled { ...@@ -266,7 +206,7 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled {
* Cross-chain Functions * * Cross-chain Functions *
*************************/ *************************/
/** /**
* @inheritdoc IL1StandardBridge * @inheritdoc IL1StandardBridge
*/ */
function finalizeETHWithdrawal( function finalizeETHWithdrawal(
...@@ -274,10 +214,7 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled { ...@@ -274,10 +214,7 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled {
address _to, address _to,
uint256 _amount, uint256 _amount,
bytes calldata _data bytes calldata _data
) ) external onlyFromCrossDomainAccount(l2TokenBridge) {
external
onlyFromCrossDomainAccount(l2TokenBridge)
{
(bool success, ) = _to.call{value: _amount}(new bytes(0)); (bool success, ) = _to.call{value: _amount}(new bytes(0));
require(success, "TransferHelper::safeTransferETH: ETH transfer failed"); require(success, "TransferHelper::safeTransferETH: ETH transfer failed");
...@@ -294,10 +231,7 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled { ...@@ -294,10 +231,7 @@ contract L1StandardBridge is IL1StandardBridge, CrossDomainEnabled {
address _to, address _to,
uint256 _amount, uint256 _amount,
bytes calldata _data bytes calldata _data
) ) external onlyFromCrossDomainAccount(l2TokenBridge) {
external
onlyFromCrossDomainAccount(l2TokenBridge)
{
deposits[_l1Token][_l2Token] = deposits[_l1Token][_l2Token] - _amount; deposits[_l1Token][_l2Token] = deposits[_l1Token][_l2Token] - _amount;
// When a withdrawal is finalized on L1, the L1 Bridge transfers the funds to the withdrawer // When a withdrawal is finalized on L1, the L1 Bridge transfers the funds to the withdrawer
......
...@@ -2,13 +2,13 @@ ...@@ -2,13 +2,13 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { AddressAliasHelper } from "../../standards/AddressAliasHelper.sol"; import {AddressAliasHelper} from "../../standards/AddressAliasHelper.sol";
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import {Lib_OVMCodec} from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import {Lib_AddressResolver} from "../../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */ /* Interface Imports */
import { ICanonicalTransactionChain } from "./ICanonicalTransactionChain.sol"; import {ICanonicalTransactionChain} from "./ICanonicalTransactionChain.sol";
import { IChainStorageContainer } from "./IChainStorageContainer.sol"; import {IChainStorageContainer} from "./IChainStorageContainer.sol";
/** /**
* @title CanonicalTransactionChain * @title CanonicalTransactionChain
...@@ -21,14 +21,13 @@ import { IChainStorageContainer } from "./IChainStorageContainer.sol"; ...@@ -21,14 +21,13 @@ import { IChainStorageContainer } from "./IChainStorageContainer.sol";
* Runtime target: EVM * Runtime target: EVM
*/ */
contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressResolver { contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressResolver {
/************* /*************
* Constants * * Constants *
*************/ *************/
// L2 tx gas-related // L2 tx gas-related
uint256 constant public MIN_ROLLUP_TX_GAS = 100000; uint256 public constant MIN_ROLLUP_TX_GAS = 100000;
uint256 constant public MAX_ROLLUP_TX_SIZE = 50000; uint256 public constant MAX_ROLLUP_TX_SIZE = 50000;
// The approximate cost of calling the enqueue function // The approximate cost of calling the enqueue function
uint256 public enqueueGasCost; uint256 public enqueueGasCost;
...@@ -40,12 +39,11 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -40,12 +39,11 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
uint256 public enqueueL2GasPrepaid; uint256 public enqueueL2GasPrepaid;
// Encoding-related (all in bytes) // Encoding-related (all in bytes)
uint256 constant internal BATCH_CONTEXT_SIZE = 16; uint256 internal constant BATCH_CONTEXT_SIZE = 16;
uint256 constant internal BATCH_CONTEXT_LENGTH_POS = 12; uint256 internal constant BATCH_CONTEXT_LENGTH_POS = 12;
uint256 constant internal BATCH_CONTEXT_START_POS = 15; uint256 internal constant BATCH_CONTEXT_START_POS = 15;
uint256 constant internal TX_DATA_HEADER_SIZE = 3; uint256 internal constant TX_DATA_HEADER_SIZE = 3;
uint256 constant internal BYTES_TILL_TX_DATA = 65; uint256 internal constant BYTES_TILL_TX_DATA = 65;
/************* /*************
* Variables * * Variables *
...@@ -53,7 +51,6 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -53,7 +51,6 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
uint256 public maxTransactionGasLimit; uint256 public maxTransactionGasLimit;
/*************** /***************
* Queue State * * Queue State *
***************/ ***************/
...@@ -61,7 +58,6 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -61,7 +58,6 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
uint40 private _nextQueueIndex; // index of the first queue element not yet included uint40 private _nextQueueIndex; // index of the first queue element not yet included
Lib_OVMCodec.QueueElement[] queueElements; Lib_OVMCodec.QueueElement[] queueElements;
/*************** /***************
* Constructor * * Constructor *
***************/ ***************/
...@@ -71,17 +67,13 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -71,17 +67,13 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
uint256 _maxTransactionGasLimit, uint256 _maxTransactionGasLimit,
uint256 _l2GasDiscountDivisor, uint256 _l2GasDiscountDivisor,
uint256 _enqueueGasCost uint256 _enqueueGasCost
) ) Lib_AddressResolver(_libAddressManager) {
Lib_AddressResolver(_libAddressManager)
{
maxTransactionGasLimit = _maxTransactionGasLimit; maxTransactionGasLimit = _maxTransactionGasLimit;
l2GasDiscountDivisor = _l2GasDiscountDivisor; l2GasDiscountDivisor = _l2GasDiscountDivisor;
enqueueGasCost = _enqueueGasCost; enqueueGasCost = _enqueueGasCost;
enqueueL2GasPrepaid = _l2GasDiscountDivisor * _enqueueGasCost; enqueueL2GasPrepaid = _l2GasDiscountDivisor * _enqueueGasCost;
} }
/********************** /**********************
* Function Modifiers * * Function Modifiers *
**********************/ **********************/
...@@ -91,10 +83,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -91,10 +83,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
* successfully call a method. * successfully call a method.
*/ */
modifier onlyBurnAdmin() { modifier onlyBurnAdmin() {
require( require(msg.sender == libAddressManager.owner(), "Only callable by the Burn Admin.");
msg.sender == libAddressManager.owner(),
"Only callable by the Burn Admin."
);
_; _;
} }
...@@ -115,14 +104,9 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -115,14 +104,9 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
// See the comment in enqueue() for the rationale behind this formula. // See the comment in enqueue() for the rationale behind this formula.
enqueueL2GasPrepaid = _l2GasDiscountDivisor * _enqueueGasCost; enqueueL2GasPrepaid = _l2GasDiscountDivisor * _enqueueGasCost;
emit L2GasParamsUpdated( emit L2GasParamsUpdated(l2GasDiscountDivisor, enqueueGasCost, enqueueL2GasPrepaid);
l2GasDiscountDivisor,
enqueueGasCost,
enqueueL2GasPrepaid
);
} }
/******************** /********************
* Public Functions * * Public Functions *
********************/ ********************/
...@@ -131,46 +115,24 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -131,46 +115,24 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
* Accesses the batch storage container. * Accesses the batch storage container.
* @return Reference to the batch storage container. * @return Reference to the batch storage container.
*/ */
function batches() function batches() public view returns (IChainStorageContainer) {
public return IChainStorageContainer(resolve("ChainStorageContainer-CTC-batches"));
view
returns (
IChainStorageContainer
)
{
return IChainStorageContainer(
resolve("ChainStorageContainer-CTC-batches")
);
} }
/** /**
* Accesses the queue storage container. * Accesses the queue storage container.
* @return Reference to the queue storage container. * @return Reference to the queue storage container.
*/ */
function queue() function queue() public view returns (IChainStorageContainer) {
public return IChainStorageContainer(resolve("ChainStorageContainer-CTC-queue"));
view
returns (
IChainStorageContainer
)
{
return IChainStorageContainer(
resolve("ChainStorageContainer-CTC-queue")
);
} }
/** /**
* Retrieves the total number of elements submitted. * Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements. * @return _totalElements Total submitted elements.
*/ */
function getTotalElements() function getTotalElements() public view returns (uint256 _totalElements) {
public (uint40 totalElements, , , ) = _getBatchExtraData();
view
returns (
uint256 _totalElements
)
{
(uint40 totalElements,,,) = _getBatchExtraData();
return uint256(totalElements); return uint256(totalElements);
} }
...@@ -178,13 +140,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -178,13 +140,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
* Retrieves the total number of batches submitted. * Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches. * @return _totalBatches Total submitted batches.
*/ */
function getTotalBatches() function getTotalBatches() public view returns (uint256 _totalBatches) {
public
view
returns (
uint256 _totalBatches
)
{
return batches().length(); return batches().length();
} }
...@@ -192,13 +148,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -192,13 +148,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
* Returns the index of the next element to be enqueued. * Returns the index of the next element to be enqueued.
* @return Index for the next queue element. * @return Index for the next queue element.
*/ */
function getNextQueueIndex() function getNextQueueIndex() public view returns (uint40) {
public
view
returns (
uint40
)
{
return _nextQueueIndex; return _nextQueueIndex;
} }
...@@ -206,14 +156,8 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -206,14 +156,8 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
* Returns the timestamp of the last transaction. * Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction. * @return Timestamp for the last transaction.
*/ */
function getLastTimestamp() function getLastTimestamp() public view returns (uint40) {
public (, , uint40 lastTimestamp, ) = _getBatchExtraData();
view
returns (
uint40
)
{
(,,uint40 lastTimestamp,) = _getBatchExtraData();
return lastTimestamp; return lastTimestamp;
} }
...@@ -221,14 +165,8 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -221,14 +165,8 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
* Returns the blocknumber of the last transaction. * Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction. * @return Blocknumber for the last transaction.
*/ */
function getLastBlockNumber() function getLastBlockNumber() public view returns (uint40) {
public (, , , uint40 lastBlockNumber) = _getBatchExtraData();
view
returns (
uint40
)
{
(,,,uint40 lastBlockNumber) = _getBatchExtraData();
return lastBlockNumber; return lastBlockNumber;
} }
...@@ -237,14 +175,10 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -237,14 +175,10 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
* @param _index Index of the queue element to access. * @param _index Index of the queue element to access.
* @return _element Queue element at the given index. * @return _element Queue element at the given index.
*/ */
function getQueueElement( function getQueueElement(uint256 _index)
uint256 _index
)
public public
view view
returns ( returns (Lib_OVMCodec.QueueElement memory _element)
Lib_OVMCodec.QueueElement memory _element
)
{ {
return queueElements[_index]; return queueElements[_index];
} }
...@@ -253,28 +187,16 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -253,28 +187,16 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
* Get the number of queue elements which have not yet been included. * Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements. * @return Number of pending queue elements.
*/ */
function getNumPendingQueueElements() function getNumPendingQueueElements() public view returns (uint40) {
public
view
returns (
uint40
)
{
return uint40(queueElements.length) - _nextQueueIndex; return uint40(queueElements.length) - _nextQueueIndex;
} }
/** /**
* Retrieves the length of the queue, including * Retrieves the length of the queue, including
* both pending and canonical transactions. * both pending and canonical transactions.
* @return Length of the queue. * @return Length of the queue.
*/ */
function getQueueLength() function getQueueLength() public view returns (uint40) {
public
view
returns (
uint40
)
{
return uint40(queueElements.length); return uint40(queueElements.length);
} }
...@@ -288,9 +210,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -288,9 +210,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
address _target, address _target,
uint256 _gasLimit, uint256 _gasLimit,
bytes memory _data bytes memory _data
) ) external {
external
{
require( require(
_data.length <= MAX_ROLLUP_TX_SIZE, _data.length <= MAX_ROLLUP_TX_SIZE,
"Transaction data size exceeds maximum for rollup transaction." "Transaction data size exceeds maximum for rollup transaction."
...@@ -301,10 +221,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -301,10 +221,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
"Transaction gas limit exceeds maximum for rollup transaction." "Transaction gas limit exceeds maximum for rollup transaction."
); );
require( require(_gasLimit >= MIN_ROLLUP_TX_GAS, "Transaction gas limit too low to enqueue.");
_gasLimit >= MIN_ROLLUP_TX_GAS,
"Transaction gas limit too low to enqueue."
);
// Transactions submitted to the queue lack a method for paying gas fees to the Sequencer. // Transactions submitted to the queue lack a method for paying gas fees to the Sequencer.
// So we need to prevent spam attacks by ensuring that the cost of enqueueing a transaction // So we need to prevent spam attacks by ensuring that the cost of enqueueing a transaction
...@@ -318,19 +235,16 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -318,19 +235,16 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
// positive integer, meaning we assume L2 gas is always less costly. // positive integer, meaning we assume L2 gas is always less costly.
// The calculation below for gasToConsume can be seen as converting the difference (between // The calculation below for gasToConsume can be seen as converting the difference (between
// the specified L2 gas limit and the prepaid L2 gas limit) to an L1 gas amount. // the specified L2 gas limit and the prepaid L2 gas limit) to an L1 gas amount.
if(_gasLimit > enqueueL2GasPrepaid) { if (_gasLimit > enqueueL2GasPrepaid) {
uint256 gasToConsume = (_gasLimit - enqueueL2GasPrepaid) / l2GasDiscountDivisor; uint256 gasToConsume = (_gasLimit - enqueueL2GasPrepaid) / l2GasDiscountDivisor;
uint256 startingGas = gasleft(); uint256 startingGas = gasleft();
// Although this check is not necessary (burn below will run out of gas if not true), it // Although this check is not necessary (burn below will run out of gas if not true), it
// gives the user an explicit reason as to why the enqueue attempt failed. // gives the user an explicit reason as to why the enqueue attempt failed.
require( require(startingGas > gasToConsume, "Insufficient gas for L2 rate limiting burn.");
startingGas > gasToConsume,
"Insufficient gas for L2 rate limiting burn."
);
uint256 i; uint256 i;
while(startingGas - gasleft() < gasToConsume) { while (startingGas - gasleft() < gasToConsume) {
i++; i++;
} }
} }
...@@ -347,14 +261,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -347,14 +261,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
sender = AddressAliasHelper.applyL1ToL2Alias(msg.sender); sender = AddressAliasHelper.applyL1ToL2Alias(msg.sender);
} }
bytes32 transactionHash = keccak256( bytes32 transactionHash = keccak256(abi.encode(sender, _target, _gasLimit, _data));
abi.encode(
sender,
_target,
_gasLimit,
_data
)
);
queueElements.push( queueElements.push(
Lib_OVMCodec.QueueElement({ Lib_OVMCodec.QueueElement({
...@@ -364,14 +271,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -364,14 +271,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
}) })
); );
uint256 queueIndex = queueElements.length - 1; uint256 queueIndex = queueElements.length - 1;
emit TransactionEnqueued( emit TransactionEnqueued(sender, _target, _gasLimit, _data, queueIndex, block.timestamp);
sender,
_target,
_gasLimit,
_data,
queueIndex,
block.timestamp
);
} }
/** /**
...@@ -382,16 +282,14 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -382,16 +282,14 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
* .param _contexts Array of batch contexts. * .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data. * .param _transactionDataFields Array of raw transaction data.
*/ */
function appendSequencerBatch() function appendSequencerBatch() external {
external
{
uint40 shouldStartAtElement; uint40 shouldStartAtElement;
uint24 totalElementsToAppend; uint24 totalElementsToAppend;
uint24 numContexts; uint24 numContexts;
assembly { assembly {
shouldStartAtElement := shr(216, calldataload(4)) shouldStartAtElement := shr(216, calldataload(4))
totalElementsToAppend := shr(232, calldataload(9)) totalElementsToAppend := shr(232, calldataload(9))
numContexts := shr(232, calldataload(12)) numContexts := shr(232, calldataload(12))
} }
require( require(
...@@ -408,10 +306,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -408,10 +306,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts
); );
require( require(msg.data.length >= nextTransactionPtr, "Not enough BatchContexts provided.");
msg.data.length >= nextTransactionPtr,
"Not enough BatchContexts provided."
);
// Counter for number of sequencer transactions appended so far. // Counter for number of sequencer transactions appended so far.
uint32 numSequencerTransactions = 0; uint32 numSequencerTransactions = 0;
...@@ -463,7 +358,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -463,7 +358,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
// Cache the previous blockhash to ensure all transaction data can be retrieved efficiently. // Cache the previous blockhash to ensure all transaction data can be retrieved efficiently.
_appendBatch( _appendBatch(
blockhash(block.number-1), blockhash(block.number - 1),
totalElementsToAppend, totalElementsToAppend,
numQueuedTransactions, numQueuedTransactions,
blockTimestamp, blockTimestamp,
...@@ -489,15 +384,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -489,15 +384,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
* @param _index The index of the BatchContext * @param _index The index of the BatchContext
* @return The BatchContext at the specified index. * @return The BatchContext at the specified index.
*/ */
function _getBatchContext( function _getBatchContext(uint256 _index) internal pure returns (BatchContext memory) {
uint256 _index
)
internal
pure
returns (
BatchContext memory
)
{
uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE; uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE;
uint256 numSequencedTransactions; uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions; uint256 numSubsequentQueueTransactions;
...@@ -505,18 +392,19 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -505,18 +392,19 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
uint256 ctxBlockNumber; uint256 ctxBlockNumber;
assembly { assembly {
numSequencedTransactions := shr(232, calldataload(contextPtr)) numSequencedTransactions := shr(232, calldataload(contextPtr))
numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3))) numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3)))
ctxTimestamp := shr(216, calldataload(add(contextPtr, 6))) ctxTimestamp := shr(216, calldataload(add(contextPtr, 6)))
ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11))) ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11)))
} }
return BatchContext({ return
numSequencedTransactions: numSequencedTransactions, BatchContext({
numSubsequentQueueTransactions: numSubsequentQueueTransactions, numSequencedTransactions: numSequencedTransactions,
timestamp: ctxTimestamp, numSubsequentQueueTransactions: numSubsequentQueueTransactions,
blockNumber: ctxBlockNumber timestamp: ctxTimestamp,
}); blockNumber: ctxBlockNumber
});
} }
/** /**
...@@ -542,19 +430,26 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -542,19 +430,26 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
uint40 lastBlockNumber; uint40 lastBlockNumber;
assembly { assembly {
extraData := shr(40, extraData) extraData := shr(40, extraData)
totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) totalElements := and(
nextQueueIndex := shr(40, and(extraData, 0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000)) extraData,
lastTimestamp := shr(80, and(extraData, 0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000)) 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF
lastBlockNumber := shr(120, and(extraData, 0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000)) )
nextQueueIndex := shr(
40,
and(extraData, 0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000)
)
lastTimestamp := shr(
80,
and(extraData, 0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000)
)
lastBlockNumber := shr(
120,
and(extraData, 0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000)
)
} }
return ( return (totalElements, nextQueueIndex, lastTimestamp, lastBlockNumber);
totalElements,
nextQueueIndex,
lastTimestamp,
lastBlockNumber
);
} }
/** /**
...@@ -570,13 +465,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -570,13 +465,7 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
uint40 _nextQueueIdx, uint40 _nextQueueIdx,
uint40 _timestamp, uint40 _timestamp,
uint40 _blockNumber uint40 _blockNumber
) ) internal pure returns (bytes27) {
internal
pure
returns (
bytes27
)
{
bytes27 extraData; bytes27 extraData;
assembly { assembly {
extraData := _totalElements extraData := _totalElements
...@@ -603,11 +492,9 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes ...@@ -603,11 +492,9 @@ contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressRes
uint256 _numQueuedTransactions, uint256 _numQueuedTransactions,
uint40 _timestamp, uint40 _timestamp,
uint40 _blockNumber uint40 _blockNumber
) ) internal {
internal
{
IChainStorageContainer batchesRef = batches(); IChainStorageContainer batchesRef = batches();
(uint40 totalElements, uint40 nextQueueIndex,,) = _getBatchExtraData(); (uint40 totalElements, uint40 nextQueueIndex, , ) = _getBatchExtraData();
Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec.ChainBatchHeader({ Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec.ChainBatchHeader({
batchIndex: batchesRef.length(), batchIndex: batchesRef.length(),
......
...@@ -2,11 +2,11 @@ ...@@ -2,11 +2,11 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_Buffer } from "../../libraries/utils/Lib_Buffer.sol"; import {Lib_Buffer} from "../../libraries/utils/Lib_Buffer.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import {Lib_AddressResolver} from "../../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */ /* Interface Imports */
import { IChainStorageContainer } from "./IChainStorageContainer.sol"; import {IChainStorageContainer} from "./IChainStorageContainer.sol";
/** /**
* @title ChainStorageContainer * @title ChainStorageContainer
...@@ -22,14 +22,12 @@ import { IChainStorageContainer } from "./IChainStorageContainer.sol"; ...@@ -22,14 +22,12 @@ import { IChainStorageContainer } from "./IChainStorageContainer.sol";
* Runtime target: EVM * Runtime target: EVM
*/ */
contract ChainStorageContainer is IChainStorageContainer, Lib_AddressResolver { contract ChainStorageContainer is IChainStorageContainer, Lib_AddressResolver {
/************* /*************
* Libraries * * Libraries *
*************/ *************/
using Lib_Buffer for Lib_Buffer.Buffer; using Lib_Buffer for Lib_Buffer.Buffer;
/************* /*************
* Variables * * Variables *
*************/ *************/
...@@ -37,7 +35,6 @@ contract ChainStorageContainer is IChainStorageContainer, Lib_AddressResolver { ...@@ -37,7 +35,6 @@ contract ChainStorageContainer is IChainStorageContainer, Lib_AddressResolver {
string public owner; string public owner;
Lib_Buffer.Buffer internal buffer; Lib_Buffer.Buffer internal buffer;
/*************** /***************
* Constructor * * Constructor *
***************/ ***************/
...@@ -46,16 +43,12 @@ contract ChainStorageContainer is IChainStorageContainer, Lib_AddressResolver { ...@@ -46,16 +43,12 @@ contract ChainStorageContainer is IChainStorageContainer, Lib_AddressResolver {
* @param _libAddressManager Address of the Address Manager. * @param _libAddressManager Address of the Address Manager.
* @param _owner Name of the contract that owns this container (will be resolved later). * @param _owner Name of the contract that owns this container (will be resolved later).
*/ */
constructor( constructor(address _libAddressManager, string memory _owner)
address _libAddressManager,
string memory _owner
)
Lib_AddressResolver(_libAddressManager) Lib_AddressResolver(_libAddressManager)
{ {
owner = _owner; owner = _owner;
} }
/********************** /**********************
* Function Modifiers * * Function Modifiers *
**********************/ **********************/
...@@ -68,7 +61,6 @@ contract ChainStorageContainer is IChainStorageContainer, Lib_AddressResolver { ...@@ -68,7 +61,6 @@ contract ChainStorageContainer is IChainStorageContainer, Lib_AddressResolver {
_; _;
} }
/******************** /********************
* Public Functions * * Public Functions *
********************/ ********************/
...@@ -76,108 +68,59 @@ contract ChainStorageContainer is IChainStorageContainer, Lib_AddressResolver { ...@@ -76,108 +68,59 @@ contract ChainStorageContainer is IChainStorageContainer, Lib_AddressResolver {
/** /**
* @inheritdoc IChainStorageContainer * @inheritdoc IChainStorageContainer
*/ */
function setGlobalMetadata( function setGlobalMetadata(bytes27 _globalMetadata) public onlyOwner {
bytes27 _globalMetadata
)
public
onlyOwner
{
return buffer.setExtraData(_globalMetadata); return buffer.setExtraData(_globalMetadata);
} }
/** /**
* @inheritdoc IChainStorageContainer * @inheritdoc IChainStorageContainer
*/ */
function getGlobalMetadata() function getGlobalMetadata() public view returns (bytes27) {
public
view
returns (
bytes27
)
{
return buffer.getExtraData(); return buffer.getExtraData();
} }
/** /**
* @inheritdoc IChainStorageContainer * @inheritdoc IChainStorageContainer
*/ */
function length() function length() public view returns (uint256) {
public
view
returns (
uint256
)
{
return uint256(buffer.getLength()); return uint256(buffer.getLength());
} }
/** /**
* @inheritdoc IChainStorageContainer * @inheritdoc IChainStorageContainer
*/ */
function push( function push(bytes32 _object) public onlyOwner {
bytes32 _object
)
public
onlyOwner
{
buffer.push(_object); buffer.push(_object);
} }
/** /**
* @inheritdoc IChainStorageContainer * @inheritdoc IChainStorageContainer
*/ */
function push( function push(bytes32 _object, bytes27 _globalMetadata) public onlyOwner {
bytes32 _object,
bytes27 _globalMetadata
)
public
onlyOwner
{
buffer.push(_object, _globalMetadata); buffer.push(_object, _globalMetadata);
} }
/** /**
* @inheritdoc IChainStorageContainer * @inheritdoc IChainStorageContainer
*/ */
function get( function get(uint256 _index) public view returns (bytes32) {
uint256 _index
)
public
view
returns (
bytes32
)
{
return buffer.get(uint40(_index)); return buffer.get(uint40(_index));
} }
/** /**
* @inheritdoc IChainStorageContainer * @inheritdoc IChainStorageContainer
*/ */
function deleteElementsAfterInclusive( function deleteElementsAfterInclusive(uint256 _index) public onlyOwner {
uint256 _index buffer.deleteElementsAfterInclusive(uint40(_index));
)
public
onlyOwner
{
buffer.deleteElementsAfterInclusive(
uint40(_index)
);
} }
/** /**
* @inheritdoc IChainStorageContainer * @inheritdoc IChainStorageContainer
*/ */
function deleteElementsAfterInclusive( function deleteElementsAfterInclusive(uint256 _index, bytes27 _globalMetadata)
uint256 _index,
bytes27 _globalMetadata
)
public public
onlyOwner onlyOwner
{ {
buffer.deleteElementsAfterInclusive( buffer.deleteElementsAfterInclusive(uint40(_index), _globalMetadata);
uint40(_index),
_globalMetadata
);
} }
} }
...@@ -2,16 +2,15 @@ ...@@ -2,16 +2,15 @@
pragma solidity >0.5.0 <0.9.0; pragma solidity >0.5.0 <0.9.0;
/* Library Imports */ /* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import {Lib_OVMCodec} from "../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */ /* Interface Imports */
import { IChainStorageContainer } from "./IChainStorageContainer.sol"; import {IChainStorageContainer} from "./IChainStorageContainer.sol";
/** /**
* @title ICanonicalTransactionChain * @title ICanonicalTransactionChain
*/ */
interface ICanonicalTransactionChain { interface ICanonicalTransactionChain {
/********** /**********
* Events * * Events *
**********/ **********/
...@@ -51,7 +50,6 @@ interface ICanonicalTransactionChain { ...@@ -51,7 +50,6 @@ interface ICanonicalTransactionChain {
bytes _extraData bytes _extraData
); );
/*********** /***********
* Structs * * Structs *
***********/ ***********/
...@@ -71,8 +69,7 @@ interface ICanonicalTransactionChain { ...@@ -71,8 +69,7 @@ interface ICanonicalTransactionChain {
* Allows the Burn Admin to update the parameters which determine the amount of gas to burn. * Allows the Burn Admin to update the parameters which determine the amount of gas to burn.
* The value of enqueueL2GasPrepaid is immediately updated as well. * The value of enqueueL2GasPrepaid is immediately updated as well.
*/ */
function setGasParams(uint256 _l2GasDiscountDivisor, uint256 _enqueueGasCost) function setGasParams(uint256 _l2GasDiscountDivisor, uint256 _enqueueGasCost) external;
external;
/******************** /********************
* Public Functions * * Public Functions *
...@@ -82,116 +79,66 @@ interface ICanonicalTransactionChain { ...@@ -82,116 +79,66 @@ interface ICanonicalTransactionChain {
* Accesses the batch storage container. * Accesses the batch storage container.
* @return Reference to the batch storage container. * @return Reference to the batch storage container.
*/ */
function batches() function batches() external view returns (IChainStorageContainer);
external
view
returns (
IChainStorageContainer
);
/** /**
* Accesses the queue storage container. * Accesses the queue storage container.
* @return Reference to the queue storage container. * @return Reference to the queue storage container.
*/ */
function queue() function queue() external view returns (IChainStorageContainer);
external
view
returns (
IChainStorageContainer
);
/** /**
* Retrieves the total number of elements submitted. * Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements. * @return _totalElements Total submitted elements.
*/ */
function getTotalElements() function getTotalElements() external view returns (uint256 _totalElements);
external
view
returns (
uint256 _totalElements
);
/** /**
* Retrieves the total number of batches submitted. * Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches. * @return _totalBatches Total submitted batches.
*/ */
function getTotalBatches() function getTotalBatches() external view returns (uint256 _totalBatches);
external
view
returns (
uint256 _totalBatches
);
/** /**
* Returns the index of the next element to be enqueued. * Returns the index of the next element to be enqueued.
* @return Index for the next queue element. * @return Index for the next queue element.
*/ */
function getNextQueueIndex() function getNextQueueIndex() external view returns (uint40);
external
view
returns (
uint40
);
/** /**
* Gets the queue element at a particular index. * Gets the queue element at a particular index.
* @param _index Index of the queue element to access. * @param _index Index of the queue element to access.
* @return _element Queue element at the given index. * @return _element Queue element at the given index.
*/ */
function getQueueElement( function getQueueElement(uint256 _index)
uint256 _index
)
external external
view view
returns ( returns (Lib_OVMCodec.QueueElement memory _element);
Lib_OVMCodec.QueueElement memory _element
);
/** /**
* Returns the timestamp of the last transaction. * Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction. * @return Timestamp for the last transaction.
*/ */
function getLastTimestamp() function getLastTimestamp() external view returns (uint40);
external
view
returns (
uint40
);
/** /**
* Returns the blocknumber of the last transaction. * Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction. * @return Blocknumber for the last transaction.
*/ */
function getLastBlockNumber() function getLastBlockNumber() external view returns (uint40);
external
view
returns (
uint40
);
/** /**
* Get the number of queue elements which have not yet been included. * Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements. * @return Number of pending queue elements.
*/ */
function getNumPendingQueueElements() function getNumPendingQueueElements() external view returns (uint40);
external
view
returns (
uint40
);
/** /**
* Retrieves the length of the queue, including * Retrieves the length of the queue, including
* both pending and canonical transactions. * both pending and canonical transactions.
* @return Length of the queue. * @return Length of the queue.
*/ */
function getQueueLength() function getQueueLength() external view returns (uint40);
external
view
returns (
uint40
);
/** /**
* Adds a transaction to the queue. * Adds a transaction to the queue.
...@@ -203,8 +150,7 @@ interface ICanonicalTransactionChain { ...@@ -203,8 +150,7 @@ interface ICanonicalTransactionChain {
address _target, address _target,
uint256 _gasLimit, uint256 _gasLimit,
bytes memory _data bytes memory _data
) ) external;
external;
/** /**
* Allows the sequencer to append a batch of transactions. * Allows the sequencer to append a batch of transactions.
...@@ -219,6 +165,5 @@ interface ICanonicalTransactionChain { ...@@ -219,6 +165,5 @@ interface ICanonicalTransactionChain {
// uint24 _totalElementsToAppend, // uint24 _totalElementsToAppend,
// BatchContext[] _contexts, // BatchContext[] _contexts,
// bytes[] _transactionDataFields // bytes[] _transactionDataFields
) ) external;
external;
} }
...@@ -5,7 +5,6 @@ pragma solidity >0.5.0 <0.9.0; ...@@ -5,7 +5,6 @@ pragma solidity >0.5.0 <0.9.0;
* @title IChainStorageContainer * @title IChainStorageContainer
*/ */
interface IChainStorageContainer { interface IChainStorageContainer {
/******************** /********************
* Public Functions * * Public Functions *
********************/ ********************/
...@@ -16,41 +15,25 @@ interface IChainStorageContainer { ...@@ -16,41 +15,25 @@ interface IChainStorageContainer {
* 27 bytes to store arbitrary data. * 27 bytes to store arbitrary data.
* @param _globalMetadata New global metadata to set. * @param _globalMetadata New global metadata to set.
*/ */
function setGlobalMetadata( function setGlobalMetadata(bytes27 _globalMetadata) external;
bytes27 _globalMetadata
)
external;
/** /**
* Retrieves the container's global metadata field. * Retrieves the container's global metadata field.
* @return Container global metadata field. * @return Container global metadata field.
*/ */
function getGlobalMetadata() function getGlobalMetadata() external view returns (bytes27);
external
view
returns (
bytes27
);
/** /**
* Retrieves the number of objects stored in the container. * Retrieves the number of objects stored in the container.
* @return Number of objects in the container. * @return Number of objects in the container.
*/ */
function length() function length() external view returns (uint256);
external
view
returns (
uint256
);
/** /**
* Pushes an object into the container. * Pushes an object into the container.
* @param _object A 32 byte value to insert into the container. * @param _object A 32 byte value to insert into the container.
*/ */
function push( function push(bytes32 _object) external;
bytes32 _object
)
external;
/** /**
* Pushes an object into the container. Function allows setting the global metadata since * Pushes an object into the container. Function allows setting the global metadata since
...@@ -59,34 +42,20 @@ interface IChainStorageContainer { ...@@ -59,34 +42,20 @@ interface IChainStorageContainer {
* @param _object A 32 byte value to insert into the container. * @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container. * @param _globalMetadata New global metadata for the container.
*/ */
function push( function push(bytes32 _object, bytes27 _globalMetadata) external;
bytes32 _object,
bytes27 _globalMetadata
)
external;
/** /**
* Retrieves an object from the container. * Retrieves an object from the container.
* @param _index Index of the particular object to access. * @param _index Index of the particular object to access.
* @return 32 byte object value. * @return 32 byte object value.
*/ */
function get( function get(uint256 _index) external view returns (bytes32);
uint256 _index
)
external
view
returns (
bytes32
);
/** /**
* Removes all objects after and including a given index. * Removes all objects after and including a given index.
* @param _index Object index to delete from. * @param _index Object index to delete from.
*/ */
function deleteElementsAfterInclusive( function deleteElementsAfterInclusive(uint256 _index) external;
uint256 _index
)
external;
/** /**
* Removes all objects after and including a given index. Also allows setting the global * Removes all objects after and including a given index. Also allows setting the global
...@@ -94,9 +63,5 @@ interface IChainStorageContainer { ...@@ -94,9 +63,5 @@ interface IChainStorageContainer {
* @param _index Object index to delete from. * @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container. * @param _globalMetadata New global metadata for the container.
*/ */
function deleteElementsAfterInclusive( function deleteElementsAfterInclusive(uint256 _index, bytes27 _globalMetadata) external;
uint256 _index,
bytes27 _globalMetadata
)
external;
} }
...@@ -2,13 +2,12 @@ ...@@ -2,13 +2,12 @@
pragma solidity >0.5.0 <0.9.0; pragma solidity >0.5.0 <0.9.0;
/* Library Imports */ /* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import {Lib_OVMCodec} from "../../libraries/codec/Lib_OVMCodec.sol";
/** /**
* @title IStateCommitmentChain * @title IStateCommitmentChain
*/ */
interface IStateCommitmentChain { interface IStateCommitmentChain {
/********** /**********
* Events * * Events *
**********/ **********/
...@@ -21,11 +20,7 @@ interface IStateCommitmentChain { ...@@ -21,11 +20,7 @@ interface IStateCommitmentChain {
bytes _extraData bytes _extraData
); );
event StateBatchDeleted( event StateBatchDeleted(uint256 indexed _batchIndex, bytes32 _batchRoot);
uint256 indexed _batchIndex,
bytes32 _batchRoot
);
/******************** /********************
* Public Functions * * Public Functions *
...@@ -35,54 +30,32 @@ interface IStateCommitmentChain { ...@@ -35,54 +30,32 @@ interface IStateCommitmentChain {
* Retrieves the total number of elements submitted. * Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements. * @return _totalElements Total submitted elements.
*/ */
function getTotalElements() function getTotalElements() external view returns (uint256 _totalElements);
external
view
returns (
uint256 _totalElements
);
/** /**
* Retrieves the total number of batches submitted. * Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches. * @return _totalBatches Total submitted batches.
*/ */
function getTotalBatches() function getTotalBatches() external view returns (uint256 _totalBatches);
external
view
returns (
uint256 _totalBatches
);
/** /**
* Retrieves the timestamp of the last batch submitted by the sequencer. * Retrieves the timestamp of the last batch submitted by the sequencer.
* @return _lastSequencerTimestamp Last sequencer batch timestamp. * @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/ */
function getLastSequencerTimestamp() function getLastSequencerTimestamp() external view returns (uint256 _lastSequencerTimestamp);
external
view
returns (
uint256 _lastSequencerTimestamp
);
/** /**
* Appends a batch of state roots to the chain. * Appends a batch of state roots to the chain.
* @param _batch Batch of state roots. * @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start. * @param _shouldStartAtElement Index of the element at which this batch should start.
*/ */
function appendStateBatch( function appendStateBatch(bytes32[] calldata _batch, uint256 _shouldStartAtElement) external;
bytes32[] calldata _batch,
uint256 _shouldStartAtElement
)
external;
/** /**
* Deletes all state roots after (and including) a given batch. * Deletes all state roots after (and including) a given batch.
* @param _batchHeader Header of the batch to start deleting from. * @param _batchHeader Header of the batch to start deleting from.
*/ */
function deleteStateBatch( function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) external;
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external;
/** /**
* Verifies a batch inclusion proof. * Verifies a batch inclusion proof.
...@@ -94,24 +67,15 @@ interface IStateCommitmentChain { ...@@ -94,24 +67,15 @@ interface IStateCommitmentChain {
bytes32 _element, bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof Lib_OVMCodec.ChainInclusionProof memory _proof
) ) external view returns (bool _verified);
external
view
returns (
bool _verified
);
/** /**
* Checks whether a given batch is still inside its fraud proof window. * Checks whether a given batch is still inside its fraud proof window.
* @param _batchHeader Header of the batch to check. * @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window. * @return _inside Whether or not the batch is inside the fraud proof window.
*/ */
function insideFraudProofWindow( function insideFraudProofWindow(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external external
view view
returns ( returns (bool _inside);
bool _inside
);
} }
...@@ -2,15 +2,15 @@ ...@@ -2,15 +2,15 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import {Lib_OVMCodec} from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import {Lib_AddressResolver} from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol"; import {Lib_MerkleTree} from "../../libraries/utils/Lib_MerkleTree.sol";
/* Interface Imports */ /* Interface Imports */
import { IStateCommitmentChain } from "./IStateCommitmentChain.sol"; import {IStateCommitmentChain} from "./IStateCommitmentChain.sol";
import { ICanonicalTransactionChain } from "./ICanonicalTransactionChain.sol"; import {ICanonicalTransactionChain} from "./ICanonicalTransactionChain.sol";
import { IBondManager } from "../verification/IBondManager.sol"; import {IBondManager} from "../verification/IBondManager.sol";
import { IChainStorageContainer } from "./IChainStorageContainer.sol"; import {IChainStorageContainer} from "./IChainStorageContainer.sol";
/** /**
* @title StateCommitmentChain * @title StateCommitmentChain
...@@ -22,7 +22,6 @@ import { IChainStorageContainer } from "./IChainStorageContainer.sol"; ...@@ -22,7 +22,6 @@ import { IChainStorageContainer } from "./IChainStorageContainer.sol";
* Runtime target: EVM * Runtime target: EVM
*/ */
contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver {
/************* /*************
* Constants * * Constants *
*************/ *************/
...@@ -30,7 +29,6 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { ...@@ -30,7 +29,6 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver {
uint256 public FRAUD_PROOF_WINDOW; uint256 public FRAUD_PROOF_WINDOW;
uint256 public SEQUENCER_PUBLISH_WINDOW; uint256 public SEQUENCER_PUBLISH_WINDOW;
/*************** /***************
* Constructor * * Constructor *
***************/ ***************/
...@@ -42,14 +40,11 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { ...@@ -42,14 +40,11 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver {
address _libAddressManager, address _libAddressManager,
uint256 _fraudProofWindow, uint256 _fraudProofWindow,
uint256 _sequencerPublishWindow uint256 _sequencerPublishWindow
) ) Lib_AddressResolver(_libAddressManager) {
Lib_AddressResolver(_libAddressManager)
{
FRAUD_PROOF_WINDOW = _fraudProofWindow; FRAUD_PROOF_WINDOW = _fraudProofWindow;
SEQUENCER_PUBLISH_WINDOW = _sequencerPublishWindow; SEQUENCER_PUBLISH_WINDOW = _sequencerPublishWindow;
} }
/******************** /********************
* Public Functions * * Public Functions *
********************/ ********************/
...@@ -58,28 +53,14 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { ...@@ -58,28 +53,14 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver {
* Accesses the batch storage container. * Accesses the batch storage container.
* @return Reference to the batch storage container. * @return Reference to the batch storage container.
*/ */
function batches() function batches() public view returns (IChainStorageContainer) {
public return IChainStorageContainer(resolve("ChainStorageContainer-SCC-batches"));
view
returns (
IChainStorageContainer
)
{
return IChainStorageContainer(
resolve("ChainStorageContainer-SCC-batches")
);
} }
/** /**
* @inheritdoc IStateCommitmentChain * @inheritdoc IStateCommitmentChain
*/ */
function getTotalElements() function getTotalElements() public view returns (uint256 _totalElements) {
public
view
returns (
uint256 _totalElements
)
{
(uint40 totalElements, ) = _getBatchExtraData(); (uint40 totalElements, ) = _getBatchExtraData();
return uint256(totalElements); return uint256(totalElements);
} }
...@@ -87,26 +68,14 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { ...@@ -87,26 +68,14 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver {
/** /**
* @inheritdoc IStateCommitmentChain * @inheritdoc IStateCommitmentChain
*/ */
function getTotalBatches() function getTotalBatches() public view returns (uint256 _totalBatches) {
public
view
returns (
uint256 _totalBatches
)
{
return batches().length(); return batches().length();
} }
/** /**
* @inheritdoc IStateCommitmentChain * @inheritdoc IStateCommitmentChain
*/ */
function getLastSequencerTimestamp() function getLastSequencerTimestamp() public view returns (uint256 _lastSequencerTimestamp) {
public
view
returns (
uint256 _lastSequencerTimestamp
)
{
(, uint40 lastSequencerTimestamp) = _getBatchExtraData(); (, uint40 lastSequencerTimestamp) = _getBatchExtraData();
return uint256(lastSequencerTimestamp); return uint256(lastSequencerTimestamp);
} }
...@@ -114,12 +83,7 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { ...@@ -114,12 +83,7 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver {
/** /**
* @inheritdoc IStateCommitmentChain * @inheritdoc IStateCommitmentChain
*/ */
function appendStateBatch( function appendStateBatch(bytes32[] memory _batch, uint256 _shouldStartAtElement) public {
bytes32[] memory _batch,
uint256 _shouldStartAtElement
)
public
{
// Fail fast in to make sure our batch roots aren't accidentally made fraudulent by the // Fail fast in to make sure our batch roots aren't accidentally made fraudulent by the
// publication of batches by some other user. // publication of batches by some other user.
require( require(
...@@ -133,43 +97,29 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { ...@@ -133,43 +97,29 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver {
"Proposer does not have enough collateral posted" "Proposer does not have enough collateral posted"
); );
require( require(_batch.length > 0, "Cannot submit an empty state batch.");
_batch.length > 0,
"Cannot submit an empty state batch."
);
require( require(
getTotalElements() + _batch.length <= getTotalElements() + _batch.length <=
ICanonicalTransactionChain(resolve("CanonicalTransactionChain")) ICanonicalTransactionChain(resolve("CanonicalTransactionChain")).getTotalElements(),
.getTotalElements(),
"Number of state roots cannot exceed the number of canonical transactions." "Number of state roots cannot exceed the number of canonical transactions."
); );
// Pass the block's timestamp and the publisher of the data // Pass the block's timestamp and the publisher of the data
// to be used in the fraud proofs // to be used in the fraud proofs
_appendBatch( _appendBatch(_batch, abi.encode(block.timestamp, msg.sender));
_batch,
abi.encode(block.timestamp, msg.sender)
);
} }
/** /**
* @inheritdoc IStateCommitmentChain * @inheritdoc IStateCommitmentChain
*/ */
function deleteStateBatch( function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) public {
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
public
{
require( require(
msg.sender == resolve("OVM_FraudVerifier"), msg.sender == resolve("OVM_FraudVerifier"),
"State batches can only be deleted by the OVM_FraudVerifier." "State batches can only be deleted by the OVM_FraudVerifier."
); );
require( require(_isValidBatchHeader(_batchHeader), "Invalid batch header.");
_isValidBatchHeader(_batchHeader),
"Invalid batch header."
);
require( require(
insideFraudProofWindow(_batchHeader), insideFraudProofWindow(_batchHeader),
...@@ -186,17 +136,8 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { ...@@ -186,17 +136,8 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver {
bytes32 _element, bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof Lib_OVMCodec.ChainInclusionProof memory _proof
) ) public view returns (bool) {
public require(_isValidBatchHeader(_batchHeader), "Invalid batch header.");
view
returns (
bool
)
{
require(
_isValidBatchHeader(_batchHeader),
"Invalid batch header."
);
require( require(
Lib_MerkleTree.verify( Lib_MerkleTree.verify(
...@@ -215,28 +156,17 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { ...@@ -215,28 +156,17 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver {
/** /**
* @inheritdoc IStateCommitmentChain * @inheritdoc IStateCommitmentChain
*/ */
function insideFraudProofWindow( function insideFraudProofWindow(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
public public
view view
returns ( returns (bool _inside)
bool _inside
)
{ {
(uint256 timestamp,) = abi.decode( (uint256 timestamp, ) = abi.decode(_batchHeader.extraData, (uint256, address));
_batchHeader.extraData,
(uint256, address)
);
require( require(timestamp != 0, "Batch header timestamp cannot be zero");
timestamp != 0,
"Batch header timestamp cannot be zero"
);
return (timestamp + FRAUD_PROOF_WINDOW) > block.timestamp; return (timestamp + FRAUD_PROOF_WINDOW) > block.timestamp;
} }
/********************** /**********************
* Internal Functions * * Internal Functions *
**********************/ **********************/
...@@ -246,28 +176,24 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { ...@@ -246,28 +176,24 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver {
* @return Total number of elements submitted. * @return Total number of elements submitted.
* @return Timestamp of the last batch submitted by the sequencer. * @return Timestamp of the last batch submitted by the sequencer.
*/ */
function _getBatchExtraData() function _getBatchExtraData() internal view returns (uint40, uint40) {
internal
view
returns (
uint40,
uint40
)
{
bytes27 extraData = batches().getGlobalMetadata(); bytes27 extraData = batches().getGlobalMetadata();
uint40 totalElements; uint40 totalElements;
uint40 lastSequencerTimestamp; uint40 lastSequencerTimestamp;
assembly { assembly {
extraData := shr(40, extraData) extraData := shr(40, extraData)
totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) totalElements := and(
lastSequencerTimestamp := shr(40, and(extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000)) extraData,
0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF
)
lastSequencerTimestamp := shr(
40,
and(extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000)
)
} }
return ( return (totalElements, lastSequencerTimestamp);
totalElements,
lastSequencerTimestamp
);
} }
/** /**
...@@ -276,15 +202,10 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { ...@@ -276,15 +202,10 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver {
* @param _lastSequencerTimestamp Timestamp of the last batch submitted by the sequencer. * @param _lastSequencerTimestamp Timestamp of the last batch submitted by the sequencer.
* @return Encoded batch context. * @return Encoded batch context.
*/ */
function _makeBatchExtraData( function _makeBatchExtraData(uint40 _totalElements, uint40 _lastSequencerTimestamp)
uint40 _totalElements,
uint40 _lastSequencerTimestamp
)
internal internal
pure pure
returns ( returns (bytes27)
bytes27
)
{ {
bytes27 extraData; bytes27 extraData;
assembly { assembly {
...@@ -301,12 +222,7 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { ...@@ -301,12 +222,7 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver {
* @param _batch Elements within the batch. * @param _batch Elements within the batch.
* @param _extraData Any extra data to append to the batch. * @param _extraData Any extra data to append to the batch.
*/ */
function _appendBatch( function _appendBatch(bytes32[] memory _batch, bytes memory _extraData) internal {
bytes32[] memory _batch,
bytes memory _extraData
)
internal
{
address sequencer = resolve("OVM_Proposer"); address sequencer = resolve("OVM_Proposer");
(uint40 totalElements, uint40 lastSequencerTimestamp) = _getBatchExtraData(); (uint40 totalElements, uint40 lastSequencerTimestamp) = _getBatchExtraData();
...@@ -355,33 +271,17 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { ...@@ -355,33 +271,17 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver {
* Removes a batch and all subsequent batches from the chain. * Removes a batch and all subsequent batches from the chain.
* @param _batchHeader Header of the batch to remove. * @param _batchHeader Header of the batch to remove.
*/ */
function _deleteBatch( function _deleteBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) internal {
Lib_OVMCodec.ChainBatchHeader memory _batchHeader require(_batchHeader.batchIndex < batches().length(), "Invalid batch index.");
)
internal
{
require(
_batchHeader.batchIndex < batches().length(),
"Invalid batch index."
);
require( require(_isValidBatchHeader(_batchHeader), "Invalid batch header.");
_isValidBatchHeader(_batchHeader),
"Invalid batch header."
);
batches().deleteElementsAfterInclusive( batches().deleteElementsAfterInclusive(
_batchHeader.batchIndex, _batchHeader.batchIndex,
_makeBatchExtraData( _makeBatchExtraData(uint40(_batchHeader.prevTotalElements), 0)
uint40(_batchHeader.prevTotalElements),
0
)
); );
emit StateBatchDeleted( emit StateBatchDeleted(_batchHeader.batchIndex, _batchHeader.batchRoot);
_batchHeader.batchIndex,
_batchHeader.batchRoot
);
} }
/** /**
...@@ -389,14 +289,10 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { ...@@ -389,14 +289,10 @@ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver {
* @param _batchHeader Batch header to validate. * @param _batchHeader Batch header to validate.
* @return Whether or not the header matches the stored one. * @return Whether or not the header matches the stored one.
*/ */
function _isValidBatchHeader( function _isValidBatchHeader(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
internal internal
view view
returns ( returns (bool)
bool
)
{ {
return Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().get(_batchHeader.batchIndex); return Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().get(_batchHeader.batchIndex);
} }
......
...@@ -2,10 +2,10 @@ ...@@ -2,10 +2,10 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Interface Imports */ /* Interface Imports */
import { IBondManager } from "./IBondManager.sol"; import {IBondManager} from "./IBondManager.sol";
/* Contract Imports */ /* Contract Imports */
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import {Lib_AddressResolver} from "../../libraries/resolver/Lib_AddressResolver.sol";
/** /**
* @title BondManager * @title BondManager
...@@ -15,15 +15,10 @@ import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolve ...@@ -15,15 +15,10 @@ import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolve
* Runtime target: EVM * Runtime target: EVM
*/ */
contract BondManager is IBondManager, Lib_AddressResolver { contract BondManager is IBondManager, Lib_AddressResolver {
/** /**
* @param _libAddressManager Address of the Address Manager. * @param _libAddressManager Address of the Address Manager.
*/ */
constructor( constructor(address _libAddressManager) Lib_AddressResolver(_libAddressManager) {}
address _libAddressManager
)
Lib_AddressResolver(_libAddressManager)
{}
/** /**
* Checks whether a given address is properly collateralized and can perform actions within * Checks whether a given address is properly collateralized and can perform actions within
...@@ -31,15 +26,7 @@ contract BondManager is IBondManager, Lib_AddressResolver { ...@@ -31,15 +26,7 @@ contract BondManager is IBondManager, Lib_AddressResolver {
* @param _who Address to check. * @param _who Address to check.
* @return true if the address is properly collateralized, false otherwise. * @return true if the address is properly collateralized, false otherwise.
*/ */
function isCollateralized( function isCollateralized(address _who) public view returns (bool) {
address _who
)
public
view
returns (
bool
)
{
// Only authenticate sequencer to submit state root batches. // Only authenticate sequencer to submit state root batches.
return _who == resolve("OVM_Proposer"); return _who == resolve("OVM_Proposer");
} }
......
...@@ -5,12 +5,9 @@ pragma solidity ^0.8.9; ...@@ -5,12 +5,9 @@ pragma solidity ^0.8.9;
* @title IBondManager * @title IBondManager
*/ */
interface IBondManager { interface IBondManager {
/******************** /********************
* Public Functions * * Public Functions *
********************/ ********************/
function isCollateralized( function isCollateralized(address _who) external view returns (bool);
address _who
) external view returns (bool);
} }
...@@ -2,13 +2,12 @@ ...@@ -2,13 +2,12 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Interface Imports */ /* Interface Imports */
import { ICrossDomainMessenger } from "../../libraries/bridge/ICrossDomainMessenger.sol"; import {ICrossDomainMessenger} from "../../libraries/bridge/ICrossDomainMessenger.sol";
/** /**
* @title IL2CrossDomainMessenger * @title IL2CrossDomainMessenger
*/ */
interface IL2CrossDomainMessenger is ICrossDomainMessenger { interface IL2CrossDomainMessenger is ICrossDomainMessenger {
/******************** /********************
* Public Functions * * Public Functions *
********************/ ********************/
......
...@@ -5,12 +5,11 @@ pragma solidity ^0.8.9; ...@@ -5,12 +5,11 @@ pragma solidity ^0.8.9;
* @title IL2ERC20Bridge * @title IL2ERC20Bridge
*/ */
interface IL2ERC20Bridge { interface IL2ERC20Bridge {
/********** /**********
* Events * * Events *
**********/ **********/
event WithdrawalInitiated ( event WithdrawalInitiated(
address indexed _l1Token, address indexed _l1Token,
address indexed _l2Token, address indexed _l2Token,
address indexed _from, address indexed _from,
...@@ -19,7 +18,7 @@ interface IL2ERC20Bridge { ...@@ -19,7 +18,7 @@ interface IL2ERC20Bridge {
bytes _data bytes _data
); );
event DepositFinalized ( event DepositFinalized(
address indexed _l1Token, address indexed _l1Token,
address indexed _l2Token, address indexed _l2Token,
address indexed _from, address indexed _from,
...@@ -28,7 +27,7 @@ interface IL2ERC20Bridge { ...@@ -28,7 +27,7 @@ interface IL2ERC20Bridge {
bytes _data bytes _data
); );
event DepositFailed ( event DepositFailed(
address indexed _l1Token, address indexed _l1Token,
address indexed _l2Token, address indexed _l2Token,
address indexed _from, address indexed _from,
...@@ -37,7 +36,6 @@ interface IL2ERC20Bridge { ...@@ -37,7 +36,6 @@ interface IL2ERC20Bridge {
bytes _data bytes _data
); );
/******************** /********************
* Public Functions * * Public Functions *
********************/ ********************/
...@@ -46,7 +44,7 @@ interface IL2ERC20Bridge { ...@@ -46,7 +44,7 @@ interface IL2ERC20Bridge {
* @dev get the address of the corresponding L1 bridge contract. * @dev get the address of the corresponding L1 bridge contract.
* @return Address of the corresponding L1 bridge contract. * @return Address of the corresponding L1 bridge contract.
*/ */
function l1TokenBridge() external returns(address); function l1TokenBridge() external returns (address);
/** /**
* @dev initiate a withdraw of some tokens to the caller's account on L1 * @dev initiate a withdraw of some tokens to the caller's account on L1
...@@ -57,13 +55,12 @@ interface IL2ERC20Bridge { ...@@ -57,13 +55,12 @@ interface IL2ERC20Bridge {
* solely as a convenience for external contracts. Aside from enforcing a maximum * solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content. * length, these contracts provide no guarantees about its content.
*/ */
function withdraw ( function withdraw(
address _l2Token, address _l2Token,
uint _amount, uint256 _amount,
uint32 _l1Gas, uint32 _l1Gas,
bytes calldata _data bytes calldata _data
) ) external;
external;
/** /**
* @dev initiate a withdraw of some token to a recipient's account on L1. * @dev initiate a withdraw of some token to a recipient's account on L1.
...@@ -75,14 +72,13 @@ interface IL2ERC20Bridge { ...@@ -75,14 +72,13 @@ interface IL2ERC20Bridge {
* solely as a convenience for external contracts. Aside from enforcing a maximum * solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content. * length, these contracts provide no guarantees about its content.
*/ */
function withdrawTo ( function withdrawTo(
address _l2Token, address _l2Token,
address _to, address _to,
uint _amount, uint256 _amount,
uint32 _l1Gas, uint32 _l1Gas,
bytes calldata _data bytes calldata _data
) ) external;
external;
/************************* /*************************
* Cross-chain Functions * * Cross-chain Functions *
...@@ -101,14 +97,12 @@ interface IL2ERC20Bridge { ...@@ -101,14 +97,12 @@ interface IL2ERC20Bridge {
* solely as a convenience for external contracts. Aside from enforcing a maximum * solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content. * length, these contracts provide no guarantees about its content.
*/ */
function finalizeDeposit ( function finalizeDeposit(
address _l1Token, address _l1Token,
address _l2Token, address _l2Token,
address _from, address _from,
address _to, address _to,
uint _amount, uint256 _amount,
bytes calldata _data bytes calldata _data
) ) external;
external;
} }
...@@ -2,60 +2,50 @@ ...@@ -2,60 +2,50 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { AddressAliasHelper } from "../../standards/AddressAliasHelper.sol"; import {AddressAliasHelper} from "../../standards/AddressAliasHelper.sol";
import { Lib_CrossDomainUtils } from "../../libraries/bridge/Lib_CrossDomainUtils.sol"; import {Lib_CrossDomainUtils} from "../../libraries/bridge/Lib_CrossDomainUtils.sol";
import { Lib_DefaultValues } from "../../libraries/constants/Lib_DefaultValues.sol"; import {Lib_DefaultValues} from "../../libraries/constants/Lib_DefaultValues.sol";
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; import {Lib_PredeployAddresses} from "../../libraries/constants/Lib_PredeployAddresses.sol";
/* Interface Imports */ /* Interface Imports */
import { IL2CrossDomainMessenger } from "./IL2CrossDomainMessenger.sol"; import {IL2CrossDomainMessenger} from "./IL2CrossDomainMessenger.sol";
import { iOVM_L2ToL1MessagePasser } from "../predeploys/iOVM_L2ToL1MessagePasser.sol"; import {iOVM_L2ToL1MessagePasser} from "../predeploys/iOVM_L2ToL1MessagePasser.sol";
/** /**
* @title L2CrossDomainMessenger * @title L2CrossDomainMessenger
* @dev The L2 Cross Domain Messenger contract sends messages from L2 to L1, and is the entry point * @dev The L2 Cross Domain Messenger contract sends messages from L2 to L1, and is the entry point
* for L2 messages sent via the L1 Cross Domain Messenger. * for L2 messages sent via the L1 Cross Domain Messenger.
* *
*/ */
contract L2CrossDomainMessenger is contract L2CrossDomainMessenger is IL2CrossDomainMessenger {
IL2CrossDomainMessenger
{
/************* /*************
* Variables * * Variables *
*************/ *************/
mapping (bytes32 => bool) public relayedMessages; mapping(bytes32 => bool) public relayedMessages;
mapping (bytes32 => bool) public successfulMessages; mapping(bytes32 => bool) public successfulMessages;
mapping (bytes32 => bool) public sentMessages; mapping(bytes32 => bool) public sentMessages;
uint256 public messageNonce; uint256 public messageNonce;
address internal xDomainMsgSender = Lib_DefaultValues.DEFAULT_XDOMAIN_SENDER; address internal xDomainMsgSender = Lib_DefaultValues.DEFAULT_XDOMAIN_SENDER;
address public l1CrossDomainMessenger; address public l1CrossDomainMessenger;
/*************** /***************
* Constructor * * Constructor *
***************/ ***************/
constructor( constructor(address _l1CrossDomainMessenger) {
address _l1CrossDomainMessenger
) {
l1CrossDomainMessenger = _l1CrossDomainMessenger; l1CrossDomainMessenger = _l1CrossDomainMessenger;
} }
/******************** /********************
* Public Functions * * Public Functions *
********************/ ********************/
function xDomainMessageSender() function xDomainMessageSender() public view returns (address) {
public require(
view xDomainMsgSender != Lib_DefaultValues.DEFAULT_XDOMAIN_SENDER,
returns ( "xDomainMessageSender is not set"
address );
)
{
require(xDomainMsgSender != Lib_DefaultValues.DEFAULT_XDOMAIN_SENDER, "xDomainMessageSender is not set");
return xDomainMsgSender; return xDomainMsgSender;
} }
...@@ -69,9 +59,7 @@ contract L2CrossDomainMessenger is ...@@ -69,9 +59,7 @@ contract L2CrossDomainMessenger is
address _target, address _target,
bytes memory _message, bytes memory _message,
uint32 _gasLimit uint32 _gasLimit
) ) public {
public
{
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target, _target,
msg.sender, msg.sender,
...@@ -82,9 +70,9 @@ contract L2CrossDomainMessenger is ...@@ -82,9 +70,9 @@ contract L2CrossDomainMessenger is
sentMessages[keccak256(xDomainCalldata)] = true; sentMessages[keccak256(xDomainCalldata)] = true;
// Actually send the message. // Actually send the message.
iOVM_L2ToL1MessagePasser( iOVM_L2ToL1MessagePasser(Lib_PredeployAddresses.L2_TO_L1_MESSAGE_PASSER).passMessageToL1(
Lib_PredeployAddresses.L2_TO_L1_MESSAGE_PASSER xDomainCalldata
).passMessageToL1(xDomainCalldata); );
// Emit an event before we bump the nonce or the nonce will be off by one. // Emit an event before we bump the nonce or the nonce will be off by one.
emit SentMessage(_target, msg.sender, _message, messageNonce, _gasLimit); emit SentMessage(_target, msg.sender, _message, messageNonce, _gasLimit);
...@@ -100,9 +88,7 @@ contract L2CrossDomainMessenger is ...@@ -100,9 +88,7 @@ contract L2CrossDomainMessenger is
address _sender, address _sender,
bytes memory _message, bytes memory _message,
uint256 _messageNonce uint256 _messageNonce
) ) public {
public
{
require( require(
AddressAliasHelper.undoL1ToL2Alias(msg.sender) == l1CrossDomainMessenger, AddressAliasHelper.undoL1ToL2Alias(msg.sender) == l1CrossDomainMessenger,
"Provided message could not be verified." "Provided message could not be verified."
...@@ -146,13 +132,7 @@ contract L2CrossDomainMessenger is ...@@ -146,13 +132,7 @@ contract L2CrossDomainMessenger is
// Store an identifier that can be used to prove that the given message was relayed by some // Store an identifier that can be used to prove that the given message was relayed by some
// user. Gives us an easy way to pay relayers for their work. // user. Gives us an easy way to pay relayers for their work.
bytes32 relayId = keccak256( bytes32 relayId = keccak256(abi.encodePacked(xDomainCalldata, msg.sender, block.number));
abi.encodePacked(
xDomainCalldata,
msg.sender,
block.number
)
);
relayedMessages[relayId] = true; relayedMessages[relayId] = true;
} }
......
...@@ -2,17 +2,17 @@ ...@@ -2,17 +2,17 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Interface Imports */ /* Interface Imports */
import { IL1StandardBridge } from "../../L1/messaging/IL1StandardBridge.sol"; import {IL1StandardBridge} from "../../L1/messaging/IL1StandardBridge.sol";
import { IL1ERC20Bridge } from "../../L1/messaging/IL1ERC20Bridge.sol"; import {IL1ERC20Bridge} from "../../L1/messaging/IL1ERC20Bridge.sol";
import { IL2ERC20Bridge } from "./IL2ERC20Bridge.sol"; import {IL2ERC20Bridge} from "./IL2ERC20Bridge.sol";
/* Library Imports */ /* Library Imports */
import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import {ERC165Checker} from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import { CrossDomainEnabled } from "../../libraries/bridge/CrossDomainEnabled.sol"; import {CrossDomainEnabled} from "../../libraries/bridge/CrossDomainEnabled.sol";
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; import {Lib_PredeployAddresses} from "../../libraries/constants/Lib_PredeployAddresses.sol";
/* Contract Imports */ /* Contract Imports */
import { IL2StandardERC20 } from "../../standards/IL2StandardERC20.sol"; import {IL2StandardERC20} from "../../standards/IL2StandardERC20.sol";
/** /**
* @title L2StandardBridge * @title L2StandardBridge
...@@ -24,7 +24,6 @@ import { IL2StandardERC20 } from "../../standards/IL2StandardERC20.sol"; ...@@ -24,7 +24,6 @@ import { IL2StandardERC20 } from "../../standards/IL2StandardERC20.sol";
* bridge to release L1 funds. * bridge to release L1 funds.
*/ */
contract L2StandardBridge is IL2ERC20Bridge, CrossDomainEnabled { contract L2StandardBridge is IL2ERC20Bridge, CrossDomainEnabled {
/******************************** /********************************
* External Contract References * * External Contract References *
********************************/ ********************************/
...@@ -39,10 +38,7 @@ contract L2StandardBridge is IL2ERC20Bridge, CrossDomainEnabled { ...@@ -39,10 +38,7 @@ contract L2StandardBridge is IL2ERC20Bridge, CrossDomainEnabled {
* @param _l2CrossDomainMessenger Cross-domain messenger used by this contract. * @param _l2CrossDomainMessenger Cross-domain messenger used by this contract.
* @param _l1TokenBridge Address of the L1 bridge deployed to the main chain. * @param _l1TokenBridge Address of the L1 bridge deployed to the main chain.
*/ */
constructor( constructor(address _l2CrossDomainMessenger, address _l1TokenBridge)
address _l2CrossDomainMessenger,
address _l1TokenBridge
)
CrossDomainEnabled(_l2CrossDomainMessenger) CrossDomainEnabled(_l2CrossDomainMessenger)
{ {
l1TokenBridge = _l1TokenBridge; l1TokenBridge = _l1TokenBridge;
...@@ -60,18 +56,8 @@ contract L2StandardBridge is IL2ERC20Bridge, CrossDomainEnabled { ...@@ -60,18 +56,8 @@ contract L2StandardBridge is IL2ERC20Bridge, CrossDomainEnabled {
uint256 _amount, uint256 _amount,
uint32 _l1Gas, uint32 _l1Gas,
bytes calldata _data bytes calldata _data
) ) external virtual {
external _initiateWithdrawal(_l2Token, msg.sender, msg.sender, _amount, _l1Gas, _data);
virtual
{
_initiateWithdrawal(
_l2Token,
msg.sender,
msg.sender,
_amount,
_l1Gas,
_data
);
} }
/** /**
...@@ -83,18 +69,8 @@ contract L2StandardBridge is IL2ERC20Bridge, CrossDomainEnabled { ...@@ -83,18 +69,8 @@ contract L2StandardBridge is IL2ERC20Bridge, CrossDomainEnabled {
uint256 _amount, uint256 _amount,
uint32 _l1Gas, uint32 _l1Gas,
bytes calldata _data bytes calldata _data
) ) external virtual {
external _initiateWithdrawal(_l2Token, msg.sender, _to, _amount, _l1Gas, _data);
virtual
{
_initiateWithdrawal(
_l2Token,
msg.sender,
_to,
_amount,
_l1Gas,
_data
);
} }
/** /**
...@@ -116,9 +92,7 @@ contract L2StandardBridge is IL2ERC20Bridge, CrossDomainEnabled { ...@@ -116,9 +92,7 @@ contract L2StandardBridge is IL2ERC20Bridge, CrossDomainEnabled {
uint256 _amount, uint256 _amount,
uint32 _l1Gas, uint32 _l1Gas,
bytes calldata _data bytes calldata _data
) ) internal {
internal
{
// When a withdrawal is initiated, we burn the withdrawer's funds to prevent subsequent L2 // When a withdrawal is initiated, we burn the withdrawer's funds to prevent subsequent L2
// usage // usage
IL2StandardERC20(_l2Token).burn(msg.sender, _amount); IL2StandardERC20(_l2Token).burn(msg.sender, _amount);
...@@ -129,30 +103,26 @@ contract L2StandardBridge is IL2ERC20Bridge, CrossDomainEnabled { ...@@ -129,30 +103,26 @@ contract L2StandardBridge is IL2ERC20Bridge, CrossDomainEnabled {
if (_l2Token == Lib_PredeployAddresses.OVM_ETH) { if (_l2Token == Lib_PredeployAddresses.OVM_ETH) {
message = abi.encodeWithSelector( message = abi.encodeWithSelector(
IL1StandardBridge.finalizeETHWithdrawal.selector, IL1StandardBridge.finalizeETHWithdrawal.selector,
_from, _from,
_to, _to,
_amount, _amount,
_data _data
); );
} else { } else {
message = abi.encodeWithSelector( message = abi.encodeWithSelector(
IL1ERC20Bridge.finalizeERC20Withdrawal.selector, IL1ERC20Bridge.finalizeERC20Withdrawal.selector,
l1Token, l1Token,
_l2Token, _l2Token,
_from, _from,
_to, _to,
_amount, _amount,
_data _data
); );
} }
// Send message up to L1 bridge // Send message up to L1 bridge
sendCrossDomainMessage( sendCrossDomainMessage(l1TokenBridge, _l1Gas, message);
l1TokenBridge,
_l1Gas,
message
);
emit WithdrawalInitiated(l1Token, _l2Token, msg.sender, _to, _amount, _data); emit WithdrawalInitiated(l1Token, _l2Token, msg.sender, _to, _amount, _data);
} }
...@@ -171,11 +141,7 @@ contract L2StandardBridge is IL2ERC20Bridge, CrossDomainEnabled { ...@@ -171,11 +141,7 @@ contract L2StandardBridge is IL2ERC20Bridge, CrossDomainEnabled {
address _to, address _to,
uint256 _amount, uint256 _amount,
bytes calldata _data bytes calldata _data
) ) external virtual onlyFromCrossDomainAccount(l1TokenBridge) {
external
virtual
onlyFromCrossDomainAccount(l1TokenBridge)
{
// Check the target token is compliant and // Check the target token is compliant and
// verify the deposited token on L1 matches the L2 deposited token representation here // verify the deposited token on L1 matches the L2 deposited token representation here
if ( if (
...@@ -199,18 +165,14 @@ contract L2StandardBridge is IL2ERC20Bridge, CrossDomainEnabled { ...@@ -199,18 +165,14 @@ contract L2StandardBridge is IL2ERC20Bridge, CrossDomainEnabled {
IL1ERC20Bridge.finalizeERC20Withdrawal.selector, IL1ERC20Bridge.finalizeERC20Withdrawal.selector,
_l1Token, _l1Token,
_l2Token, _l2Token,
_to, // switched the _to and _from here to bounce back the deposit to the sender _to, // switched the _to and _from here to bounce back the deposit to the sender
_from, _from,
_amount, _amount,
_data _data
); );
// Send message up to L1 bridge // Send message up to L1 bridge
sendCrossDomainMessage( sendCrossDomainMessage(l1TokenBridge, 0, message);
l1TokenBridge,
0,
message
);
emit DepositFailed(_l1Token, _l2Token, _from, _to, _amount, _data); emit DepositFailed(_l1Token, _l2Token, _from, _to, _amount, _data);
} }
} }
......
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Contract Imports */ /* Contract Imports */
import { L2StandardERC20 } from "../../standards/L2StandardERC20.sol"; import {L2StandardERC20} from "../../standards/L2StandardERC20.sol";
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; import {Lib_PredeployAddresses} from "../../libraries/constants/Lib_PredeployAddresses.sol";
/** /**
* @title L2StandardTokenFactory * @title L2StandardTokenFactory
...@@ -11,7 +11,6 @@ import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployA ...@@ -11,7 +11,6 @@ import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployA
* compatible with and working on the standard bridge. * compatible with and working on the standard bridge.
*/ */
contract L2StandardTokenFactory { contract L2StandardTokenFactory {
event StandardL2TokenCreated(address indexed _l1Token, address indexed _l2Token); event StandardL2TokenCreated(address indexed _l1Token, address indexed _l2Token);
/** /**
...@@ -24,10 +23,8 @@ contract L2StandardTokenFactory { ...@@ -24,10 +23,8 @@ contract L2StandardTokenFactory {
address _l1Token, address _l1Token,
string memory _name, string memory _name,
string memory _symbol string memory _symbol
) ) external {
external require(_l1Token != address(0), "Must provide L1 token address");
{
require (_l1Token != address(0), "Must provide L1 token address");
L2StandardERC20 l2Token = new L2StandardERC20( L2StandardERC20 l2Token = new L2StandardERC20(
Lib_PredeployAddresses.L2_STANDARD_BRIDGE, Lib_PredeployAddresses.L2_STANDARD_BRIDGE,
......
...@@ -9,7 +9,6 @@ pragma solidity ^0.8.9; ...@@ -9,7 +9,6 @@ pragma solidity ^0.8.9;
* ovmCREATE or ovmCREATE2 operation to proceed if the deployer's address whitelisted. * ovmCREATE or ovmCREATE2 operation to proceed if the deployer's address whitelisted.
*/ */
contract OVM_DeployerWhitelist { contract OVM_DeployerWhitelist {
/********** /**********
* Events * * Events *
**********/ **********/
...@@ -18,15 +17,13 @@ contract OVM_DeployerWhitelist { ...@@ -18,15 +17,13 @@ contract OVM_DeployerWhitelist {
event WhitelistStatusChanged(address deployer, bool whitelisted); event WhitelistStatusChanged(address deployer, bool whitelisted);
event WhitelistDisabled(address oldOwner); event WhitelistDisabled(address oldOwner);
/********************** /**********************
* Contract Constants * * Contract Constants *
**********************/ **********************/
// WARNING: When owner is set to address(0), the whitelist is disabled. // WARNING: When owner is set to address(0), the whitelist is disabled.
address public owner; address public owner;
mapping (address => bool) public whitelist; mapping(address => bool) public whitelist;
/********************** /**********************
* Function Modifiers * * Function Modifiers *
...@@ -36,14 +33,10 @@ contract OVM_DeployerWhitelist { ...@@ -36,14 +33,10 @@ contract OVM_DeployerWhitelist {
* Blocks functions to anyone except the contract owner. * Blocks functions to anyone except the contract owner.
*/ */
modifier onlyOwner() { modifier onlyOwner() {
require( require(msg.sender == owner, "Function can only be called by the owner of this contract.");
msg.sender == owner,
"Function can only be called by the owner of this contract."
);
_; _;
} }
/******************** /********************
* Public Functions * * Public Functions *
********************/ ********************/
...@@ -53,13 +46,7 @@ contract OVM_DeployerWhitelist { ...@@ -53,13 +46,7 @@ contract OVM_DeployerWhitelist {
* @param _deployer Address to update permissions for. * @param _deployer Address to update permissions for.
* @param _isWhitelisted Whether or not the address is whitelisted. * @param _isWhitelisted Whether or not the address is whitelisted.
*/ */
function setWhitelistedDeployer( function setWhitelistedDeployer(address _deployer, bool _isWhitelisted) external onlyOwner {
address _deployer,
bool _isWhitelisted
)
external
onlyOwner
{
whitelist[_deployer] = _isWhitelisted; whitelist[_deployer] = _isWhitelisted;
emit WhitelistStatusChanged(_deployer, _isWhitelisted); emit WhitelistStatusChanged(_deployer, _isWhitelisted);
} }
...@@ -68,12 +55,7 @@ contract OVM_DeployerWhitelist { ...@@ -68,12 +55,7 @@ contract OVM_DeployerWhitelist {
* Updates the owner of this contract. * Updates the owner of this contract.
* @param _owner Address of the new owner. * @param _owner Address of the new owner.
*/ */
function setOwner( function setOwner(address _owner) public onlyOwner {
address _owner
)
public
onlyOwner
{
// Prevent users from setting the whitelist owner to address(0) except via // Prevent users from setting the whitelist owner to address(0) except via
// enableArbitraryContractDeployment. If you want to burn the whitelist owner, send it to any // enableArbitraryContractDeployment. If you want to burn the whitelist owner, send it to any
// other address that doesn't have a corresponding knowable private key. // other address that doesn't have a corresponding knowable private key.
...@@ -89,10 +71,7 @@ contract OVM_DeployerWhitelist { ...@@ -89,10 +71,7 @@ contract OVM_DeployerWhitelist {
/** /**
* Permanently enables arbitrary contract deployment and deletes the owner. * Permanently enables arbitrary contract deployment and deletes the owner.
*/ */
function enableArbitraryContractDeployment() function enableArbitraryContractDeployment() external onlyOwner {
external
onlyOwner
{
emit WhitelistDisabled(owner); emit WhitelistDisabled(owner);
owner = address(0); owner = address(0);
} }
...@@ -102,15 +81,7 @@ contract OVM_DeployerWhitelist { ...@@ -102,15 +81,7 @@ contract OVM_DeployerWhitelist {
* @param _deployer Address to check. * @param _deployer Address to check.
* @return _allowed Whether or not the address can deploy contracts. * @return _allowed Whether or not the address can deploy contracts.
*/ */
function isDeployerAllowed( function isDeployerAllowed(address _deployer) external view returns (bool) {
address _deployer
)
external
view
returns (
bool
)
{
return (owner == address(0) || whitelist[_deployer]); return (owner == address(0) || whitelist[_deployer]);
} }
} }
...@@ -2,10 +2,10 @@ ...@@ -2,10 +2,10 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; import {Lib_PredeployAddresses} from "../../libraries/constants/Lib_PredeployAddresses.sol";
/* Contract Imports */ /* Contract Imports */
import { L2StandardERC20 } from "../../standards/L2StandardERC20.sol"; import {L2StandardERC20} from "../../standards/L2StandardERC20.sol";
/** /**
* @title OVM_ETH * @title OVM_ETH
...@@ -13,21 +13,14 @@ import { L2StandardERC20 } from "../../standards/L2StandardERC20.sol"; ...@@ -13,21 +13,14 @@ import { L2StandardERC20 } from "../../standards/L2StandardERC20.sol";
* unlike on Layer 1, Layer 2 accounts do not have a balance field. * unlike on Layer 1, Layer 2 accounts do not have a balance field.
*/ */
contract OVM_ETH is L2StandardERC20 { contract OVM_ETH is L2StandardERC20 {
/*************** /***************
* Constructor * * Constructor *
***************/ ***************/
constructor() constructor()
L2StandardERC20( L2StandardERC20(Lib_PredeployAddresses.L2_STANDARD_BRIDGE, address(0), "Ether", "ETH")
Lib_PredeployAddresses.L2_STANDARD_BRIDGE,
address(0),
"Ether",
"ETH"
)
{} {}
// ETH ERC20 features are disabled until further notice. // ETH ERC20 features are disabled until further notice.
// Discussion here: https://github.com/ethereum-optimism/optimism/discussions/1444 // Discussion here: https://github.com/ethereum-optimism/optimism/discussions/1444
...@@ -39,15 +32,29 @@ contract OVM_ETH is L2StandardERC20 { ...@@ -39,15 +32,29 @@ contract OVM_ETH is L2StandardERC20 {
revert("OVM_ETH: approve is disabled pending further community discussion."); revert("OVM_ETH: approve is disabled pending further community discussion.");
} }
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
revert("OVM_ETH: transferFrom is disabled pending further community discussion."); revert("OVM_ETH: transferFrom is disabled pending further community discussion.");
} }
function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { function increaseAllowance(address spender, uint256 addedValue)
public
virtual
override
returns (bool)
{
revert("OVM_ETH: increaseAllowance is disabled pending further community discussion."); revert("OVM_ETH: increaseAllowance is disabled pending further community discussion.");
} }
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
override
returns (bool)
{
revert("OVM_ETH: decreaseAllowance is disabled pending further community discussion."); revert("OVM_ETH: decreaseAllowance is disabled pending further community discussion.");
} }
} }
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* External Imports */ /* External Imports */
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
/** /**
* @title OVM_GasPriceOracle * @title OVM_GasPriceOracle
...@@ -16,12 +16,10 @@ import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; ...@@ -16,12 +16,10 @@ import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
* the deployed bytecode instead of running the initcode. * the deployed bytecode instead of running the initcode.
*/ */
contract OVM_GasPriceOracle is Ownable { contract OVM_GasPriceOracle is Ownable {
/************* /*************
* Variables * * Variables *
*************/ *************/
// Current L2 gas price // Current L2 gas price
uint256 public gasPrice; uint256 public gasPrice;
// Current L1 base fee // Current L1 base fee
...@@ -40,11 +38,7 @@ contract OVM_GasPriceOracle is Ownable { ...@@ -40,11 +38,7 @@ contract OVM_GasPriceOracle is Ownable {
/** /**
* @param _owner Address that will initially own this contract. * @param _owner Address that will initially own this contract.
*/ */
constructor( constructor(address _owner) Ownable() {
address _owner
)
Ownable()
{
transferOwnership(_owner); transferOwnership(_owner);
} }
...@@ -66,12 +60,7 @@ contract OVM_GasPriceOracle is Ownable { ...@@ -66,12 +60,7 @@ contract OVM_GasPriceOracle is Ownable {
* Allows the owner to modify the l2 gas price. * Allows the owner to modify the l2 gas price.
* @param _gasPrice New l2 gas price. * @param _gasPrice New l2 gas price.
*/ */
function setGasPrice( function setGasPrice(uint256 _gasPrice) public onlyOwner {
uint256 _gasPrice
)
public
onlyOwner
{
gasPrice = _gasPrice; gasPrice = _gasPrice;
emit GasPriceUpdated(_gasPrice); emit GasPriceUpdated(_gasPrice);
} }
...@@ -80,12 +69,7 @@ contract OVM_GasPriceOracle is Ownable { ...@@ -80,12 +69,7 @@ contract OVM_GasPriceOracle is Ownable {
* Allows the owner to modify the l1 base fee. * Allows the owner to modify the l1 base fee.
* @param _baseFee New l1 base fee * @param _baseFee New l1 base fee
*/ */
function setL1BaseFee( function setL1BaseFee(uint256 _baseFee) public onlyOwner {
uint256 _baseFee
)
public
onlyOwner
{
l1BaseFee = _baseFee; l1BaseFee = _baseFee;
emit L1BaseFeeUpdated(_baseFee); emit L1BaseFeeUpdated(_baseFee);
} }
...@@ -94,12 +78,7 @@ contract OVM_GasPriceOracle is Ownable { ...@@ -94,12 +78,7 @@ contract OVM_GasPriceOracle is Ownable {
* Allows the owner to modify the overhead. * Allows the owner to modify the overhead.
* @param _overhead New overhead * @param _overhead New overhead
*/ */
function setOverhead( function setOverhead(uint256 _overhead) public onlyOwner {
uint256 _overhead
)
public
onlyOwner
{
overhead = _overhead; overhead = _overhead;
emit OverheadUpdated(_overhead); emit OverheadUpdated(_overhead);
} }
...@@ -108,12 +87,7 @@ contract OVM_GasPriceOracle is Ownable { ...@@ -108,12 +87,7 @@ contract OVM_GasPriceOracle is Ownable {
* Allows the owner to modify the scalar. * Allows the owner to modify the scalar.
* @param _scalar New scalar * @param _scalar New scalar
*/ */
function setScalar( function setScalar(uint256 _scalar) public onlyOwner {
uint256 _scalar
)
public
onlyOwner
{
scalar = _scalar; scalar = _scalar;
emit ScalarUpdated(_scalar); emit ScalarUpdated(_scalar);
} }
...@@ -122,12 +96,7 @@ contract OVM_GasPriceOracle is Ownable { ...@@ -122,12 +96,7 @@ contract OVM_GasPriceOracle is Ownable {
* Allows the owner to modify the decimals. * Allows the owner to modify the decimals.
* @param _decimals New decimals * @param _decimals New decimals
*/ */
function setDecimals( function setDecimals(uint256 _decimals) public onlyOwner {
uint256 _decimals
)
public
onlyOwner
{
decimals = _decimals; decimals = _decimals;
emit DecimalsUpdated(_decimals); emit DecimalsUpdated(_decimals);
} }
...@@ -139,13 +108,7 @@ contract OVM_GasPriceOracle is Ownable { ...@@ -139,13 +108,7 @@ contract OVM_GasPriceOracle is Ownable {
* @param _data Unsigned RLP encoded tx, 6 elements * @param _data Unsigned RLP encoded tx, 6 elements
* @return L1 fee that should be paid for the tx * @return L1 fee that should be paid for the tx
*/ */
function getL1Fee(bytes memory _data) function getL1Fee(bytes memory _data) public view returns (uint256) {
public
view
returns (
uint256
)
{
uint256 l1GasUsed = getL1GasUsed(_data); uint256 l1GasUsed = getL1GasUsed(_data);
uint256 l1Fee = l1GasUsed * l1BaseFee; uint256 l1Fee = l1GasUsed * l1BaseFee;
uint256 divisor = 10**decimals; uint256 divisor = 10**decimals;
...@@ -176,13 +139,7 @@ contract OVM_GasPriceOracle is Ownable { ...@@ -176,13 +139,7 @@ contract OVM_GasPriceOracle is Ownable {
* @param _data Unsigned RLP encoded tx, 6 elements * @param _data Unsigned RLP encoded tx, 6 elements
* @return Amount of L1 gas used for a transaction * @return Amount of L1 gas used for a transaction
*/ */
function getL1GasUsed(bytes memory _data) function getL1GasUsed(bytes memory _data) public view returns (uint256) {
public
view
returns (
uint256
)
{
uint256 total = 0; uint256 total = 0;
for (uint256 i = 0; i < _data.length; i++) { for (uint256 i = 0; i < _data.length; i++) {
if (_data[i] == 0) { if (_data[i] == 0) {
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Interface Imports */ /* Interface Imports */
import { iOVM_L2ToL1MessagePasser } from "./iOVM_L2ToL1MessagePasser.sol"; import {iOVM_L2ToL1MessagePasser} from "./iOVM_L2ToL1MessagePasser.sol";
/** /**
* @title OVM_L2ToL1MessagePasser * @title OVM_L2ToL1MessagePasser
...@@ -12,12 +12,11 @@ import { iOVM_L2ToL1MessagePasser } from "./iOVM_L2ToL1MessagePasser.sol"; ...@@ -12,12 +12,11 @@ import { iOVM_L2ToL1MessagePasser } from "./iOVM_L2ToL1MessagePasser.sol";
* contract's `sentMessages` mapping. * contract's `sentMessages` mapping.
*/ */
contract OVM_L2ToL1MessagePasser is iOVM_L2ToL1MessagePasser { contract OVM_L2ToL1MessagePasser is iOVM_L2ToL1MessagePasser {
/********************** /**********************
* Contract Variables * * Contract Variables *
**********************/ **********************/
mapping (bytes32 => bool) public sentMessages; mapping(bytes32 => bool) public sentMessages;
/******************** /********************
* Public Functions * * Public Functions *
...@@ -27,19 +26,10 @@ contract OVM_L2ToL1MessagePasser is iOVM_L2ToL1MessagePasser { ...@@ -27,19 +26,10 @@ contract OVM_L2ToL1MessagePasser is iOVM_L2ToL1MessagePasser {
* Passes a message to L1. * Passes a message to L1.
* @param _message Message to pass to L1. * @param _message Message to pass to L1.
*/ */
function passMessageToL1( function passMessageToL1(bytes memory _message) public {
bytes memory _message
)
public
{
// Note: although this function is public, only messages sent from the // Note: although this function is public, only messages sent from the
// L2CrossDomainMessenger will be relayed by the L1CrossDomainMessenger. // L2CrossDomainMessenger will be relayed by the L1CrossDomainMessenger.
// This is enforced by a check in L1CrossDomainMessenger._verifyStorageProof(). // This is enforced by a check in L1CrossDomainMessenger._verifyStorageProof().
sentMessages[keccak256( sentMessages[keccak256(abi.encodePacked(_message, msg.sender))] = true;
abi.encodePacked(
_message,
msg.sender
)
)] = true;
} }
} }
...@@ -2,10 +2,10 @@ ...@@ -2,10 +2,10 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; import {Lib_PredeployAddresses} from "../../libraries/constants/Lib_PredeployAddresses.sol";
/* Contract Imports */ /* Contract Imports */
import { L2StandardBridge } from "../messaging/L2StandardBridge.sol"; import {L2StandardBridge} from "../messaging/L2StandardBridge.sol";
/** /**
* @title OVM_SequencerFeeVault * @title OVM_SequencerFeeVault
...@@ -13,7 +13,6 @@ import { L2StandardBridge } from "../messaging/L2StandardBridge.sol"; ...@@ -13,7 +13,6 @@ import { L2StandardBridge } from "../messaging/L2StandardBridge.sol";
* but "good enough for now". * but "good enough for now".
*/ */
contract OVM_SequencerFeeVault { contract OVM_SequencerFeeVault {
/************* /*************
* Constants * * Constants *
*************/ *************/
...@@ -21,7 +20,6 @@ contract OVM_SequencerFeeVault { ...@@ -21,7 +20,6 @@ contract OVM_SequencerFeeVault {
// Minimum ETH balance that can be withdrawn in a single withdrawal. // Minimum ETH balance that can be withdrawn in a single withdrawal.
uint256 public constant MIN_WITHDRAWAL_AMOUNT = 15 ether; uint256 public constant MIN_WITHDRAWAL_AMOUNT = 15 ether;
/************* /*************
* Variables * * Variables *
*************/ *************/
...@@ -29,7 +27,6 @@ contract OVM_SequencerFeeVault { ...@@ -29,7 +27,6 @@ contract OVM_SequencerFeeVault {
// Address on L1 that will hold the fees once withdrawn. Dynamically initialized within l2geth. // Address on L1 that will hold the fees once withdrawn. Dynamically initialized within l2geth.
address public l1FeeWallet; address public l1FeeWallet;
/*************** /***************
* Constructor * * Constructor *
***************/ ***************/
...@@ -39,27 +36,21 @@ contract OVM_SequencerFeeVault { ...@@ -39,27 +36,21 @@ contract OVM_SequencerFeeVault {
* Currently HAS NO EFFECT in production because l2geth will mutate this storage slot during * Currently HAS NO EFFECT in production because l2geth will mutate this storage slot during
* the genesis block. This is ONLY for testing purposes. * the genesis block. This is ONLY for testing purposes.
*/ */
constructor( constructor(address _l1FeeWallet) {
address _l1FeeWallet
) {
l1FeeWallet = _l1FeeWallet; l1FeeWallet = _l1FeeWallet;
} }
/************ /************
* Fallback * * Fallback *
************/ ************/
receive() external payable {} receive() external payable {}
/******************** /********************
* Public Functions * * Public Functions *
********************/ ********************/
function withdraw() function withdraw() public {
public
{
require( require(
address(this).balance >= MIN_WITHDRAWAL_AMOUNT, address(this).balance >= MIN_WITHDRAWAL_AMOUNT,
"OVM_SequencerFeeVault: withdrawal amount must be greater than minimum withdrawal amount" "OVM_SequencerFeeVault: withdrawal amount must be greater than minimum withdrawal amount"
......
...@@ -5,7 +5,6 @@ pragma solidity ^0.8.9; ...@@ -5,7 +5,6 @@ pragma solidity ^0.8.9;
* @title iOVM_L1BlockNumber * @title iOVM_L1BlockNumber
*/ */
interface iOVM_L1BlockNumber { interface iOVM_L1BlockNumber {
/******************** /********************
* Public Functions * * Public Functions *
********************/ ********************/
......
...@@ -5,17 +5,11 @@ pragma solidity ^0.8.9; ...@@ -5,17 +5,11 @@ pragma solidity ^0.8.9;
* @title iOVM_L2ToL1MessagePasser * @title iOVM_L2ToL1MessagePasser
*/ */
interface iOVM_L2ToL1MessagePasser { interface iOVM_L2ToL1MessagePasser {
/********** /**********
* Events * * Events *
**********/ **********/
event L2ToL1Message( event L2ToL1Message(uint256 _nonce, address _sender, bytes _data);
uint256 _nonce,
address _sender,
bytes _data
);
/******************** /********************
* Public Functions * * Public Functions *
......
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
import { iL1ChugSplashDeployer } from "./interfaces/iL1ChugSplashDeployer.sol"; import {iL1ChugSplashDeployer} from "./interfaces/iL1ChugSplashDeployer.sol";
/** /**
* @title L1ChugSplashProxy * @title L1ChugSplashProxy
...@@ -15,24 +15,22 @@ import { iL1ChugSplashDeployer } from "./interfaces/iL1ChugSplashDeployer.sol"; ...@@ -15,24 +15,22 @@ import { iL1ChugSplashDeployer } from "./interfaces/iL1ChugSplashDeployer.sol";
* modifier. And there almost certainly is not a good reason to not have that modifier. Beware! * modifier. And there almost certainly is not a good reason to not have that modifier. Beware!
*/ */
contract L1ChugSplashProxy { contract L1ChugSplashProxy {
/************* /*************
* Constants * * Constants *
*************/ *************/
// "Magic" prefix. When prepended to some arbitrary bytecode and used to create a contract, the // "Magic" prefix. When prepended to some arbitrary bytecode and used to create a contract, the
// appended bytecode will be deployed as given. // appended bytecode will be deployed as given.
bytes13 constant internal DEPLOY_CODE_PREFIX = 0x600D380380600D6000396000f3; bytes13 internal constant DEPLOY_CODE_PREFIX = 0x600D380380600D6000396000f3;
// bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1) // bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
bytes32 constant internal IMPLEMENTATION_KEY = bytes32 internal constant IMPLEMENTATION_KEY =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
// bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1) // bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)
bytes32 constant internal OWNER_KEY = bytes32 internal constant OWNER_KEY =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/*************** /***************
* Constructor * * Constructor *
***************/ ***************/
...@@ -40,13 +38,10 @@ contract L1ChugSplashProxy { ...@@ -40,13 +38,10 @@ contract L1ChugSplashProxy {
/** /**
* @param _owner Address of the initial contract owner. * @param _owner Address of the initial contract owner.
*/ */
constructor( constructor(address _owner) {
address _owner
) {
_setOwner(_owner); _setOwner(_owner);
} }
/********************** /**********************
* Function Modifiers * * Function Modifiers *
**********************/ **********************/
...@@ -62,9 +57,7 @@ contract L1ChugSplashProxy { ...@@ -62,9 +57,7 @@ contract L1ChugSplashProxy {
// L1ChugSplashDeployer contract and Solidity will throw errors if we do a normal call and // L1ChugSplashDeployer contract and Solidity will throw errors if we do a normal call and
// it turns out that it isn't the right type of contract. // it turns out that it isn't the right type of contract.
(bool success, bytes memory returndata) = owner.staticcall( (bool success, bytes memory returndata) = owner.staticcall(
abi.encodeWithSelector( abi.encodeWithSelector(iL1ChugSplashDeployer.isUpgrading.selector)
iL1ChugSplashDeployer.isUpgrading.selector
)
); );
// If the call was unsuccessful then we assume that there's no "isUpgrading" method and we // If the call was unsuccessful then we assume that there's no "isUpgrading" method and we
...@@ -75,10 +68,7 @@ contract L1ChugSplashProxy { ...@@ -75,10 +68,7 @@ contract L1ChugSplashProxy {
// case that the isUpgrading function returned something other than 0 or 1. But we only // case that the isUpgrading function returned something other than 0 or 1. But we only
// really care about the case where this value is 0 (= false). // really care about the case where this value is 0 (= false).
uint256 ret = abi.decode(returndata, (uint256)); uint256 ret = abi.decode(returndata, (uint256));
require( require(ret == 0, "L1ChugSplashProxy: system is currently being upgraded");
ret == 0,
"L1ChugSplashProxy: system is currently being upgraded"
);
} }
_; _;
...@@ -107,20 +97,15 @@ contract L1ChugSplashProxy { ...@@ -107,20 +97,15 @@ contract L1ChugSplashProxy {
} }
} }
/********************* /*********************
* Fallback Function * * Fallback Function *
*********************/ *********************/
fallback() fallback() external payable {
external
payable
{
// Proxy call by default. // Proxy call by default.
_doProxyCall(); _doProxyCall();
} }
/******************** /********************
* Public Functions * * Public Functions *
********************/ ********************/
...@@ -132,12 +117,7 @@ contract L1ChugSplashProxy { ...@@ -132,12 +117,7 @@ contract L1ChugSplashProxy {
* us a lot more freedom on the client side. Can only be triggered by the contract owner. * us a lot more freedom on the client side. Can only be triggered by the contract owner.
* @param _code New contract code to run inside this contract. * @param _code New contract code to run inside this contract.
*/ */
function setCode( function setCode(bytes memory _code) public proxyCallIfNotOwner {
bytes memory _code
)
proxyCallIfNotOwner
public
{
// Get the code hash of the current implementation. // Get the code hash of the current implementation.
address implementation = _getImplementation(); address implementation = _getImplementation();
...@@ -147,10 +127,7 @@ contract L1ChugSplashProxy { ...@@ -147,10 +127,7 @@ contract L1ChugSplashProxy {
} }
// Create the deploycode by appending the magic prefix. // Create the deploycode by appending the magic prefix.
bytes memory deploycode = abi.encodePacked( bytes memory deploycode = abi.encodePacked(DEPLOY_CODE_PREFIX, _code);
DEPLOY_CODE_PREFIX,
_code
);
// Deploy the code and set the new implementation address. // Deploy the code and set the new implementation address.
address newImplementation; address newImplementation;
...@@ -176,13 +153,7 @@ contract L1ChugSplashProxy { ...@@ -176,13 +153,7 @@ contract L1ChugSplashProxy {
* @param _key Storage key to modify. * @param _key Storage key to modify.
* @param _value New value for the storage key. * @param _value New value for the storage key.
*/ */
function setStorage( function setStorage(bytes32 _key, bytes32 _value) public proxyCallIfNotOwner {
bytes32 _key,
bytes32 _value
)
proxyCallIfNotOwner
public
{
assembly { assembly {
sstore(_key, _value) sstore(_key, _value)
} }
...@@ -192,12 +163,7 @@ contract L1ChugSplashProxy { ...@@ -192,12 +163,7 @@ contract L1ChugSplashProxy {
* Changes the owner of the proxy contract. Only callable by the owner. * Changes the owner of the proxy contract. Only callable by the owner.
* @param _owner New owner of the proxy contract. * @param _owner New owner of the proxy contract.
*/ */
function setOwner( function setOwner(address _owner) public proxyCallIfNotOwner {
address _owner
)
proxyCallIfNotOwner
public
{
_setOwner(_owner); _setOwner(_owner);
} }
...@@ -206,13 +172,7 @@ contract L1ChugSplashProxy { ...@@ -206,13 +172,7 @@ contract L1ChugSplashProxy {
* eth_call and setting the "from" address to address(0). * eth_call and setting the "from" address to address(0).
* @return Owner address. * @return Owner address.
*/ */
function getOwner() function getOwner() public proxyCallIfNotOwner returns (address) {
proxyCallIfNotOwner
public
returns (
address
)
{
return _getOwner(); return _getOwner();
} }
...@@ -221,17 +181,10 @@ contract L1ChugSplashProxy { ...@@ -221,17 +181,10 @@ contract L1ChugSplashProxy {
* eth_call and setting the "from" address to address(0). * eth_call and setting the "from" address to address(0).
* @return Implementation address. * @return Implementation address.
*/ */
function getImplementation() function getImplementation() public proxyCallIfNotOwner returns (address) {
proxyCallIfNotOwner
public
returns (
address
)
{
return _getImplementation(); return _getImplementation();
} }
/********************** /**********************
* Internal Functions * * Internal Functions *
**********************/ **********************/
...@@ -240,11 +193,7 @@ contract L1ChugSplashProxy { ...@@ -240,11 +193,7 @@ contract L1ChugSplashProxy {
* Sets the implementation address. * Sets the implementation address.
* @param _implementation New implementation address. * @param _implementation New implementation address.
*/ */
function _setImplementation( function _setImplementation(address _implementation) internal {
address _implementation
)
internal
{
assembly { assembly {
sstore(IMPLEMENTATION_KEY, _implementation) sstore(IMPLEMENTATION_KEY, _implementation)
} }
...@@ -254,13 +203,7 @@ contract L1ChugSplashProxy { ...@@ -254,13 +203,7 @@ contract L1ChugSplashProxy {
* Queries the implementation address. * Queries the implementation address.
* @return Implementation address. * @return Implementation address.
*/ */
function _getImplementation() function _getImplementation() internal view returns (address) {
internal
view
returns (
address
)
{
address implementation; address implementation;
assembly { assembly {
implementation := sload(IMPLEMENTATION_KEY) implementation := sload(IMPLEMENTATION_KEY)
...@@ -272,11 +215,7 @@ contract L1ChugSplashProxy { ...@@ -272,11 +215,7 @@ contract L1ChugSplashProxy {
* Changes the owner of the proxy contract. * Changes the owner of the proxy contract.
* @param _owner New owner of the proxy contract. * @param _owner New owner of the proxy contract.
*/ */
function _setOwner( function _setOwner(address _owner) internal {
address _owner
)
internal
{
assembly { assembly {
sstore(OWNER_KEY, _owner) sstore(OWNER_KEY, _owner)
} }
...@@ -286,13 +225,7 @@ contract L1ChugSplashProxy { ...@@ -286,13 +225,7 @@ contract L1ChugSplashProxy {
* Queries the owner of the proxy contract. * Queries the owner of the proxy contract.
* @return Owner address. * @return Owner address.
*/ */
function _getOwner() function _getOwner() internal view returns (address) {
internal
view
returns (
address
)
{
address owner; address owner;
assembly { assembly {
owner := sload(OWNER_KEY) owner := sload(OWNER_KEY)
...@@ -305,15 +238,7 @@ contract L1ChugSplashProxy { ...@@ -305,15 +238,7 @@ contract L1ChugSplashProxy {
* @param _account Address of the account to get a code hash for. * @param _account Address of the account to get a code hash for.
* @return Code hash for the account. * @return Code hash for the account.
*/ */
function _getAccountCodeHash( function _getAccountCodeHash(address _account) internal view returns (bytes32) {
address _account
)
internal
view
returns (
bytes32
)
{
bytes32 codeHash; bytes32 codeHash;
assembly { assembly {
codeHash := extcodehash(_account) codeHash := extcodehash(_account)
...@@ -324,16 +249,10 @@ contract L1ChugSplashProxy { ...@@ -324,16 +249,10 @@ contract L1ChugSplashProxy {
/** /**
* Performs the proxy call via a delegatecall. * Performs the proxy call via a delegatecall.
*/ */
function _doProxyCall() function _doProxyCall() internal onlyWhenNotPaused {
onlyWhenNotPaused
internal
{
address implementation = _getImplementation(); address implementation = _getImplementation();
require( require(implementation != address(0), "L1ChugSplashProxy: implementation is not set yet");
implementation != address(0),
"L1ChugSplashProxy: implementation is not set yet"
);
assembly { assembly {
// Copy calldata into memory at 0x0....calldatasize. // Copy calldata into memory at 0x0....calldatasize.
......
...@@ -5,10 +5,5 @@ pragma solidity ^0.8.9; ...@@ -5,10 +5,5 @@ pragma solidity ^0.8.9;
* @title iL1ChugSplashDeployer * @title iL1ChugSplashDeployer
*/ */
interface iL1ChugSplashDeployer { interface iL1ChugSplashDeployer {
function isUpgrading() function isUpgrading() external view returns (bool);
external
view
returns (
bool
);
} }
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
pragma solidity >0.5.0 <0.9.0; pragma solidity >0.5.0 <0.9.0;
/* Interface Imports */ /* Interface Imports */
import { ICrossDomainMessenger } from "./ICrossDomainMessenger.sol"; import {ICrossDomainMessenger} from "./ICrossDomainMessenger.sol";
/** /**
* @title CrossDomainEnabled * @title CrossDomainEnabled
...@@ -12,7 +12,6 @@ import { ICrossDomainMessenger } from "./ICrossDomainMessenger.sol"; ...@@ -12,7 +12,6 @@ import { ICrossDomainMessenger } from "./ICrossDomainMessenger.sol";
* Runtime target: defined by inheriting contract * Runtime target: defined by inheriting contract
*/ */
contract CrossDomainEnabled { contract CrossDomainEnabled {
/************* /*************
* Variables * * Variables *
*************/ *************/
...@@ -20,7 +19,6 @@ contract CrossDomainEnabled { ...@@ -20,7 +19,6 @@ contract CrossDomainEnabled {
// Messenger contract used to send and recieve messages from the other domain. // Messenger contract used to send and recieve messages from the other domain.
address public messenger; address public messenger;
/*************** /***************
* Constructor * * Constructor *
***************/ ***************/
...@@ -28,13 +26,10 @@ contract CrossDomainEnabled { ...@@ -28,13 +26,10 @@ contract CrossDomainEnabled {
/** /**
* @param _messenger Address of the CrossDomainMessenger on the current layer. * @param _messenger Address of the CrossDomainMessenger on the current layer.
*/ */
constructor( constructor(address _messenger) {
address _messenger
) {
messenger = _messenger; messenger = _messenger;
} }
/********************** /**********************
* Function Modifiers * * Function Modifiers *
**********************/ **********************/
...@@ -44,9 +39,7 @@ contract CrossDomainEnabled { ...@@ -44,9 +39,7 @@ contract CrossDomainEnabled {
* @param _sourceDomainAccount The only account on the originating domain which is * @param _sourceDomainAccount The only account on the originating domain which is
* authenticated to call this function. * authenticated to call this function.
*/ */
modifier onlyFromCrossDomainAccount( modifier onlyFromCrossDomainAccount(address _sourceDomainAccount) {
address _sourceDomainAccount
) {
require( require(
msg.sender == address(getCrossDomainMessenger()), msg.sender == address(getCrossDomainMessenger()),
"OVM_XCHAIN: messenger contract unauthenticated" "OVM_XCHAIN: messenger contract unauthenticated"
...@@ -60,7 +53,6 @@ contract CrossDomainEnabled { ...@@ -60,7 +53,6 @@ contract CrossDomainEnabled {
_; _;
} }
/********************** /**********************
* Internal Functions * * Internal Functions *
**********************/ **********************/
...@@ -70,13 +62,7 @@ contract CrossDomainEnabled { ...@@ -70,13 +62,7 @@ contract CrossDomainEnabled {
* needs to override. * needs to override.
* @return The address of the cross-domain messenger contract which should be used. * @return The address of the cross-domain messenger contract which should be used.
*/ */
function getCrossDomainMessenger() function getCrossDomainMessenger() internal virtual returns (ICrossDomainMessenger) {
internal
virtual
returns (
ICrossDomainMessenger
)
{
return ICrossDomainMessenger(messenger); return ICrossDomainMessenger(messenger);
} }
...@@ -91,9 +77,7 @@ contract CrossDomainEnabled { ...@@ -91,9 +77,7 @@ contract CrossDomainEnabled {
address _crossDomainTarget, address _crossDomainTarget,
uint32 _gasLimit, uint32 _gasLimit,
bytes memory _message bytes memory _message
) ) internal {
internal
{
getCrossDomainMessenger().sendMessage(_crossDomainTarget, _message, _gasLimit); getCrossDomainMessenger().sendMessage(_crossDomainTarget, _message, _gasLimit);
} }
} }
...@@ -5,7 +5,6 @@ pragma solidity >0.5.0 <0.9.0; ...@@ -5,7 +5,6 @@ pragma solidity >0.5.0 <0.9.0;
* @title ICrossDomainMessenger * @title ICrossDomainMessenger
*/ */
interface ICrossDomainMessenger { interface ICrossDomainMessenger {
/********** /**********
* Events * * Events *
**********/ **********/
...@@ -15,18 +14,17 @@ interface ICrossDomainMessenger { ...@@ -15,18 +14,17 @@ interface ICrossDomainMessenger {
address sender, address sender,
bytes message, bytes message,
uint256 messageNonce, uint256 messageNonce,
uint256 gasLimit); uint256 gasLimit
);
event RelayedMessage(bytes32 indexed msgHash); event RelayedMessage(bytes32 indexed msgHash);
event FailedRelayedMessage(bytes32 indexed msgHash); event FailedRelayedMessage(bytes32 indexed msgHash);
/************* /*************
* Variables * * Variables *
*************/ *************/
function xDomainMessageSender() external view returns (address); function xDomainMessageSender() external view returns (address);
/******************** /********************
* Public Functions * * Public Functions *
********************/ ********************/
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import {Lib_RLPReader} from "../rlp/Lib_RLPReader.sol";
/** /**
* @title Lib_CrossDomainUtils * @title Lib_CrossDomainUtils
...@@ -21,19 +21,14 @@ library Lib_CrossDomainUtils { ...@@ -21,19 +21,14 @@ library Lib_CrossDomainUtils {
address _sender, address _sender,
bytes memory _message, bytes memory _message,
uint256 _messageNonce uint256 _messageNonce
) ) internal pure returns (bytes memory) {
internal return
pure abi.encodeWithSignature(
returns ( "relayMessage(address,address,bytes,uint256)",
bytes memory _target,
) _sender,
{ _message,
return abi.encodeWithSignature( _messageNonce
"relayMessage(address,address,bytes,uint256)", );
_target,
_sender,
_message,
_messageNonce
);
} }
} }
...@@ -2,16 +2,15 @@ ...@@ -2,16 +2,15 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import {Lib_RLPReader} from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import {Lib_RLPWriter} from "../rlp/Lib_RLPWriter.sol";
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import {Lib_BytesUtils} from "../utils/Lib_BytesUtils.sol";
import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol"; import {Lib_Bytes32Utils} from "../utils/Lib_Bytes32Utils.sol";
/** /**
* @title Lib_OVMCodec * @title Lib_OVMCodec
*/ */
library Lib_OVMCodec { library Lib_OVMCodec {
/********* /*********
* Enums * * Enums *
*********/ *********/
...@@ -21,7 +20,6 @@ library Lib_OVMCodec { ...@@ -21,7 +20,6 @@ library Lib_OVMCodec {
L1TOL2_QUEUE L1TOL2_QUEUE
} }
/*********** /***********
* Structs * * Structs *
***********/ ***********/
...@@ -58,10 +56,10 @@ library Lib_OVMCodec { ...@@ -58,10 +56,10 @@ library Lib_OVMCodec {
struct TransactionChainElement { struct TransactionChainElement {
bool isSequenced; bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY bytes txData; // SEQUENCER TX ONLY
} }
struct QueueElement { struct QueueElement {
...@@ -70,7 +68,6 @@ library Lib_OVMCodec { ...@@ -70,7 +68,6 @@ library Lib_OVMCodec {
uint40 blockNumber; uint40 blockNumber;
} }
/********************** /**********************
* Internal Functions * * Internal Functions *
**********************/ **********************/
...@@ -80,24 +77,21 @@ library Lib_OVMCodec { ...@@ -80,24 +77,21 @@ library Lib_OVMCodec {
* @param _transaction OVM transaction to encode. * @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes. * @return Encoded transaction bytes.
*/ */
function encodeTransaction( function encodeTransaction(Transaction memory _transaction)
Transaction memory _transaction
)
internal internal
pure pure
returns ( returns (bytes memory)
bytes memory
)
{ {
return abi.encodePacked( return
_transaction.timestamp, abi.encodePacked(
_transaction.blockNumber, _transaction.timestamp,
_transaction.l1QueueOrigin, _transaction.blockNumber,
_transaction.l1TxOrigin, _transaction.l1QueueOrigin,
_transaction.entrypoint, _transaction.l1TxOrigin,
_transaction.gasLimit, _transaction.entrypoint,
_transaction.data _transaction.gasLimit,
); _transaction.data
);
} }
/** /**
...@@ -105,15 +99,7 @@ library Lib_OVMCodec { ...@@ -105,15 +99,7 @@ library Lib_OVMCodec {
* @param _transaction OVM transaction to encode. * @param _transaction OVM transaction to encode.
* @return Hashed transaction * @return Hashed transaction
*/ */
function hashTransaction( function hashTransaction(Transaction memory _transaction) internal pure returns (bytes32) {
Transaction memory _transaction
)
internal
pure
returns (
bytes32
)
{
return keccak256(encodeTransaction(_transaction)); return keccak256(encodeTransaction(_transaction));
} }
...@@ -122,23 +108,16 @@ library Lib_OVMCodec { ...@@ -122,23 +108,16 @@ library Lib_OVMCodec {
* @param _encoded RLP-encoded account state. * @param _encoded RLP-encoded account state.
* @return Account state struct. * @return Account state struct.
*/ */
function decodeEVMAccount( function decodeEVMAccount(bytes memory _encoded) internal pure returns (EVMAccount memory) {
bytes memory _encoded
)
internal
pure
returns (
EVMAccount memory
)
{
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded); Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return EVMAccount({ return
nonce: Lib_RLPReader.readUint256(accountState[0]), EVMAccount({
balance: Lib_RLPReader.readUint256(accountState[1]), nonce: Lib_RLPReader.readUint256(accountState[0]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]), balance: Lib_RLPReader.readUint256(accountState[1]),
codeHash: Lib_RLPReader.readBytes32(accountState[3]) storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
}); codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
} }
/** /**
...@@ -146,22 +125,19 @@ library Lib_OVMCodec { ...@@ -146,22 +125,19 @@ library Lib_OVMCodec {
* @param _batchHeader Header to hash. * @param _batchHeader Header to hash.
* @return Hash of the header. * @return Hash of the header.
*/ */
function hashBatchHeader( function hashBatchHeader(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
internal internal
pure pure
returns ( returns (bytes32)
bytes32
)
{ {
return keccak256( return
abi.encode( keccak256(
_batchHeader.batchRoot, abi.encode(
_batchHeader.batchSize, _batchHeader.batchRoot,
_batchHeader.prevTotalElements, _batchHeader.batchSize,
_batchHeader.extraData _batchHeader.prevTotalElements,
) _batchHeader.extraData
); )
);
} }
} }
...@@ -5,10 +5,8 @@ pragma solidity ^0.8.9; ...@@ -5,10 +5,8 @@ pragma solidity ^0.8.9;
* @title Lib_DefaultValues * @title Lib_DefaultValues
*/ */
library Lib_DefaultValues { library Lib_DefaultValues {
// The default x-domain message sender being set to a non-zero value makes // The default x-domain message sender being set to a non-zero value makes
// deployment a bit more expensive, but in exchange the refund on every call to // deployment a bit more expensive, but in exchange the refund on every call to
// `relayMessage` by the L1 and L2 messengers will be higher. // `relayMessage` by the L1 and L2 messengers will be higher.
address internal constant DEFAULT_XDOMAIN_SENDER = 0x000000000000000000000000000000000000dEaD; address internal constant DEFAULT_XDOMAIN_SENDER = 0x000000000000000000000000000000000000dEaD;
} }
...@@ -10,11 +10,13 @@ library Lib_PredeployAddresses { ...@@ -10,11 +10,13 @@ library Lib_PredeployAddresses {
address internal constant DEPLOYER_WHITELIST = 0x4200000000000000000000000000000000000002; address internal constant DEPLOYER_WHITELIST = 0x4200000000000000000000000000000000000002;
address payable internal constant OVM_ETH = payable(0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000); address payable internal constant OVM_ETH = payable(0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000);
// solhint-disable-next-line max-line-length // solhint-disable-next-line max-line-length
address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000007; address internal constant L2_CROSS_DOMAIN_MESSENGER =
0x4200000000000000000000000000000000000007;
address internal constant LIB_ADDRESS_MANAGER = 0x4200000000000000000000000000000000000008; address internal constant LIB_ADDRESS_MANAGER = 0x4200000000000000000000000000000000000008;
address internal constant PROXY_EOA = 0x4200000000000000000000000000000000000009; address internal constant PROXY_EOA = 0x4200000000000000000000000000000000000009;
address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010; address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010;
address internal constant SEQUENCER_FEE_WALLET = 0x4200000000000000000000000000000000000011; address internal constant SEQUENCER_FEE_WALLET = 0x4200000000000000000000000000000000000011;
address internal constant L2_STANDARD_TOKEN_FACTORY = 0x4200000000000000000000000000000000000012; address internal constant L2_STANDARD_TOKEN_FACTORY =
0x4200000000000000000000000000000000000012;
address internal constant L1_BLOCK_NUMBER = 0x4200000000000000000000000000000000000013; address internal constant L1_BLOCK_NUMBER = 0x4200000000000000000000000000000000000013;
} }
...@@ -2,30 +2,23 @@ ...@@ -2,30 +2,23 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* External Imports */ /* External Imports */
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
/** /**
* @title Lib_AddressManager * @title Lib_AddressManager
*/ */
contract Lib_AddressManager is Ownable { contract Lib_AddressManager is Ownable {
/********** /**********
* Events * * Events *
**********/ **********/
event AddressSet( event AddressSet(string indexed _name, address _newAddress, address _oldAddress);
string indexed _name,
address _newAddress,
address _oldAddress
);
/************* /*************
* Variables * * Variables *
*************/ *************/
mapping (bytes32 => address) private addresses; mapping(bytes32 => address) private addresses;
/******************** /********************
* Public Functions * * Public Functions *
...@@ -36,22 +29,12 @@ contract Lib_AddressManager is Ownable { ...@@ -36,22 +29,12 @@ contract Lib_AddressManager is Ownable {
* @param _name String name to associate an address with. * @param _name String name to associate an address with.
* @param _address Address to associate with the name. * @param _address Address to associate with the name.
*/ */
function setAddress( function setAddress(string memory _name, address _address) external onlyOwner {
string memory _name,
address _address
)
external
onlyOwner
{
bytes32 nameHash = _getNameHash(_name); bytes32 nameHash = _getNameHash(_name);
address oldAddress = addresses[nameHash]; address oldAddress = addresses[nameHash];
addresses[nameHash] = _address; addresses[nameHash] = _address;
emit AddressSet( emit AddressSet(_name, _address, oldAddress);
_name,
_address,
oldAddress
);
} }
/** /**
...@@ -59,19 +42,10 @@ contract Lib_AddressManager is Ownable { ...@@ -59,19 +42,10 @@ contract Lib_AddressManager is Ownable {
* @param _name Name to retrieve an address for. * @param _name Name to retrieve an address for.
* @return Address associated with the given name. * @return Address associated with the given name.
*/ */
function getAddress( function getAddress(string memory _name) external view returns (address) {
string memory _name
)
external
view
returns (
address
)
{
return addresses[_getNameHash(_name)]; return addresses[_getNameHash(_name)];
} }
/********************** /**********************
* Internal Functions * * Internal Functions *
**********************/ **********************/
...@@ -81,15 +55,7 @@ contract Lib_AddressManager is Ownable { ...@@ -81,15 +55,7 @@ contract Lib_AddressManager is Ownable {
* @param _name Name to compute a hash for. * @param _name Name to compute a hash for.
* @return Hash of the given name. * @return Hash of the given name.
*/ */
function _getNameHash( function _getNameHash(string memory _name) internal pure returns (bytes32) {
string memory _name
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_name)); return keccak256(abi.encodePacked(_name));
} }
} }
...@@ -2,20 +2,18 @@ ...@@ -2,20 +2,18 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_AddressManager } from "./Lib_AddressManager.sol"; import {Lib_AddressManager} from "./Lib_AddressManager.sol";
/** /**
* @title Lib_AddressResolver * @title Lib_AddressResolver
*/ */
abstract contract Lib_AddressResolver { abstract contract Lib_AddressResolver {
/************* /*************
* Variables * * Variables *
*************/ *************/
Lib_AddressManager public libAddressManager; Lib_AddressManager public libAddressManager;
/*************** /***************
* Constructor * * Constructor *
***************/ ***************/
...@@ -23,13 +21,10 @@ abstract contract Lib_AddressResolver { ...@@ -23,13 +21,10 @@ abstract contract Lib_AddressResolver {
/** /**
* @param _libAddressManager Address of the Lib_AddressManager. * @param _libAddressManager Address of the Lib_AddressManager.
*/ */
constructor( constructor(address _libAddressManager) {
address _libAddressManager
) {
libAddressManager = Lib_AddressManager(_libAddressManager); libAddressManager = Lib_AddressManager(_libAddressManager);
} }
/******************** /********************
* Public Functions * * Public Functions *
********************/ ********************/
...@@ -39,15 +34,7 @@ abstract contract Lib_AddressResolver { ...@@ -39,15 +34,7 @@ abstract contract Lib_AddressResolver {
* @param _name Name to resolve an address for. * @param _name Name to resolve an address for.
* @return Address associated with the given name. * @return Address associated with the given name.
*/ */
function resolve( function resolve(string memory _name) public view returns (address) {
string memory _name
)
public
view
returns (
address
)
{
return libAddressManager.getAddress(_name); return libAddressManager.getAddress(_name);
} }
} }
...@@ -2,13 +2,12 @@ ...@@ -2,13 +2,12 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_AddressManager } from "./Lib_AddressManager.sol"; import {Lib_AddressManager} from "./Lib_AddressManager.sol";
/** /**
* @title Lib_ResolvedDelegateProxy * @title Lib_ResolvedDelegateProxy
*/ */
contract Lib_ResolvedDelegateProxy { contract Lib_ResolvedDelegateProxy {
/************* /*************
* Variables * * Variables *
*************/ *************/
...@@ -21,9 +20,8 @@ contract Lib_ResolvedDelegateProxy { ...@@ -21,9 +20,8 @@ contract Lib_ResolvedDelegateProxy {
// There is a known flaw in this contract, and we will remove it from the repository // There is a known flaw in this contract, and we will remove it from the repository
// in the near future. Due to the very limited way that we are using it, this flaw is // in the near future. Due to the very limited way that we are using it, this flaw is
// not an issue in our system. // not an issue in our system.
mapping (address => string) private implementationName; mapping(address => string) private implementationName;
mapping (address => Lib_AddressManager) private addressManager; mapping(address => Lib_AddressManager) private addressManager;
/*************** /***************
* Constructor * * Constructor *
...@@ -33,31 +31,21 @@ contract Lib_ResolvedDelegateProxy { ...@@ -33,31 +31,21 @@ contract Lib_ResolvedDelegateProxy {
* @param _libAddressManager Address of the Lib_AddressManager. * @param _libAddressManager Address of the Lib_AddressManager.
* @param _implementationName implementationName of the contract to proxy to. * @param _implementationName implementationName of the contract to proxy to.
*/ */
constructor( constructor(address _libAddressManager, string memory _implementationName) {
address _libAddressManager,
string memory _implementationName
) {
addressManager[address(this)] = Lib_AddressManager(_libAddressManager); addressManager[address(this)] = Lib_AddressManager(_libAddressManager);
implementationName[address(this)] = _implementationName; implementationName[address(this)] = _implementationName;
} }
/********************* /*********************
* Fallback Function * * Fallback Function *
*********************/ *********************/
fallback() fallback() external payable {
external
payable
{
address target = addressManager[address(this)].getAddress( address target = addressManager[address(this)].getAddress(
(implementationName[address(this)]) (implementationName[address(this)])
); );
require( require(target != address(0), "Target address must be initialized.");
target != address(0),
"Target address must be initialized."
);
(bool success, bytes memory returndata) = target.delegatecall(msg.data); (bool success, bytes memory returndata) = target.delegatecall(msg.data);
......
...@@ -6,13 +6,11 @@ pragma solidity ^0.8.9; ...@@ -6,13 +6,11 @@ pragma solidity ^0.8.9;
* @dev Adapted from "RLPReader" by Hamdi Allam (hamdi.allam97@gmail.com). * @dev Adapted from "RLPReader" by Hamdi Allam (hamdi.allam97@gmail.com).
*/ */
library Lib_RLPReader { library Lib_RLPReader {
/************* /*************
* Constants * * Constants *
*************/ *************/
uint256 constant internal MAX_LIST_LENGTH = 32; uint256 internal constant MAX_LIST_LENGTH = 32;
/********* /*********
* Enums * * Enums *
...@@ -23,7 +21,6 @@ library Lib_RLPReader { ...@@ -23,7 +21,6 @@ library Lib_RLPReader {
LIST_ITEM LIST_ITEM
} }
/*********** /***********
* Structs * * Structs *
***********/ ***********/
...@@ -33,7 +30,6 @@ library Lib_RLPReader { ...@@ -33,7 +30,6 @@ library Lib_RLPReader {
uint256 ptr; uint256 ptr;
} }
/********************** /**********************
* Internal Functions * * Internal Functions *
**********************/ **********************/
...@@ -43,24 +39,13 @@ library Lib_RLPReader { ...@@ -43,24 +39,13 @@ library Lib_RLPReader {
* @param _in Input bytes to convert. * @param _in Input bytes to convert.
* @return Output memory reference. * @return Output memory reference.
*/ */
function toRLPItem( function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) {
bytes memory _in
)
internal
pure
returns (
RLPItem memory
)
{
uint256 ptr; uint256 ptr;
assembly { assembly {
ptr := add(_in, 32) ptr := add(_in, 32)
} }
return RLPItem({ return RLPItem({length: _in.length, ptr: ptr});
length: _in.length,
ptr: ptr
});
} }
/** /**
...@@ -68,25 +53,10 @@ library Lib_RLPReader { ...@@ -68,25 +53,10 @@ library Lib_RLPReader {
* @param _in RLP list value. * @param _in RLP list value.
* @return Decoded RLP list items. * @return Decoded RLP list items.
*/ */
function readList( function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory) {
RLPItem memory _in (uint256 listOffset, , RLPItemType itemType) = _decodeLength(_in);
)
internal
pure
returns (
RLPItem[] memory
)
{
(
uint256 listOffset,
,
RLPItemType itemType
) = _decodeLength(_in);
require( require(itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value.");
itemType == RLPItemType.LIST_ITEM,
"Invalid RLP list value."
);
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over // writing to the length. Since we can't know the number of RLP items without looping over
...@@ -97,23 +67,13 @@ library Lib_RLPReader { ...@@ -97,23 +67,13 @@ library Lib_RLPReader {
uint256 itemCount = 0; uint256 itemCount = 0;
uint256 offset = listOffset; uint256 offset = listOffset;
while (offset < _in.length) { while (offset < _in.length) {
require( require(itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length.");
itemCount < MAX_LIST_LENGTH,
"Provided RLP list exceeds max list length."
);
( (uint256 itemOffset, uint256 itemLength, ) = _decodeLength(
uint256 itemOffset, RLPItem({length: _in.length - offset, ptr: _in.ptr + offset})
uint256 itemLength, );
) = _decodeLength(RLPItem({
length: _in.length - offset,
ptr: _in.ptr + offset
}));
out[itemCount] = RLPItem({ out[itemCount] = RLPItem({length: itemLength + itemOffset, ptr: _in.ptr + offset});
length: itemLength + itemOffset,
ptr: _in.ptr + offset
});
itemCount += 1; itemCount += 1;
offset += itemOffset + itemLength; offset += itemOffset + itemLength;
...@@ -132,18 +92,8 @@ library Lib_RLPReader { ...@@ -132,18 +92,8 @@ library Lib_RLPReader {
* @param _in RLP list value. * @param _in RLP list value.
* @return Decoded RLP list items. * @return Decoded RLP list items.
*/ */
function readList( function readList(bytes memory _in) internal pure returns (RLPItem[] memory) {
bytes memory _in return readList(toRLPItem(_in));
)
internal
pure
returns (
RLPItem[] memory
)
{
return readList(
toRLPItem(_in)
);
} }
/** /**
...@@ -151,25 +101,10 @@ library Lib_RLPReader { ...@@ -151,25 +101,10 @@ library Lib_RLPReader {
* @param _in RLP bytes value. * @param _in RLP bytes value.
* @return Decoded bytes. * @return Decoded bytes.
*/ */
function readBytes( function readBytes(RLPItem memory _in) internal pure returns (bytes memory) {
RLPItem memory _in (uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
)
internal
pure
returns (
bytes memory
)
{
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require( require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value.");
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes value."
);
return _copy(_in.ptr, itemOffset, itemLength); return _copy(_in.ptr, itemOffset, itemLength);
} }
...@@ -179,18 +114,8 @@ library Lib_RLPReader { ...@@ -179,18 +114,8 @@ library Lib_RLPReader {
* @param _in RLP bytes value. * @param _in RLP bytes value.
* @return Decoded bytes. * @return Decoded bytes.
*/ */
function readBytes( function readBytes(bytes memory _in) internal pure returns (bytes memory) {
bytes memory _in return readBytes(toRLPItem(_in));
)
internal
pure
returns (
bytes memory
)
{
return readBytes(
toRLPItem(_in)
);
} }
/** /**
...@@ -198,15 +123,7 @@ library Lib_RLPReader { ...@@ -198,15 +123,7 @@ library Lib_RLPReader {
* @param _in RLP string value. * @param _in RLP string value.
* @return Decoded string. * @return Decoded string.
*/ */
function readString( function readString(RLPItem memory _in) internal pure returns (string memory) {
RLPItem memory _in
)
internal
pure
returns (
string memory
)
{
return string(readBytes(_in)); return string(readBytes(_in));
} }
...@@ -215,18 +132,8 @@ library Lib_RLPReader { ...@@ -215,18 +132,8 @@ library Lib_RLPReader {
* @param _in RLP string value. * @param _in RLP string value.
* @return Decoded string. * @return Decoded string.
*/ */
function readString( function readString(bytes memory _in) internal pure returns (string memory) {
bytes memory _in return readString(toRLPItem(_in));
)
internal
pure
returns (
string memory
)
{
return readString(
toRLPItem(_in)
);
} }
/** /**
...@@ -234,30 +141,12 @@ library Lib_RLPReader { ...@@ -234,30 +141,12 @@ library Lib_RLPReader {
* @param _in RLP bytes32 value. * @param _in RLP bytes32 value.
* @return Decoded bytes32. * @return Decoded bytes32.
*/ */
function readBytes32( function readBytes32(RLPItem memory _in) internal pure returns (bytes32) {
RLPItem memory _in require(_in.length <= 33, "Invalid RLP bytes32 value.");
)
internal (uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
pure
returns ( require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value.");
bytes32
)
{
require(
_in.length <= 33,
"Invalid RLP bytes32 value."
);
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes32 value."
);
uint256 ptr = _in.ptr + itemOffset; uint256 ptr = _in.ptr + itemOffset;
bytes32 out; bytes32 out;
...@@ -278,18 +167,8 @@ library Lib_RLPReader { ...@@ -278,18 +167,8 @@ library Lib_RLPReader {
* @param _in RLP bytes32 value. * @param _in RLP bytes32 value.
* @return Decoded bytes32. * @return Decoded bytes32.
*/ */
function readBytes32( function readBytes32(bytes memory _in) internal pure returns (bytes32) {
bytes memory _in return readBytes32(toRLPItem(_in));
)
internal
pure
returns (
bytes32
)
{
return readBytes32(
toRLPItem(_in)
);
} }
/** /**
...@@ -297,15 +176,7 @@ library Lib_RLPReader { ...@@ -297,15 +176,7 @@ library Lib_RLPReader {
* @param _in RLP uint256 value. * @param _in RLP uint256 value.
* @return Decoded uint256. * @return Decoded uint256.
*/ */
function readUint256( function readUint256(RLPItem memory _in) internal pure returns (uint256) {
RLPItem memory _in
)
internal
pure
returns (
uint256
)
{
return uint256(readBytes32(_in)); return uint256(readBytes32(_in));
} }
...@@ -314,18 +185,8 @@ library Lib_RLPReader { ...@@ -314,18 +185,8 @@ library Lib_RLPReader {
* @param _in RLP uint256 value. * @param _in RLP uint256 value.
* @return Decoded uint256. * @return Decoded uint256.
*/ */
function readUint256( function readUint256(bytes memory _in) internal pure returns (uint256) {
bytes memory _in return readUint256(toRLPItem(_in));
)
internal
pure
returns (
uint256
)
{
return readUint256(
toRLPItem(_in)
);
} }
/** /**
...@@ -333,19 +194,8 @@ library Lib_RLPReader { ...@@ -333,19 +194,8 @@ library Lib_RLPReader {
* @param _in RLP bool value. * @param _in RLP bool value.
* @return Decoded bool. * @return Decoded bool.
*/ */
function readBool( function readBool(RLPItem memory _in) internal pure returns (bool) {
RLPItem memory _in require(_in.length == 1, "Invalid RLP boolean value.");
)
internal
pure
returns (
bool
)
{
require(
_in.length == 1,
"Invalid RLP boolean value."
);
uint256 ptr = _in.ptr; uint256 ptr = _in.ptr;
uint256 out; uint256 out;
...@@ -353,10 +203,7 @@ library Lib_RLPReader { ...@@ -353,10 +203,7 @@ library Lib_RLPReader {
out := byte(0, mload(ptr)) out := byte(0, mload(ptr))
} }
require( require(out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1");
out == 0 || out == 1,
"Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1"
);
return out != 0; return out != 0;
} }
...@@ -366,18 +213,8 @@ library Lib_RLPReader { ...@@ -366,18 +213,8 @@ library Lib_RLPReader {
* @param _in RLP bool value. * @param _in RLP bool value.
* @return Decoded bool. * @return Decoded bool.
*/ */
function readBool( function readBool(bytes memory _in) internal pure returns (bool) {
bytes memory _in return readBool(toRLPItem(_in));
)
internal
pure
returns (
bool
)
{
return readBool(
toRLPItem(_in)
);
} }
/** /**
...@@ -385,23 +222,12 @@ library Lib_RLPReader { ...@@ -385,23 +222,12 @@ library Lib_RLPReader {
* @param _in RLP address value. * @param _in RLP address value.
* @return Decoded address. * @return Decoded address.
*/ */
function readAddress( function readAddress(RLPItem memory _in) internal pure returns (address) {
RLPItem memory _in
)
internal
pure
returns (
address
)
{
if (_in.length == 1) { if (_in.length == 1) {
return address(0); return address(0);
} }
require( require(_in.length == 21, "Invalid RLP address value.");
_in.length == 21,
"Invalid RLP address value."
);
return address(uint160(readUint256(_in))); return address(uint160(readUint256(_in)));
} }
...@@ -411,18 +237,8 @@ library Lib_RLPReader { ...@@ -411,18 +237,8 @@ library Lib_RLPReader {
* @param _in RLP address value. * @param _in RLP address value.
* @return Decoded address. * @return Decoded address.
*/ */
function readAddress( function readAddress(bytes memory _in) internal pure returns (address) {
bytes memory _in return readAddress(toRLPItem(_in));
)
internal
pure
returns (
address
)
{
return readAddress(
toRLPItem(_in)
);
} }
/** /**
...@@ -430,19 +246,10 @@ library Lib_RLPReader { ...@@ -430,19 +246,10 @@ library Lib_RLPReader {
* @param _in RLP item to read. * @param _in RLP item to read.
* @return Raw RLP bytes. * @return Raw RLP bytes.
*/ */
function readRawBytes( function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory) {
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
return _copy(_in); return _copy(_in);
} }
/********************* /*********************
* Private Functions * * Private Functions *
*********************/ *********************/
...@@ -454,9 +261,7 @@ library Lib_RLPReader { ...@@ -454,9 +261,7 @@ library Lib_RLPReader {
* @return Length of the encoded data. * @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM). * @return RLP item type (LIST_ITEM or DATA_ITEM).
*/ */
function _decodeLength( function _decodeLength(RLPItem memory _in)
RLPItem memory _in
)
private private
pure pure
returns ( returns (
...@@ -465,10 +270,7 @@ library Lib_RLPReader { ...@@ -465,10 +270,7 @@ library Lib_RLPReader {
RLPItemType RLPItemType
) )
{ {
require( require(_in.length > 0, "RLP item cannot be null.");
_in.length > 0,
"RLP item cannot be null."
);
uint256 ptr = _in.ptr; uint256 ptr = _in.ptr;
uint256 prefix; uint256 prefix;
...@@ -485,68 +287,44 @@ library Lib_RLPReader { ...@@ -485,68 +287,44 @@ library Lib_RLPReader {
uint256 strLen = prefix - 0x80; uint256 strLen = prefix - 0x80;
require( require(_in.length > strLen, "Invalid RLP short string.");
_in.length > strLen,
"Invalid RLP short string."
);
return (1, strLen, RLPItemType.DATA_ITEM); return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) { } else if (prefix <= 0xbf) {
// Long string. // Long string.
uint256 lenOfStrLen = prefix - 0xb7; uint256 lenOfStrLen = prefix - 0xb7;
require( require(_in.length > lenOfStrLen, "Invalid RLP long string length.");
_in.length > lenOfStrLen,
"Invalid RLP long string length."
);
uint256 strLen; uint256 strLen;
assembly { assembly {
// Pick out the string length. // Pick out the string length.
strLen := div( strLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)))
mload(add(ptr, 1)),
exp(256, sub(32, lenOfStrLen))
)
} }
require( require(_in.length > lenOfStrLen + strLen, "Invalid RLP long string.");
_in.length > lenOfStrLen + strLen,
"Invalid RLP long string."
);
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM); return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) { } else if (prefix <= 0xf7) {
// Short list. // Short list.
uint256 listLen = prefix - 0xc0; uint256 listLen = prefix - 0xc0;
require( require(_in.length > listLen, "Invalid RLP short list.");
_in.length > listLen,
"Invalid RLP short list."
);
return (1, listLen, RLPItemType.LIST_ITEM); return (1, listLen, RLPItemType.LIST_ITEM);
} else { } else {
// Long list. // Long list.
uint256 lenOfListLen = prefix - 0xf7; uint256 lenOfListLen = prefix - 0xf7;
require( require(_in.length > lenOfListLen, "Invalid RLP long list length.");
_in.length > lenOfListLen,
"Invalid RLP long list length."
);
uint256 listLen; uint256 listLen;
assembly { assembly {
// Pick out the list length. // Pick out the list length.
listLen := div( listLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)))
mload(add(ptr, 1)),
exp(256, sub(32, lenOfListLen))
)
} }
require( require(_in.length > lenOfListLen + listLen, "Invalid RLP long list.");
_in.length > lenOfListLen + listLen,
"Invalid RLP long list."
);
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM); return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
} }
...@@ -563,13 +341,7 @@ library Lib_RLPReader { ...@@ -563,13 +341,7 @@ library Lib_RLPReader {
uint256 _src, uint256 _src,
uint256 _offset, uint256 _offset,
uint256 _length uint256 _length
) ) private pure returns (bytes memory) {
private
pure
returns (
bytes memory
)
{
bytes memory out = new bytes(_length); bytes memory out = new bytes(_length);
if (out.length == 0) { if (out.length == 0) {
return out; return out;
...@@ -594,17 +366,11 @@ library Lib_RLPReader { ...@@ -594,17 +366,11 @@ library Lib_RLPReader {
// Pick out the remaining bytes. // Pick out the remaining bytes.
uint256 mask; uint256 mask;
unchecked { unchecked {
mask = 256 ** (32 - (_length % 32)) - 1; mask = 256**(32 - (_length % 32)) - 1;
} }
assembly { assembly {
mstore( mstore(dest, or(and(mload(src), not(mask)), and(mload(dest), mask)))
dest,
or(
and(mload(src), not(mask)),
and(mload(dest), mask)
)
)
} }
return out; return out;
} }
...@@ -614,15 +380,7 @@ library Lib_RLPReader { ...@@ -614,15 +380,7 @@ library Lib_RLPReader {
* @param _in RLP item to copy. * @param _in RLP item to copy.
* @return Copied bytes. * @return Copied bytes.
*/ */
function _copy( function _copy(RLPItem memory _in) private pure returns (bytes memory) {
RLPItem memory _in
)
private
pure
returns (
bytes memory
)
{
return _copy(_in.ptr, 0, _in.length); return _copy(_in.ptr, 0, _in.length);
} }
} }
...@@ -6,7 +6,6 @@ pragma solidity ^0.8.9; ...@@ -6,7 +6,6 @@ pragma solidity ^0.8.9;
* @author Bakaoh (with modifications) * @author Bakaoh (with modifications)
*/ */
library Lib_RLPWriter { library Lib_RLPWriter {
/********************** /**********************
* Internal Functions * * Internal Functions *
**********************/ **********************/
...@@ -16,15 +15,7 @@ library Lib_RLPWriter { ...@@ -16,15 +15,7 @@ library Lib_RLPWriter {
* @param _in The byte string to encode. * @param _in The byte string to encode.
* @return The RLP encoded string in bytes. * @return The RLP encoded string in bytes.
*/ */
function writeBytes( function writeBytes(bytes memory _in) internal pure returns (bytes memory) {
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded; bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) { if (_in.length == 1 && uint8(_in[0]) < 128) {
...@@ -41,15 +32,7 @@ library Lib_RLPWriter { ...@@ -41,15 +32,7 @@ library Lib_RLPWriter {
* @param _in The list of RLP encoded byte strings. * @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes. * @return The RLP encoded list of items in bytes.
*/ */
function writeList( function writeList(bytes[] memory _in) internal pure returns (bytes memory) {
bytes[] memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory list = _flatten(_in); bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list); return abi.encodePacked(_writeLength(list.length, 192), list);
} }
...@@ -59,15 +42,7 @@ library Lib_RLPWriter { ...@@ -59,15 +42,7 @@ library Lib_RLPWriter {
* @param _in The string to encode. * @param _in The string to encode.
* @return The RLP encoded string in bytes. * @return The RLP encoded string in bytes.
*/ */
function writeString( function writeString(string memory _in) internal pure returns (bytes memory) {
string memory _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(bytes(_in)); return writeBytes(bytes(_in));
} }
...@@ -76,15 +51,7 @@ library Lib_RLPWriter { ...@@ -76,15 +51,7 @@ library Lib_RLPWriter {
* @param _in The address to encode. * @param _in The address to encode.
* @return The RLP encoded address in bytes. * @return The RLP encoded address in bytes.
*/ */
function writeAddress( function writeAddress(address _in) internal pure returns (bytes memory) {
address _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(abi.encodePacked(_in)); return writeBytes(abi.encodePacked(_in));
} }
...@@ -93,15 +60,7 @@ library Lib_RLPWriter { ...@@ -93,15 +60,7 @@ library Lib_RLPWriter {
* @param _in The uint256 to encode. * @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes. * @return The RLP encoded uint256 in bytes.
*/ */
function writeUint( function writeUint(uint256 _in) internal pure returns (bytes memory) {
uint256 _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(_toBinary(_in)); return writeBytes(_toBinary(_in));
} }
...@@ -110,21 +69,12 @@ library Lib_RLPWriter { ...@@ -110,21 +69,12 @@ library Lib_RLPWriter {
* @param _in The bool to encode. * @param _in The bool to encode.
* @return The RLP encoded bool in bytes. * @return The RLP encoded bool in bytes.
*/ */
function writeBool( function writeBool(bool _in) internal pure returns (bytes memory) {
bool _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded = new bytes(1); bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded; return encoded;
} }
/********************* /*********************
* Private Functions * * Private Functions *
*********************/ *********************/
...@@ -135,16 +85,7 @@ library Lib_RLPWriter { ...@@ -135,16 +85,7 @@ library Lib_RLPWriter {
* @param _offset 128 if item is string, 192 if item is list. * @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes. * @return RLP encoded bytes.
*/ */
function _writeLength( function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory) {
uint256 _len,
uint256 _offset
)
private
pure
returns (
bytes memory
)
{
bytes memory encoded; bytes memory encoded;
if (_len < 56) { if (_len < 56) {
...@@ -160,8 +101,8 @@ library Lib_RLPWriter { ...@@ -160,8 +101,8 @@ library Lib_RLPWriter {
encoded = new bytes(lenLen + 1); encoded = new bytes(lenLen + 1);
encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55); encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);
for(i = 1; i <= lenLen; i++) { for (i = 1; i <= lenLen; i++) {
encoded[i] = bytes1(uint8((_len / (256**(lenLen-i))) % 256)); encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256));
} }
} }
...@@ -174,15 +115,7 @@ library Lib_RLPWriter { ...@@ -174,15 +115,7 @@ library Lib_RLPWriter {
* @param _x The integer to encode. * @param _x The integer to encode.
* @return RLP encoded bytes. * @return RLP encoded bytes.
*/ */
function _toBinary( function _toBinary(uint256 _x) private pure returns (bytes memory) {
uint256 _x
)
private
pure
returns (
bytes memory
)
{
bytes memory b = abi.encodePacked(_x); bytes memory b = abi.encodePacked(_x);
uint256 i = 0; uint256 i = 0;
...@@ -211,15 +144,12 @@ library Lib_RLPWriter { ...@@ -211,15 +144,12 @@ library Lib_RLPWriter {
uint256 _dest, uint256 _dest,
uint256 _src, uint256 _src,
uint256 _len uint256 _len
) ) private pure {
private
pure
{
uint256 dest = _dest; uint256 dest = _dest;
uint256 src = _src; uint256 src = _src;
uint256 len = _len; uint256 len = _len;
for(; len >= 32; len -= 32) { for (; len >= 32; len -= 32) {
assembly { assembly {
mstore(dest, mload(src)) mstore(dest, mload(src))
} }
...@@ -229,7 +159,7 @@ library Lib_RLPWriter { ...@@ -229,7 +159,7 @@ library Lib_RLPWriter {
uint256 mask; uint256 mask;
unchecked { unchecked {
mask = 256 ** (32 - len) - 1; mask = 256**(32 - len) - 1;
} }
assembly { assembly {
let srcpart := and(mload(src), not(mask)) let srcpart := and(mload(src), not(mask))
...@@ -244,15 +174,7 @@ library Lib_RLPWriter { ...@@ -244,15 +174,7 @@ library Lib_RLPWriter {
* @param _list List of byte strings to flatten. * @param _list List of byte strings to flatten.
* @return The flattened byte string. * @return The flattened byte string.
*/ */
function _flatten( function _flatten(bytes[] memory _list) private pure returns (bytes memory) {
bytes[] memory _list
)
private
pure
returns (
bytes memory
)
{
if (_list.length == 0) { if (_list.length == 0) {
return new bytes(0); return new bytes(0);
} }
...@@ -265,13 +187,17 @@ library Lib_RLPWriter { ...@@ -265,13 +187,17 @@ library Lib_RLPWriter {
bytes memory flattened = new bytes(len); bytes memory flattened = new bytes(len);
uint256 flattenedPtr; uint256 flattenedPtr;
assembly { flattenedPtr := add(flattened, 0x20) } assembly {
flattenedPtr := add(flattened, 0x20)
}
for(i = 0; i < _list.length; i++) { for (i = 0; i < _list.length; i++) {
bytes memory item = _list[i]; bytes memory item = _list[i];
uint256 listPtr; uint256 listPtr;
assembly { listPtr := add(item, 0x20)} assembly {
listPtr := add(item, 0x20)
}
_memcpy(flattenedPtr, listPtr, item.length); _memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length; flattenedPtr += _list[i].length;
......
...@@ -2,15 +2,14 @@ ...@@ -2,15 +2,14 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import {Lib_BytesUtils} from "../utils/Lib_BytesUtils.sol";
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import {Lib_RLPReader} from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import {Lib_RLPWriter} from "../rlp/Lib_RLPWriter.sol";
/** /**
* @title Lib_MerkleTrie * @title Lib_MerkleTrie
*/ */
library Lib_MerkleTrie { library Lib_MerkleTrie {
/******************* /*******************
* Data Structures * * Data Structures *
*******************/ *******************/
...@@ -26,7 +25,6 @@ library Lib_MerkleTrie { ...@@ -26,7 +25,6 @@ library Lib_MerkleTrie {
Lib_RLPReader.RLPItem[] decoded; Lib_RLPReader.RLPItem[] decoded;
} }
/********************** /**********************
* Contract Constants * * Contract Constants *
**********************/ **********************/
...@@ -50,9 +48,8 @@ library Lib_MerkleTrie { ...@@ -50,9 +48,8 @@ library Lib_MerkleTrie {
// Just a utility constant. RLP represents `NULL` as 0x80. // Just a utility constant. RLP represents `NULL` as 0x80.
bytes1 constant RLP_NULL = bytes1(0x80); bytes1 constant RLP_NULL = bytes1(0x80);
bytes constant RLP_NULL_BYTES = hex'80'; bytes constant RLP_NULL_BYTES = hex"80";
bytes32 constant internal KECCAK256_RLP_NULL_BYTES = keccak256(RLP_NULL_BYTES); bytes32 internal constant KECCAK256_RLP_NULL_BYTES = keccak256(RLP_NULL_BYTES);
/********************** /**********************
* Internal Functions * * Internal Functions *
...@@ -75,21 +72,10 @@ library Lib_MerkleTrie { ...@@ -75,21 +72,10 @@ library Lib_MerkleTrie {
bytes memory _value, bytes memory _value,
bytes memory _proof, bytes memory _proof,
bytes32 _root bytes32 _root
) ) internal pure returns (bool _verified) {
internal (bool exists, bytes memory value) = get(_key, _proof, _root);
pure
returns (
bool _verified
)
{
(
bool exists,
bytes memory value
) = get(_key, _proof, _root);
return ( return (exists && Lib_BytesUtils.equal(_value, value));
exists && Lib_BytesUtils.equal(_value, value)
);
} }
/** /**
...@@ -108,13 +94,7 @@ library Lib_MerkleTrie { ...@@ -108,13 +94,7 @@ library Lib_MerkleTrie {
bytes memory _value, bytes memory _value,
bytes memory _proof, bytes memory _proof,
bytes32 _root bytes32 _root
) ) internal pure returns (bytes32 _updatedRoot) {
internal
pure
returns (
bytes32 _updatedRoot
)
{
// Special case when inserting the very first node. // Special case when inserting the very first node.
if (_root == KECCAK256_RLP_NULL_BYTES) { if (_root == KECCAK256_RLP_NULL_BYTES) {
return getSingleNodeRootHash(_key, _value); return getSingleNodeRootHash(_key, _value);
...@@ -139,31 +119,21 @@ library Lib_MerkleTrie { ...@@ -139,31 +119,21 @@ library Lib_MerkleTrie {
bytes memory _key, bytes memory _key,
bytes memory _proof, bytes memory _proof,
bytes32 _root bytes32 _root
) ) internal pure returns (bool _exists, bytes memory _value) {
internal
pure
returns (
bool _exists,
bytes memory _value
)
{
TrieNode[] memory proof = _parseProof(_proof); TrieNode[] memory proof = _parseProof(_proof);
(uint256 pathLength, bytes memory keyRemainder, bool isFinalNode) = (uint256 pathLength, bytes memory keyRemainder, bool isFinalNode) = _walkNodePath(
_walkNodePath(proof, _key, _root); proof,
_key,
_root
);
bool exists = keyRemainder.length == 0; bool exists = keyRemainder.length == 0;
require( require(exists || isFinalNode, "Provided proof is invalid.");
exists || isFinalNode,
"Provided proof is invalid."
);
bytes memory value = exists ? _getNodeValue(proof[pathLength - 1]) : bytes(""); bytes memory value = exists ? _getNodeValue(proof[pathLength - 1]) : bytes("");
return ( return (exists, value);
exists,
value
);
} }
/** /**
...@@ -172,23 +142,14 @@ library Lib_MerkleTrie { ...@@ -172,23 +142,14 @@ library Lib_MerkleTrie {
* @param _value Value for the single node. * @param _value Value for the single node.
* @return _updatedRoot Hash of the trie. * @return _updatedRoot Hash of the trie.
*/ */
function getSingleNodeRootHash( function getSingleNodeRootHash(bytes memory _key, bytes memory _value)
bytes memory _key,
bytes memory _value
)
internal internal
pure pure
returns ( returns (bytes32 _updatedRoot)
bytes32 _updatedRoot
)
{ {
return keccak256(_makeLeafNode( return keccak256(_makeLeafNode(Lib_BytesUtils.toNibbles(_key), _value).encoded);
Lib_BytesUtils.toNibbles(_key),
_value
).encoded);
} }
/********************* /*********************
* Private Functions * * Private Functions *
*********************/ *********************/
...@@ -234,10 +195,7 @@ library Lib_MerkleTrie { ...@@ -234,10 +195,7 @@ library Lib_MerkleTrie {
if (currentKeyIndex == 0) { if (currentKeyIndex == 0) {
// First proof element is always the root node. // First proof element is always the root node.
require( require(keccak256(currentNode.encoded) == currentNodeID, "Invalid root hash");
keccak256(currentNode.encoded) == currentNodeID,
"Invalid root hash"
);
} else if (currentNode.encoded.length >= 32) { } else if (currentNode.encoded.length >= 32) {
// Nodes 32 bytes or larger are hashed inside branch nodes. // Nodes 32 bytes or larger are hashed inside branch nodes.
require( require(
...@@ -269,7 +227,7 @@ library Lib_MerkleTrie { ...@@ -269,7 +227,7 @@ library Lib_MerkleTrie {
} else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) { } else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {
bytes memory path = _getNodePath(currentNode); bytes memory path = _getNodePath(currentNode);
uint8 prefix = uint8(path[0]); uint8 prefix = uint8(path[0]);
uint8 offset = 2 - prefix % 2; uint8 offset = 2 - (prefix % 2);
bytes memory pathRemainder = Lib_BytesUtils.slice(path, offset); bytes memory pathRemainder = Lib_BytesUtils.slice(path, offset);
bytes memory keyRemainder = Lib_BytesUtils.slice(key, currentKeyIndex); bytes memory keyRemainder = Lib_BytesUtils.slice(key, currentKeyIndex);
uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder); uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder);
...@@ -331,13 +289,7 @@ library Lib_MerkleTrie { ...@@ -331,13 +289,7 @@ library Lib_MerkleTrie {
bytes memory _key, bytes memory _key,
bytes memory _keyRemainder, bytes memory _keyRemainder,
bytes memory _value bytes memory _value
) ) private pure returns (TrieNode[] memory _newPath) {
private
pure
returns (
TrieNode[] memory _newPath
)
{
bytes memory keyRemainder = _keyRemainder; bytes memory keyRemainder = _keyRemainder;
// Most of our logic depends on the status of the last node in the path. // Most of our logic depends on the status of the last node in the path.
...@@ -369,8 +321,9 @@ library Lib_MerkleTrie { ...@@ -369,8 +321,9 @@ library Lib_MerkleTrie {
_getSharedNibbleLength( _getSharedNibbleLength(
_getNodeKey(lastNode), _getNodeKey(lastNode),
Lib_BytesUtils.slice(Lib_BytesUtils.toNibbles(_key), l) Lib_BytesUtils.slice(Lib_BytesUtils.toNibbles(_key), l)
) == _getNodeKey(lastNode).length ) ==
&& keyRemainder.length == 0 _getNodeKey(lastNode).length &&
keyRemainder.length == 0
) { ) {
matchLeaf = true; matchLeaf = true;
} }
...@@ -394,8 +347,10 @@ library Lib_MerkleTrie { ...@@ -394,8 +347,10 @@ library Lib_MerkleTrie {
totalNewNodes += 1; totalNewNodes += 1;
// Create a new leaf node, slicing our remainder since the first byte points // Create a new leaf node, slicing our remainder since the first byte points
// to our branch node. // to our branch node.
newNodes[totalNewNodes] = newNodes[totalNewNodes] = _makeLeafNode(
_makeLeafNode(Lib_BytesUtils.slice(keyRemainder, 1), _value); Lib_BytesUtils.slice(keyRemainder, 1),
_value
);
totalNewNodes += 1; totalNewNodes += 1;
} }
} else { } else {
...@@ -433,23 +388,27 @@ library Lib_MerkleTrie { ...@@ -433,23 +388,27 @@ library Lib_MerkleTrie {
if (lastNodeType == NodeType.LeafNode) { if (lastNodeType == NodeType.LeafNode) {
// We're dealing with a leaf node. // We're dealing with a leaf node.
// We'll modify the key and insert the old leaf node into the branch index. // We'll modify the key and insert the old leaf node into the branch index.
TrieNode memory modifiedLastNode = TrieNode memory modifiedLastNode = _makeLeafNode(
_makeLeafNode(lastNodeKey, _getNodeValue(lastNode)); lastNodeKey,
newBranch = _getNodeValue(lastNode)
_editBranchIndex( );
newBranch, newBranch = _editBranchIndex(
branchKey, newBranch,
_getNodeHash(modifiedLastNode.encoded)); branchKey,
_getNodeHash(modifiedLastNode.encoded)
);
} else if (lastNodeKey.length != 0) { } else if (lastNodeKey.length != 0) {
// We're dealing with a shrinking extension node. // We're dealing with a shrinking extension node.
// We need to modify the node to decrease the size of the key. // We need to modify the node to decrease the size of the key.
TrieNode memory modifiedLastNode = TrieNode memory modifiedLastNode = _makeExtensionNode(
_makeExtensionNode(lastNodeKey, _getNodeValue(lastNode)); lastNodeKey,
newBranch = _getNodeValue(lastNode)
_editBranchIndex( );
newBranch, newBranch = _editBranchIndex(
branchKey, newBranch,
_getNodeHash(modifiedLastNode.encoded)); branchKey,
_getNodeHash(modifiedLastNode.encoded)
);
} else { } else {
// We're dealing with an unnecessary extension node. // We're dealing with an unnecessary extension node.
// We're going to delete the node entirely. // We're going to delete the node entirely.
...@@ -490,15 +449,10 @@ library Lib_MerkleTrie { ...@@ -490,15 +449,10 @@ library Lib_MerkleTrie {
* @param _key Key for the k/v pair. * @param _key Key for the k/v pair.
* @return _updatedRoot Root hash for the updated trie. * @return _updatedRoot Root hash for the updated trie.
*/ */
function _getUpdatedTrieRoot( function _getUpdatedTrieRoot(TrieNode[] memory _nodes, bytes memory _key)
TrieNode[] memory _nodes,
bytes memory _key
)
private private
pure pure
returns ( returns (bytes32 _updatedRoot)
bytes32 _updatedRoot
)
{ {
bytes memory key = Lib_BytesUtils.toNibbles(_key); bytes memory key = Lib_BytesUtils.toNibbles(_key);
...@@ -554,24 +508,13 @@ library Lib_MerkleTrie { ...@@ -554,24 +508,13 @@ library Lib_MerkleTrie {
* @param _proof RLP-encoded proof to parse. * @param _proof RLP-encoded proof to parse.
* @return _parsed Proof parsed into easily accessible structs. * @return _parsed Proof parsed into easily accessible structs.
*/ */
function _parseProof( function _parseProof(bytes memory _proof) private pure returns (TrieNode[] memory _parsed) {
bytes memory _proof
)
private
pure
returns (
TrieNode[] memory _parsed
)
{
Lib_RLPReader.RLPItem[] memory nodes = Lib_RLPReader.readList(_proof); Lib_RLPReader.RLPItem[] memory nodes = Lib_RLPReader.readList(_proof);
TrieNode[] memory proof = new TrieNode[](nodes.length); TrieNode[] memory proof = new TrieNode[](nodes.length);
for (uint256 i = 0; i < nodes.length; i++) { for (uint256 i = 0; i < nodes.length; i++) {
bytes memory encoded = Lib_RLPReader.readBytes(nodes[i]); bytes memory encoded = Lib_RLPReader.readBytes(nodes[i]);
proof[i] = TrieNode({ proof[i] = TrieNode({encoded: encoded, decoded: Lib_RLPReader.readList(encoded)});
encoded: encoded,
decoded: Lib_RLPReader.readList(encoded)
});
} }
return proof; return proof;
...@@ -584,15 +527,7 @@ library Lib_MerkleTrie { ...@@ -584,15 +527,7 @@ library Lib_MerkleTrie {
* @param _node Node to pull an ID for. * @param _node Node to pull an ID for.
* @return _nodeID ID for the node, depending on the size of its contents. * @return _nodeID ID for the node, depending on the size of its contents.
*/ */
function _getNodeID( function _getNodeID(Lib_RLPReader.RLPItem memory _node) private pure returns (bytes32 _nodeID) {
Lib_RLPReader.RLPItem memory _node
)
private
pure
returns (
bytes32 _nodeID
)
{
bytes memory nodeID; bytes memory nodeID;
if (_node.length < 32) { if (_node.length < 32) {
...@@ -611,15 +546,7 @@ library Lib_MerkleTrie { ...@@ -611,15 +546,7 @@ library Lib_MerkleTrie {
* @param _node Node to get a path for. * @param _node Node to get a path for.
* @return _path Node path, converted to an array of nibbles. * @return _path Node path, converted to an array of nibbles.
*/ */
function _getNodePath( function _getNodePath(TrieNode memory _node) private pure returns (bytes memory _path) {
TrieNode memory _node
)
private
pure
returns (
bytes memory _path
)
{
return Lib_BytesUtils.toNibbles(Lib_RLPReader.readBytes(_node.decoded[0])); return Lib_BytesUtils.toNibbles(Lib_RLPReader.readBytes(_node.decoded[0]));
} }
...@@ -629,15 +556,7 @@ library Lib_MerkleTrie { ...@@ -629,15 +556,7 @@ library Lib_MerkleTrie {
* @param _node Node to get a key for. * @param _node Node to get a key for.
* @return _key Node key, converted to an array of nibbles. * @return _key Node key, converted to an array of nibbles.
*/ */
function _getNodeKey( function _getNodeKey(TrieNode memory _node) private pure returns (bytes memory _key) {
TrieNode memory _node
)
private
pure
returns (
bytes memory _key
)
{
return _removeHexPrefix(_getNodePath(_node)); return _removeHexPrefix(_getNodePath(_node));
} }
...@@ -646,15 +565,7 @@ library Lib_MerkleTrie { ...@@ -646,15 +565,7 @@ library Lib_MerkleTrie {
* @param _node Node to get a value for. * @param _node Node to get a value for.
* @return _value Node value, as hex bytes. * @return _value Node value, as hex bytes.
*/ */
function _getNodeValue( function _getNodeValue(TrieNode memory _node) private pure returns (bytes memory _value) {
TrieNode memory _node
)
private
pure
returns (
bytes memory _value
)
{
return Lib_RLPReader.readBytes(_node.decoded[_node.decoded.length - 1]); return Lib_RLPReader.readBytes(_node.decoded[_node.decoded.length - 1]);
} }
...@@ -664,15 +575,7 @@ library Lib_MerkleTrie { ...@@ -664,15 +575,7 @@ library Lib_MerkleTrie {
* @param _encoded Encoded node to hash. * @param _encoded Encoded node to hash.
* @return _hash Hash of the encoded node. Simply the input if < 32 bytes. * @return _hash Hash of the encoded node. Simply the input if < 32 bytes.
*/ */
function _getNodeHash( function _getNodeHash(bytes memory _encoded) private pure returns (bytes memory _hash) {
bytes memory _encoded
)
private
pure
returns (
bytes memory _hash
)
{
if (_encoded.length < 32) { if (_encoded.length < 32) {
return _encoded; return _encoded;
} else { } else {
...@@ -685,15 +588,7 @@ library Lib_MerkleTrie { ...@@ -685,15 +588,7 @@ library Lib_MerkleTrie {
* @param _node Node to determine a type for. * @param _node Node to determine a type for.
* @return _type Type of the node; BranchNode/ExtensionNode/LeafNode. * @return _type Type of the node; BranchNode/ExtensionNode/LeafNode.
*/ */
function _getNodeType( function _getNodeType(TrieNode memory _node) private pure returns (NodeType _type) {
TrieNode memory _node
)
private
pure
returns (
NodeType _type
)
{
if (_node.decoded.length == BRANCH_NODE_LENGTH) { if (_node.decoded.length == BRANCH_NODE_LENGTH) {
return NodeType.BranchNode; return NodeType.BranchNode;
} else if (_node.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) { } else if (_node.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {
...@@ -717,15 +612,10 @@ library Lib_MerkleTrie { ...@@ -717,15 +612,10 @@ library Lib_MerkleTrie {
* @param _b Second nibble array. * @param _b Second nibble array.
* @return _shared Number of shared nibbles. * @return _shared Number of shared nibbles.
*/ */
function _getSharedNibbleLength( function _getSharedNibbleLength(bytes memory _a, bytes memory _b)
bytes memory _a,
bytes memory _b
)
private private
pure pure
returns ( returns (uint256 _shared)
uint256 _shared
)
{ {
uint256 i = 0; uint256 i = 0;
while (_a.length > i && _b.length > i && _a[i] == _b[i]) { while (_a.length > i && _b.length > i && _a[i] == _b[i]) {
...@@ -739,21 +629,10 @@ library Lib_MerkleTrie { ...@@ -739,21 +629,10 @@ library Lib_MerkleTrie {
* @param _raw RLP-encoded node to convert. * @param _raw RLP-encoded node to convert.
* @return _node Node as a TrieNode struct. * @return _node Node as a TrieNode struct.
*/ */
function _makeNode( function _makeNode(bytes[] memory _raw) private pure returns (TrieNode memory _node) {
bytes[] memory _raw
)
private
pure
returns (
TrieNode memory _node
)
{
bytes memory encoded = Lib_RLPWriter.writeList(_raw); bytes memory encoded = Lib_RLPWriter.writeList(_raw);
return TrieNode({ return TrieNode({encoded: encoded, decoded: Lib_RLPReader.readList(encoded)});
encoded: encoded,
decoded: Lib_RLPReader.readList(encoded)
});
} }
/** /**
...@@ -761,14 +640,10 @@ library Lib_MerkleTrie { ...@@ -761,14 +640,10 @@ library Lib_MerkleTrie {
* @param _items RLP-decoded node to convert. * @param _items RLP-decoded node to convert.
* @return _node Node as a TrieNode struct. * @return _node Node as a TrieNode struct.
*/ */
function _makeNode( function _makeNode(Lib_RLPReader.RLPItem[] memory _items)
Lib_RLPReader.RLPItem[] memory _items
)
private private
pure pure
returns ( returns (TrieNode memory _node)
TrieNode memory _node
)
{ {
bytes[] memory raw = new bytes[](_items.length); bytes[] memory raw = new bytes[](_items.length);
for (uint256 i = 0; i < _items.length; i++) { for (uint256 i = 0; i < _items.length; i++) {
...@@ -783,15 +658,10 @@ library Lib_MerkleTrie { ...@@ -783,15 +658,10 @@ library Lib_MerkleTrie {
* @param _value Value for the extension node. * @param _value Value for the extension node.
* @return _node New extension node with the given k/v pair. * @return _node New extension node with the given k/v pair.
*/ */
function _makeExtensionNode( function _makeExtensionNode(bytes memory _key, bytes memory _value)
bytes memory _key,
bytes memory _value
)
private private
pure pure
returns ( returns (TrieNode memory _node)
TrieNode memory _node
)
{ {
bytes[] memory raw = new bytes[](2); bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_key, false); bytes memory key = _addHexPrefix(_key, false);
...@@ -806,15 +676,10 @@ library Lib_MerkleTrie { ...@@ -806,15 +676,10 @@ library Lib_MerkleTrie {
* @param _value New value for the extension node. * @param _value New value for the extension node.
* @return New node with the same key and different value. * @return New node with the same key and different value.
*/ */
function _editExtensionNodeValue( function _editExtensionNodeValue(TrieNode memory _node, bytes memory _value)
TrieNode memory _node,
bytes memory _value
)
private private
pure pure
returns ( returns (TrieNode memory)
TrieNode memory
)
{ {
bytes[] memory raw = new bytes[](2); bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_getNodeKey(_node), false); bytes memory key = _addHexPrefix(_getNodeKey(_node), false);
...@@ -836,15 +701,10 @@ library Lib_MerkleTrie { ...@@ -836,15 +701,10 @@ library Lib_MerkleTrie {
* @param _value Value for the leaf node. * @param _value Value for the leaf node.
* @return _node New leaf node with the given k/v pair. * @return _node New leaf node with the given k/v pair.
*/ */
function _makeLeafNode( function _makeLeafNode(bytes memory _key, bytes memory _value)
bytes memory _key,
bytes memory _value
)
private private
pure pure
returns ( returns (TrieNode memory _node)
TrieNode memory _node
)
{ {
bytes[] memory raw = new bytes[](2); bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_key, true); bytes memory key = _addHexPrefix(_key, true);
...@@ -857,13 +717,7 @@ library Lib_MerkleTrie { ...@@ -857,13 +717,7 @@ library Lib_MerkleTrie {
* @notice Creates an empty branch node. * @notice Creates an empty branch node.
* @return _node Empty branch node as a TrieNode struct. * @return _node Empty branch node as a TrieNode struct.
*/ */
function _makeEmptyBranchNode() function _makeEmptyBranchNode() private pure returns (TrieNode memory _node) {
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](BRANCH_NODE_LENGTH); bytes[] memory raw = new bytes[](BRANCH_NODE_LENGTH);
for (uint256 i = 0; i < raw.length; i++) { for (uint256 i = 0; i < raw.length; i++) {
raw[i] = RLP_NULL_BYTES; raw[i] = RLP_NULL_BYTES;
...@@ -877,15 +731,10 @@ library Lib_MerkleTrie { ...@@ -877,15 +731,10 @@ library Lib_MerkleTrie {
* @param _value Value to insert into the branch. * @param _value Value to insert into the branch.
* @return _updatedNode Modified branch node. * @return _updatedNode Modified branch node.
*/ */
function _editBranchValue( function _editBranchValue(TrieNode memory _branch, bytes memory _value)
TrieNode memory _branch,
bytes memory _value
)
private private
pure pure
returns ( returns (TrieNode memory _updatedNode)
TrieNode memory _updatedNode
)
{ {
bytes memory encoded = Lib_RLPWriter.writeBytes(_value); bytes memory encoded = Lib_RLPWriter.writeBytes(_value);
_branch.decoded[_branch.decoded.length - 1] = Lib_RLPReader.toRLPItem(encoded); _branch.decoded[_branch.decoded.length - 1] = Lib_RLPReader.toRLPItem(encoded);
...@@ -903,13 +752,7 @@ library Lib_MerkleTrie { ...@@ -903,13 +752,7 @@ library Lib_MerkleTrie {
TrieNode memory _branch, TrieNode memory _branch,
uint8 _index, uint8 _index,
bytes memory _value bytes memory _value
) ) private pure returns (TrieNode memory _updatedNode) {
private
pure
returns (
TrieNode memory _updatedNode
)
{
bytes memory encoded = _value.length < 32 ? _value : Lib_RLPWriter.writeBytes(_value); bytes memory encoded = _value.length < 32 ? _value : Lib_RLPWriter.writeBytes(_value);
_branch.decoded[_index] = Lib_RLPReader.toRLPItem(encoded); _branch.decoded[_index] = Lib_RLPReader.toRLPItem(encoded);
return _makeNode(_branch.decoded); return _makeNode(_branch.decoded);
...@@ -921,15 +764,10 @@ library Lib_MerkleTrie { ...@@ -921,15 +764,10 @@ library Lib_MerkleTrie {
* @param _isLeaf Whether or not the key belongs to a leaf. * @param _isLeaf Whether or not the key belongs to a leaf.
* @return _prefixedKey Prefixed key. * @return _prefixedKey Prefixed key.
*/ */
function _addHexPrefix( function _addHexPrefix(bytes memory _key, bool _isLeaf)
bytes memory _key,
bool _isLeaf
)
private private
pure pure
returns ( returns (bytes memory _prefixedKey)
bytes memory _prefixedKey
)
{ {
uint8 prefix = _isLeaf ? uint8(0x02) : uint8(0x00); uint8 prefix = _isLeaf ? uint8(0x02) : uint8(0x00);
uint8 offset = uint8(_key.length % 2); uint8 offset = uint8(_key.length % 2);
...@@ -943,14 +781,10 @@ library Lib_MerkleTrie { ...@@ -943,14 +781,10 @@ library Lib_MerkleTrie {
* @param _path Path to remove the prefix from. * @param _path Path to remove the prefix from.
* @return _unprefixedKey Unprefixed key. * @return _unprefixedKey Unprefixed key.
*/ */
function _removeHexPrefix( function _removeHexPrefix(bytes memory _path)
bytes memory _path
)
private private
pure pure
returns ( returns (bytes memory _unprefixedKey)
bytes memory _unprefixedKey
)
{ {
if (uint8(_path[0]) % 2 == 0) { if (uint8(_path[0]) % 2 == 0) {
return Lib_BytesUtils.slice(_path, 2); return Lib_BytesUtils.slice(_path, 2);
...@@ -974,13 +808,7 @@ library Lib_MerkleTrie { ...@@ -974,13 +808,7 @@ library Lib_MerkleTrie {
uint256 _aLength, uint256 _aLength,
TrieNode[] memory _b, TrieNode[] memory _b,
uint256 _bLength uint256 _bLength
) ) private pure returns (TrieNode[] memory _joined) {
private
pure
returns (
TrieNode[] memory _joined
)
{
TrieNode[] memory ret = new TrieNode[](_aLength + _bLength); TrieNode[] memory ret = new TrieNode[](_aLength + _bLength);
// Copy elements from the first array. // Copy elements from the first array.
......
...@@ -2,13 +2,12 @@ ...@@ -2,13 +2,12 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_MerkleTrie } from "./Lib_MerkleTrie.sol"; import {Lib_MerkleTrie} from "./Lib_MerkleTrie.sol";
/** /**
* @title Lib_SecureMerkleTrie * @title Lib_SecureMerkleTrie
*/ */
library Lib_SecureMerkleTrie { library Lib_SecureMerkleTrie {
/********************** /**********************
* Internal Functions * * Internal Functions *
**********************/ **********************/
...@@ -30,13 +29,7 @@ library Lib_SecureMerkleTrie { ...@@ -30,13 +29,7 @@ library Lib_SecureMerkleTrie {
bytes memory _value, bytes memory _value,
bytes memory _proof, bytes memory _proof,
bytes32 _root bytes32 _root
) ) internal pure returns (bool _verified) {
internal
pure
returns (
bool _verified
)
{
bytes memory key = _getSecureKey(_key); bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.verifyInclusionProof(key, _value, _proof, _root); return Lib_MerkleTrie.verifyInclusionProof(key, _value, _proof, _root);
} }
...@@ -57,13 +50,7 @@ library Lib_SecureMerkleTrie { ...@@ -57,13 +50,7 @@ library Lib_SecureMerkleTrie {
bytes memory _value, bytes memory _value,
bytes memory _proof, bytes memory _proof,
bytes32 _root bytes32 _root
) ) internal pure returns (bytes32 _updatedRoot) {
internal
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = _getSecureKey(_key); bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.update(key, _value, _proof, _root); return Lib_MerkleTrie.update(key, _value, _proof, _root);
} }
...@@ -80,14 +67,7 @@ library Lib_SecureMerkleTrie { ...@@ -80,14 +67,7 @@ library Lib_SecureMerkleTrie {
bytes memory _key, bytes memory _key,
bytes memory _proof, bytes memory _proof,
bytes32 _root bytes32 _root
) ) internal pure returns (bool _exists, bytes memory _value) {
internal
pure
returns (
bool _exists,
bytes memory _value
)
{
bytes memory key = _getSecureKey(_key); bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.get(key, _proof, _root); return Lib_MerkleTrie.get(key, _proof, _root);
} }
...@@ -98,21 +78,15 @@ library Lib_SecureMerkleTrie { ...@@ -98,21 +78,15 @@ library Lib_SecureMerkleTrie {
* @param _value Value for the single node. * @param _value Value for the single node.
* @return _updatedRoot Hash of the trie. * @return _updatedRoot Hash of the trie.
*/ */
function getSingleNodeRootHash( function getSingleNodeRootHash(bytes memory _key, bytes memory _value)
bytes memory _key,
bytes memory _value
)
internal internal
pure pure
returns ( returns (bytes32 _updatedRoot)
bytes32 _updatedRoot
)
{ {
bytes memory key = _getSecureKey(_key); bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.getSingleNodeRootHash(key, _value); return Lib_MerkleTrie.getSingleNodeRootHash(key, _value);
} }
/********************* /*********************
* Private Functions * * Private Functions *
*********************/ *********************/
...@@ -122,15 +96,7 @@ library Lib_SecureMerkleTrie { ...@@ -122,15 +96,7 @@ library Lib_SecureMerkleTrie {
* @param _key Key to get a secure key from. * @param _key Key to get a secure key from.
* @return _secureKey Secure version of the key. * @return _secureKey Secure version of the key.
*/ */
function _getSecureKey( function _getSecureKey(bytes memory _key) private pure returns (bytes memory _secureKey) {
bytes memory _key
)
private
pure
returns (
bytes memory _secureKey
)
{
return abi.encodePacked(keccak256(_key)); return abi.encodePacked(keccak256(_key));
} }
} }
...@@ -8,34 +8,30 @@ pragma solidity ^0.8.9; ...@@ -8,34 +8,30 @@ pragma solidity ^0.8.9;
* overwritable "extra data" field so we can store more information with a single SSTORE. * overwritable "extra data" field so we can store more information with a single SSTORE.
*/ */
library Lib_Buffer { library Lib_Buffer {
/************* /*************
* Libraries * * Libraries *
*************/ *************/
using Lib_Buffer for Buffer; using Lib_Buffer for Buffer;
/*********** /***********
* Structs * * Structs *
***********/ ***********/
struct Buffer { struct Buffer {
bytes32 context; bytes32 context;
mapping (uint256 => bytes32) buf; mapping(uint256 => bytes32) buf;
} }
struct BufferContext { struct BufferContext {
// Stores the length of the array. Uint40 is way more elements than we'll ever reasonably // Stores the length of the array. Uint40 is way more elements than we'll ever reasonably
// need in an array and we get an extra 27 bytes of extra data to play with. // need in an array and we get an extra 27 bytes of extra data to play with.
uint40 length; uint40 length;
// Arbitrary extra data that can be modified whenever the length is updated. Useful for // Arbitrary extra data that can be modified whenever the length is updated. Useful for
// squeezing out some gas optimizations. // squeezing out some gas optimizations.
bytes27 extraData; bytes27 extraData;
} }
/********************** /**********************
* Internal Functions * * Internal Functions *
**********************/ **********************/
...@@ -50,9 +46,7 @@ library Lib_Buffer { ...@@ -50,9 +46,7 @@ library Lib_Buffer {
Buffer storage _self, Buffer storage _self,
bytes32 _value, bytes32 _value,
bytes27 _extraData bytes27 _extraData
) ) internal {
internal
{
BufferContext memory ctx = _self.getContext(); BufferContext memory ctx = _self.getContext();
_self.buf[ctx.length] = _value; _self.buf[ctx.length] = _value;
...@@ -68,18 +62,10 @@ library Lib_Buffer { ...@@ -68,18 +62,10 @@ library Lib_Buffer {
* @param _self Buffer to access. * @param _self Buffer to access.
* @param _value Value to push to the buffer. * @param _value Value to push to the buffer.
*/ */
function push( function push(Buffer storage _self, bytes32 _value) internal {
Buffer storage _self,
bytes32 _value
)
internal
{
BufferContext memory ctx = _self.getContext(); BufferContext memory ctx = _self.getContext();
_self.push( _self.push(_value, ctx.extraData);
_value,
ctx.extraData
);
} }
/** /**
...@@ -88,22 +74,10 @@ library Lib_Buffer { ...@@ -88,22 +74,10 @@ library Lib_Buffer {
* @param _index Element index to retrieve. * @param _index Element index to retrieve.
* @return Value of the element at the given index. * @return Value of the element at the given index.
*/ */
function get( function get(Buffer storage _self, uint256 _index) internal view returns (bytes32) {
Buffer storage _self,
uint256 _index
)
internal
view
returns (
bytes32
)
{
BufferContext memory ctx = _self.getContext(); BufferContext memory ctx = _self.getContext();
require( require(_index < ctx.length, "Index out of bounds.");
_index < ctx.length,
"Index out of bounds."
);
return _self.buf[_index]; return _self.buf[_index];
} }
...@@ -118,15 +92,10 @@ library Lib_Buffer { ...@@ -118,15 +92,10 @@ library Lib_Buffer {
Buffer storage _self, Buffer storage _self,
uint40 _index, uint40 _index,
bytes27 _extraData bytes27 _extraData
) ) internal {
internal
{
BufferContext memory ctx = _self.getContext(); BufferContext memory ctx = _self.getContext();
require( require(_index < ctx.length, "Index out of bounds.");
_index < ctx.length,
"Index out of bounds."
);
// Set our length and extra data, save the context. // Set our length and extra data, save the context.
ctx.length = _index; ctx.length = _index;
...@@ -139,17 +108,9 @@ library Lib_Buffer { ...@@ -139,17 +108,9 @@ library Lib_Buffer {
* @param _self Buffer to access. * @param _self Buffer to access.
* @param _index Index of the element to delete from (inclusive). * @param _index Index of the element to delete from (inclusive).
*/ */
function deleteElementsAfterInclusive( function deleteElementsAfterInclusive(Buffer storage _self, uint40 _index) internal {
Buffer storage _self,
uint40 _index
)
internal
{
BufferContext memory ctx = _self.getContext(); BufferContext memory ctx = _self.getContext();
_self.deleteElementsAfterInclusive( _self.deleteElementsAfterInclusive(_index, ctx.extraData);
_index,
ctx.extraData
);
} }
/** /**
...@@ -157,15 +118,7 @@ library Lib_Buffer { ...@@ -157,15 +118,7 @@ library Lib_Buffer {
* @param _self Buffer to access. * @param _self Buffer to access.
* @return Current global index. * @return Current global index.
*/ */
function getLength( function getLength(Buffer storage _self) internal view returns (uint40) {
Buffer storage _self
)
internal
view
returns (
uint40
)
{
BufferContext memory ctx = _self.getContext(); BufferContext memory ctx = _self.getContext();
return ctx.length; return ctx.length;
} }
...@@ -175,12 +128,7 @@ library Lib_Buffer { ...@@ -175,12 +128,7 @@ library Lib_Buffer {
* @param _self Buffer to access. * @param _self Buffer to access.
* @param _extraData New global extra data. * @param _extraData New global extra data.
*/ */
function setExtraData( function setExtraData(Buffer storage _self, bytes27 _extraData) internal {
Buffer storage _self,
bytes27 _extraData
)
internal
{
BufferContext memory ctx = _self.getContext(); BufferContext memory ctx = _self.getContext();
ctx.extraData = _extraData; ctx.extraData = _extraData;
_self.setContext(ctx); _self.setContext(ctx);
...@@ -191,15 +139,7 @@ library Lib_Buffer { ...@@ -191,15 +139,7 @@ library Lib_Buffer {
* @param _self Buffer to access. * @param _self Buffer to access.
* @return Current global extra data. * @return Current global extra data.
*/ */
function getExtraData( function getExtraData(Buffer storage _self) internal view returns (bytes27) {
Buffer storage _self
)
internal
view
returns (
bytes27
)
{
BufferContext memory ctx = _self.getContext(); BufferContext memory ctx = _self.getContext();
return ctx.extraData; return ctx.extraData;
} }
...@@ -209,12 +149,7 @@ library Lib_Buffer { ...@@ -209,12 +149,7 @@ library Lib_Buffer {
* @param _self Buffer to access. * @param _self Buffer to access.
* @param _ctx Current buffer context. * @param _ctx Current buffer context.
*/ */
function setContext( function setContext(Buffer storage _self, BufferContext memory _ctx) internal {
Buffer storage _self,
BufferContext memory _ctx
)
internal
{
bytes32 context; bytes32 context;
uint40 length = _ctx.length; uint40 length = _ctx.length;
bytes27 extraData = _ctx.extraData; bytes27 extraData = _ctx.extraData;
...@@ -233,26 +168,21 @@ library Lib_Buffer { ...@@ -233,26 +168,21 @@ library Lib_Buffer {
* @param _self Buffer to access. * @param _self Buffer to access.
* @return Current buffer context. * @return Current buffer context.
*/ */
function getContext( function getContext(Buffer storage _self) internal view returns (BufferContext memory) {
Buffer storage _self
)
internal
view
returns (
BufferContext memory
)
{
bytes32 context = _self.context; bytes32 context = _self.context;
uint40 length; uint40 length;
bytes27 extraData; bytes27 extraData;
assembly { assembly {
length := and(context, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) length := and(
extraData := and(context, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000) context,
0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF
)
extraData := and(
context,
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000
)
} }
return BufferContext({ return BufferContext({length: length, extraData: extraData});
length: length,
extraData: extraData
});
} }
} }
...@@ -5,7 +5,6 @@ pragma solidity ^0.8.9; ...@@ -5,7 +5,6 @@ pragma solidity ^0.8.9;
* @title Lib_Byte32Utils * @title Lib_Byte32Utils
*/ */
library Lib_Bytes32Utils { library Lib_Bytes32Utils {
/********************** /**********************
* Internal Functions * * Internal Functions *
**********************/ **********************/
...@@ -15,15 +14,7 @@ library Lib_Bytes32Utils { ...@@ -15,15 +14,7 @@ library Lib_Bytes32Utils {
* @param _in Input bytes32 value. * @param _in Input bytes32 value.
* @return Bytes32 as a boolean. * @return Bytes32 as a boolean.
*/ */
function toBool( function toBool(bytes32 _in) internal pure returns (bool) {
bytes32 _in
)
internal
pure
returns (
bool
)
{
return _in != 0; return _in != 0;
} }
...@@ -32,15 +23,7 @@ library Lib_Bytes32Utils { ...@@ -32,15 +23,7 @@ library Lib_Bytes32Utils {
* @param _in Input boolean value. * @param _in Input boolean value.
* @return Boolean as a bytes32. * @return Boolean as a bytes32.
*/ */
function fromBool( function fromBool(bool _in) internal pure returns (bytes32) {
bool _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in ? 1 : 0)); return bytes32(uint256(_in ? 1 : 0));
} }
...@@ -49,15 +32,7 @@ library Lib_Bytes32Utils { ...@@ -49,15 +32,7 @@ library Lib_Bytes32Utils {
* @param _in Input bytes32 value. * @param _in Input bytes32 value.
* @return Bytes32 as an address. * @return Bytes32 as an address.
*/ */
function toAddress( function toAddress(bytes32 _in) internal pure returns (address) {
bytes32 _in
)
internal
pure
returns (
address
)
{
return address(uint160(uint256(_in))); return address(uint160(uint256(_in)));
} }
...@@ -66,15 +41,7 @@ library Lib_Bytes32Utils { ...@@ -66,15 +41,7 @@ library Lib_Bytes32Utils {
* @param _in Input address value. * @param _in Input address value.
* @return Address as a bytes32. * @return Address as a bytes32.
*/ */
function fromAddress( function fromAddress(address _in) internal pure returns (bytes32) {
address _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(uint160(_in))); return bytes32(uint256(uint160(_in)));
} }
} }
...@@ -5,7 +5,6 @@ pragma solidity ^0.8.9; ...@@ -5,7 +5,6 @@ pragma solidity ^0.8.9;
* @title Lib_BytesUtils * @title Lib_BytesUtils
*/ */
library Lib_BytesUtils { library Lib_BytesUtils {
/********************** /**********************
* Internal Functions * * Internal Functions *
**********************/ **********************/
...@@ -14,13 +13,7 @@ library Lib_BytesUtils { ...@@ -14,13 +13,7 @@ library Lib_BytesUtils {
bytes memory _bytes, bytes memory _bytes,
uint256 _start, uint256 _start,
uint256 _length uint256 _length
) ) internal pure returns (bytes memory) {
internal
pure
returns (
bytes memory
)
{
require(_length + 31 >= _length, "slice_overflow"); require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow"); require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds"); require(_bytes.length >= _start + _length, "slice_outOfBounds");
...@@ -83,16 +76,7 @@ library Lib_BytesUtils { ...@@ -83,16 +76,7 @@ library Lib_BytesUtils {
return tempBytes; return tempBytes;
} }
function slice( function slice(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) {
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
bytes memory
)
{
if (_start >= _bytes.length) { if (_start >= _bytes.length) {
return bytes(""); return bytes("");
} }
...@@ -100,15 +84,7 @@ library Lib_BytesUtils { ...@@ -100,15 +84,7 @@ library Lib_BytesUtils {
return slice(_bytes, _start, _bytes.length - _start); return slice(_bytes, _start, _bytes.length - _start);
} }
function toBytes32( function toBytes32(bytes memory _bytes) internal pure returns (bytes32) {
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
if (_bytes.length < 32) { if (_bytes.length < 32) {
bytes32 ret; bytes32 ret;
assembly { assembly {
...@@ -117,30 +93,14 @@ library Lib_BytesUtils { ...@@ -117,30 +93,14 @@ library Lib_BytesUtils {
return ret; return ret;
} }
return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes return abi.decode(_bytes, (bytes32)); // will truncate if input length > 32 bytes
} }
function toUint256( function toUint256(bytes memory _bytes) internal pure returns (uint256) {
bytes memory _bytes
)
internal
pure
returns (
uint256
)
{
return uint256(toBytes32(_bytes)); return uint256(toBytes32(_bytes));
} }
function toNibbles( function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory nibbles = new bytes(_bytes.length * 2); bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) { for (uint256 i = 0; i < _bytes.length; i++) {
...@@ -151,15 +111,7 @@ library Lib_BytesUtils { ...@@ -151,15 +111,7 @@ library Lib_BytesUtils {
return nibbles; return nibbles;
} }
function fromNibbles( function fromNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory ret = new bytes(_bytes.length / 2); bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) { for (uint256 i = 0; i < ret.length; i++) {
...@@ -169,16 +121,7 @@ library Lib_BytesUtils { ...@@ -169,16 +121,7 @@ library Lib_BytesUtils {
return ret; return ret;
} }
function equal( function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) {
bytes memory _bytes,
bytes memory _other
)
internal
pure
returns (
bool
)
{
return keccak256(_bytes) == keccak256(_other); return keccak256(_bytes) == keccak256(_other);
} }
} }
...@@ -6,7 +6,6 @@ pragma solidity ^0.8.9; ...@@ -6,7 +6,6 @@ pragma solidity ^0.8.9;
* @author River Keefer * @author River Keefer
*/ */
library Lib_MerkleTree { library Lib_MerkleTree {
/********************** /**********************
* Internal Functions * * Internal Functions *
**********************/ **********************/
...@@ -20,19 +19,8 @@ library Lib_MerkleTree { ...@@ -20,19 +19,8 @@ library Lib_MerkleTree {
* @param _elements Array of hashes from which to generate a merkle root. * @param _elements Array of hashes from which to generate a merkle root.
* @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above). * @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above).
*/ */
function getMerkleRoot( function getMerkleRoot(bytes32[] memory _elements) internal pure returns (bytes32) {
bytes32[] memory _elements require(_elements.length > 0, "Lib_MerkleTree: Must provide at least one leaf hash.");
)
internal
pure
returns (
bytes32
)
{
require(
_elements.length > 0,
"Lib_MerkleTree: Must provide at least one leaf hash."
);
if (_elements.length == 1) { if (_elements.length == 1) {
return _elements[0]; return _elements[0];
...@@ -71,18 +59,18 @@ library Lib_MerkleTree { ...@@ -71,18 +59,18 @@ library Lib_MerkleTree {
uint256 depth = 0; uint256 depth = 0;
// Common sub-expressions // Common sub-expressions
uint256 halfRowSize; // rowSize / 2 uint256 halfRowSize; // rowSize / 2
bool rowSizeIsOdd; // rowSize % 2 == 1 bool rowSizeIsOdd; // rowSize % 2 == 1
while (rowSize > 1) { while (rowSize > 1) {
halfRowSize = rowSize / 2; halfRowSize = rowSize / 2;
rowSizeIsOdd = rowSize % 2 == 1; rowSizeIsOdd = rowSize % 2 == 1;
for (uint256 i = 0; i < halfRowSize; i++) { for (uint256 i = 0; i < halfRowSize; i++) {
leftSibling = _elements[(2 * i) ]; leftSibling = _elements[(2 * i)];
rightSibling = _elements[(2 * i) + 1]; rightSibling = _elements[(2 * i) + 1];
assembly { assembly {
mstore(add(buf, 32), leftSibling ) mstore(add(buf, 32), leftSibling)
mstore(add(buf, 64), rightSibling) mstore(add(buf, 64), rightSibling)
} }
...@@ -90,7 +78,7 @@ library Lib_MerkleTree { ...@@ -90,7 +78,7 @@ library Lib_MerkleTree {
} }
if (rowSizeIsOdd) { if (rowSizeIsOdd) {
leftSibling = _elements[rowSize - 1]; leftSibling = _elements[rowSize - 1];
rightSibling = bytes32(defaults[depth]); rightSibling = bytes32(defaults[depth]);
assembly { assembly {
mstore(add(buf, 32), leftSibling) mstore(add(buf, 32), leftSibling)
...@@ -125,22 +113,10 @@ library Lib_MerkleTree { ...@@ -125,22 +113,10 @@ library Lib_MerkleTree {
uint256 _index, uint256 _index,
bytes32[] memory _siblings, bytes32[] memory _siblings,
uint256 _totalLeaves uint256 _totalLeaves
) ) internal pure returns (bool) {
internal require(_totalLeaves > 0, "Lib_MerkleTree: Total leaves must be greater than zero.");
pure
returns (
bool
)
{
require(
_totalLeaves > 0,
"Lib_MerkleTree: Total leaves must be greater than zero."
);
require( require(_index < _totalLeaves, "Lib_MerkleTree: Index out of bounds.");
_index < _totalLeaves,
"Lib_MerkleTree: Index out of bounds."
);
require( require(
_siblings.length == _ceilLog2(_totalLeaves), _siblings.length == _ceilLog2(_totalLeaves),
...@@ -151,19 +127,9 @@ library Lib_MerkleTree { ...@@ -151,19 +127,9 @@ library Lib_MerkleTree {
for (uint256 i = 0; i < _siblings.length; i++) { for (uint256 i = 0; i < _siblings.length; i++) {
if ((_index & 1) == 1) { if ((_index & 1) == 1) {
computedRoot = keccak256( computedRoot = keccak256(abi.encodePacked(_siblings[i], computedRoot));
abi.encodePacked(
_siblings[i],
computedRoot
)
);
} else { } else {
computedRoot = keccak256( computedRoot = keccak256(abi.encodePacked(computedRoot, _siblings[i]));
abi.encodePacked(
computedRoot,
_siblings[i]
)
);
} }
_index >>= 1; _index >>= 1;
...@@ -172,7 +138,6 @@ library Lib_MerkleTree { ...@@ -172,7 +138,6 @@ library Lib_MerkleTree {
return _root == computedRoot; return _root == computedRoot;
} }
/********************* /*********************
* Private Functions * * Private Functions *
*********************/ *********************/
...@@ -182,19 +147,8 @@ library Lib_MerkleTree { ...@@ -182,19 +147,8 @@ library Lib_MerkleTree {
* @param _in Unsigned input to calculate the log. * @param _in Unsigned input to calculate the log.
* @return ceil(log_base_2(_in)) * @return ceil(log_base_2(_in))
*/ */
function _ceilLog2( function _ceilLog2(uint256 _in) private pure returns (uint256) {
uint256 _in require(_in > 0, "Lib_MerkleTree: Cannot compute ceil(log_2) of 0.");
)
private
pure
returns (
uint256
)
{
require(
_in > 0,
"Lib_MerkleTree: Cannot compute ceil(log_2) of 0."
);
if (_in == 1) { if (_in == 1) {
return 0; return 0;
...@@ -205,14 +159,14 @@ library Lib_MerkleTree { ...@@ -205,14 +159,14 @@ library Lib_MerkleTree {
uint256 val = _in; uint256 val = _in;
uint256 highest = 0; uint256 highest = 0;
for (uint256 i = 128; i >= 1; i >>= 1) { for (uint256 i = 128; i >= 1; i >>= 1) {
if (val & (uint(1) << i) - 1 << i != 0) { if (val & (((uint256(1) << i) - 1) << i) != 0) {
highest += i; highest += i;
val >>= i; val >>= i;
} }
} }
// Increment by one if this is not a perfect logarithm. // Increment by one if this is not a perfect logarithm.
if ((uint(1) << highest) != _in) { if ((uint256(1) << highest) != _in) {
highest += 1; highest += 1;
} }
......
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
/* /*
......
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
interface IL2StandardERC20 is IERC20, IERC165 { interface IL2StandardERC20 is IERC20, IERC165 {
function l1Token() external returns (address); function l1Token() external returns (address);
......
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./IL2StandardERC20.sol"; import "./IL2StandardERC20.sol";
contract L2StandardERC20 is IL2StandardERC20, ERC20 { contract L2StandardERC20 is IL2StandardERC20, ERC20 {
...@@ -19,22 +19,21 @@ contract L2StandardERC20 is IL2StandardERC20, ERC20 { ...@@ -19,22 +19,21 @@ contract L2StandardERC20 is IL2StandardERC20, ERC20 {
address _l1Token, address _l1Token,
string memory _name, string memory _name,
string memory _symbol string memory _symbol
) ) ERC20(_name, _symbol) {
ERC20(_name, _symbol) {
l1Token = _l1Token; l1Token = _l1Token;
l2Bridge = _l2Bridge; l2Bridge = _l2Bridge;
} }
modifier onlyL2Bridge { modifier onlyL2Bridge() {
require(msg.sender == l2Bridge, "Only L2 Bridge can mint and burn"); require(msg.sender == l2Bridge, "Only L2 Bridge can mint and burn");
_; _;
} }
function supportsInterface(bytes4 _interfaceId) public pure returns (bool) { function supportsInterface(bytes4 _interfaceId) public pure returns (bool) {
bytes4 firstSupportedInterface = bytes4(keccak256("supportsInterface(bytes4)")); // ERC165 bytes4 firstSupportedInterface = bytes4(keccak256("supportsInterface(bytes4)")); // ERC165
bytes4 secondSupportedInterface = IL2StandardERC20.l1Token.selector bytes4 secondSupportedInterface = IL2StandardERC20.l1Token.selector ^
^ IL2StandardERC20.mint.selector IL2StandardERC20.mint.selector ^
^ IL2StandardERC20.burn.selector; IL2StandardERC20.burn.selector;
return _interfaceId == firstSupportedInterface || _interfaceId == secondSupportedInterface; return _interfaceId == firstSupportedInterface || _interfaceId == secondSupportedInterface;
} }
......
...@@ -2,20 +2,14 @@ ...@@ -2,20 +2,14 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
contract Helper_GasMeasurer { contract Helper_GasMeasurer {
function measureCallGas( function measureCallGas(address _target, bytes memory _data) public returns (uint256) {
address _target,
bytes memory _data
)
public
returns ( uint256 )
{
uint256 gasBefore; uint256 gasBefore;
uint256 gasAfter; uint256 gasAfter;
uint256 calldataStart; uint256 calldataStart;
uint256 calldataLength; uint256 calldataLength;
assembly { assembly {
calldataStart := add(_data,0x20) calldataStart := add(_data, 0x20)
calldataLength := mload(_data) calldataLength := mload(_data)
} }
......
...@@ -5,22 +5,15 @@ contract Helper_SimpleProxy { ...@@ -5,22 +5,15 @@ contract Helper_SimpleProxy {
address internal owner; address internal owner;
address internal target; address internal target;
constructor() constructor() {
{
owner = msg.sender; owner = msg.sender;
} }
fallback() fallback() external {
external
{
makeExternalCall(target, msg.data); makeExternalCall(target, msg.data);
} }
function setTarget( function setTarget(address _target) public {
address _target
)
public
{
if (msg.sender == owner) { if (msg.sender == owner) {
target = _target; target = _target;
} else { } else {
...@@ -28,12 +21,7 @@ contract Helper_SimpleProxy { ...@@ -28,12 +21,7 @@ contract Helper_SimpleProxy {
} }
} }
function makeExternalCall( function makeExternalCall(address _target, bytes memory _calldata) internal {
address _target,
bytes memory _calldata
)
internal
{
(bool success, bytes memory returndata) = _target.call(_calldata); (bool success, bytes memory returndata) = _target.call(_calldata);
if (success) { if (success) {
......
...@@ -6,9 +6,9 @@ contract TestERC20 { ...@@ -6,9 +6,9 @@ contract TestERC20 {
string public constant name = "Test"; string public constant name = "Test";
string public constant symbol = "TST"; string public constant symbol = "TST";
uint8 public constant decimals = 18; uint8 public constant decimals = 18;
uint256 public totalSupply; uint256 public totalSupply;
mapping(address => uint) public balanceOf; mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint)) public allowance; mapping(address => mapping(address => uint256)) public allowance;
event Approval(address indexed owner, address indexed spender, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value);
...@@ -21,12 +21,20 @@ contract TestERC20 { ...@@ -21,12 +21,20 @@ contract TestERC20 {
emit Transfer(address(0), to, value); emit Transfer(address(0), to, value);
} }
function _approve(address owner, address spender, uint256 value) private { function _approve(
address owner,
address spender,
uint256 value
) private {
allowance[owner][spender] = value; allowance[owner][spender] = value;
emit Approval(owner, spender, value); emit Approval(owner, spender, value);
} }
function _transfer(address from, address to, uint256 value) private { function _transfer(
address from,
address to,
uint256 value
) private {
balanceOf[from] = balanceOf[from] - value; balanceOf[from] = balanceOf[from] - value;
balanceOf[to] = balanceOf[to] + value; balanceOf[to] = balanceOf[to] + value;
emit Transfer(from, to, value); emit Transfer(from, to, value);
...@@ -42,8 +50,12 @@ contract TestERC20 { ...@@ -42,8 +50,12 @@ contract TestERC20 {
return true; return true;
} }
function transferFrom(address from, address to, uint256 value) external returns (bool) { function transferFrom(
if (allowance[from][msg.sender] != type(uint).max) { address from,
address to,
uint256 value
) external returns (bool) {
if (allowance[from][msg.sender] != type(uint256).max) {
allowance[from][msg.sender] = allowance[from][msg.sender] - value; allowance[from][msg.sender] = allowance[from][msg.sender] - value;
} }
_transfer(from, to, value); _transfer(from, to, value);
......
...@@ -2,32 +2,24 @@ ...@@ -2,32 +2,24 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import {Lib_OVMCodec} from "../../libraries/codec/Lib_OVMCodec.sol";
/** /**
* @title TestLib_OVMCodec * @title TestLib_OVMCodec
*/ */
contract TestLib_OVMCodec { contract TestLib_OVMCodec {
function encodeTransaction( function encodeTransaction(Lib_OVMCodec.Transaction memory _transaction)
Lib_OVMCodec.Transaction memory _transaction
)
public public
pure pure
returns ( returns (bytes memory _encoded)
bytes memory _encoded
)
{ {
return Lib_OVMCodec.encodeTransaction(_transaction); return Lib_OVMCodec.encodeTransaction(_transaction);
} }
function hashTransaction( function hashTransaction(Lib_OVMCodec.Transaction memory _transaction)
Lib_OVMCodec.Transaction memory _transaction
)
public public
pure pure
returns ( returns (bytes32 _hash)
bytes32 _hash
)
{ {
return Lib_OVMCodec.hashTransaction(_transaction); return Lib_OVMCodec.hashTransaction(_transaction);
} }
......
...@@ -2,22 +2,13 @@ ...@@ -2,22 +2,13 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_RLPReader } from "../../libraries/rlp/Lib_RLPReader.sol"; import {Lib_RLPReader} from "../../libraries/rlp/Lib_RLPReader.sol";
/** /**
* @title TestLib_RLPReader * @title TestLib_RLPReader
*/ */
contract TestLib_RLPReader { contract TestLib_RLPReader {
function readList(bytes memory _in) public pure returns (bytes[] memory) {
function readList(
bytes memory _in
)
public
pure
returns (
bytes[] memory
)
{
Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_in); Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_in);
bytes[] memory out = new bytes[](decoded.length); bytes[] memory out = new bytes[](decoded.length);
for (uint256 i = 0; i < out.length; i++) { for (uint256 i = 0; i < out.length; i++) {
...@@ -26,75 +17,27 @@ contract TestLib_RLPReader { ...@@ -26,75 +17,27 @@ contract TestLib_RLPReader {
return out; return out;
} }
function readString( function readString(bytes memory _in) public pure returns (string memory) {
bytes memory _in
)
public
pure
returns (
string memory
)
{
return Lib_RLPReader.readString(_in); return Lib_RLPReader.readString(_in);
} }
function readBytes( function readBytes(bytes memory _in) public pure returns (bytes memory) {
bytes memory _in
)
public
pure
returns (
bytes memory
)
{
return Lib_RLPReader.readBytes(_in); return Lib_RLPReader.readBytes(_in);
} }
function readBytes32( function readBytes32(bytes memory _in) public pure returns (bytes32) {
bytes memory _in
)
public
pure
returns (
bytes32
)
{
return Lib_RLPReader.readBytes32(_in); return Lib_RLPReader.readBytes32(_in);
} }
function readUint256( function readUint256(bytes memory _in) public pure returns (uint256) {
bytes memory _in
)
public
pure
returns (
uint256
)
{
return Lib_RLPReader.readUint256(_in); return Lib_RLPReader.readUint256(_in);
} }
function readBool( function readBool(bytes memory _in) public pure returns (bool) {
bytes memory _in
)
public
pure
returns (
bool
)
{
return Lib_RLPReader.readBool(_in); return Lib_RLPReader.readBool(_in);
} }
function readAddress( function readAddress(bytes memory _in) public pure returns (address) {
bytes memory _in
)
public
pure
returns (
address
)
{
return Lib_RLPReader.readAddress(_in); return Lib_RLPReader.readAddress(_in);
} }
} }
...@@ -2,94 +2,38 @@ ...@@ -2,94 +2,38 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_RLPWriter } from "../../libraries/rlp/Lib_RLPWriter.sol"; import {Lib_RLPWriter} from "../../libraries/rlp/Lib_RLPWriter.sol";
import { TestERC20 } from "../../test-helpers/TestERC20.sol"; import {TestERC20} from "../../test-helpers/TestERC20.sol";
/** /**
* @title TestLib_RLPWriter * @title TestLib_RLPWriter
*/ */
contract TestLib_RLPWriter { contract TestLib_RLPWriter {
function writeBytes(bytes memory _in) public pure returns (bytes memory _out) {
function writeBytes(
bytes memory _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeBytes(_in); return Lib_RLPWriter.writeBytes(_in);
} }
function writeList( function writeList(bytes[] memory _in) public pure returns (bytes memory _out) {
bytes[] memory _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeList(_in); return Lib_RLPWriter.writeList(_in);
} }
function writeString( function writeString(string memory _in) public pure returns (bytes memory _out) {
string memory _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeString(_in); return Lib_RLPWriter.writeString(_in);
} }
function writeAddress( function writeAddress(address _in) public pure returns (bytes memory _out) {
address _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeAddress(_in); return Lib_RLPWriter.writeAddress(_in);
} }
function writeUint( function writeUint(uint256 _in) public pure returns (bytes memory _out) {
uint256 _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeUint(_in); return Lib_RLPWriter.writeUint(_in);
} }
function writeBool( function writeBool(bool _in) public pure returns (bytes memory _out) {
bool _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeBool(_in); return Lib_RLPWriter.writeBool(_in);
} }
function writeAddressWithTaintedMemory( function writeAddressWithTaintedMemory(address _in) public returns (bytes memory _out) {
address _in
)
public
returns (
bytes memory _out
)
{
new TestERC20(); new TestERC20();
return Lib_RLPWriter.writeAddress(_in); return Lib_RLPWriter.writeAddress(_in);
} }
......
...@@ -2,33 +2,17 @@ ...@@ -2,33 +2,17 @@
pragma solidity ^0.8.8; pragma solidity ^0.8.8;
/* Library Imports */ /* Library Imports */
import { AddressAliasHelper } from "../../standards/AddressAliasHelper.sol"; import {AddressAliasHelper} from "../../standards/AddressAliasHelper.sol";
/** /**
* @title TestLib_AddressAliasHelper * @title TestLib_AddressAliasHelper
*/ */
contract TestLib_AddressAliasHelper { contract TestLib_AddressAliasHelper {
function applyL1ToL2Alias( function applyL1ToL2Alias(address _address) public pure returns (address) {
address _address
)
public
pure
returns (
address
)
{
return AddressAliasHelper.applyL1ToL2Alias(_address); return AddressAliasHelper.applyL1ToL2Alias(_address);
} }
function undoL1ToL2Alias( function undoL1ToL2Alias(address _address) public pure returns (address) {
address _address
)
public
pure
returns (
address
)
{
return AddressAliasHelper.undoL1ToL2Alias(_address); return AddressAliasHelper.undoL1ToL2Alias(_address);
} }
} }
...@@ -2,31 +2,19 @@ ...@@ -2,31 +2,19 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_MerkleTrie } from "../../libraries/trie/Lib_MerkleTrie.sol"; import {Lib_MerkleTrie} from "../../libraries/trie/Lib_MerkleTrie.sol";
/** /**
* @title TestLib_MerkleTrie * @title TestLib_MerkleTrie
*/ */
contract TestLib_MerkleTrie { contract TestLib_MerkleTrie {
function verifyInclusionProof( function verifyInclusionProof(
bytes memory _key, bytes memory _key,
bytes memory _value, bytes memory _value,
bytes memory _proof, bytes memory _proof,
bytes32 _root bytes32 _root
) ) public pure returns (bool) {
public return Lib_MerkleTrie.verifyInclusionProof(_key, _value, _proof, _root);
pure
returns (
bool
)
{
return Lib_MerkleTrie.verifyInclusionProof(
_key,
_value,
_proof,
_root
);
} }
function update( function update(
...@@ -34,53 +22,23 @@ contract TestLib_MerkleTrie { ...@@ -34,53 +22,23 @@ contract TestLib_MerkleTrie {
bytes memory _value, bytes memory _value,
bytes memory _proof, bytes memory _proof,
bytes32 _root bytes32 _root
) ) public pure returns (bytes32) {
public return Lib_MerkleTrie.update(_key, _value, _proof, _root);
pure
returns (
bytes32
)
{
return Lib_MerkleTrie.update(
_key,
_value,
_proof,
_root
);
} }
function get( function get(
bytes memory _key, bytes memory _key,
bytes memory _proof, bytes memory _proof,
bytes32 _root bytes32 _root
) ) public pure returns (bool, bytes memory) {
public return Lib_MerkleTrie.get(_key, _proof, _root);
pure
returns (
bool,
bytes memory
)
{
return Lib_MerkleTrie.get(
_key,
_proof,
_root
);
} }
function getSingleNodeRootHash( function getSingleNodeRootHash(bytes memory _key, bytes memory _value)
bytes memory _key,
bytes memory _value
)
public public
pure pure
returns ( returns (bytes32)
bytes32
)
{ {
return Lib_MerkleTrie.getSingleNodeRootHash( return Lib_MerkleTrie.getSingleNodeRootHash(_key, _value);
_key,
_value
);
} }
} }
...@@ -2,31 +2,19 @@ ...@@ -2,31 +2,19 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_SecureMerkleTrie } from "../../libraries/trie/Lib_SecureMerkleTrie.sol"; import {Lib_SecureMerkleTrie} from "../../libraries/trie/Lib_SecureMerkleTrie.sol";
/** /**
* @title TestLib_SecureMerkleTrie * @title TestLib_SecureMerkleTrie
*/ */
contract TestLib_SecureMerkleTrie { contract TestLib_SecureMerkleTrie {
function verifyInclusionProof( function verifyInclusionProof(
bytes memory _key, bytes memory _key,
bytes memory _value, bytes memory _value,
bytes memory _proof, bytes memory _proof,
bytes32 _root bytes32 _root
) ) public pure returns (bool) {
public return Lib_SecureMerkleTrie.verifyInclusionProof(_key, _value, _proof, _root);
pure
returns (
bool
)
{
return Lib_SecureMerkleTrie.verifyInclusionProof(
_key,
_value,
_proof,
_root
);
} }
function update( function update(
...@@ -34,53 +22,23 @@ contract TestLib_SecureMerkleTrie { ...@@ -34,53 +22,23 @@ contract TestLib_SecureMerkleTrie {
bytes memory _value, bytes memory _value,
bytes memory _proof, bytes memory _proof,
bytes32 _root bytes32 _root
) ) public pure returns (bytes32) {
public return Lib_SecureMerkleTrie.update(_key, _value, _proof, _root);
pure
returns (
bytes32
)
{
return Lib_SecureMerkleTrie.update(
_key,
_value,
_proof,
_root
);
} }
function get( function get(
bytes memory _key, bytes memory _key,
bytes memory _proof, bytes memory _proof,
bytes32 _root bytes32 _root
) ) public pure returns (bool, bytes memory) {
public return Lib_SecureMerkleTrie.get(_key, _proof, _root);
pure
returns (
bool,
bytes memory
)
{
return Lib_SecureMerkleTrie.get(
_key,
_proof,
_root
);
} }
function getSingleNodeRootHash( function getSingleNodeRootHash(bytes memory _key, bytes memory _value)
bytes memory _key,
bytes memory _value
)
public public
pure pure
returns ( returns (bytes32)
bytes32
)
{ {
return Lib_SecureMerkleTrie.getSingleNodeRootHash( return Lib_SecureMerkleTrie.getSingleNodeRootHash(_key, _value);
_key,
_value
);
} }
} }
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_Buffer } from "../../libraries/utils/Lib_Buffer.sol"; import {Lib_Buffer} from "../../libraries/utils/Lib_Buffer.sol";
/** /**
* @title TestLib_Buffer * @title TestLib_Buffer
...@@ -12,79 +12,31 @@ contract TestLib_Buffer { ...@@ -12,79 +12,31 @@ contract TestLib_Buffer {
Lib_Buffer.Buffer internal buf; Lib_Buffer.Buffer internal buf;
function push( function push(bytes32 _value, bytes27 _extraData) public {
bytes32 _value, buf.push(_value, _extraData);
bytes27 _extraData
)
public
{
buf.push(
_value,
_extraData
);
} }
function get( function get(uint256 _index) public view returns (bytes32) {
uint256 _index
)
public
view
returns (
bytes32
)
{
return buf.get(_index); return buf.get(_index);
} }
function deleteElementsAfterInclusive( function deleteElementsAfterInclusive(uint40 _index) public {
uint40 _index return buf.deleteElementsAfterInclusive(_index);
)
public
{
return buf.deleteElementsAfterInclusive(
_index
);
} }
function deleteElementsAfterInclusive( function deleteElementsAfterInclusive(uint40 _index, bytes27 _extraData) public {
uint40 _index, return buf.deleteElementsAfterInclusive(_index, _extraData);
bytes27 _extraData
)
public
{
return buf.deleteElementsAfterInclusive(
_index,
_extraData
);
} }
function getLength() function getLength() public view returns (uint40) {
public
view
returns (
uint40
)
{
return buf.getLength(); return buf.getLength();
} }
function setExtraData( function setExtraData(bytes27 _extraData) public {
bytes27 _extraData return buf.setExtraData(_extraData);
)
public
{
return buf.setExtraData(
_extraData
);
} }
function getExtraData() function getExtraData() public view returns (bytes27) {
public
view
returns (
bytes27
)
{
return buf.getExtraData(); return buf.getExtraData();
} }
} }
...@@ -2,58 +2,25 @@ ...@@ -2,58 +2,25 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; import {Lib_Bytes32Utils} from "../../libraries/utils/Lib_Bytes32Utils.sol";
/** /**
* @title TestLib_Byte32Utils * @title TestLib_Byte32Utils
*/ */
contract TestLib_Bytes32Utils { contract TestLib_Bytes32Utils {
function toBool(bytes32 _in) public pure returns (bool _out) {
function toBool(
bytes32 _in
)
public
pure
returns (
bool _out
)
{
return Lib_Bytes32Utils.toBool(_in); return Lib_Bytes32Utils.toBool(_in);
} }
function fromBool( function fromBool(bool _in) public pure returns (bytes32 _out) {
bool _in
)
public
pure
returns (
bytes32 _out
)
{
return Lib_Bytes32Utils.fromBool(_in); return Lib_Bytes32Utils.fromBool(_in);
} }
function toAddress( function toAddress(bytes32 _in) public pure returns (address _out) {
bytes32 _in
)
public
pure
returns (
address _out
)
{
return Lib_Bytes32Utils.toAddress(_in); return Lib_Bytes32Utils.toAddress(_in);
} }
function fromAddress( function fromAddress(address _in) public pure returns (bytes32 _out) {
address _in
)
public
pure
returns (
bytes32 _out
)
{
return Lib_Bytes32Utils.fromAddress(_in); return Lib_Bytes32Utils.fromAddress(_in);
} }
} }
...@@ -2,119 +2,55 @@ ...@@ -2,119 +2,55 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_BytesUtils } from "../../libraries/utils/Lib_BytesUtils.sol"; import {Lib_BytesUtils} from "../../libraries/utils/Lib_BytesUtils.sol";
import { TestERC20 } from "../../test-helpers/TestERC20.sol"; import {TestERC20} from "../../test-helpers/TestERC20.sol";
/** /**
* @title TestLib_BytesUtils * @title TestLib_BytesUtils
*/ */
contract TestLib_BytesUtils { contract TestLib_BytesUtils {
function concat(bytes memory _preBytes, bytes memory _postBytes)
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
public public
pure pure
returns (bytes memory) returns (bytes memory)
{ {
return abi.encodePacked( return abi.encodePacked(_preBytes, _postBytes);
_preBytes,
_postBytes
);
} }
function slice( function slice(
bytes memory _bytes, bytes memory _bytes,
uint256 _start, uint256 _start,
uint256 _length uint256 _length
) ) public pure returns (bytes memory) {
public return Lib_BytesUtils.slice(_bytes, _start, _length);
pure
returns (bytes memory)
{
return Lib_BytesUtils.slice(
_bytes,
_start,
_length
);
} }
function toBytes32( function toBytes32(bytes memory _bytes) public pure returns (bytes32) {
bytes memory _bytes return Lib_BytesUtils.toBytes32(_bytes);
)
public
pure
returns (bytes32)
{
return Lib_BytesUtils.toBytes32(
_bytes
);
} }
function toUint256( function toUint256(bytes memory _bytes) public pure returns (uint256) {
bytes memory _bytes return Lib_BytesUtils.toUint256(_bytes);
)
public
pure
returns (uint256)
{
return Lib_BytesUtils.toUint256(
_bytes
);
} }
function toNibbles( function toNibbles(bytes memory _bytes) public pure returns (bytes memory) {
bytes memory _bytes return Lib_BytesUtils.toNibbles(_bytes);
)
public
pure
returns (bytes memory)
{
return Lib_BytesUtils.toNibbles(
_bytes
);
} }
function fromNibbles( function fromNibbles(bytes memory _bytes) public pure returns (bytes memory) {
bytes memory _bytes return Lib_BytesUtils.fromNibbles(_bytes);
)
public
pure
returns (bytes memory)
{
return Lib_BytesUtils.fromNibbles(
_bytes
);
} }
function equal( function equal(bytes memory _bytes, bytes memory _other) public pure returns (bool) {
bytes memory _bytes, return Lib_BytesUtils.equal(_bytes, _other);
bytes memory _other
)
public
pure
returns (bool)
{
return Lib_BytesUtils.equal(
_bytes,
_other
);
} }
function sliceWithTaintedMemory( function sliceWithTaintedMemory(
bytes memory _bytes, bytes memory _bytes,
uint256 _start, uint256 _start,
uint256 _length uint256 _length
) ) public returns (bytes memory) {
public
returns (bytes memory)
{
new TestERC20(); new TestERC20();
return Lib_BytesUtils.slice( return Lib_BytesUtils.slice(_bytes, _start, _length);
_bytes,
_start,
_length
);
} }
} }
...@@ -2,25 +2,14 @@ ...@@ -2,25 +2,14 @@
pragma solidity ^0.8.9; pragma solidity ^0.8.9;
/* Library Imports */ /* Library Imports */
import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol"; import {Lib_MerkleTree} from "../../libraries/utils/Lib_MerkleTree.sol";
/** /**
* @title TestLib_MerkleTree * @title TestLib_MerkleTree
*/ */
contract TestLib_MerkleTree { contract TestLib_MerkleTree {
function getMerkleRoot(bytes32[] memory _elements) public pure returns (bytes32) {
function getMerkleRoot( return Lib_MerkleTree.getMerkleRoot(_elements);
bytes32[] memory _elements
)
public
pure
returns (
bytes32
)
{
return Lib_MerkleTree.getMerkleRoot(
_elements
);
} }
function verify( function verify(
...@@ -29,19 +18,7 @@ contract TestLib_MerkleTree { ...@@ -29,19 +18,7 @@ contract TestLib_MerkleTree {
uint256 _index, uint256 _index,
bytes32[] memory _siblings, bytes32[] memory _siblings,
uint256 _totalLeaves uint256 _totalLeaves
) ) public pure returns (bool) {
public return Lib_MerkleTree.verify(_root, _leaf, _index, _siblings, _totalLeaves);
pure
returns (
bool
)
{
return Lib_MerkleTree.verify(
_root,
_leaf,
_index,
_siblings,
_totalLeaves
);
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment