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