Commit be0011d2 authored by Mark Tyneway's avatar Mark Tyneway

contracts-bedrock: run forge fmt

parent 2ef045ce
......@@ -106,7 +106,7 @@ contract DeployConfig is Script {
} catch {
try vm.parseJsonUint(_json, "$.l1StartingBlockTag") returns (uint256 tag) {
return _getBlockByTag(vm.toString(tag));
} catch {}
} catch { }
}
}
revert("l1StartingBlockTag must be a bytes32, string or uint256 or cannot fetch l1StartingBlockTag");
......
......@@ -39,7 +39,7 @@ contract DeployL2 is Deployer {
}
/// @notice Deploy the EAS implementation.
function deployEAS() broadcast() public returns (address) {
function deployEAS() public broadcast returns (address) {
EAS eas = new EAS();
ISchemaRegistry registry = eas.getSchemaRegistry();
......@@ -55,7 +55,7 @@ contract DeployL2 is Deployer {
}
/// @notice Deploy the SchemaManager implementation.
function deploySchemaRegistry() broadcast() public returns (address) {
function deploySchemaRegistry() public broadcast returns (address) {
SchemaRegistry registry = new SchemaRegistry();
save("SchemaRegistry", address(registry));
......@@ -67,4 +67,3 @@ contract DeployL2 is Deployer {
return address(registry);
}
}
......@@ -53,17 +53,17 @@ abstract contract Deployer is Script {
/// @notice The path to the temp deployments file
string internal tempDeploymentsPath;
/// @notice Error for when attempting to fetch a deployment and it does not exist
error DeploymentDoesNotExist(string);
/// @notice Error for when trying to save an invalid deployment
error InvalidDeployment(string);
/// @notice The storage slot that holds the address of the implementation.
/// bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
bytes32 internal constant IMPLEMENTATION_KEY =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
bytes32 internal constant IMPLEMENTATION_KEY = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/// @notice The storage slot that holds the address of the owner.
/// bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)
bytes32 internal constant OWNER_KEY =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
bytes32 internal constant OWNER_KEY = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/// @notice Create the global variables and set up the filesystem
function setUp() public virtual {
......@@ -76,7 +76,7 @@ abstract contract Deployer is Script {
deployPath = string.concat(root, "/broadcast/", deployScript, ".s.sol/", vm.toString(chainId), "/", deployFile);
deploymentsDir = string.concat(root, "/deployments/", deploymentContext);
try vm.createDir(deploymentsDir, true) {} catch (bytes memory) {}
try vm.createDir(deploymentsDir, true) { } catch (bytes memory) { }
string memory chainIdPath = string.concat(deploymentsDir, "/.chainId");
try vm.readFile(chainIdPath) returns (string memory localChainId) {
......@@ -89,7 +89,8 @@ abstract contract Deployer is Script {
console.log("Connected to network with chainid %s", chainId);
tempDeploymentsPath = string.concat(deploymentsDir, "/.deploy");
try vm.readFile(tempDeploymentsPath) returns (string memory) {} catch {
try vm.readFile(tempDeploymentsPath) returns (string memory) { }
catch {
vm.writeJson("{}", tempDeploymentsPath);
}
console.log("Storing temp deployment data in %s", tempDeploymentsPath);
......@@ -121,7 +122,7 @@ abstract contract Deployer is Script {
try vm.readFile(artifactPath) returns (string memory res) {
numDeployments = stdJson.readUint(string(res), "$.numDeployments");
vm.removeFile(artifactPath);
} catch {}
} catch { }
numDeployments++;
Artifact memory artifact = Artifact({
......@@ -142,10 +143,7 @@ abstract contract Deployer is Script {
string memory json = _serializeArtifact(artifact);
vm.writeJson({
json: json,
path: artifactPath
});
vm.writeJson({ json: json, path: artifactPath });
}
console.log("Synced temp deploy files, deleting %s", tempDeploymentsPath);
......@@ -154,7 +152,7 @@ abstract contract Deployer is Script {
/// @notice Returns the name of the deployment script. Children contracts
/// must implement this to ensure that the deploy artifacts can be found.
function name() public virtual pure returns (string memory);
function name() public pure virtual returns (string memory);
/// @notice Returns all of the deployments done in the current context.
function newDeployments() external view returns (Deployment[] memory) {
......@@ -222,10 +220,7 @@ abstract contract Deployer is Script {
revert InvalidDeployment("AlreadyExists");
}
Deployment memory deployment = Deployment({
name: _name,
addr: payable(_deployed)
});
Deployment memory deployment = Deployment({ name: _name, addr: payable(_deployed) });
_namedDeployments[_name] = deployment;
_newDeployments.push(deployment);
_writeTemp(_name, _deployed);
......@@ -247,10 +242,7 @@ abstract contract Deployer is Script {
for (uint256 i; i < names.length; i++) {
string memory contractName = names[i];
address addr = stdJson.readAddress(json, string.concat("$.", contractName));
deployments[i] = Deployment({
name: contractName,
addr: payable(addr)
});
deployments[i] = Deployment({ name: contractName, addr: payable(addr) });
}
return deployments;
}
......@@ -260,7 +252,17 @@ abstract contract Deployer is Script {
string[] memory cmd = new string[](3);
cmd[0] = Executables.bash;
cmd[1] = "-c";
cmd[2] = string.concat(Executables.jq, " -r '.transactions[] | select(.contractAddress == ", '"', vm.toString(_addr), '"', ") | select(.transactionType == ", '"CREATE"', ")' < ", deployPath);
cmd[2] = string.concat(
Executables.jq,
" -r '.transactions[] | select(.contractAddress == ",
'"',
vm.toString(_addr),
'"',
") | select(.transactionType == ",
'"CREATE"',
")' < ",
deployPath
);
bytes memory res = vm.ffi(cmd);
return string(res);
}
......@@ -284,13 +286,16 @@ abstract contract Deployer is Script {
return code;
}
/// @notice Removes the semantic versioning from a contract name. The semver will exist if the contract is compiled more than
/// @notice Removes the semantic versioning from a contract name. The semver will exist if the contract is compiled
/// more than
/// once with different versions of the compiler.
function _stripSemver(string memory _name) internal returns (string memory) {
string[] memory cmd = new string[](3);
cmd[0] = Executables.bash;
cmd[1] = "-c";
cmd[2] = string.concat(Executables.echo, " ", _name, " | ", Executables.sed, " -E 's/[.][0-9]+\\.[0-9]+\\.[0-9]+//g'");
cmd[2] = string.concat(
Executables.echo, " ", _name, " | ", Executables.sed, " -E 's/[.][0-9]+\\.[0-9]+\\.[0-9]+//g'"
);
bytes memory res = vm.ffi(cmd);
return string(res);
}
......@@ -326,7 +331,8 @@ abstract contract Deployer is Script {
cmd[2] = string.concat(Executables.forge, " config --json | ", Executables.jq, " -r .out");
bytes memory res = vm.ffi(cmd);
string memory contractName = _stripSemver(_name);
string memory forgeArtifactPath = string.concat(vm.projectRoot(), "/", string(res), "/", contractName, ".sol/", _name, ".json");
string memory forgeArtifactPath =
string.concat(vm.projectRoot(), "/", string(res), "/", contractName, ".sol/", _name, ".json");
return forgeArtifactPath;
}
......@@ -342,7 +348,15 @@ abstract contract Deployer is Script {
string[] memory cmd = new string[](3);
cmd[0] = Executables.bash;
cmd[1] = "-c";
cmd[2] = string.concat(Executables.jq, " -r '.receipts[] | select(.contractAddress == ", '"', vm.toString(addr), '"', ")' < ", deployPath);
cmd[2] = string.concat(
Executables.jq,
" -r '.receipts[] | select(.contractAddress == ",
'"',
vm.toString(addr),
'"',
")' < ",
deployPath
);
bytes memory res = vm.ffi(cmd);
string memory receipt = string(res);
return receipt;
......@@ -400,10 +414,7 @@ abstract contract Deployer is Script {
/// @notice Adds a deployment to the temp deployments file
function _writeTemp(string memory _name, address _deployed) internal {
vm.writeJson({
json: stdJson.serialize("", _name, _deployed),
path: tempDeploymentsPath
});
vm.writeJson({ json: stdJson.serialize("", _name, _deployed), path: tempDeploymentsPath });
}
/// @notice Turns an Artifact into a json serialized string
......@@ -438,7 +449,7 @@ abstract contract Deployer is Script {
uint256 chainid = vm.envOr("CHAIN_ID", block.chainid);
if (chainid == Chains.Mainnet) {
return "mainnet";
} else if (chainid == Chains.Goerli) {
} else if (chainid == Chains.Goerli) {
return "goerli";
} else if (chainid == Chains.OPGoerli) {
return "optimism-goerli";
......@@ -471,15 +482,9 @@ abstract contract Deployer is Script {
string memory path = string.concat(deploymentsDir, "/", _name, ".json");
try vm.readFile(path) returns (string memory json) {
bytes memory addr = stdJson.parseRaw(json, "$.address");
return Deployment({
addr: abi.decode(addr, (address)),
name: _name
});
return Deployment({ addr: abi.decode(addr, (address)), name: _name });
} catch {
return Deployment({
addr: payable(address(0)),
name: ""
});
return Deployment({ addr: payable(address(0)), name: "" });
}
}
}
......@@ -54,13 +54,7 @@ contract FaultDisputeGameViz is Script, FaultDisputeGame_Init {
uint256 numClaims = uint256(vm.load(address(gameProxy), bytes32(uint256(1))));
IFaultDisputeGame.ClaimData[] memory gameData = new IFaultDisputeGame.ClaimData[](numClaims);
for (uint256 i = 0; i < numClaims; i++) {
(
uint32 parentIndex,
bool countered,
Claim claim,
Position position,
Clock clock
) = gameProxy.claimData(i);
(uint32 parentIndex, bool countered, Claim claim, Position position, Clock clock) = gameProxy.claimData(i);
gameData[i] = IFaultDisputeGame.ClaimData({
parentIndex: parentIndex,
......
......@@ -31,20 +31,20 @@ contract FeeVaultWithdrawal is Script {
address vault = vaults[i];
bool shouldCall = canWithdrawal(vault);
if (shouldCall) {
calls.push(IMulticall3.Call3({
target: vault,
allowFailure: false,
callData: abi.encodeWithSelector(FeeVault.withdraw.selector)
}));
calls.push(
IMulticall3.Call3({
target: vault,
allowFailure: false,
callData: abi.encodeWithSelector(FeeVault.withdraw.selector)
})
);
address recipient = FeeVault(payable(vault)).RECIPIENT();
uint256 balance = vault.balance;
log(balance, recipient, vault);
} else {
string memory logline = string.concat(
vm.toString(vault),
" does not have a large enough balance to withdraw."
);
string memory logline =
string.concat(vm.toString(vault), " does not have a large enough balance to withdraw.");
console.log(logline);
}
}
......@@ -67,12 +67,7 @@ contract FeeVaultWithdrawal is Script {
/// @notice Logs the information relevant to the user.
function log(uint256 _balance, address _recipient, address _vault) internal view {
string memory logline = string.concat(
"Withdrawing ",
vm.toString(_balance),
" to ",
vm.toString(_recipient),
" from ",
vm.toString(_vault)
"Withdrawing ", vm.toString(_balance), " to ", vm.toString(_recipient), " from ", vm.toString(_vault)
);
console.log(logline);
}
......
......@@ -31,11 +31,7 @@ contract SemverLock is Script {
commands = new string[](3);
commands[0] = "bash";
commands[1] = "-c";
commands[2] = string.concat(
"echo \"",
_files[i],
"\"| sed -E \'s|src/.*/(.+)\\.sol|\\1|\'"
);
commands[2] = string.concat("echo \"", _files[i], "\"| sed -E \'s|src/.*/(.+)\\.sol|\\1|\'");
string memory contractName = string(vm.ffi(commands));
commands[0] = "bash";
......@@ -44,14 +40,8 @@ contract SemverLock is Script {
string memory artifactsDir = string(vm.ffi(commands));
// Parse the artifact to get the contract's initcode hash.
bytes memory initCode = vm.getCode(string.concat(
artifactsDir,
"/",
contractName,
".sol/",
contractName,
".json"
));
bytes memory initCode =
vm.getCode(string.concat(artifactsDir, "/", contractName, ".sol/", contractName, ".json"));
// Serialize the source hash in JSON.
string memory j = vm.serializeBytes32(out, _files[i], keccak256(abi.encodePacked(fileContents, initCode)));
......
......@@ -35,7 +35,12 @@ interface IGnosisSafe {
function approveHash(bytes32 hashToApprove) external;
function approvedHashes(address, bytes32) external view returns (uint256);
function changeThreshold(uint256 _threshold) external;
function checkNSignatures(bytes32 dataHash, bytes memory data, bytes memory signatures, uint256 requiredSignatures)
function checkNSignatures(
bytes32 dataHash,
bytes memory data,
bytes memory signatures,
uint256 requiredSignatures
)
external
view;
function checkSignatures(bytes32 dataHash, bytes memory data, bytes memory signatures) external view;
......@@ -53,7 +58,10 @@ interface IGnosisSafe {
address gasToken,
address refundReceiver,
uint256 _nonce
) external view returns (bytes memory);
)
external
view
returns (bytes memory);
function execTransaction(
address to,
uint256 value,
......@@ -65,15 +73,31 @@ interface IGnosisSafe {
address gasToken,
address refundReceiver,
bytes memory signatures
) external payable returns (bool success);
function execTransactionFromModule(address to, uint256 value, bytes memory data, Enum.Operation operation)
)
external
payable
returns (bool success);
function execTransactionFromModuleReturnData(address to, uint256 value, bytes memory data, Enum.Operation operation)
function execTransactionFromModule(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
)
external
returns (bool success);
function execTransactionFromModuleReturnData(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
)
external
returns (bool success, bytes memory returnData);
function getChainId() external view returns (uint256);
function getModulesPaginated(address start, uint256 pageSize)
function getModulesPaginated(
address start,
uint256 pageSize
)
external
view
returns (address[] memory array, address next);
......@@ -91,12 +115,22 @@ interface IGnosisSafe {
address gasToken,
address refundReceiver,
uint256 _nonce
) external view returns (bytes32);
)
external
view
returns (bytes32);
function isModuleEnabled(address module) external view returns (bool);
function isOwner(address owner) external view returns (bool);
function nonce() external view returns (uint256);
function removeOwner(address prevOwner, address owner, uint256 _threshold) external;
function requiredTxGas(address to, uint256 value, bytes memory data, Enum.Operation operation) external returns (uint256);
function requiredTxGas(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
)
external
returns (uint256);
function setFallbackHandler(address handler) external;
function setGuard(address guard) external;
function setup(
......@@ -108,7 +142,8 @@ interface IGnosisSafe {
address paymentToken,
uint256 payment,
address paymentReceiver
) external;
)
external;
function signedMessages(bytes32) external view returns (uint256);
function simulateAndRevert(address targetContract, bytes memory calldataPayload) external;
function swapOwner(address prevOwner, address oldOwner, address newOwner) external;
......
......@@ -68,7 +68,7 @@ contract DeleteOutput is SafeBuilder {
}
/// @notice Test coverage of the script.
function test_script_succeeds() skipWhenNotForking external {
function test_script_succeeds() external skipWhenNotForking {
uint256 _index = getLatestIndex();
require(_index != 0, "DeleteOutput: No outputs to delete.");
......@@ -103,10 +103,7 @@ contract DeleteOutput is SafeBuilder {
calls[0] = IMulticall3.Call3({
target: oracle,
allowFailure: false,
callData: abi.encodeCall(
L2OutputOracle.deleteL2Outputs,
(index)
)
callData: abi.encodeCall(L2OutputOracle.deleteL2Outputs, (index))
});
return abi.encodeCall(IMulticall3.aggregate3, (calls));
......
......@@ -21,12 +21,10 @@ import { ProxyAdmin } from "../../src/universal/ProxyAdmin.sol";
/// for the most simple user experience when using automation and no indexer.
/// Run the command without the `--broadcast` flag and it will print a tenderly URL.
abstract contract SafeBuilder is EnhancedScript, GlobalConstants {
////////////////////////////////////////////////////////////////
// State //
////////////////////////////////////////////////////////////////
/// @notice Interface for multicall3.
IMulticall3 internal constant multicall = IMulticall3(MULTICALL3_ADDRESS);
......@@ -38,10 +36,10 @@ abstract contract SafeBuilder is EnhancedScript, GlobalConstants {
////////////////////////////////////////////////////////////////
/// @notice Follow up assertions to ensure that the script ran to completion.
function _postCheck() internal virtual view;
function _postCheck() internal view virtual;
/// @notice Creates the calldata
function buildCalldata(address _proxyAdmin) internal virtual view returns (bytes memory);
function buildCalldata(address _proxyAdmin) internal view virtual returns (bytes memory);
/// @notice Internal helper function to compute the safe transaction hash.
function computeSafeTransactionHash(address _safe, address _proxyAdmin) public virtual returns (bytes32) {
......@@ -119,11 +117,7 @@ abstract contract SafeBuilder is EnhancedScript, GlobalConstants {
// Send a transaction to approve the hash
safe.approveHash(hash);
logSimulationLink({
_to: address(safe),
_from: msg.sender,
_data: abi.encodeCall(safe.approveHash, (hash))
});
logSimulationLink({ _to: address(safe), _from: msg.sender, _data: abi.encodeCall(safe.approveHash, (hash)) });
uint256 threshold = safe.getThreshold();
address[] memory owners = safe.getOwners();
......@@ -169,7 +163,7 @@ abstract contract SafeBuilder is EnhancedScript, GlobalConstants {
payable(address(0)),
signatures
)
)
)
});
require(success, "call not successful");
......@@ -206,4 +200,3 @@ abstract contract SafeBuilder is EnhancedScript, GlobalConstants {
return signatures;
}
}
......@@ -28,31 +28,26 @@ contract EASUpgrader is SafeBuilder, Deployer {
mapping(uint256 => ContractSet) internal proxies;
/// @notice The expected versions for the contracts to be upgraded to.
string constant internal EAS_Version = "1.0.0";
string constant internal SchemaRegistry_Version = "1.0.0";
string internal constant EAS_Version = "1.0.0";
string internal constant SchemaRegistry_Version = "1.0.0";
/// @notice Place the contract addresses in storage so they can be used when building calldata.
function setUp() public override {
super.setUp();
implementations[OP_GOERLI] = ContractSet({
EAS: getAddress("EAS"),
SchemaRegistry: getAddress("SchemaRegistry")
});
implementations[OP_GOERLI] =
ContractSet({ EAS: getAddress("EAS"), SchemaRegistry: getAddress("SchemaRegistry") });
proxies[OP_GOERLI] = ContractSet({
EAS: Predeploys.EAS,
SchemaRegistry: Predeploys.SCHEMA_REGISTRY
});
proxies[OP_GOERLI] = ContractSet({ EAS: Predeploys.EAS, SchemaRegistry: Predeploys.SCHEMA_REGISTRY });
}
/// @notice
function name() public override pure returns (string memory) {
function name() public pure override returns (string memory) {
return "EASUpgrader";
}
/// @notice Follow up assertions to ensure that the script ran to completion.
function _postCheck() internal override view {
function _postCheck() internal view override {
ContractSet memory prox = getProxies();
require(_versionHash(prox.EAS) == keccak256(bytes(EAS_Version)), "EAS");
require(_versionHash(prox.SchemaRegistry) == keccak256(bytes(SchemaRegistry_Version)), "SchemaRegistry");
......@@ -65,7 +60,7 @@ contract EASUpgrader is SafeBuilder, Deployer {
/// @notice Test coverage of the logic. Should only run on goerli but other chains
/// could be added.
function test_script_succeeds() skipWhenNotForking external {
function test_script_succeeds() external skipWhenNotForking {
address _safe;
address _proxyAdmin;
......@@ -96,7 +91,7 @@ contract EASUpgrader is SafeBuilder, Deployer {
/// @notice Builds the calldata that the multisig needs to make for the upgrade to happen.
/// A total of 9 calls are made to the proxy admin to upgrade the implementations
/// of the predeploys.
function buildCalldata(address _proxyAdmin) internal override view returns (bytes memory) {
function buildCalldata(address _proxyAdmin) internal view override returns (bytes memory) {
IMulticall3.Call3[] memory calls = new IMulticall3.Call3[](2);
ContractSet memory impl = getImplementations();
......@@ -106,20 +101,14 @@ contract EASUpgrader is SafeBuilder, Deployer {
calls[0] = IMulticall3.Call3({
target: _proxyAdmin,
allowFailure: false,
callData: abi.encodeCall(
ProxyAdmin.upgrade,
(payable(prox.EAS), impl.EAS)
)
callData: abi.encodeCall(ProxyAdmin.upgrade, (payable(prox.EAS), impl.EAS))
});
// Upgrade SchemaRegistry
calls[1] = IMulticall3.Call3({
target: _proxyAdmin,
allowFailure: false,
callData: abi.encodeCall(
ProxyAdmin.upgrade,
(payable(prox.SchemaRegistry), impl.SchemaRegistry)
)
callData: abi.encodeCall(ProxyAdmin.upgrade, (payable(prox.SchemaRegistry), impl.SchemaRegistry))
});
return abi.encodeCall(IMulticall3.aggregate3, (calls));
......
......@@ -15,7 +15,6 @@ import { Semver } from "../../src/universal/Semver.sol";
/// @title PostSherlockL1
/// @notice Upgrade script for upgrading the L1 contracts after the sherlock audit.
contract PostSherlockL1 is SafeBuilder {
/// @notice Address of the ProxyAdmin, passed in via constructor of `run`.
ProxyAdmin internal PROXY_ADMIN;
......@@ -38,13 +37,13 @@ contract PostSherlockL1 is SafeBuilder {
mapping(uint256 => ContractSet) internal proxies;
/// @notice The expected versions for the contracts to be upgraded to.
string constant internal L1CrossDomainMessenger_Version = "1.4.0";
string constant internal L1StandardBridge_Version = "1.1.0";
string constant internal L2OutputOracle_Version = "1.3.0";
string constant internal OptimismMintableERC20Factory_Version = "1.1.0";
string constant internal OptimismPortal_Version = "1.6.0";
string constant internal SystemConfig_Version = "1.3.0";
string constant internal L1ERC721Bridge_Version = "1.1.1";
string internal constant L1CrossDomainMessenger_Version = "1.4.0";
string internal constant L1StandardBridge_Version = "1.1.0";
string internal constant L2OutputOracle_Version = "1.3.0";
string internal constant OptimismMintableERC20Factory_Version = "1.1.0";
string internal constant OptimismPortal_Version = "1.6.0";
string internal constant SystemConfig_Version = "1.3.0";
string internal constant L1ERC721Bridge_Version = "1.1.1";
/// @notice Place the contract addresses in storage so they can be used when building calldata.
function setUp() external {
......@@ -70,12 +69,18 @@ contract PostSherlockL1 is SafeBuilder {
}
/// @notice Follow up assertions to ensure that the script ran to completion.
function _postCheck() internal override view {
function _postCheck() internal view override {
ContractSet memory prox = getProxies();
require(_versionHash(prox.L1CrossDomainMessenger) == keccak256(bytes(L1CrossDomainMessenger_Version)), "L1CrossDomainMessenger");
require(
_versionHash(prox.L1CrossDomainMessenger) == keccak256(bytes(L1CrossDomainMessenger_Version)),
"L1CrossDomainMessenger"
);
require(_versionHash(prox.L1StandardBridge) == keccak256(bytes(L1StandardBridge_Version)), "L1StandardBridge");
require(_versionHash(prox.L2OutputOracle) == keccak256(bytes(L2OutputOracle_Version)), "L2OutputOracle");
require(_versionHash(prox.OptimismMintableERC20Factory) == keccak256(bytes(OptimismMintableERC20Factory_Version)), "OptimismMintableERC20Factory");
require(
_versionHash(prox.OptimismMintableERC20Factory) == keccak256(bytes(OptimismMintableERC20Factory_Version)),
"OptimismMintableERC20Factory"
);
require(_versionHash(prox.OptimismPortal) == keccak256(bytes(OptimismPortal_Version)), "OptimismPortal");
require(_versionHash(prox.SystemConfig) == keccak256(bytes(SystemConfig_Version)), "SystemConfig");
require(_versionHash(prox.L1ERC721Bridge) == keccak256(bytes(L1ERC721Bridge_Version)), "L1ERC721Bridge");
......@@ -86,18 +91,41 @@ contract PostSherlockL1 is SafeBuilder {
// Check that the codehashes of all implementations match the proxies set implementations.
ContractSet memory impl = getImplementations();
require(PROXY_ADMIN.getProxyImplementation(prox.L1CrossDomainMessenger).codehash == impl.L1CrossDomainMessenger.codehash, "L1CrossDomainMessenger codehash");
require(PROXY_ADMIN.getProxyImplementation(prox.L1StandardBridge).codehash == impl.L1StandardBridge.codehash, "L1StandardBridge codehash");
require(PROXY_ADMIN.getProxyImplementation(prox.L2OutputOracle).codehash == impl.L2OutputOracle.codehash, "L2OutputOracle codehash");
require(PROXY_ADMIN.getProxyImplementation(prox.OptimismMintableERC20Factory).codehash == impl.OptimismMintableERC20Factory.codehash, "OptimismMintableERC20Factory codehash");
require(PROXY_ADMIN.getProxyImplementation(prox.OptimismPortal).codehash == impl.OptimismPortal.codehash, "OptimismPortal codehash");
require(PROXY_ADMIN.getProxyImplementation(prox.SystemConfig).codehash == impl.SystemConfig.codehash, "SystemConfig codehash");
require(PROXY_ADMIN.getProxyImplementation(prox.L1ERC721Bridge).codehash == impl.L1ERC721Bridge.codehash, "L1ERC721Bridge codehash");
require(
PROXY_ADMIN.getProxyImplementation(prox.L1CrossDomainMessenger).codehash
== impl.L1CrossDomainMessenger.codehash,
"L1CrossDomainMessenger codehash"
);
require(
PROXY_ADMIN.getProxyImplementation(prox.L1StandardBridge).codehash == impl.L1StandardBridge.codehash,
"L1StandardBridge codehash"
);
require(
PROXY_ADMIN.getProxyImplementation(prox.L2OutputOracle).codehash == impl.L2OutputOracle.codehash,
"L2OutputOracle codehash"
);
require(
PROXY_ADMIN.getProxyImplementation(prox.OptimismMintableERC20Factory).codehash
== impl.OptimismMintableERC20Factory.codehash,
"OptimismMintableERC20Factory codehash"
);
require(
PROXY_ADMIN.getProxyImplementation(prox.OptimismPortal).codehash == impl.OptimismPortal.codehash,
"OptimismPortal codehash"
);
require(
PROXY_ADMIN.getProxyImplementation(prox.SystemConfig).codehash == impl.SystemConfig.codehash,
"SystemConfig codehash"
);
require(
PROXY_ADMIN.getProxyImplementation(prox.L1ERC721Bridge).codehash == impl.L1ERC721Bridge.codehash,
"L1ERC721Bridge codehash"
);
}
/// @notice Test coverage of the logic. Should only run on goerli but other chains
/// could be added.
function test_script_succeeds() skipWhenNotForking external {
function test_script_succeeds() external skipWhenNotForking {
address _safe;
address _proxyAdmin;
......@@ -130,7 +158,7 @@ contract PostSherlockL1 is SafeBuilder {
/// @notice Builds the calldata that the multisig needs to make for the upgrade to happen.
/// A total of 8 calls are made, 7 upgrade implementations and 1 sets the resource
/// config to the default value in the SystemConfig contract.
function buildCalldata(address _proxyAdmin) internal override view returns (bytes memory) {
function buildCalldata(address _proxyAdmin) internal view override returns (bytes memory) {
IMulticall3.Call3[] memory calls = new IMulticall3.Call3[](8);
ContractSet memory impl = getImplementations();
......@@ -141,29 +169,22 @@ contract PostSherlockL1 is SafeBuilder {
target: _proxyAdmin,
allowFailure: false,
callData: abi.encodeCall(
ProxyAdmin.upgrade,
(payable(prox.L1CrossDomainMessenger), impl.L1CrossDomainMessenger)
)
ProxyAdmin.upgrade, (payable(prox.L1CrossDomainMessenger), impl.L1CrossDomainMessenger)
)
});
// Upgrade the L1StandardBridge
calls[1] = IMulticall3.Call3({
target: _proxyAdmin,
allowFailure: false,
callData: abi.encodeCall(
ProxyAdmin.upgrade,
(payable(prox.L1StandardBridge), impl.L1StandardBridge)
)
callData: abi.encodeCall(ProxyAdmin.upgrade, (payable(prox.L1StandardBridge), impl.L1StandardBridge))
});
// Upgrade the L2OutputOracle
calls[2] = IMulticall3.Call3({
target: _proxyAdmin,
allowFailure: false,
callData: abi.encodeCall(
ProxyAdmin.upgrade,
(payable(prox.L2OutputOracle), impl.L2OutputOracle)
)
callData: abi.encodeCall(ProxyAdmin.upgrade, (payable(prox.L2OutputOracle), impl.L2OutputOracle))
});
// Upgrade the OptimismMintableERC20Factory
......@@ -171,39 +192,29 @@ contract PostSherlockL1 is SafeBuilder {
target: _proxyAdmin,
allowFailure: false,
callData: abi.encodeCall(
ProxyAdmin.upgrade,
(payable(prox.OptimismMintableERC20Factory), impl.OptimismMintableERC20Factory)
)
ProxyAdmin.upgrade, (payable(prox.OptimismMintableERC20Factory), impl.OptimismMintableERC20Factory)
)
});
// Upgrade the OptimismPortal
calls[4] = IMulticall3.Call3({
target: _proxyAdmin,
allowFailure: false,
callData: abi.encodeCall(
ProxyAdmin.upgrade,
(payable(prox.OptimismPortal), impl.OptimismPortal)
)
callData: abi.encodeCall(ProxyAdmin.upgrade, (payable(prox.OptimismPortal), impl.OptimismPortal))
});
// Upgrade the SystemConfig
calls[5] = IMulticall3.Call3({
target: _proxyAdmin,
allowFailure: false,
callData: abi.encodeCall(
ProxyAdmin.upgrade,
(payable(prox.SystemConfig), impl.SystemConfig)
)
callData: abi.encodeCall(ProxyAdmin.upgrade, (payable(prox.SystemConfig), impl.SystemConfig))
});
// Upgrade the L1ERC721Bridge
calls[6] = IMulticall3.Call3({
target: _proxyAdmin,
allowFailure: false,
callData: abi.encodeCall(
ProxyAdmin.upgrade,
(payable(prox.L1ERC721Bridge), impl.L1ERC721Bridge)
)
callData: abi.encodeCall(ProxyAdmin.upgrade, (payable(prox.L1ERC721Bridge), impl.L1ERC721Bridge))
});
// Set the default resource config
......
This diff is collapsed.
......@@ -11,7 +11,8 @@ struct AttestationRequestData {
bool revocable; // Whether the attestation is revocable.
bytes32 refUID; // The UID of the related attestation.
bytes data; // Custom attestation data.
uint256 value; // An explicit ETH amount to send to the resolver. This is important to prevent accidental user errors.
uint256 value; // An explicit ETH amount to send to the resolver. This is important to prevent accidental user
// errors.
}
/// @dev A struct representing the full arguments of the attestation request.
......@@ -38,14 +39,16 @@ struct MultiAttestationRequest {
struct MultiDelegatedAttestationRequest {
bytes32 schema; // The unique identifier of the schema.
AttestationRequestData[] data; // The arguments of the attestation requests.
EIP712Signature[] signatures; // The EIP712 signatures data. Please note that the signatures are assumed to be signed with increasing nonces.
EIP712Signature[] signatures; // The EIP712 signatures data. Please note that the signatures are assumed to be
// signed with increasing nonces.
address attester; // The attesting account.
}
/// @dev A struct representing the arguments of the revocation request.
struct RevocationRequestData {
bytes32 uid; // The UID of the attestation to revoke.
uint256 value; // An explicit ETH amount to send to the resolver. This is important to prevent accidental user errors.
uint256 value; // An explicit ETH amount to send to the resolver. This is important to prevent accidental user
// errors.
}
/// @dev A struct representing the full arguments of the revocation request.
......@@ -72,7 +75,8 @@ struct MultiRevocationRequest {
struct MultiDelegatedRevocationRequest {
bytes32 schema; // The unique identifier of the schema.
RevocationRequestData[] data; // The arguments of the revocation requests.
EIP712Signature[] signatures; // The EIP712 signatures data. Please note that the signatures are assumed to be signed with increasing nonces.
EIP712Signature[] signatures; // The EIP712 signatures data. Please note that the signatures are assumed to be
// signed with increasing nonces.
address revoker; // The revoking account.
}
......@@ -152,9 +156,10 @@ interface IEAS {
///
/// @param delegatedRequest The arguments of the delegated attestation request.
/// @return The UID of the new attestation.
function attestByDelegation(
DelegatedAttestationRequest calldata delegatedRequest
) external payable returns (bytes32);
function attestByDelegation(DelegatedAttestationRequest calldata delegatedRequest)
external
payable
returns (bytes32);
/// @notice Attests to multiple schemas.
///
......@@ -194,7 +199,10 @@ interface IEAS {
/// @param multiRequests The arguments of the multi attestation requests. The requests should be grouped by distinct
/// schema ids to benefit from the best batching optimization.
/// @return The UIDs of the new attestations.
function multiAttest(MultiAttestationRequest[] calldata multiRequests) external payable returns (bytes32[] memory);
function multiAttest(MultiAttestationRequest[] calldata multiRequests)
external
payable
returns (bytes32[] memory);
/// @notice Attests to multiple schemas using via provided EIP712 signatures.
///
......@@ -234,9 +242,10 @@ interface IEAS {
/// @param multiDelegatedRequests The arguments of the delegated multi attestation requests. The requests should be
/// grouped by distinct schema ids to benefit from the best batching optimization.
/// @return The UIDs of the new attestations.
function multiAttestByDelegation(
MultiDelegatedAttestationRequest[] calldata multiDelegatedRequests
) external payable returns (bytes32[] memory);
function multiAttestByDelegation(MultiDelegatedAttestationRequest[] calldata multiDelegatedRequests)
external
payable
returns (bytes32[] memory);
/// @notice Revokes an existing attestation to a specific schema.
///
......@@ -328,11 +337,12 @@ interface IEAS {
/// revoker: '0x244934dd3e31bE2c81f84ECf0b3E6329F5381992'
/// }])
///
/// @param multiDelegatedRequests The arguments of the delegated multi revocation attestation requests. The requests should be
/// @param multiDelegatedRequests The arguments of the delegated multi revocation attestation requests. The requests
/// should be
/// grouped by distinct schema ids to benefit from the best batching optimization.
function multiRevokeByDelegation(
MultiDelegatedRevocationRequest[] calldata multiDelegatedRequests
) external payable;
function multiRevokeByDelegation(MultiDelegatedRevocationRequest[] calldata multiDelegatedRequests)
external
payable;
/// @notice Timestamps the specified bytes32 data.
/// @param data The data to timestamp.
......
......@@ -22,16 +22,12 @@ contract SchemaRegistry is ISchemaRegistry, Semver {
uint256[MAX_GAP - 1] private __gap;
/// @dev Creates a new SchemaRegistry instance.
constructor() Semver(1, 0, 1) {}
constructor() Semver(1, 0, 1) { }
/// @inheritdoc ISchemaRegistry
function register(string calldata schema, ISchemaResolver resolver, bool revocable) external returns (bytes32) {
SchemaRecord memory schemaRecord = SchemaRecord({
uid: EMPTY_UID,
schema: schema,
resolver: resolver,
revocable: revocable
});
SchemaRecord memory schemaRecord =
SchemaRecord({ uid: EMPTY_UID, schema: schema, resolver: resolver, revocable: revocable });
bytes32 uid = _getUID(schemaRecord);
if (_registry[uid].uid != EMPTY_UID) {
......
......@@ -20,7 +20,8 @@ import { EIP712Signature, InvalidSignature, MAX_GAP, stringToBytes32, bytes32ToS
/// @notice The EIP712 typed signatures verifier for EAS delegated attestations.
abstract contract EIP712Verifier is EIP712 {
// The hash of the data type used to relay calls to the attest function. It's the value of
// keccak256("Attest(bytes32 schema,address recipient,uint64 expirationTime,bool revocable,bytes32 refUID,bytes data,uint256 nonce)").
// keccak256("Attest(bytes32 schema,address recipient,uint64 expirationTime,bool revocable,bytes32 refUID,bytes
// data,uint256 nonce)").
bytes32 private constant ATTEST_TYPEHASH = 0xdbfdf8dc2b135c26253e00d5b6cbe6f20457e003fd526d97cea183883570de61;
// The hash of the data type used to relay calls to the revoke function. It's the value of
......
......@@ -22,7 +22,10 @@ interface ISchemaResolver {
function multiAttest(
Attestation[] calldata attestations,
uint256[] calldata values
) external payable returns (bool);
)
external
payable
returns (bool);
/// @notice Processes an attestation revocation and verifies if it can be revoked.
/// @param attestation The existing attestation to be revoked.
......@@ -36,5 +39,8 @@ interface ISchemaResolver {
function multiRevoke(
Attestation[] calldata attestations,
uint256[] calldata values
) external payable returns (bool);
)
external
payable
returns (bool);
}
......@@ -56,7 +56,12 @@ abstract contract SchemaResolver is ISchemaResolver, Semver {
function multiAttest(
Attestation[] calldata attestations,
uint256[] calldata values
) external payable onlyEAS returns (bool) {
)
external
payable
onlyEAS
returns (bool)
{
uint256 length = attestations.length;
// We are keeping track of the remaining ETH amount that can be sent to resolvers and will keep deducting
......@@ -95,7 +100,12 @@ abstract contract SchemaResolver is ISchemaResolver, Semver {
function multiRevoke(
Attestation[] calldata attestations,
uint256[] calldata values
) external payable onlyEAS returns (bool) {
)
external
payable
onlyEAS
returns (bool)
{
uint256 length = attestations.length;
// We are keeping track of the remaining ETH amount that can be sent to resolvers and will keep deducting
......@@ -128,8 +138,10 @@ abstract contract SchemaResolver is ISchemaResolver, Semver {
/// @notice A resolver callback that should be implemented by child contracts.
/// @param attestation The new attestation.
/// @param value An explicit ETH amount that was sent to the resolver. Please note that this value is verified in
/// both attest() and multiAttest() callbacks EAS-only callbacks and that in case of multi attestations, it'll
/// usually hold that msg.value != value, since msg.value aggregated the sent ETH amounts for all the attestations
/// both attest() and multiAttest() callbacks EAS-only callbacks and that in case of multi attestations,
/// it'll
/// usually hold that msg.value != value, since msg.value aggregated the sent ETH amounts for all the
/// attestations
/// in the batch.
/// @return Whether the attestation is valid.
function onAttest(Attestation calldata attestation, uint256 value) internal virtual returns (bool);
......@@ -137,8 +149,10 @@ abstract contract SchemaResolver is ISchemaResolver, Semver {
/// @notice Processes an attestation revocation and verifies if it can be revoked.
/// @param attestation The existing attestation to be revoked.
/// @param value An explicit ETH amount that was sent to the resolver. Please note that this value is verified in
/// both revoke() and multiRevoke() callbacks EAS-only callbacks and that in case of multi attestations, it'll
/// usually hold that msg.value != value, since msg.value aggregated the sent ETH amounts for all the attestations
/// both revoke() and multiRevoke() callbacks EAS-only callbacks and that in case of multi attestations,
/// it'll
/// usually hold that msg.value != value, since msg.value aggregated the sent ETH amounts for all the
/// attestations
/// in the batch.
/// @return Whether the attestation can be revoked.
function onRevoke(Attestation calldata attestation, uint256 value) internal virtual returns (bool);
......
......@@ -37,12 +37,7 @@ contract L1CrossDomainMessenger is CrossDomainMessenger, Semver {
}
/// @inheritdoc CrossDomainMessenger
function _sendMessage(
address _to,
uint64 _gasLimit,
uint256 _value,
bytes memory _data
) internal override {
function _sendMessage(address _to, uint64 _gasLimit, uint256 _value, bytes memory _data) internal override {
PORTAL.depositTransaction{ value: _value }(_to, _value, _gasLimit, false, _data);
}
......
......@@ -46,7 +46,10 @@ contract L1ERC721Bridge is ERC721Bridge, Semver {
address _to,
uint256 _tokenId,
bytes calldata _extraData
) external onlyOtherBridge {
)
external
onlyOtherBridge
{
require(_localToken != address(this), "L1ERC721Bridge: local token cannot be self");
// Checks that the L1/L2 NFT pair has a token ID that is escrowed in the L1 Bridge.
......@@ -76,18 +79,15 @@ contract L1ERC721Bridge is ERC721Bridge, Semver {
uint256 _tokenId,
uint32 _minGasLimit,
bytes calldata _extraData
) internal override {
)
internal
override
{
require(_remoteToken != address(0), "L1ERC721Bridge: remote token cannot be address(0)");
// Construct calldata for _l2Token.finalizeBridgeERC721(_to, _tokenId)
bytes memory message = abi.encodeWithSelector(
L2ERC721Bridge.finalizeBridgeERC721.selector,
_remoteToken,
_localToken,
_from,
_to,
_tokenId,
_extraData
L2ERC721Bridge.finalizeBridgeERC721.selector, _remoteToken, _localToken, _from, _to, _tokenId, _extraData
);
// Lock token into bridge
......
......@@ -23,12 +23,7 @@ contract L1StandardBridge is StandardBridge, Semver {
/// @param to Address of the recipient on L2.
/// @param amount Amount of ETH deposited.
/// @param extraData Extra data attached to the deposit.
event ETHDepositInitiated(
address indexed from,
address indexed to,
uint256 amount,
bytes extraData
);
event ETHDepositInitiated(address indexed from, address indexed to, uint256 amount, bytes extraData);
/// @custom:legacy
/// @notice Emitted whenever a withdrawal of ETH from L2 to L1 is finalized.
......@@ -36,12 +31,7 @@ contract L1StandardBridge is StandardBridge, Semver {
/// @param to Address of the recipient on L1.
/// @param amount Amount of ETH withdrawn.
/// @param extraData Extra data attached to the withdrawal.
event ETHWithdrawalFinalized(
address indexed from,
address indexed to,
uint256 amount,
bytes extraData
);
event ETHWithdrawalFinalized(address indexed from, address indexed to, uint256 amount, bytes extraData);
/// @custom:legacy
/// @notice Emitted whenever an ERC20 deposit is initiated.
......@@ -79,10 +69,7 @@ contract L1StandardBridge is StandardBridge, Semver {
/// @custom:semver 1.2.0
/// @notice Constructs the L1StandardBridge contract.
constructor()
Semver(1, 2, 0)
StandardBridge(StandardBridge(payable(Predeploys.L2_STANDARD_BRIDGE)))
{
constructor() Semver(1, 2, 0) StandardBridge(StandardBridge(payable(Predeploys.L2_STANDARD_BRIDGE))) {
initialize({ _messenger: CrossDomainMessenger(address(0)) });
}
......@@ -130,11 +117,7 @@ contract L1StandardBridge is StandardBridge, Semver {
/// @param _extraData Optional data to forward to L2.
/// Data supplied here will not be used to execute any code on L2 and is
/// only emitted as extra data for the convenience of off-chain tooling.
function depositETHTo(
address _to,
uint32 _minGasLimit,
bytes calldata _extraData
) external payable {
function depositETHTo(address _to, uint32 _minGasLimit, bytes calldata _extraData) external payable {
_initiateETHDeposit(msg.sender, _to, _minGasLimit, _extraData);
}
......@@ -153,16 +136,12 @@ contract L1StandardBridge is StandardBridge, Semver {
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _extraData
) external virtual onlyEOA {
_initiateERC20Deposit(
_l1Token,
_l2Token,
msg.sender,
msg.sender,
_amount,
_minGasLimit,
_extraData
);
)
external
virtual
onlyEOA
{
_initiateERC20Deposit(_l1Token, _l2Token, msg.sender, msg.sender, _amount, _minGasLimit, _extraData);
}
/// @custom:legacy
......@@ -182,16 +161,11 @@ contract L1StandardBridge is StandardBridge, Semver {
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _extraData
) external virtual {
_initiateERC20Deposit(
_l1Token,
_l2Token,
msg.sender,
_to,
_amount,
_minGasLimit,
_extraData
);
)
external
virtual
{
_initiateERC20Deposit(_l1Token, _l2Token, msg.sender, _to, _amount, _minGasLimit, _extraData);
}
/// @custom:legacy
......@@ -205,7 +179,10 @@ contract L1StandardBridge is StandardBridge, Semver {
address _to,
uint256 _amount,
bytes calldata _extraData
) external payable {
)
external
payable
{
finalizeBridgeETH(_from, _to, _amount, _extraData);
}
......@@ -224,7 +201,9 @@ contract L1StandardBridge is StandardBridge, Semver {
address _to,
uint256 _amount,
bytes calldata _extraData
) external {
)
external
{
finalizeBridgeERC20(_l1Token, _l2Token, _from, _to, _amount, _extraData);
}
......@@ -240,12 +219,7 @@ contract L1StandardBridge is StandardBridge, Semver {
/// @param _to Address of the recipient on L2.
/// @param _minGasLimit Minimum gas limit for the deposit message on L2.
/// @param _extraData Optional data to forward to L2.
function _initiateETHDeposit(
address _from,
address _to,
uint32 _minGasLimit,
bytes memory _extraData
) internal {
function _initiateETHDeposit(address _from, address _to, uint32 _minGasLimit, bytes memory _extraData) internal {
_initiateBridgeETH(_from, _to, msg.value, _minGasLimit, _extraData);
}
......@@ -265,7 +239,9 @@ contract L1StandardBridge is StandardBridge, Semver {
uint256 _amount,
uint32 _minGasLimit,
bytes memory _extraData
) internal {
)
internal
{
_initiateBridgeERC20(_l1Token, _l2Token, _from, _to, _amount, _minGasLimit, _extraData);
}
......@@ -277,7 +253,10 @@ contract L1StandardBridge is StandardBridge, Semver {
address _to,
uint256 _amount,
bytes memory _extraData
) internal override {
)
internal
override
{
emit ETHDepositInitiated(_from, _to, _amount, _extraData);
super._emitETHBridgeInitiated(_from, _to, _amount, _extraData);
}
......@@ -290,7 +269,10 @@ contract L1StandardBridge is StandardBridge, Semver {
address _to,
uint256 _amount,
bytes memory _extraData
) internal override {
)
internal
override
{
emit ETHWithdrawalFinalized(_from, _to, _amount, _extraData);
super._emitETHBridgeFinalized(_from, _to, _amount, _extraData);
}
......@@ -305,7 +287,10 @@ contract L1StandardBridge is StandardBridge, Semver {
address _to,
uint256 _amount,
bytes memory _extraData
) internal override {
)
internal
override
{
emit ERC20DepositInitiated(_localToken, _remoteToken, _from, _to, _amount, _extraData);
super._emitERC20BridgeInitiated(_localToken, _remoteToken, _from, _to, _amount, _extraData);
}
......@@ -320,7 +305,10 @@ contract L1StandardBridge is StandardBridge, Semver {
address _to,
uint256 _amount,
bytes memory _extraData
) internal override {
)
internal
override
{
emit ERC20WithdrawalFinalized(_localToken, _remoteToken, _from, _to, _amount, _extraData);
super._emitERC20BridgeFinalized(_localToken, _remoteToken, _from, _to, _amount, _extraData);
}
......
......@@ -54,10 +54,7 @@ contract L2OutputOracle is Initializable, Semver {
/// @param l2BlockNumber The L2 block number of the output root.
/// @param l1Timestamp The L1 timestamp when proposed.
event OutputProposed(
bytes32 indexed outputRoot,
uint256 indexed l2OutputIndex,
uint256 indexed l2BlockNumber,
uint256 l1Timestamp
bytes32 indexed outputRoot, uint256 indexed l2OutputIndex, uint256 indexed l2BlockNumber, uint256 l1Timestamp
);
/// @notice Emitted when outputs are deleted.
......@@ -75,23 +72,17 @@ contract L2OutputOracle is Initializable, Semver {
uint256 _submissionInterval,
uint256 _l2BlockTime,
uint256 _finalizationPeriodSeconds
) Semver(1, 4, 0) {
)
Semver(1, 4, 0)
{
require(_l2BlockTime > 0, "L2OutputOracle: L2 block time must be greater than 0");
require(
_submissionInterval > 0,
"L2OutputOracle: submission interval must be greater than 0"
);
require(_submissionInterval > 0, "L2OutputOracle: submission interval must be greater than 0");
SUBMISSION_INTERVAL = _submissionInterval;
L2_BLOCK_TIME = _l2BlockTime;
FINALIZATION_PERIOD_SECONDS = _finalizationPeriodSeconds;
initialize({
_startingBlockNumber: 0,
_startingTimestamp: 0,
_proposer: address(0),
_challenger: address(0)
});
initialize({ _startingBlockNumber: 0, _startingTimestamp: 0, _proposer: address(0), _challenger: address(0) });
}
/// @notice Initializer.
......@@ -104,7 +95,10 @@ contract L2OutputOracle is Initializable, Semver {
uint256 _startingTimestamp,
address _proposer,
address _challenger
) public reinitializer(2) {
)
public
reinitializer(2)
{
require(
_startingTimestamp <= block.timestamp,
"L2OutputOracle: starting L2 timestamp must be less than current time"
......@@ -151,15 +145,11 @@ contract L2OutputOracle is Initializable, Semver {
/// All outputs after this output will also be deleted.
// solhint-disable-next-line ordering
function deleteL2Outputs(uint256 _l2OutputIndex) external {
require(
msg.sender == challenger,
"L2OutputOracle: only the challenger address can delete outputs"
);
require(msg.sender == challenger, "L2OutputOracle: only the challenger address can delete outputs");
// Make sure we're not *increasing* the length of the array.
require(
_l2OutputIndex < l2Outputs.length,
"L2OutputOracle: cannot delete outputs after the latest output index"
_l2OutputIndex < l2Outputs.length, "L2OutputOracle: cannot delete outputs after the latest output index"
);
// Do not allow deleting any outputs that have already been finalized.
......@@ -190,11 +180,11 @@ contract L2OutputOracle is Initializable, Semver {
uint256 _l2BlockNumber,
bytes32 _l1BlockHash,
uint256 _l1BlockNumber
) external payable {
require(
msg.sender == proposer,
"L2OutputOracle: only the proposer address can propose new outputs"
);
)
external
payable
{
require(msg.sender == proposer, "L2OutputOracle: only the proposer address can propose new outputs");
require(
_l2BlockNumber == nextBlockNumber(),
......@@ -206,10 +196,7 @@ contract L2OutputOracle is Initializable, Semver {
"L2OutputOracle: cannot propose L2 output in the future"
);
require(
_outputRoot != bytes32(0),
"L2OutputOracle: L2 output proposal cannot be the zero hash"
);
require(_outputRoot != bytes32(0), "L2OutputOracle: L2 output proposal cannot be the zero hash");
if (_l1BlockHash != bytes32(0)) {
// This check allows the proposer to propose an output based on a given L1 block,
......@@ -240,11 +227,7 @@ contract L2OutputOracle is Initializable, Semver {
/// @notice Returns an output by index. Needed to return a struct instead of a tuple.
/// @param _l2OutputIndex Index of the output to return.
/// @return The output at the given index.
function getL2Output(uint256 _l2OutputIndex)
external
view
returns (Types.OutputProposal memory)
{
function getL2Output(uint256 _l2OutputIndex) external view returns (Types.OutputProposal memory) {
return l2Outputs[_l2OutputIndex];
}
......@@ -261,10 +244,7 @@ contract L2OutputOracle is Initializable, Semver {
);
// Make sure there's at least one output proposed.
require(
l2Outputs.length > 0,
"L2OutputOracle: cannot get output as no outputs have been proposed yet"
);
require(l2Outputs.length > 0, "L2OutputOracle: cannot get output as no outputs have been proposed yet");
// Find the output via binary search, guaranteed to exist.
uint256 lo = 0;
......@@ -286,11 +266,7 @@ contract L2OutputOracle is Initializable, Semver {
/// block.
/// @param _l2BlockNumber L2 block number to find a checkpoint for.
/// @return First checkpoint that commits to the given L2 block number.
function getL2OutputAfter(uint256 _l2BlockNumber)
external
view
returns (Types.OutputProposal memory)
{
function getL2OutputAfter(uint256 _l2BlockNumber) external view returns (Types.OutputProposal memory) {
return l2Outputs[getL2OutputIndexAfter(_l2BlockNumber)];
}
......@@ -312,10 +288,7 @@ contract L2OutputOracle is Initializable, Semver {
/// block number.
/// @return Latest submitted L2 block number.
function latestBlockNumber() public view returns (uint256) {
return
l2Outputs.length == 0
? startingBlockNumber
: l2Outputs[l2Outputs.length - 1].l2BlockNumber;
return l2Outputs.length == 0 ? startingBlockNumber : l2Outputs[l2Outputs.length - 1].l2BlockNumber;
}
/// @notice Computes the block number of the next L2 block that needs to be checkpointed.
......
......@@ -70,22 +70,13 @@ contract OptimismPortal is Initializable, ResourceMetering, Semver {
/// @param to Address that the deposit transaction is directed to.
/// @param version Version of this deposit transaction event.
/// @param opaqueData ABI encoded deposit data to be parsed off-chain.
event TransactionDeposited(
address indexed from,
address indexed to,
uint256 indexed version,
bytes opaqueData
);
event TransactionDeposited(address indexed from, address indexed to, uint256 indexed version, bytes opaqueData);
/// @notice Emitted when a withdrawal transaction is proven.
/// @param withdrawalHash Hash of the withdrawal transaction.
/// @param from Address that triggered the withdrawal transaction.
/// @param to Address that the withdrawal transaction is directed to.
event WithdrawalProven(
bytes32 indexed withdrawalHash,
address indexed from,
address indexed to
);
event WithdrawalProven(bytes32 indexed withdrawalHash, address indexed from, address indexed to);
/// @notice Emitted when a withdrawal transaction is finalized.
/// @param withdrawalHash Hash of the withdrawal transaction.
......@@ -127,7 +118,10 @@ contract OptimismPortal is Initializable, ResourceMetering, Semver {
address _guardian,
SystemConfig _systemConfig,
bool _paused
) public reinitializer(2) {
)
public
reinitializer(2)
{
l2Sender = Constants.DEFAULT_L2_SENDER;
l2Oracle = _l2Oracle;
systemConfig = _systemConfig;
......@@ -199,12 +193,7 @@ contract OptimismPortal is Initializable, ResourceMetering, Semver {
/// Used internally by the ResourceMetering contract.
/// The SystemConfig is the source of truth for the resource config.
/// @return ResourceMetering ResourceConfig
function _resourceConfig()
internal
view
override
returns (ResourceMetering.ResourceConfig memory)
{
function _resourceConfig() internal view override returns (ResourceMetering.ResourceConfig memory) {
return systemConfig.resourceConfig();
}
......@@ -218,14 +207,14 @@ contract OptimismPortal is Initializable, ResourceMetering, Semver {
uint256 _l2OutputIndex,
Types.OutputRootProof calldata _outputRootProof,
bytes[] calldata _withdrawalProof
) external whenNotPaused {
)
external
whenNotPaused
{
// Prevent users from creating a deposit transaction where this address is the message
// sender on L2. Because this is checked here, we do not need to check again in
// `finalizeWithdrawalTransaction`.
require(
_tx.target != address(this),
"OptimismPortal: you cannot send messages to the portal contract"
);
require(_tx.target != address(this), "OptimismPortal: you cannot send messages to the portal contract");
// Get the output root and load onto the stack to prevent multiple mloads. This will
// revert if there is no output root for the given block number.
......@@ -233,8 +222,7 @@ contract OptimismPortal is Initializable, ResourceMetering, Semver {
// Verify that the output root can be generated with the elements in the proof.
require(
outputRoot == Hashing.hashOutputRootProof(_outputRootProof),
"OptimismPortal: invalid output root proof"
outputRoot == Hashing.hashOutputRootProof(_outputRootProof), "OptimismPortal: invalid output root proof"
);
// Load the ProvenWithdrawal into memory, using the withdrawal hash as a unique identifier.
......@@ -248,9 +236,8 @@ contract OptimismPortal is Initializable, ResourceMetering, Semver {
// to re-prove their withdrawal only in the case that the output root for their specified
// output index has been updated.
require(
provenWithdrawal.timestamp == 0 ||
l2Oracle.getL2Output(provenWithdrawal.l2OutputIndex).outputRoot !=
provenWithdrawal.outputRoot,
provenWithdrawal.timestamp == 0
|| l2Oracle.getL2Output(provenWithdrawal.l2OutputIndex).outputRoot != provenWithdrawal.outputRoot,
"OptimismPortal: withdrawal hash has already been proven"
);
......@@ -270,10 +257,7 @@ contract OptimismPortal is Initializable, ResourceMetering, Semver {
// be relayed on L1.
require(
SecureMerkleTrie.verifyInclusionProof(
abi.encode(storageKey),
hex"01",
_withdrawalProof,
_outputRootProof.messagePasserStorageRoot
abi.encode(storageKey), hex"01", _withdrawalProof, _outputRootProof.messagePasserStorageRoot
),
"OptimismPortal: invalid withdrawal inclusion proof"
);
......@@ -293,16 +277,12 @@ contract OptimismPortal is Initializable, ResourceMetering, Semver {
/// @notice Finalizes a withdrawal transaction.
/// @param _tx Withdrawal transaction to finalize.
function finalizeWithdrawalTransaction(Types.WithdrawalTransaction memory _tx)
external
whenNotPaused
{
function finalizeWithdrawalTransaction(Types.WithdrawalTransaction memory _tx) external whenNotPaused {
// Make sure that the l2Sender has not yet been set. The l2Sender is set to a value other
// than the default value when a withdrawal transaction is being finalized. This check is
// a defacto reentrancy guard.
require(
l2Sender == Constants.DEFAULT_L2_SENDER,
"OptimismPortal: can only trigger one withdrawal per transaction"
l2Sender == Constants.DEFAULT_L2_SENDER, "OptimismPortal: can only trigger one withdrawal per transaction"
);
// Grab the proven withdrawal from the `provenWithdrawals` map.
......@@ -312,10 +292,7 @@ contract OptimismPortal is Initializable, ResourceMetering, Semver {
// A withdrawal can only be finalized if it has been proven. We know that a withdrawal has
// been proven at least once when its timestamp is non-zero. Unproven withdrawals will have
// a timestamp of zero.
require(
provenWithdrawal.timestamp != 0,
"OptimismPortal: withdrawal has not been proven yet"
);
require(provenWithdrawal.timestamp != 0, "OptimismPortal: withdrawal has not been proven yet");
// As a sanity check, we make sure that the proven withdrawal's timestamp is greater than
// starting timestamp inside the L2OutputOracle. Not strictly necessary but extra layer of
......@@ -353,10 +330,7 @@ contract OptimismPortal is Initializable, ResourceMetering, Semver {
);
// Check that this withdrawal has not already been finalized, this is replay protection.
require(
finalizedWithdrawals[withdrawalHash] == false,
"OptimismPortal: withdrawal has already been finalized"
);
require(finalizedWithdrawals[withdrawalHash] == false, "OptimismPortal: withdrawal has already been finalized");
// Mark the withdrawal as finalized so it can't be replayed.
finalizedWithdrawals[withdrawalHash] = true;
......@@ -403,22 +377,20 @@ contract OptimismPortal is Initializable, ResourceMetering, Semver {
uint64 _gasLimit,
bool _isCreation,
bytes memory _data
) public payable metered(_gasLimit) {
)
public
payable
metered(_gasLimit)
{
// Just to be safe, make sure that people specify address(0) as the target when doing
// contract creations.
if (_isCreation) {
require(
_to == address(0),
"OptimismPortal: must send to address(0) when creating a contract"
);
require(_to == address(0), "OptimismPortal: must send to address(0) when creating a contract");
}
// Prevent depositing transactions that have too small of a gas limit. Users should pay
// more for more resource usage.
require(
_gasLimit >= minimumGasLimit(uint64(_data.length)),
"OptimismPortal: gas limit too small"
);
require(_gasLimit >= minimumGasLimit(uint64(_data.length)), "OptimismPortal: gas limit too small");
// Prevent the creation of deposit transactions that have too much calldata. This gives an
// upper limit on the size of unsafe blocks over the p2p network. 120kb is chosen to ensure
......@@ -435,13 +407,7 @@ contract OptimismPortal is Initializable, ResourceMetering, Semver {
// Compute the opaque data that will be emitted as part of the TransactionDeposited event.
// We use opaque data so that we can update the TransactionDeposited event in the future
// without breaking the current interface.
bytes memory opaqueData = abi.encodePacked(
msg.value,
_value,
_gasLimit,
_isCreation,
_data
);
bytes memory opaqueData = abi.encodePacked(msg.value, _value, _gasLimit, _isCreation, _data);
// Emit a TransactionDeposited event so that the rollup node can derive a deposit
// transaction for this deposit.
......
......@@ -76,16 +76,16 @@ abstract contract ResourceMetering is Initializable {
uint256 blockDiff = block.number - params.prevBlockNum;
ResourceConfig memory config = _resourceConfig();
int256 targetResourceLimit = int256(uint256(config.maxResourceLimit)) /
int256(uint256(config.elasticityMultiplier));
int256 targetResourceLimit =
int256(uint256(config.maxResourceLimit)) / int256(uint256(config.elasticityMultiplier));
if (blockDiff > 0) {
// Handle updating EIP-1559 style gas parameters. We use EIP-1559 to restrict the rate
// at which deposits can be created and therefore limit the potential for deposits to
// spam the L2 system. Fee scheme is very similar to EIP-1559 with minor changes.
int256 gasUsedDelta = int256(uint256(params.prevBoughtGas)) - targetResourceLimit;
int256 baseFeeDelta = (int256(uint256(params.prevBaseFee)) * gasUsedDelta) /
(targetResourceLimit * int256(uint256(config.baseFeeMaxChangeDenominator)));
int256 baseFeeDelta = (int256(uint256(params.prevBaseFee)) * gasUsedDelta)
/ (targetResourceLimit * int256(uint256(config.baseFeeMaxChangeDenominator)));
// Update base fee by adding the base fee delta and clamp the resulting value between
// min and max.
......@@ -155,10 +155,6 @@ abstract contract ResourceMetering is Initializable {
/// child contract.
// solhint-disable-next-line func-name-mixedcase
function __ResourceMetering_init() internal onlyInitializing {
params = ResourceParams({
prevBaseFee: 1 gwei,
prevBoughtGas: 0,
prevBlockNum: uint64(block.number)
});
params = ResourceParams({ prevBaseFee: 1 gwei, prevBoughtGas: 0, prevBlockNum: uint64(block.number) });
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.15;
import {
OwnableUpgradeable
} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { Semver } from "../universal/Semver.sol";
import { ResourceMetering } from "./ResourceMetering.sol";
......@@ -54,28 +52,23 @@ contract SystemConfig is OwnableUpgradeable, Semver {
bytes32(uint256(keccak256("systemconfig.l1crossdomainmessenger")) - 1);
/// @notice Storage slot that the L1ERC721Bridge address is stored at.
bytes32 public constant L1_ERC_721_BRIDGE_SLOT =
bytes32(uint256(keccak256("systemconfig.l1erc721bridge")) - 1);
bytes32 public constant L1_ERC_721_BRIDGE_SLOT = bytes32(uint256(keccak256("systemconfig.l1erc721bridge")) - 1);
/// @notice Storage slot that the L1StandardBridge address is stored at.
bytes32 public constant L1_STANDARD_BRIDGE_SLOT =
bytes32(uint256(keccak256("systemconfig.l1standardbridge")) - 1);
bytes32 public constant L1_STANDARD_BRIDGE_SLOT = bytes32(uint256(keccak256("systemconfig.l1standardbridge")) - 1);
/// @notice Storage slot that the L2OutputOracle address is stored at.
bytes32 public constant L2_OUTPUT_ORACLE_SLOT =
bytes32(uint256(keccak256("systemconfig.l2outputoracle")) - 1);
bytes32 public constant L2_OUTPUT_ORACLE_SLOT = bytes32(uint256(keccak256("systemconfig.l2outputoracle")) - 1);
/// @notice Storage slot that the OptimismPortal address is stored at.
bytes32 public constant OPTIMISM_PORTAL_SLOT =
bytes32(uint256(keccak256("systemconfig.optimismportal")) - 1);
bytes32 public constant OPTIMISM_PORTAL_SLOT = bytes32(uint256(keccak256("systemconfig.optimismportal")) - 1);
/// @notice Storage slot that the OptimismMintableERC20Factory address is stored at.
bytes32 public constant OPTIMISM_MINTABLE_ERC20_FACTORY_SLOT =
bytes32(uint256(keccak256("systemconfig.optimismmintableerc20factory")) - 1);
/// @notice Storage slot that the batch inbox address is stored at.
bytes32 public constant BATCH_INBOX_SLOT =
bytes32(uint256(keccak256("systemconfig.batchinbox")) - 1);
bytes32 public constant BATCH_INBOX_SLOT = bytes32(uint256(keccak256("systemconfig.batchinbox")) - 1);
/// @notice Fixed L2 gas overhead. Used as part of the L2 fee calculation.
uint256 public overhead;
......@@ -165,7 +158,10 @@ contract SystemConfig is OwnableUpgradeable, Semver {
uint256 _startBlock,
address _batchInbox,
SystemConfig.Addresses memory _addresses
) public reinitializer(2) {
)
public
reinitializer(2)
{
__Ownable_init();
transferOwnership(_owner);
......@@ -346,29 +342,19 @@ contract SystemConfig is OwnableUpgradeable, Semver {
function _setResourceConfig(ResourceMetering.ResourceConfig memory _config) internal {
// Min base fee must be less than or equal to max base fee.
require(
_config.minimumBaseFee <= _config.maximumBaseFee,
"SystemConfig: min base fee must be less than max base"
_config.minimumBaseFee <= _config.maximumBaseFee, "SystemConfig: min base fee must be less than max base"
);
// Base fee change denominator must be greater than 1.
require(
_config.baseFeeMaxChangeDenominator > 1,
"SystemConfig: denominator must be larger than 1"
);
require(_config.baseFeeMaxChangeDenominator > 1, "SystemConfig: denominator must be larger than 1");
// Max resource limit plus system tx gas must be less than or equal to the L2 gas limit.
// The gas limit must be increased before these values can be increased.
require(
_config.maxResourceLimit + _config.systemTxMaxGas <= gasLimit,
"SystemConfig: gas limit too low"
);
require(_config.maxResourceLimit + _config.systemTxMaxGas <= gasLimit, "SystemConfig: gas limit too low");
// Elasticity multiplier must be greater than 0.
require(
_config.elasticityMultiplier > 0,
"SystemConfig: elasticity multiplier cannot be 0"
);
require(_config.elasticityMultiplier > 0, "SystemConfig: elasticity multiplier cannot be 0");
// No precision loss when computing target resource limit.
require(
((_config.maxResourceLimit / _config.elasticityMultiplier) *
_config.elasticityMultiplier) == _config.maxResourceLimit,
((_config.maxResourceLimit / _config.elasticityMultiplier) * _config.elasticityMultiplier)
== _config.maxResourceLimit,
"SystemConfig: precision loss with target resource limit"
);
......
......@@ -18,5 +18,8 @@ contract BaseFeeVault is FeeVault, Semver {
address _recipient,
uint256 _minWithdrawalAmount,
WithdrawalNetwork _withdrawalNetwork
) FeeVault(_recipient, _minWithdrawalAmount, _withdrawalNetwork) Semver(1, 3, 0) {}
)
FeeVault(_recipient, _minWithdrawalAmount, _withdrawalNetwork)
Semver(1, 3, 0)
{ }
}
......@@ -14,8 +14,7 @@ abstract contract CrossDomainOwnable is Ownable {
/// `msg.sender` is the owner of the contract.
function _checkOwner() internal view override {
require(
owner() == AddressAliasHelper.undoL1ToL2Alias(msg.sender),
"CrossDomainOwnable: caller is not the owner"
owner() == AddressAliasHelper.undoL1ToL2Alias(msg.sender), "CrossDomainOwnable: caller is not the owner"
);
}
}
......@@ -15,18 +15,10 @@ abstract contract CrossDomainOwnable2 is Ownable {
/// `xDomainMessageSender` is the owner of the contract. This value is set to the caller
/// of the L1CrossDomainMessenger.
function _checkOwner() internal view override {
L2CrossDomainMessenger messenger = L2CrossDomainMessenger(
Predeploys.L2_CROSS_DOMAIN_MESSENGER
);
L2CrossDomainMessenger messenger = L2CrossDomainMessenger(Predeploys.L2_CROSS_DOMAIN_MESSENGER);
require(
msg.sender == address(messenger),
"CrossDomainOwnable2: caller is not the messenger"
);
require(msg.sender == address(messenger), "CrossDomainOwnable2: caller is not the messenger");
require(
owner() == messenger.xDomainMessageSender(),
"CrossDomainOwnable2: caller is not the owner"
);
require(owner() == messenger.xDomainMessageSender(), "CrossDomainOwnable2: caller is not the owner");
}
}
......@@ -20,11 +20,7 @@ abstract contract CrossDomainOwnable3 is Ownable {
/// @param previousOwner The previous owner of the contract.
/// @param newOwner The new owner of the contract.
/// @param isLocal Configures the `isLocal` contract variable.
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner,
bool isLocal
);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner, bool isLocal);
/// @notice Allows for ownership to be transferred with specifying the locality.
/// @param _owner The new owner of the contract.
......@@ -46,19 +42,11 @@ abstract contract CrossDomainOwnable3 is Ownable {
if (isLocal) {
require(owner() == msg.sender, "CrossDomainOwnable3: caller is not the owner");
} else {
L2CrossDomainMessenger messenger = L2CrossDomainMessenger(
Predeploys.L2_CROSS_DOMAIN_MESSENGER
);
L2CrossDomainMessenger messenger = L2CrossDomainMessenger(Predeploys.L2_CROSS_DOMAIN_MESSENGER);
require(
msg.sender == address(messenger),
"CrossDomainOwnable3: caller is not the messenger"
);
require(msg.sender == address(messenger), "CrossDomainOwnable3: caller is not the messenger");
require(
owner() == messenger.xDomainMessageSender(),
"CrossDomainOwnable3: caller is not the owner"
);
require(owner() == messenger.xDomainMessageSender(), "CrossDomainOwnable3: caller is not the owner");
}
}
}
......@@ -25,7 +25,7 @@ contract GasPriceOracle is Semver {
/// @custom:semver 1.0.1
/// @notice Constructs the GasPriceOracle contract.
constructor() Semver(1, 0, 1) {}
constructor() Semver(1, 0, 1) { }
/// @notice Computes the L1 portion of the fee based on the size of the rlp encoded input
/// transaction, the current L1 base fee, and the various dynamic parameters.
......@@ -34,7 +34,7 @@ contract GasPriceOracle is Semver {
function getL1Fee(bytes memory _data) external view returns (uint256) {
uint256 l1GasUsed = getL1GasUsed(_data);
uint256 l1Fee = l1GasUsed * l1BaseFee();
uint256 divisor = 10**DECIMALS;
uint256 divisor = 10 ** DECIMALS;
uint256 unscaled = l1Fee * scalar();
uint256 scaled = unscaled / divisor;
return scaled;
......
......@@ -40,7 +40,7 @@ contract L1Block is Semver {
/// @custom:semver 1.0.1
/// @notice Constructs the L1Block contract.
constructor() Semver(1, 0, 1) {}
constructor() Semver(1, 0, 1) { }
/// @notice Updates the L1 block values.
/// @param _number L1 blocknumber.
......@@ -60,11 +60,10 @@ contract L1Block is Semver {
bytes32 _batcherHash,
uint256 _l1FeeOverhead,
uint256 _l1FeeScalar
) external {
require(
msg.sender == DEPOSITOR_ACCOUNT,
"L1Block: only the depositor account can set L1 block values"
);
)
external
{
require(msg.sender == DEPOSITOR_ACCOUNT, "L1Block: only the depositor account can set L1 block values");
number = _number;
timestamp = _timestamp;
......
......@@ -18,5 +18,8 @@ contract L1FeeVault is FeeVault, Semver {
address _recipient,
uint256 _minWithdrawalAmount,
WithdrawalNetwork _withdrawalNetwork
) FeeVault(_recipient, _minWithdrawalAmount, _withdrawalNetwork) Semver(1, 3, 0) {}
)
FeeVault(_recipient, _minWithdrawalAmount, _withdrawalNetwork)
Semver(1, 3, 0)
{ }
}
......@@ -17,10 +17,7 @@ contract L2CrossDomainMessenger is CrossDomainMessenger, Semver {
/// @custom:semver 1.5.0
/// @notice Constructs the L2CrossDomainMessenger contract.
/// @param _l1CrossDomainMessenger Address of the L1CrossDomainMessenger contract.
constructor(address _l1CrossDomainMessenger)
Semver(1, 5, 0)
CrossDomainMessenger(_l1CrossDomainMessenger)
{
constructor(address _l1CrossDomainMessenger) Semver(1, 5, 0) CrossDomainMessenger(_l1CrossDomainMessenger) {
initialize();
}
......@@ -38,15 +35,10 @@ contract L2CrossDomainMessenger is CrossDomainMessenger, Semver {
}
/// @inheritdoc CrossDomainMessenger
function _sendMessage(
address _to,
uint64 _gasLimit,
uint256 _value,
bytes memory _data
) internal override {
L2ToL1MessagePasser(payable(Predeploys.L2_TO_L1_MESSAGE_PASSER)).initiateWithdrawal{
value: _value
}(_to, _gasLimit, _data);
function _sendMessage(address _to, uint64 _gasLimit, uint256 _value, bytes memory _data) internal override {
L2ToL1MessagePasser(payable(Predeploys.L2_TO_L1_MESSAGE_PASSER)).initiateWithdrawal{ value: _value }(
_to, _gasLimit, _data
);
}
/// @inheritdoc CrossDomainMessenger
......
......@@ -48,7 +48,10 @@ contract L2ERC721Bridge is ERC721Bridge, Semver {
address _to,
uint256 _tokenId,
bytes calldata _extraData
) external onlyOtherBridge {
)
external
onlyOtherBridge
{
require(_localToken != address(this), "L2ERC721Bridge: local token cannot be self");
// Note that supportsInterface makes a callback to the _localToken address which is user
......@@ -80,7 +83,10 @@ contract L2ERC721Bridge is ERC721Bridge, Semver {
uint256 _tokenId,
uint32 _minGasLimit,
bytes calldata _extraData
) internal override {
)
internal
override
{
require(_remoteToken != address(0), "L2ERC721Bridge: remote token cannot be address(0)");
// Check that the withdrawal is being initiated by the NFT owner
......@@ -92,10 +98,7 @@ contract L2ERC721Bridge is ERC721Bridge, Semver {
// Construct calldata for l1ERC721Bridge.finalizeBridgeERC721(_to, _tokenId)
// slither-disable-next-line reentrancy-events
address remoteToken = IOptimismMintableERC721(_localToken).remoteToken();
require(
remoteToken == _remoteToken,
"L2ERC721Bridge: remote token does not match given value"
);
require(remoteToken == _remoteToken, "L2ERC721Bridge: remote token does not match given value");
// When a withdrawal is initiated, we burn the withdrawer's NFT to prevent subsequent L2
// usage
......@@ -103,13 +106,7 @@ contract L2ERC721Bridge is ERC721Bridge, Semver {
IOptimismMintableERC721(_localToken).burn(_from, _tokenId);
bytes memory message = abi.encodeWithSelector(
L1ERC721Bridge.finalizeBridgeERC721.selector,
remoteToken,
_localToken,
_from,
_to,
_tokenId,
_extraData
L1ERC721Bridge.finalizeBridgeERC721.selector, remoteToken, _localToken, _from, _to, _tokenId, _extraData
);
// Send message to L1 bridge
......
......@@ -60,20 +60,13 @@ contract L2StandardBridge is StandardBridge, Semver {
/// @notice Initializer
function initialize() public reinitializer(2) {
__StandardBridge_init({
_messenger: CrossDomainMessenger(Predeploys.L2_CROSS_DOMAIN_MESSENGER)
});
__StandardBridge_init({ _messenger: CrossDomainMessenger(Predeploys.L2_CROSS_DOMAIN_MESSENGER) });
}
/// @notice Allows EOAs to bridge ETH by sending directly to the bridge.
receive() external payable override onlyEOA {
_initiateWithdrawal(
Predeploys.LEGACY_ERC20_ETH,
msg.sender,
msg.sender,
msg.value,
RECEIVE_DEFAULT_GAS_LIMIT,
bytes("")
Predeploys.LEGACY_ERC20_ETH, msg.sender, msg.sender, msg.value, RECEIVE_DEFAULT_GAS_LIMIT, bytes("")
);
}
......@@ -90,7 +83,12 @@ contract L2StandardBridge is StandardBridge, Semver {
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _extraData
) external payable virtual onlyEOA {
)
external
payable
virtual
onlyEOA
{
_initiateWithdrawal(_l2Token, msg.sender, msg.sender, _amount, _minGasLimit, _extraData);
}
......@@ -113,7 +111,11 @@ contract L2StandardBridge is StandardBridge, Semver {
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _extraData
) external payable virtual {
)
external
payable
virtual
{
_initiateWithdrawal(_l2Token, msg.sender, _to, _amount, _minGasLimit, _extraData);
}
......@@ -133,7 +135,11 @@ contract L2StandardBridge is StandardBridge, Semver {
address _to,
uint256 _amount,
bytes calldata _extraData
) external payable virtual {
)
external
payable
virtual
{
if (_l1Token == address(0) && _l2Token == Predeploys.LEGACY_ERC20_ETH) {
finalizeBridgeETH(_from, _to, _amount, _extraData);
} else {
......@@ -163,7 +169,9 @@ contract L2StandardBridge is StandardBridge, Semver {
uint256 _amount,
uint32 _minGasLimit,
bytes memory _extraData
) internal {
)
internal
{
if (_l2Token == Predeploys.LEGACY_ERC20_ETH) {
_initiateBridgeETH(_from, _to, _amount, _minGasLimit, _extraData);
} else {
......@@ -180,15 +188,11 @@ contract L2StandardBridge is StandardBridge, Semver {
address _to,
uint256 _amount,
bytes memory _extraData
) internal override {
emit WithdrawalInitiated(
address(0),
Predeploys.LEGACY_ERC20_ETH,
_from,
_to,
_amount,
_extraData
);
)
internal
override
{
emit WithdrawalInitiated(address(0), Predeploys.LEGACY_ERC20_ETH, _from, _to, _amount, _extraData);
super._emitETHBridgeInitiated(_from, _to, _amount, _extraData);
}
......@@ -200,15 +204,11 @@ contract L2StandardBridge is StandardBridge, Semver {
address _to,
uint256 _amount,
bytes memory _extraData
) internal override {
emit DepositFinalized(
address(0),
Predeploys.LEGACY_ERC20_ETH,
_from,
_to,
_amount,
_extraData
);
)
internal
override
{
emit DepositFinalized(address(0), Predeploys.LEGACY_ERC20_ETH, _from, _to, _amount, _extraData);
super._emitETHBridgeFinalized(_from, _to, _amount, _extraData);
}
......@@ -222,7 +222,10 @@ contract L2StandardBridge is StandardBridge, Semver {
address _to,
uint256 _amount,
bytes memory _extraData
) internal override {
)
internal
override
{
emit WithdrawalInitiated(_remoteToken, _localToken, _from, _to, _amount, _extraData);
super._emitERC20BridgeInitiated(_localToken, _remoteToken, _from, _to, _amount, _extraData);
}
......@@ -237,7 +240,10 @@ contract L2StandardBridge is StandardBridge, Semver {
address _to,
uint256 _amount,
bytes memory _extraData
) internal override {
)
internal
override
{
emit DepositFinalized(_remoteToken, _localToken, _from, _to, _amount, _extraData);
super._emitERC20BridgeFinalized(_localToken, _remoteToken, _from, _to, _amount, _extraData);
}
......
......@@ -50,7 +50,7 @@ contract L2ToL1MessagePasser is Semver {
/// @custom:semver 1.0.1
/// @notice Constructs the L2ToL1MessagePasser contract.
constructor() Semver(1, 0, 1) {}
constructor() Semver(1, 0, 1) { }
/// @notice Allows users to withdraw ETH by sending directly to this contract.
receive() external payable {
......@@ -71,11 +71,7 @@ contract L2ToL1MessagePasser is Semver {
/// @param _target Address to call on L1 execution.
/// @param _gasLimit Minimum gas limit for executing the message on L1.
/// @param _data Data to forward to L1 target.
function initiateWithdrawal(
address _target,
uint256 _gasLimit,
bytes memory _data
) public payable {
function initiateWithdrawal(address _target, uint256 _gasLimit, bytes memory _data) public payable {
bytes32 withdrawalHash = Hashing.hashWithdrawal(
Types.WithdrawalTransaction({
nonce: messageNonce(),
......@@ -89,15 +85,7 @@ contract L2ToL1MessagePasser is Semver {
sentMessages[withdrawalHash] = true;
emit MessagePassed(
messageNonce(),
msg.sender,
_target,
msg.value,
_gasLimit,
_data,
withdrawalHash
);
emit MessagePassed(messageNonce(), msg.sender, _target, msg.value, _gasLimit, _data, withdrawalHash);
unchecked {
++msgNonce;
......
......@@ -19,7 +19,10 @@ contract SequencerFeeVault is FeeVault, Semver {
address _recipient,
uint256 _minWithdrawalAmount,
WithdrawalNetwork _withdrawalNetwork
) FeeVault(_recipient, _minWithdrawalAmount, _withdrawalNetwork) Semver(1, 3, 0) {}
)
FeeVault(_recipient, _minWithdrawalAmount, _withdrawalNetwork)
Semver(1, 3, 0)
{ }
/// @custom:legacy
/// @notice Legacy getter for the recipient address.
......
......@@ -16,11 +16,7 @@ contract PreimageOracle is IPreimageOracle {
mapping(bytes32 => mapping(uint256 => bool)) public preimagePartOk;
/// @inheritdoc IPreimageOracle
function readPreimage(bytes32 _key, uint256 _offset)
external
view
returns (bytes32 dat_, uint256 datLen_)
{
function readPreimage(bytes32 _key, uint256 _offset) external view returns (bytes32 dat_, uint256 datLen_) {
require(preimagePartOk[_key][_offset], "pre-image must exist");
// Calculate the length of the pre-image data
......@@ -40,12 +36,7 @@ contract PreimageOracle is IPreimageOracle {
/// and restrict local pre-image insertion to the dispute-managing contract.
/// For now we permit anyone to write any pre-image unchecked, to make testing easy.
/// This method is DANGEROUS. And NOT FOR PRODUCTION.
function cheat(
uint256 partOffset,
bytes32 key,
bytes32 part,
uint256 size
) external {
function cheat(uint256 partOffset, bytes32 key, bytes32 part, uint256 size) external {
preimagePartOk[key][partOffset] = true;
preimageParts[key][partOffset] = part;
preimageLengths[key] = size;
......@@ -57,7 +48,10 @@ contract PreimageOracle is IPreimageOracle {
bytes32 _word,
uint256 _size,
uint256 _partOffset
) external returns (bytes32 key_) {
)
external
returns (bytes32 key_)
{
// Compute the localized key from the given local identifier.
key_ = PreimageKeyLib.localizeIdent(_ident);
......
......@@ -9,10 +9,7 @@ interface IPreimageOracle {
/// @param _offset The offset of the preimage to read.
/// @return dat_ The preimage data.
/// @return datLen_ The length of the preimage data.
function readPreimage(bytes32 _key, uint256 _offset)
external
view
returns (bytes32 dat_, uint256 datLen_);
function readPreimage(bytes32 _key, uint256 _offset) external view returns (bytes32 dat_, uint256 datLen_);
/// @notice Loads of local data part into the preimage oracle.
/// @param _ident The identifier of the local data.
......@@ -38,7 +35,9 @@ interface IPreimageOracle {
bytes32 _word,
uint256 _size,
uint256 _partOffset
) external returns (bytes32 key_);
)
external
returns (bytes32 key_);
/// @notice Prepares a preimage to be read by keccak256 key, starting at
/// the given offset and up to 32 bytes (clipped at preimage length, if out of data).
......
......@@ -14,11 +14,7 @@ contract BlockOracle {
}
/// @notice Emitted when a block is checkpointed.
event Checkpoint(
uint256 indexed blockNumber,
Hash indexed blockHash,
Timestamp indexed childTimestamp
);
event Checkpoint(uint256 indexed blockNumber, Hash indexed blockHash, Timestamp indexed childTimestamp);
/// @notice Maps block numbers to block hashes and timestamps
mapping(uint256 => BlockInfo) internal blocks;
......
......@@ -2,9 +2,7 @@
pragma solidity ^0.8.15;
import { ClonesWithImmutableArgs } from "@cwia/ClonesWithImmutableArgs.sol";
import {
OwnableUpgradeable
} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { Semver } from "src/universal/Semver.sol";
import { IDisputeGame } from "./interfaces/IDisputeGame.sol";
......@@ -58,7 +56,11 @@ contract DisputeGameFactory is OwnableUpgradeable, IDisputeGameFactory, Semver {
GameType _gameType,
Claim _rootClaim,
bytes calldata _extraData
) external view returns (IDisputeGame proxy_, uint256 timestamp_) {
)
external
view
returns (IDisputeGame proxy_, uint256 timestamp_)
{
Hash uuid = getGameUUID(_gameType, _rootClaim, _extraData);
GameId slot = _disputeGames[uuid];
(address addr, uint256 timestamp) = _unpackSlot(slot);
......@@ -67,11 +69,7 @@ contract DisputeGameFactory is OwnableUpgradeable, IDisputeGameFactory, Semver {
}
/// @inheritdoc IDisputeGameFactory
function gameAtIndex(uint256 _index)
external
view
returns (IDisputeGame proxy_, uint256 timestamp_)
{
function gameAtIndex(uint256 _index) external view returns (IDisputeGame proxy_, uint256 timestamp_) {
GameId slot = _disputeGameList[_index];
(address addr, uint256 timestamp) = _unpackSlot(slot);
proxy_ = IDisputeGame(addr);
......@@ -83,7 +81,10 @@ contract DisputeGameFactory is OwnableUpgradeable, IDisputeGameFactory, Semver {
GameType gameType,
Claim rootClaim,
bytes calldata extraData
) external returns (IDisputeGame proxy) {
)
external
returns (IDisputeGame proxy)
{
// Grab the implementation contract for the given `GameType`.
IDisputeGame impl = gameImpls[gameType];
......@@ -109,11 +110,7 @@ contract DisputeGameFactory is OwnableUpgradeable, IDisputeGameFactory, Semver {
}
/// @inheritdoc IDisputeGameFactory
function getGameUUID(
GameType gameType,
Claim rootClaim,
bytes memory extraData
) public pure returns (Hash _uuid) {
function getGameUUID(GameType gameType, Claim rootClaim, bytes memory extraData) public pure returns (Hash _uuid) {
assembly {
// Grab the offsets of the other memory locations we will need to temporarily overwrite.
let gameTypeOffset := sub(extraData, 0x60)
......
......@@ -94,7 +94,9 @@ contract FaultDisputeGame is IFaultDisputeGame, Clone, Semver {
IBigStepper _vm,
L2OutputOracle _l2oo,
BlockOracle _blockOracle
) Semver(0, 0, 7) {
)
Semver(0, 0, 7)
{
GAME_TYPE = _gameType;
ABSOLUTE_PRESTATE = _absolutePrestate;
MAX_GAME_DEPTH = _maxGameDepth;
......@@ -109,12 +111,7 @@ contract FaultDisputeGame is IFaultDisputeGame, Clone, Semver {
////////////////////////////////////////////////////////////////
/// @inheritdoc IFaultDisputeGame
function step(
uint256 _claimIndex,
bool _isAttack,
bytes calldata _stateData,
bytes calldata _proof
) external {
function step(uint256 _claimIndex, bool _isAttack, bytes calldata _stateData, bytes calldata _proof) external {
// INVARIANT: Steps cannot be made unless the game is currently in progress.
if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
......@@ -139,10 +136,7 @@ contract FaultDisputeGame is IFaultDisputeGame, Clone, Semver {
// the game state.
preStateClaim = stepPos.indexAtDepth() == 0
? ABSOLUTE_PRESTATE
: findTraceAncestor(
Position.wrap(Position.unwrap(parentPos) - 1),
parent.parentIndex
).claim;
: findTraceAncestor(Position.wrap(Position.unwrap(parentPos) - 1), parent.parentIndex).claim;
// For all attacks, the poststate is the parent claim.
postState = parent;
......@@ -150,10 +144,7 @@ contract FaultDisputeGame is IFaultDisputeGame, Clone, Semver {
// If the step is a defense, the poststate exists elsewhere in the game state,
// and the parent claim is the expected pre-state.
preStateClaim = parent.claim;
postState = findTraceAncestor(
Position.wrap(Position.unwrap(parentPos) + 1),
parent.parentIndex
);
postState = findTraceAncestor(Position.wrap(Position.unwrap(parentPos) + 1), parent.parentIndex);
}
// INVARIANT: The prestate is always invalid if the passed `_stateData` is not the
......@@ -185,11 +176,7 @@ contract FaultDisputeGame is IFaultDisputeGame, Clone, Semver {
/// @param _challengeIndex The index of the claim being moved against.
/// @param _claim The claim at the next logical position in the game.
/// @param _isAttack Whether or not the move is an attack or defense.
function move(
uint256 _challengeIndex,
Claim _claim,
bool _isAttack
) public payable {
function move(uint256 _challengeIndex, Claim _claim, bool _isAttack) public payable {
// INVARIANT: Moves cannot be made unless the game is currently in progress.
if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
......@@ -225,11 +212,10 @@ contract FaultDisputeGame is IFaultDisputeGame, Clone, Semver {
Duration nextDuration = Duration.wrap(
uint64(
// First, fetch the duration of the grandparent claim.
Duration.unwrap(grandparentClock.duration()) +
// Second, add the difference between the current block timestamp and the
// parent's clock timestamp.
block.timestamp -
Timestamp.unwrap(parent.clock.timestamp())
Duration.unwrap(grandparentClock.duration())
// Second, add the difference between the current block timestamp and the
// parent's clock timestamp.
+ block.timestamp - Timestamp.unwrap(parent.clock.timestamp())
)
);
......@@ -362,7 +348,7 @@ contract FaultDisputeGame is IFaultDisputeGame, Clone, Semver {
// The most recent claim is always a dangling, non-bottom node so we start with that
uint256 leftMostIndex = claimData.length - 1;
uint256 leftMostTraceIndex = type(uint128).max;
for (uint256 i = leftMostIndex; i < type(uint64).max; ) {
for (uint256 i = leftMostIndex; i < type(uint64).max;) {
// Fetch the claim at the current index.
ClaimData storage claim = claimData[i];
......@@ -396,13 +382,10 @@ contract FaultDisputeGame is IFaultDisputeGame, Clone, Semver {
// claim, it is uncountered, and we check if 3.5 days has passed since its
// creation.
uint256 parentIndex = leftMostUncontested.parentIndex;
Clock opposingClock = parentIndex == type(uint32).max
? leftMostUncontested.clock
: claimData[parentIndex].clock;
Clock opposingClock = parentIndex == type(uint32).max ? leftMostUncontested.clock : claimData[parentIndex].clock;
if (
Duration.unwrap(opposingClock.duration()) +
(block.timestamp - Timestamp.unwrap(opposingClock.timestamp())) <=
Duration.unwrap(GAME_DURATION) >> 1
Duration.unwrap(opposingClock.duration()) + (block.timestamp - Timestamp.unwrap(opposingClock.timestamp()))
<= Duration.unwrap(GAME_DURATION) >> 1
) {
revert ClockNotExpired();
}
......@@ -410,8 +393,10 @@ contract FaultDisputeGame is IFaultDisputeGame, Clone, Semver {
// If the left-most dangling node is at an even depth, the defender wins.
// Otherwise, the challenger wins and the root claim is deemed invalid.
if (
// slither-disable-next-line weak-prng
leftMostUncontested.position.depth() % 2 == 0 && leftMostTraceIndex != type(uint128).max
leftMostUncontested
.position
// slither-disable-next-line weak-prng
.depth() % 2 == 0 && leftMostTraceIndex != type(uint128).max
) {
status_ = GameStatus.DEFENDER_WINS;
} else {
......@@ -435,15 +420,7 @@ contract FaultDisputeGame is IFaultDisputeGame, Clone, Semver {
}
/// @inheritdoc IDisputeGame
function gameData()
external
view
returns (
GameType gameType_,
Claim rootClaim_,
bytes memory extraData_
)
{
function gameData() external view returns (GameType gameType_, Claim rootClaim_, bytes memory extraData_) {
gameType_ = gameType();
rootClaim_ = rootClaim();
extraData_ = extraData();
......@@ -543,11 +520,7 @@ contract FaultDisputeGame is IFaultDisputeGame, Clone, Semver {
/// @return ancestor_ The ancestor claim that commits to the same trace index as `_pos`.
// TODO(clabby): Can we form a relationship between the trace path and the position to avoid
// looping?
function findTraceAncestor(Position _pos, uint256 _start)
internal
view
returns (ClaimData storage ancestor_)
{
function findTraceAncestor(Position _pos, uint256 _start) internal view returns (ClaimData storage ancestor_) {
// Grab the trace ancestor's expected position.
Position preStateTraceAncestor = _pos.traceAncestor();
......
......@@ -30,9 +30,7 @@ interface IBigStepper {
/// @param _stateData The preimage of the prestate hash.
/// @param _proof A proof for the inclusion of the prestate's memory in the merkle tree.
/// @return postState_ The poststate hash after the instruction step.
function step(bytes calldata _stateData, bytes calldata _proof)
external
returns (bytes32 postState_);
function step(bytes calldata _stateData, bytes calldata _proof) external returns (bytes32 postState_);
/// @notice Returns the preimage oracle used by the stepper.
function oracle() external view returns (IPreimageOracle oracle_);
......
......@@ -30,11 +30,7 @@ interface IBondManager {
/// @param _bondOwner is the address that owns the bond.
/// @param _minClaimHold is the minimum amount of time the owner
/// must wait before reclaiming their bond.
function post(
bytes32 _bondId,
address _bondOwner,
uint128 _minClaimHold
) external payable;
function post(bytes32 _bondId, address _bondOwner, uint128 _minClaimHold) external payable;
/// @notice Seizes the bond with the given id.
/// @dev This function will revert if there is no bond at the given id.
......
......@@ -56,12 +56,5 @@ interface IDisputeGame is IInitializable {
/// @return gameType_ The type of proof system being used.
/// @return rootClaim_ The root claim of the DisputeGame.
/// @return extraData_ Any extra data supplied to the dispute game contract by the creator.
function gameData()
external
view
returns (
GameType gameType_,
Claim rootClaim_,
bytes memory extraData_
);
function gameData() external view returns (GameType gameType_, Claim rootClaim_, bytes memory extraData_);
}
......@@ -12,11 +12,7 @@ interface IDisputeGameFactory {
/// @param disputeProxy The address of the dispute game proxy
/// @param gameType The type of the dispute game proxy's implementation
/// @param rootClaim The root claim of the dispute game
event DisputeGameCreated(
address indexed disputeProxy,
GameType indexed gameType,
Claim indexed rootClaim
);
event DisputeGameCreated(address indexed disputeProxy, GameType indexed gameType, Claim indexed rootClaim);
/// @notice Emitted when a new game implementation added to the factory
/// @param impl The implementation contract for the given `GameType`.
......@@ -40,7 +36,10 @@ interface IDisputeGameFactory {
GameType gameType,
Claim rootClaim,
bytes calldata extraData
) external view returns (IDisputeGame _proxy, uint256 _timestamp);
)
external
view
returns (IDisputeGame _proxy, uint256 _timestamp);
/// @notice `gameAtIndex` returns the dispute game contract address and its creation timestamp
/// at the given index. Each created dispute game increments the underlying index.
......@@ -48,10 +47,7 @@ interface IDisputeGameFactory {
/// @return _proxy The clone of the `DisputeGame` created with the given parameters.
/// Returns `address(0)` if nonexistent.
/// @return _timestamp The timestamp of the creation of the dispute game.
function gameAtIndex(uint256 _index)
external
view
returns (IDisputeGame _proxy, uint256 _timestamp);
function gameAtIndex(uint256 _index) external view returns (IDisputeGame _proxy, uint256 _timestamp);
/// @notice `gameImpls` is a mapping that maps `GameType`s to their respective
/// `IDisputeGame` implementations.
......@@ -69,7 +65,9 @@ interface IDisputeGameFactory {
GameType gameType,
Claim rootClaim,
bytes calldata extraData
) external returns (IDisputeGame proxy);
)
external
returns (IDisputeGame proxy);
/// @notice Sets the implementation contract for a specific `GameType`.
/// @dev May only be called by the `owner`.
......@@ -88,5 +86,8 @@ interface IDisputeGameFactory {
GameType gameType,
Claim rootClaim,
bytes memory extraData
) external pure returns (Hash _uuid);
)
external
pure
returns (Hash _uuid);
}
......@@ -66,12 +66,7 @@ interface IFaultDisputeGame is IDisputeGame {
/// the move is a defense. If the step is an attack on the first instruction, it is
/// the absolute prestate of the fault proof VM.
/// @param _proof Proof to access memory nodes in the VM's merkle state tree.
function step(
uint256 _claimIndex,
bool _isAttack,
bytes calldata _stateData,
bytes calldata _proof
) external;
function step(uint256 _claimIndex, bool _isAttack, bytes calldata _stateData, bytes calldata _proof) external;
/// @notice Posts the requested local data to the VM's `PreimageOralce`.
/// @param _ident The local identifier of the data to post.
......
......@@ -6,7 +6,6 @@ import "src/libraries/DisputeTypes.sol";
/// @title Hashing
/// @notice This library contains all of the hashing utilities used in the Cannon contracts.
library LibHashing {
/// @notice Hashes a claim and a position together.
/// @param _claim A Claim type.
/// @param _position The position of `claim`.
......
......@@ -6,7 +6,6 @@ import "src/libraries/DisputeTypes.sol";
/// @title LibPosition
/// @notice This library contains helper functions for working with the `Position` type.
library LibPosition {
/// @notice Computes a generalized index (2^{depth} + indexAtDepth).
/// @param _depth The depth of the position.
/// @param _indexAtDepth The index at the depth of the position.
......@@ -36,13 +35,14 @@ library LibPosition {
_position := or(_position, shr(8, _position))
_position := or(_position, shr(16, _position))
depth_ := or(
depth_,
byte(
shr(251, mul(_position, shl(224, 0x07c4acdd))),
0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f
depth_ :=
or(
depth_,
byte(
shr(251, mul(_position, shl(224, 0x07c4acdd))),
0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f
)
)
)
}
}
......@@ -93,10 +93,7 @@ library LibPosition {
/// @param _position The position to get the relative deepest, right most gindex of.
/// @param _maxDepth The maximum depth of the game.
/// @return rightIndex_ The deepest, right most gindex relative to the `position`.
function rightIndex(
Position _position,
uint256 _maxDepth
) internal pure returns (Position rightIndex_) {
function rightIndex(Position _position, uint256 _maxDepth) internal pure returns (Position rightIndex_) {
uint256 msb = depth(_position);
assembly {
let remaining := sub(_maxDepth, msb)
......@@ -110,17 +107,11 @@ library LibPosition {
/// @param _position The position to get the relative trace index of.
/// @param _maxDepth The maximum depth of the game.
/// @return traceIndex_ The trace index relative to the `position`.
function traceIndex(
Position _position,
uint256 _maxDepth
) internal pure returns (uint256 traceIndex_) {
function traceIndex(Position _position, uint256 _maxDepth) internal pure returns (uint256 traceIndex_) {
uint256 msb = depth(_position);
assembly {
let remaining := sub(_maxDepth, msb)
traceIndex_ := sub(
or(shl(remaining, _position), sub(shl(remaining, 1), 1)),
shl(_maxDepth, 1)
)
traceIndex_ := sub(or(shl(remaining, _position), sub(shl(remaining, 1), 1)), shl(_maxDepth, 1))
}
}
......
......@@ -14,7 +14,7 @@ import "@openzeppelin/contracts/access/Ownable.sol";
/// inflation schedule.
contract GovernanceToken is ERC20Burnable, ERC20Votes, Ownable {
/// @notice Constructs the GovernanceToken contract.
constructor() ERC20("Optimism", "OP") ERC20Permit("Optimism") {}
constructor() ERC20("Optimism", "OP") ERC20Permit("Optimism") { }
/// @notice Allows the owner to mint tokens.
/// @param _account The account receiving minted tokens.
......@@ -27,11 +27,7 @@ contract GovernanceToken is ERC20Burnable, ERC20Votes, Ownable {
/// @param from The account sending tokens.
/// @param to The account receiving tokens.
/// @param amount The amount of tokens being transfered.
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC20, ERC20Votes) {
function _afterTokenTransfer(address from, address to, uint256 amount) internal override(ERC20, ERC20Votes) {
super._afterTokenTransfer(from, to, amount);
}
......
......@@ -41,10 +41,7 @@ contract MintManager is Ownable {
/// @param _amount The amount of tokens to mint.
function mint(address _account, uint256 _amount) public onlyOwner {
if (mintPermittedAfter > 0) {
require(
mintPermittedAfter <= block.timestamp,
"MintManager: minting not permitted yet"
);
require(mintPermittedAfter <= block.timestamp, "MintManager: minting not permitted yet");
require(
_amount <= (governanceToken.totalSupply() * MINT_CAP) / DENOMINATOR,
......@@ -59,10 +56,7 @@ contract MintManager is Ownable {
/// @notice Upgrade the owner of the governance token to a new MintManager.
/// @param _newMintManager The MintManager to upgrade to.
function upgrade(address _newMintManager) public onlyOwner {
require(
_newMintManager != address(0),
"MintManager: mint manager cannot be the zero address"
);
require(_newMintManager != address(0), "MintManager: mint manager cannot be the zero address");
governanceToken.transferOwnership(_newMintManager);
}
......
......@@ -36,15 +36,12 @@ contract DeployerWhitelist is Semver {
/// @notice Blocks functions to anyone except the contract owner.
modifier onlyOwner() {
require(
msg.sender == owner,
"DeployerWhitelist: function can only be called by the owner of this contract"
);
require(msg.sender == owner, "DeployerWhitelist: function can only be called by the owner of this contract");
_;
}
/// @custom:semver 1.0.1
constructor() Semver(1, 0, 1) {}
constructor() Semver(1, 0, 1) { }
/// @notice Adds or removes an address from the deployment whitelist.
/// @param _deployer Address to update permissions for.
......@@ -60,10 +57,7 @@ contract DeployerWhitelist is Semver {
// 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 other address that doesn't have a corresponding knowable private key.
require(
_owner != address(0),
"DeployerWhitelist: can only be disabled via enableArbitraryContractDeployment"
);
require(_owner != address(0), "DeployerWhitelist: can only be disabled via enableArbitraryContractDeployment");
emit OwnerChanged(owner, _owner);
owner = _owner;
......
......@@ -15,7 +15,7 @@ import { Semver } from "../universal/Semver.sol";
/// contract instead.
contract L1BlockNumber is Semver {
/// @custom:semver 1.0.1
constructor() Semver(1, 0, 1) {}
constructor() Semver(1, 0, 1) { }
/// @notice Returns the L1 block number.
receive() external payable {
......
......@@ -22,12 +22,10 @@ contract L1ChugSplashProxy {
bytes13 internal constant DEPLOY_CODE_PREFIX = 0x600D380380600D6000396000f3;
/// @notice bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
bytes32 internal constant IMPLEMENTATION_KEY =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
bytes32 internal constant IMPLEMENTATION_KEY = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/// @notice bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)
bytes32 internal constant OWNER_KEY =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
bytes32 internal constant OWNER_KEY = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/// @notice Blocks a function from being called when the parent signals that the system should
/// be paused via an isUpgrading function.
......@@ -37,9 +35,8 @@ contract L1ChugSplashProxy {
// We do a low-level call because there's no guarantee that the owner actually *is* an
// 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.
(bool success, bytes memory returndata) = owner.staticcall(
abi.encodeWithSelector(IL1ChugSplashDeployer.isUpgrading.selector)
);
(bool success, bytes memory returndata) =
owner.staticcall(abi.encodeWithSelector(IL1ChugSplashDeployer.isUpgrading.selector));
// If the call was unsuccessful then we assume that there's no "isUpgrading" method and we
// can just continue as normal. We also expect that the return value is exactly 32 bytes
......@@ -195,9 +192,7 @@ contract L1ChugSplashProxy {
returndatacopy(0x0, 0x0, returndatasize())
// Success == 0 means a revert. We'll revert too and pass the data up.
if iszero(success) {
revert(0x0, returndatasize())
}
if iszero(success) { revert(0x0, returndatasize()) }
// Otherwise we'll just return and pass the data up.
return(0x0, returndatasize())
......
......@@ -14,9 +14,7 @@ import { OptimismMintableERC20 } from "../universal/OptimismMintableERC20.sol";
/// disabled as part of the EVM equivalence upgrade.
contract LegacyERC20ETH is OptimismMintableERC20 {
/// @notice Initializes the contract as an Optimism Mintable ERC20.
constructor()
OptimismMintableERC20(Predeploys.L2_STANDARD_BRIDGE, address(0), "Ether", "ETH")
{}
constructor() OptimismMintableERC20(Predeploys.L2_STANDARD_BRIDGE, address(0), "Ether", "ETH") { }
/// @notice Returns the ETH balance of the target account. Overrides the base behavior of the
/// contract to preserve the invariant that the balance within this contract always
......@@ -53,11 +51,7 @@ contract LegacyERC20ETH is OptimismMintableERC20 {
/// @custom:blocked
/// @notice Transfers funds from some sender account.
function transferFrom(
address,
address,
uint256
) public virtual override returns (bool) {
function transferFrom(address, address, uint256) public virtual override returns (bool) {
revert("LegacyERC20ETH: transferFrom is disabled");
}
......
......@@ -14,7 +14,7 @@ contract LegacyMessagePasser is Semver {
mapping(bytes32 => bool) public sentMessages;
/// @custom:semver 1.0.1
constructor() Semver(1, 0, 1) {}
constructor() Semver(1, 0, 1) { }
/// @notice Passes a message to L1.
/// @param _message Message to pass to L1.
......
......@@ -29,7 +29,9 @@ contract LegacyMintableERC20 is ILegacyMintableERC20, ERC20 {
address _l1Token,
string memory _name,
string memory _symbol
) ERC20(_name, _symbol) {
)
ERC20(_name, _symbol)
{
l1Token = _l1Token;
l2Bridge = _l2Bridge;
}
......@@ -43,9 +45,8 @@ contract LegacyMintableERC20 is ILegacyMintableERC20, ERC20 {
/// @notice EIP165 implementation.
function supportsInterface(bytes4 _interfaceId) public pure returns (bool) {
bytes4 firstSupportedInterface = bytes4(keccak256("supportsInterface(bytes4)")); // ERC165
bytes4 secondSupportedInterface = ILegacyMintableERC20.l1Token.selector ^
ILegacyMintableERC20.mint.selector ^
ILegacyMintableERC20.burn.selector;
bytes4 secondSupportedInterface = ILegacyMintableERC20.l1Token.selector ^ ILegacyMintableERC20.mint.selector
^ ILegacyMintableERC20.burn.selector;
return _interfaceId == firstSupportedInterface || _interfaceId == secondSupportedInterface;
}
......
......@@ -32,9 +32,7 @@ contract ResolvedDelegateProxy {
/// @notice Fallback, performs a delegatecall to the resolved implementation address.
// solhint-disable-next-line no-complex-fallback
fallback() external payable {
address target = addressManager[address(this)].getAddress(
(implementationName[address(this)])
);
address target = addressManager[address(this)].getAddress((implementationName[address(this)]));
require(target != address(0), "ResolvedDelegateProxy: target address must be initialized");
......
......@@ -12,11 +12,7 @@ library Arithmetic {
/// @param _min The minimum value.
/// @param _max The maximum value.
/// @return The clamped value.
function clamp(
int256 _value,
int256 _min,
int256 _max
) internal pure returns (int256) {
function clamp(int256 _value, int256 _min, int256 _max) internal pure returns (int256) {
return SignedMath.min(SignedMath.max(_value, _min), _max);
}
......@@ -26,13 +22,7 @@ library Arithmetic {
/// @param _denominator Fractional denominator.
/// @param _exponent Power function exponent.
/// @return Result of c * (1 - 1/d)^exp.
function cdexp(
int256 _coefficient,
int256 _denominator,
int256 _exponent
) internal pure returns (int256) {
return
(_coefficient *
(FixedPointMathLib.powWad(1e18 - (1e18 / _denominator), _exponent * 1e18))) / 1e18;
function cdexp(int256 _coefficient, int256 _denominator, int256 _exponent) internal pure returns (int256) {
return (_coefficient * (FixedPointMathLib.powWad(1e18 - (1e18 / _denominator), _exponent * 1e18))) / 1e18;
}
}
......@@ -12,11 +12,7 @@ library Bytes {
/// @param _start Starting index of the slice.
/// @param _length Length of the slice.
/// @return Slice of the input byte array.
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory) {
unchecked {
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
......@@ -56,9 +52,7 @@ library Bytes {
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
} { mstore(mc, mload(cc)) }
mstore(tempBytes, _length)
......@@ -125,11 +119,7 @@ library Bytes {
let nibblesStart := add(_nibbles, 0x20)
// Loop through each byte in the input array
for {
let i := 0x00
} lt(i, bytesLength) {
i := add(i, 0x01)
} {
for { let i := 0x00 } lt(i, bytesLength) { i := add(i, 0x01) } {
// Get the starting offset of the next 2 bytes in the nibbles array
let offset := add(nibblesStart, shl(0x01, i))
// Load the byte at the current index within the `_bytes` array
......
......@@ -46,11 +46,7 @@ contract Clone {
/// @param argOffset The offset of the arg in the packed data
/// @param arrLen Number of elements in the array
/// @return arr The array
function _getArgUint256Array(uint256 argOffset, uint64 arrLen)
internal
pure
returns (uint256[] memory arr)
{
function _getArgUint256Array(uint256 argOffset, uint64 arrLen) internal pure returns (uint256[] memory arr) {
uint256 offset = _getImmutableArgsOffset() + argOffset;
arr = new uint256[](arrLen);
......@@ -63,11 +59,7 @@ contract Clone {
/// @param argOffset The offset of the arg in the packed data
/// @param arrLen Number of elements in the array
/// @return arr The array
function _getArgDynBytes(uint256 argOffset, uint64 arrLen)
internal
pure
returns (bytes memory arr)
{
function _getArgDynBytes(uint256 argOffset, uint64 arrLen) internal pure returns (bytes memory arr) {
uint256 offset = _getImmutableArgsOffset() + argOffset;
arr = new bytes(arrLen);
......
......@@ -23,11 +23,7 @@ library Constants {
/// @notice Returns the default values for the ResourceConfig. These are the recommended values
/// for a production network.
function DEFAULT_RESOURCE_CONFIG()
internal
pure
returns (ResourceMetering.ResourceConfig memory)
{
function DEFAULT_RESOURCE_CONFIG() internal pure returns (ResourceMetering.ResourceConfig memory) {
ResourceMetering.ResourceConfig memory config = ResourceMetering.ResourceConfig({
maxResourceLimit: 20_000_000,
elasticityMultiplier: 10,
......
......@@ -60,8 +60,9 @@ type Position is uint128;
type GameType is uint8;
/// @notice The current status of the dispute game.
enum GameStatus {
// The game is currently in progress, and has not been resolved.
enum GameStatus
// The game is currently in progress, and has not been resolved.
{
IN_PROGRESS,
// The game has concluded, and the `rootClaim` was challenged successfully.
CHALLENGER_WINS,
......
......@@ -13,11 +13,7 @@ library Encoding {
/// transaction is prefixed with 0x7e to identify its EIP-2718 type.
/// @param _tx User deposit transaction to encode.
/// @return RLP encoded L2 deposit transaction.
function encodeDepositTransaction(Types.UserDepositTransaction memory _tx)
internal
pure
returns (bytes memory)
{
function encodeDepositTransaction(Types.UserDepositTransaction memory _tx) internal pure returns (bytes memory) {
bytes32 source = Hashing.hashDepositSource(_tx.l1BlockHash, _tx.logIndex);
bytes[] memory raw = new bytes[](8);
raw[0] = RLPWriter.writeBytes(abi.encodePacked(source));
......@@ -47,7 +43,11 @@ library Encoding {
uint256 _value,
uint256 _gasLimit,
bytes memory _data
) internal pure returns (bytes memory) {
)
internal
pure
returns (bytes memory)
{
(, uint16 version) = decodeVersionedNonce(_nonce);
if (version == 0) {
return encodeCrossDomainMessageV0(_target, _sender, _data, _nonce);
......@@ -69,15 +69,12 @@ library Encoding {
address _sender,
bytes memory _data,
uint256 _nonce
) internal pure returns (bytes memory) {
return
abi.encodeWithSignature(
"relayMessage(address,address,bytes,uint256)",
_target,
_sender,
_data,
_nonce
);
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSignature("relayMessage(address,address,bytes,uint256)", _target, _sender, _data, _nonce);
}
/// @notice Encodes a cross domain message based on the V1 (current) encoding.
......@@ -95,17 +92,20 @@ library Encoding {
uint256 _value,
uint256 _gasLimit,
bytes memory _data
) internal pure returns (bytes memory) {
return
abi.encodeWithSignature(
"relayMessage(uint256,address,address,uint256,uint256,bytes)",
_nonce,
_sender,
_target,
_value,
_gasLimit,
_data
);
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSignature(
"relayMessage(uint256,address,address,uint256,uint256,bytes)",
_nonce,
_sender,
_target,
_value,
_gasLimit,
_data
);
}
/// @notice Adds a version number into the first two bytes of a message nonce.
......
......@@ -12,11 +12,7 @@ library Hashing {
/// system.
/// @param _tx User deposit transaction to hash.
/// @return Hash of the RLP encoded L2 deposit transaction.
function hashDepositTransaction(Types.UserDepositTransaction memory _tx)
internal
pure
returns (bytes32)
{
function hashDepositTransaction(Types.UserDepositTransaction memory _tx) internal pure returns (bytes32) {
return keccak256(Encoding.encodeDepositTransaction(_tx));
}
......@@ -26,11 +22,7 @@ library Hashing {
/// @param _l1BlockHash Hash of the L1 block where the deposit was included.
/// @param _logIndex The index of the log that created the deposit transaction.
/// @return Hash of the deposit transaction's "source hash".
function hashDepositSource(bytes32 _l1BlockHash, uint256 _logIndex)
internal
pure
returns (bytes32)
{
function hashDepositSource(bytes32 _l1BlockHash, uint256 _logIndex) internal pure returns (bytes32) {
bytes32 depositId = keccak256(abi.encode(_l1BlockHash, _logIndex));
return keccak256(abi.encode(bytes32(0), depositId));
}
......@@ -51,7 +43,11 @@ library Hashing {
uint256 _value,
uint256 _gasLimit,
bytes memory _data
) internal pure returns (bytes32) {
)
internal
pure
returns (bytes32)
{
(, uint16 version) = Encoding.decodeVersionedNonce(_nonce);
if (version == 0) {
return hashCrossDomainMessageV0(_target, _sender, _data, _nonce);
......@@ -73,7 +69,11 @@ library Hashing {
address _sender,
bytes memory _data,
uint256 _nonce
) internal pure returns (bytes32) {
)
internal
pure
returns (bytes32)
{
return keccak256(Encoding.encodeCrossDomainMessageV0(_target, _sender, _data, _nonce));
}
......@@ -92,51 +92,33 @@ library Hashing {
uint256 _value,
uint256 _gasLimit,
bytes memory _data
) internal pure returns (bytes32) {
return
keccak256(
Encoding.encodeCrossDomainMessageV1(
_nonce,
_sender,
_target,
_value,
_gasLimit,
_data
)
);
)
internal
pure
returns (bytes32)
{
return keccak256(Encoding.encodeCrossDomainMessageV1(_nonce, _sender, _target, _value, _gasLimit, _data));
}
/// @notice Derives the withdrawal hash according to the encoding in the L2 Withdrawer contract
/// @param _tx Withdrawal transaction to hash.
/// @return Hashed withdrawal transaction.
function hashWithdrawal(Types.WithdrawalTransaction memory _tx)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(_tx.nonce, _tx.sender, _tx.target, _tx.value, _tx.gasLimit, _tx.data)
);
function hashWithdrawal(Types.WithdrawalTransaction memory _tx) internal pure returns (bytes32) {
return keccak256(abi.encode(_tx.nonce, _tx.sender, _tx.target, _tx.value, _tx.gasLimit, _tx.data));
}
/// @notice Hashes the various elements of an output root proof into an output root hash which
/// can be used to check if the proof is valid.
/// @param _outputRootProof Output root proof which should hash to an output root.
/// @return Hashed output root proof.
function hashOutputRootProof(Types.OutputRootProof memory _outputRootProof)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
_outputRootProof.version,
_outputRootProof.stateRoot,
_outputRootProof.messagePasserStorageRoot,
_outputRootProof.latestBlockhash
)
);
function hashOutputRootProof(Types.OutputRootProof memory _outputRootProof) internal pure returns (bytes32) {
return keccak256(
abi.encode(
_outputRootProof.version,
_outputRootProof.stateRoot,
_outputRootProof.messagePasserStorageRoot,
_outputRootProof.latestBlockhash
)
);
}
}
......@@ -19,14 +19,13 @@ library LegacyCrossDomainUtils {
address _sender,
bytes memory _message,
uint256 _messageNonce
) internal pure returns (bytes memory) {
return
abi.encodeWithSignature(
"relayMessage(address,address,bytes,uint256)",
_target,
_sender,
_message,
_messageNonce
);
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSignature(
"relayMessage(address,address,bytes,uint256)", _target, _sender, _message, _messageNonce
);
}
}
......@@ -8,8 +8,7 @@ library Predeploys {
address internal constant L2_TO_L1_MESSAGE_PASSER = 0x4200000000000000000000000000000000000016;
/// @notice Address of the L2CrossDomainMessenger predeploy.
address internal constant L2_CROSS_DOMAIN_MESSENGER =
0x4200000000000000000000000000000000000007;
address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000007;
/// @notice Address of the L2StandardBridge predeploy.
address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010;
......@@ -21,12 +20,10 @@ library Predeploys {
address internal constant SEQUENCER_FEE_WALLET = 0x4200000000000000000000000000000000000011;
/// @notice Address of the OptimismMintableERC20Factory predeploy.
address internal constant OPTIMISM_MINTABLE_ERC20_FACTORY =
0x4200000000000000000000000000000000000012;
address internal constant OPTIMISM_MINTABLE_ERC20_FACTORY = 0x4200000000000000000000000000000000000012;
/// @notice Address of the OptimismMintableERC721Factory predeploy.
address internal constant OPTIMISM_MINTABLE_ERC721_FACTORY =
0x4200000000000000000000000000000000000017;
address internal constant OPTIMISM_MINTABLE_ERC721_FACTORY = 0x4200000000000000000000000000000000000017;
/// @notice Address of the L1Block predeploy.
address internal constant L1_BLOCK_ATTRIBUTES = 0x4200000000000000000000000000000000000015;
......
......@@ -9,22 +9,19 @@ library SafeCall {
/// @param _target Address to call
/// @param _gas Amount of gas to pass to the call
/// @param _value Amount of value to pass to the call
function send(
address _target,
uint256 _gas,
uint256 _value
) internal returns (bool) {
function send(address _target, uint256 _gas, uint256 _value) internal returns (bool) {
bool _success;
assembly {
_success := call(
_gas, // gas
_target, // recipient
_value, // ether value
0, // inloc
0, // inlen
0, // outloc
0 // outlen
)
_success :=
call(
_gas, // gas
_target, // recipient
_value, // ether value
0, // inloc
0, // inlen
0, // outloc
0 // outlen
)
}
return _success;
}
......@@ -34,23 +31,19 @@ library SafeCall {
/// @param _gas Amount of gas to pass to the call
/// @param _value Amount of value to pass to the call
/// @param _calldata Calldata to pass to the call
function call(
address _target,
uint256 _gas,
uint256 _value,
bytes memory _calldata
) internal returns (bool) {
function call(address _target, uint256 _gas, uint256 _value, bytes memory _calldata) internal returns (bool) {
bool _success;
assembly {
_success := call(
_gas, // gas
_target, // recipient
_value, // ether value
add(_calldata, 32), // inloc
mload(_calldata), // inlen
0, // outloc
0 // outlen
)
_success :=
call(
_gas, // gas
_target, // recipient
_value, // ether value
add(_calldata, 32), // inloc
mload(_calldata), // inlen
0, // outloc
0 // outlen
)
}
return _success;
}
......@@ -82,9 +75,7 @@ library SafeCall {
bool _hasMinGas;
assembly {
// Equation: gas × 63 ≥ minGas × 64 + 63(40_000 + reservedGas)
_hasMinGas := iszero(
lt(mul(gas(), 63), add(mul(_minGas, 64), mul(add(40000, _reservedGas), 63)))
)
_hasMinGas := iszero(lt(mul(gas(), 63), add(mul(_minGas, 64), mul(add(40000, _reservedGas), 63))))
}
return _hasMinGas;
}
......@@ -101,7 +92,10 @@ library SafeCall {
uint256 _minGas,
uint256 _value,
bytes memory _calldata
) internal returns (bool) {
)
internal
returns (bool)
{
bool _success;
bool _hasMinGas = hasMinGas(_minGas, 0);
assembly {
......@@ -132,15 +126,16 @@ library SafeCall {
// `_minGas` does not account for the `memory_expansion_cost` and `code_execution_cost`
// factors of the dynamic cost of the `CALL` opcode), the call will receive at least
// the minimum amount of gas specified.
_success := call(
gas(), // gas
_target, // recipient
_value, // ether value
add(_calldata, 32), // inloc
mload(_calldata), // inlen
0x00, // outloc
0x00 // outlen
)
_success :=
call(
gas(), // gas
_target, // recipient
_value, // ether value
add(_calldata, 32), // inloc
mload(_calldata), // inlen
0x00, // outloc
0x00 // outlen
)
}
return _success;
}
......
......@@ -34,10 +34,7 @@ library RLPReader {
/// @return out_ Output memory reference.
function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory out_) {
// Empty arrays are not RLP items.
require(
_in.length > 0,
"RLPReader: length of an RLP item must be greater than zero to be decodable"
);
require(_in.length > 0, "RLPReader: length of an RLP item must be greater than zero to be decodable");
MemoryPointer ptr;
assembly {
......@@ -53,15 +50,9 @@ library RLPReader {
function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory out_) {
(uint256 listOffset, uint256 listLength, RLPItemType itemType) = _decodeLength(_in);
require(
itemType == RLPItemType.LIST_ITEM,
"RLPReader: decoded item type for list is not a list item"
);
require(itemType == RLPItemType.LIST_ITEM, "RLPReader: decoded item type for list is not a list item");
require(
listOffset + listLength == _in.length,
"RLPReader: list item has an invalid data remainder"
);
require(listOffset + listLength == _in.length, "RLPReader: list item has an invalid data remainder");
// 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
......@@ -72,11 +63,8 @@ library RLPReader {
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
(uint256 itemOffset, uint256 itemLength, ) = _decodeLength(
RLPItem({
length: _in.length - offset,
ptr: MemoryPointer.wrap(MemoryPointer.unwrap(_in.ptr) + offset)
})
(uint256 itemOffset, uint256 itemLength,) = _decodeLength(
RLPItem({ length: _in.length - offset, ptr: MemoryPointer.wrap(MemoryPointer.unwrap(_in.ptr) + offset) })
);
// We don't need to check itemCount < out.length explicitly because Solidity already
......@@ -109,15 +97,9 @@ library RLPReader {
function readBytes(RLPItem memory _in) internal pure returns (bytes memory out_) {
(uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"RLPReader: decoded item type for bytes is not a data item"
);
require(itemType == RLPItemType.DATA_ITEM, "RLPReader: decoded item type for bytes is not a data item");
require(
_in.length == itemOffset + itemLength,
"RLPReader: bytes value contains an invalid remainder"
);
require(_in.length == itemOffset + itemLength, "RLPReader: bytes value contains an invalid remainder");
out_ = _copy(_in.ptr, itemOffset, itemLength);
}
......@@ -144,19 +126,12 @@ library RLPReader {
function _decodeLength(RLPItem memory _in)
private
pure
returns (
uint256 offset_,
uint256 length_,
RLPItemType type_
)
returns (uint256 offset_, uint256 length_, RLPItemType type_)
{
// Short-circuit if there's nothing to decode, note that we perform this check when
// the user creates an RLP item via toRLPItem, but it's always possible for them to bypass
// that function and create an RLP item directly. So we need to check this anyway.
require(
_in.length > 0,
"RLPReader: length of an RLP item must be greater than zero to be decodable"
);
require(_in.length > 0, "RLPReader: length of an RLP item must be greater than zero to be decodable");
MemoryPointer ptr = _in.ptr;
uint256 prefix;
......@@ -174,8 +149,7 @@ library RLPReader {
uint256 strLen = prefix - 0x80;
require(
_in.length > strLen,
"RLPReader: length of content must be greater than string length (short string)"
_in.length > strLen, "RLPReader: length of content must be greater than string length (short string)"
);
bytes1 firstByteOfContent;
......@@ -204,8 +178,7 @@ library RLPReader {
}
require(
firstByteOfContent != 0x00,
"RLPReader: length of content must not have any leading zeros (long string)"
firstByteOfContent != 0x00, "RLPReader: length of content must not have any leading zeros (long string)"
);
uint256 strLen;
......@@ -213,10 +186,7 @@ library RLPReader {
strLen := shr(sub(256, mul(8, lenOfStrLen)), mload(add(ptr, 1)))
}
require(
strLen > 55,
"RLPReader: length of content must be greater than 55 bytes (long string)"
);
require(strLen > 55, "RLPReader: length of content must be greater than 55 bytes (long string)");
require(
_in.length > lenOfStrLen + strLen,
......@@ -229,10 +199,7 @@ library RLPReader {
// slither-disable-next-line variable-scope
uint256 listLen = prefix - 0xc0;
require(
_in.length > listLen,
"RLPReader: length of content must be greater than list length (short list)"
);
require(_in.length > listLen, "RLPReader: length of content must be greater than list length (short list)");
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
......@@ -250,8 +217,7 @@ library RLPReader {
}
require(
firstByteOfContent != 0x00,
"RLPReader: length of content must not have any leading zeros (long list)"
firstByteOfContent != 0x00, "RLPReader: length of content must not have any leading zeros (long list)"
);
uint256 listLen;
......@@ -259,10 +225,7 @@ library RLPReader {
listLen := shr(sub(256, mul(8, lenOfListLen)), mload(add(ptr, 1)))
}
require(
listLen > 55,
"RLPReader: length of content must be greater than 55 bytes (long list)"
);
require(listLen > 55, "RLPReader: length of content must be greater than 55 bytes (long list)");
require(
_in.length > lenOfListLen + listLen,
......@@ -278,11 +241,7 @@ library RLPReader {
/// @param _offset Offset to start reading from.
/// @param _length Number of bytes to read.
/// @return out_ Copied bytes.
function _copy(
MemoryPointer _src,
uint256 _offset,
uint256 _length
) private pure returns (bytes memory out_) {
function _copy(MemoryPointer _src, uint256 _offset, uint256 _length) private pure returns (bytes memory out_) {
out_ = new bytes(_length);
if (_length == 0) {
return out_;
......@@ -295,17 +254,9 @@ library RLPReader {
assembly {
let dest := add(out_, 32)
let i := 0
for {
} lt(i, _length) {
i := add(i, 32)
} {
mstore(add(dest, i), mload(add(src, i)))
}
for { } lt(i, _length) { i := add(i, 32) } { mstore(add(dest, i), mload(add(src, i))) }
if gt(i, _length) {
mstore(add(dest, _length), 0)
}
if gt(i, _length) { mstore(add(dest, _length), 0) }
}
}
}
......@@ -74,7 +74,7 @@ library RLPWriter {
out_ = new bytes(lenLen + 1);
out_[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);
for (i = 1; i <= lenLen; i++) {
out_[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256));
out_[i] = bytes1(uint8((_len / (256 ** (lenLen - i))) % 256));
}
}
}
......@@ -103,11 +103,7 @@ library RLPWriter {
/// @param _dest Destination location.
/// @param _src Source location.
/// @param _len Length of memory to copy.
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
) private pure {
function _memcpy(uint256 _dest, uint256 _src, uint256 _len) private pure {
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
......@@ -122,7 +118,7 @@ library RLPWriter {
uint256 mask;
unchecked {
mask = 256**(32 - len) - 1;
mask = 256 ** (32 - len) - 1;
}
assembly {
let srcpart := and(mload(src), not(mask))
......
......@@ -52,7 +52,11 @@ library MerkleTrie {
bytes memory _value,
bytes[] memory _proof,
bytes32 _root
) internal pure returns (bool valid_) {
)
internal
pure
returns (bool valid_)
{
valid_ = Bytes.equal(_value, get(_key, _proof, _root));
}
......@@ -61,11 +65,7 @@ library MerkleTrie {
/// @param _proof Merkle trie inclusion proof for the key.
/// @param _root Known root of the Merkle trie.
/// @return value_ Value of the key if it exists.
function get(
bytes memory _key,
bytes[] memory _proof,
bytes32 _root
) internal pure returns (bytes memory value_) {
function get(bytes memory _key, bytes[] memory _proof, bytes32 _root) internal pure returns (bytes memory value_) {
require(_key.length > 0, "MerkleTrie: empty key");
TrieNode[] memory proof = _parseProof(_proof);
......@@ -78,10 +78,7 @@ library MerkleTrie {
TrieNode memory currentNode = proof[i];
// Key index should never exceed total key length or we'll be out of bounds.
require(
currentKeyIndex <= key.length,
"MerkleTrie: key index exceeds total key length"
);
require(currentKeyIndex <= key.length, "MerkleTrie: key index exceeds total key length");
if (currentKeyIndex == 0) {
// First proof element is always the root node.
......@@ -97,10 +94,7 @@ library MerkleTrie {
);
} else {
// Nodes smaller than 32 bytes aren't hashed.
require(
Bytes.equal(currentNode.encoded, currentNodeID),
"MerkleTrie: invalid internal node hash"
);
require(Bytes.equal(currentNode.encoded, currentNodeID), "MerkleTrie: invalid internal node hash");
}
if (currentNode.decoded.length == BRANCH_NODE_LENGTH) {
......@@ -111,16 +105,10 @@ library MerkleTrie {
// even when the value wasn't explicitly placed there. Geth treats a value of
// bytes(0) as "key does not exist" and so we do the same.
value_ = RLPReader.readBytes(currentNode.decoded[TREE_RADIX]);
require(
value_.length > 0,
"MerkleTrie: value length must be greater than zero (branch)"
);
require(value_.length > 0, "MerkleTrie: value length must be greater than zero (branch)");
// Extra proof elements are not allowed.
require(
i == proof.length - 1,
"MerkleTrie: value node must be last node in proof (branch)"
);
require(i == proof.length - 1, "MerkleTrie: value node must be last node in proof (branch)");
return value_;
} else {
......@@ -164,16 +152,10 @@ library MerkleTrie {
// say that if the value is empty, the key should not exist and the proof is
// invalid.
value_ = RLPReader.readBytes(currentNode.decoded[1]);
require(
value_.length > 0,
"MerkleTrie: value length must be greater than zero (leaf)"
);
require(value_.length > 0, "MerkleTrie: value length must be greater than zero (leaf)");
// Extra proof elements are not allowed.
require(
i == proof.length - 1,
"MerkleTrie: value node must be last node in proof (leaf)"
);
require(i == proof.length - 1, "MerkleTrie: value node must be last node in proof (leaf)");
return value_;
} else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {
......@@ -200,7 +182,7 @@ library MerkleTrie {
function _parseProof(bytes[] memory _proof) private pure returns (TrieNode[] memory proof_) {
uint256 length = _proof.length;
proof_ = new TrieNode[](length);
for (uint256 i = 0; i < length; ) {
for (uint256 i = 0; i < length;) {
proof_[i] = TrieNode({ encoded: _proof[i], decoded: RLPReader.readList(_proof[i]) });
unchecked {
++i;
......@@ -227,13 +209,9 @@ library MerkleTrie {
/// @param _a First nibble array.
/// @param _b Second nibble array.
/// @return shared_ Number of shared nibbles.
function _getSharedNibbleLength(bytes memory _a, bytes memory _b)
private
pure
returns (uint256 shared_)
{
function _getSharedNibbleLength(bytes memory _a, bytes memory _b) private pure returns (uint256 shared_) {
uint256 max = (_a.length < _b.length) ? _a.length : _b.length;
for (; shared_ < max && _a[shared_] == _b[shared_]; ) {
for (; shared_ < max && _a[shared_] == _b[shared_];) {
unchecked {
++shared_;
}
......
......@@ -21,7 +21,11 @@ library SecureMerkleTrie {
bytes memory _value,
bytes[] memory _proof,
bytes32 _root
) internal pure returns (bool valid_) {
)
internal
pure
returns (bool valid_)
{
bytes memory key = _getSecureKey(_key);
valid_ = MerkleTrie.verifyInclusionProof(key, _value, _proof, _root);
}
......@@ -31,11 +35,7 @@ library SecureMerkleTrie {
/// @param _proof Merkle trie inclusion proof for the key.
/// @param _root Known root of the Merkle trie.
/// @return value_ Value of the key if it exists.
function get(
bytes memory _key,
bytes[] memory _proof,
bytes32 _root
) internal pure returns (bytes memory value_) {
function get(bytes memory _key, bytes[] memory _proof, bytes32 _root) internal pure returns (bytes memory value_) {
bytes memory key = _getSecureKey(_key);
value_ = MerkleTrie.get(key, _proof, _root);
}
......
......@@ -25,27 +25,17 @@ contract AssetReceiver is Transactor {
/// @param recipient Address that received the withdrawal.
/// @param asset Address of the token being withdrawn.
/// @param amount ERC20 amount withdrawn.
event WithdrewERC20(
address indexed withdrawer,
address indexed recipient,
address indexed asset,
uint256 amount
);
event WithdrewERC20(address indexed withdrawer, address indexed recipient, address indexed asset, uint256 amount);
/// @notice Emitted when ERC20 tokens are withdrawn from this address.
/// @param withdrawer Address that triggered the withdrawal.
/// @param recipient Address that received the withdrawal.
/// @param asset Address of the token being withdrawn.
/// @param id Token ID being withdrawn.
event WithdrewERC721(
address indexed withdrawer,
address indexed recipient,
address indexed asset,
uint256 id
);
event WithdrewERC721(address indexed withdrawer, address indexed recipient, address indexed asset, uint256 id);
/// @param _owner Initial contract owner.
constructor(address _owner) Transactor(_owner) {}
constructor(address _owner) Transactor(_owner) { }
/// @notice Make sure we can receive ETH.
receive() external payable {
......@@ -63,7 +53,7 @@ contract AssetReceiver is Transactor {
/// @param _amount Amount of ETH to withdraw.
function withdrawETH(address payable _to, uint256 _amount) public onlyOwner {
// slither-disable-next-line reentrancy-unlimited-gas
(bool success, ) = _to.call{ value: _amount }("");
(bool success,) = _to.call{ value: _amount }("");
success; // Suppress warning; We ignore the low-level call result.
emit WithdrewETH(msg.sender, _to, _amount);
}
......@@ -79,11 +69,7 @@ contract AssetReceiver is Transactor {
/// @param _asset ERC20 token to withdraw.
/// @param _to Address to receive the ERC20 balance.
/// @param _amount Amount of ERC20 to withdraw.
function withdrawERC20(
ERC20 _asset,
address _to,
uint256 _amount
) public onlyOwner {
function withdrawERC20(ERC20 _asset, address _to, uint256 _amount) public onlyOwner {
// slither-disable-next-line unchecked-transfer
_asset.transfer(_to, _amount);
// slither-disable-next-line reentrancy-events
......@@ -94,11 +80,7 @@ contract AssetReceiver is Transactor {
/// @param _asset ERC721 token to withdraw.
/// @param _to Address to receive the ERC721 token.
/// @param _id Token ID of the ERC721 token to withdraw.
function withdrawERC721(
ERC721 _asset,
address _to,
uint256 _id
) external onlyOwner {
function withdrawERC721(ERC721 _asset, address _to, uint256 _id) external onlyOwner {
_asset.transferFrom(address(this), _to, _id);
// slither-disable-next-line reentrancy-events
emit WithdrewERC721(msg.sender, _to, address(_asset), _id);
......
......@@ -7,7 +7,7 @@ import { Owned } from "@rari-capital/solmate/src/auth/Owned.sol";
/// @notice Transactor is a minimal contract that can send transactions.
contract Transactor is Owned {
/// @param _owner Initial contract owner.
constructor(address _owner) Owned(_owner) {}
constructor(address _owner) Owned(_owner) { }
/// @notice Sends a CALL to a target address.
/// @param _target Address to call.
......@@ -19,7 +19,12 @@ contract Transactor is Owned {
address _target,
bytes memory _data,
uint256 _value
) external payable onlyOwner returns (bool success_, bytes memory data_) {
)
external
payable
onlyOwner
returns (bool success_, bytes memory data_)
{
(success_, data_) = _target.call{ value: _value }(_data);
}
......@@ -28,7 +33,10 @@ contract Transactor is Owned {
/// @param _data Data to send with the call.
/// @return success_ Boolean success value.
/// @return data_ Bytes data returned by the call.
function DELEGATECALL(address _target, bytes memory _data)
function DELEGATECALL(
address _target,
bytes memory _data
)
external
payable
onlyOwner
......
......@@ -33,11 +33,7 @@ contract TransferOnion is ReentrancyGuard {
/// @param _token Address of the token to distribute.
/// @param _sender Address of the sender to distribute from.
/// @param _shell Initial shell of the onion.
constructor(
ERC20 _token,
address _sender,
bytes32 _shell
) {
constructor(ERC20 _token, address _sender, bytes32 _shell) {
TOKEN = _token;
SENDER = _sender;
shell = _shell;
......@@ -48,7 +44,7 @@ contract TransferOnion is ReentrancyGuard {
function peel(Layer[] memory _layers) public nonReentrant {
bytes32 tempShell = shell;
uint256 length = _layers.length;
for (uint256 i = 0; i < length; ) {
for (uint256 i = 0; i < length;) {
Layer memory layer = _layers[i];
// Confirm that the onion layer is correct.
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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