diff --git a/packages/protocol/contracts/L1/ITaikoL1.sol b/packages/protocol/contracts/L1/ITaikoL1.sol index 7823dccd6da..82cc6d8df72 100644 --- a/packages/protocol/contracts/L1/ITaikoL1.sol +++ b/packages/protocol/contracts/L1/ITaikoL1.sol @@ -7,31 +7,28 @@ import "./TaikoData.sol"; /// @custom:security-contact security@taiko.xyz interface ITaikoL1 { /// @notice Proposes a Taiko L2 block. - /// @param params Block parameters, currently an encoded BlockParams object. - /// @param txList txList data if calldata is used for DA. - /// @return meta The metadata of the proposed L2 block. - /// @return depositsProcessed The Ether deposits processed. + /// @param _params Block parameters, currently an encoded BlockParams object. + /// @param _txList txList data if calldata is used for DA. + /// @return meta_ The metadata of the proposed L2 block. + /// @return deposits_ The Ether deposits processed. function proposeBlock( - bytes calldata params, - bytes calldata txList + bytes calldata _params, + bytes calldata _txList ) external payable - returns ( - TaikoData.BlockMetadata memory meta, - TaikoData.EthDeposit[] memory depositsProcessed - ); + returns (TaikoData.BlockMetadata memory meta_, TaikoData.EthDeposit[] memory deposits_); /// @notice Proves or contests a block transition. - /// @param blockId The index of the block to prove. This is also used to + /// @param _blockId The index of the block to prove. This is also used to /// select the right implementation version. - /// @param input An abi-encoded (BlockMetadata, Transition, TierProof) - /// tuple. - function proveBlock(uint64 blockId, bytes calldata input) external; + /// @param _input An abi-encoded (TaikoData.BlockMetadata, TaikoData.Transition, + /// TaikoData.TierProof) tuple. + function proveBlock(uint64 _blockId, bytes calldata _input) external; /// @notice Verifies up to a certain number of blocks. - /// @param maxBlocksToVerify Max number of blocks to verify. - function verifyBlocks(uint64 maxBlocksToVerify) external; + /// @param _maxBlocksToVerify Max number of blocks to verify. + function verifyBlocks(uint64 _maxBlocksToVerify) external; /// @notice Gets the configuration of the TaikoL1 contract. /// @return Config struct containing configuration parameters. diff --git a/packages/protocol/contracts/L1/TaikoL1.sol b/packages/protocol/contracts/L1/TaikoL1.sol index 6d9669c0901..4c12105d35f 100644 --- a/packages/protocol/contracts/L1/TaikoL1.sol +++ b/packages/protocol/contracts/L1/TaikoL1.sol @@ -53,21 +53,18 @@ contract TaikoL1 is EssentialContract, ITaikoL1, TaikoEvents, TaikoErrors { /// @inheritdoc ITaikoL1 function proposeBlock( - bytes calldata params, - bytes calldata txList + bytes calldata _params, + bytes calldata _txList ) external payable nonReentrant whenNotPaused - returns ( - TaikoData.BlockMetadata memory meta, - TaikoData.EthDeposit[] memory depositsProcessed - ) + returns (TaikoData.BlockMetadata memory meta_, TaikoData.EthDeposit[] memory deposits_) { TaikoData.Config memory config = getConfig(); - (meta, depositsProcessed) = LibProposing.proposeBlock(state, config, this, params, txList); + (meta_, deposits_) = LibProposing.proposeBlock(state, config, this, _params, _txList); if (!state.slotB.provingPaused) { LibVerifying.verifyBlocks(state, config, this, config.maxBlocksToVerifyPerProposal); @@ -76,8 +73,8 @@ contract TaikoL1 is EssentialContract, ITaikoL1, TaikoEvents, TaikoErrors { /// @inheritdoc ITaikoL1 function proveBlock( - uint64 blockId, - bytes calldata input + uint64 _blockId, + bytes calldata _input ) external nonReentrant @@ -88,9 +85,9 @@ contract TaikoL1 is EssentialContract, ITaikoL1, TaikoEvents, TaikoErrors { TaikoData.BlockMetadata memory meta, TaikoData.Transition memory tran, TaikoData.TierProof memory proof - ) = abi.decode(input, (TaikoData.BlockMetadata, TaikoData.Transition, TaikoData.TierProof)); + ) = abi.decode(_input, (TaikoData.BlockMetadata, TaikoData.Transition, TaikoData.TierProof)); - if (blockId != meta.id) revert L1_INVALID_BLOCK_ID(); + if (_blockId != meta.id) revert L1_INVALID_BLOCK_ID(); TaikoData.Config memory config = getConfig(); @@ -100,27 +97,27 @@ contract TaikoL1 is EssentialContract, ITaikoL1, TaikoEvents, TaikoErrors { } /// @inheritdoc ITaikoL1 - function verifyBlocks(uint64 maxBlocksToVerify) + function verifyBlocks(uint64 _maxBlocksToVerify) external nonReentrant whenNotPaused whenProvingNotPaused { - LibVerifying.verifyBlocks(state, getConfig(), this, maxBlocksToVerify); + LibVerifying.verifyBlocks(state, getConfig(), this, _maxBlocksToVerify); } /// @notice Pause block proving. - /// @param pause True if paused. - function pauseProving(bool pause) external { + /// @param _pause True if paused. + function pauseProving(bool _pause) external { _authorizePause(msg.sender); - LibProving.pauseProving(state, pause); + LibProving.pauseProving(state, _pause); } /// @notice Deposits Ether to Layer 2. - /// @param recipient Address of the recipient for the deposited Ether on + /// @param _recipient Address of the recipient for the deposited Ether on /// Layer 2. - function depositEtherToL2(address recipient) external payable nonReentrant whenNotPaused { - LibDepositing.depositEtherToL2(state, getConfig(), this, recipient); + function depositEtherToL2(address _recipient) external payable nonReentrant whenNotPaused { + LibDepositing.depositEtherToL2(state, getConfig(), this, _recipient); } /// @inheritdoc EssentialContract @@ -130,59 +127,59 @@ contract TaikoL1 is EssentialContract, ITaikoL1, TaikoEvents, TaikoErrors { } /// @notice Checks if Ether deposit is allowed for Layer 2. - /// @param amount Amount of Ether to be deposited. + /// @param _amount Amount of Ether to be deposited. /// @return true if Ether deposit is allowed, false otherwise. - function canDepositEthToL2(uint256 amount) public view returns (bool) { - return LibDepositing.canDepositEthToL2(state, getConfig(), amount); + function canDepositEthToL2(uint256 _amount) public view returns (bool) { + return LibDepositing.canDepositEthToL2(state, getConfig(), _amount); } /// @notice See {LibProposing-isBlobReusable}. - function isBlobReusable(bytes32 blobHash) public view returns (bool) { - return LibProposing.isBlobReusable(state, getConfig(), blobHash); + function isBlobReusable(bytes32 _blobHash) public view returns (bool) { + return LibProposing.isBlobReusable(state, getConfig(), _blobHash); } /// @notice Gets the details of a block. - /// @param blockId Index of the block. - /// @return blk The block. - /// @return ts The transition used to verify this block. - function getBlock(uint64 blockId) + /// @param _blockId Index of the block. + /// @return blk_ The block. + /// @return ts_ The transition used to verify this block. + function getBlock(uint64 _blockId) public view - returns (TaikoData.Block memory blk, TaikoData.TransitionState memory ts) + returns (TaikoData.Block memory blk_, TaikoData.TransitionState memory ts_) { uint64 slot; - (blk, slot) = LibUtils.getBlock(state, getConfig(), blockId); + (blk_, slot) = LibUtils.getBlock(state, getConfig(), _blockId); - if (blk.verifiedTransitionId != 0) { - ts = state.transitions[slot][blk.verifiedTransitionId]; + if (blk_.verifiedTransitionId != 0) { + ts_ = state.transitions[slot][blk_.verifiedTransitionId]; } } /// @notice Gets the state transition for a specific block. - /// @param blockId Index of the block. - /// @param parentHash Parent hash of the block. - /// @return TransitionState The state transition data of the block. + /// @param _blockId Index of the block. + /// @param _parentHash Parent hash of the block. + /// @return The state transition data of the block. function getTransition( - uint64 blockId, - bytes32 parentHash + uint64 _blockId, + bytes32 _parentHash ) public view returns (TaikoData.TransitionState memory) { - return LibUtils.getTransition(state, getConfig(), blockId, parentHash); + return LibUtils.getTransition(state, getConfig(), _blockId, _parentHash); } /// @notice Gets the state variables of the TaikoL1 contract. - /// @return a State variables stored at SlotA. - /// @return b State variables stored at SlotB. + /// @return a_ State variables stored at SlotA. + /// @return b_ State variables stored at SlotB. function getStateVariables() public view - returns (TaikoData.SlotA memory a, TaikoData.SlotB memory b) + returns (TaikoData.SlotA memory a_, TaikoData.SlotB memory b_) { - a = state.slotA; - b = state.slotB; + a_ = state.slotA; + b_ = state.slotB; } /// @inheritdoc ITaikoL1 diff --git a/packages/protocol/contracts/L1/TaikoToken.sol b/packages/protocol/contracts/L1/TaikoToken.sol index e4f281f8c8c..0b2ec09c6c7 100644 --- a/packages/protocol/contracts/L1/TaikoToken.sol +++ b/packages/protocol/contracts/L1/TaikoToken.sol @@ -42,10 +42,10 @@ contract TaikoToken is EssentialContract, ERC20SnapshotUpgradeable, ERC20VotesUp } /// @notice Burns tokens from the specified address. - /// @param from The address to burn tokens from. - /// @param amount The amount of tokens to burn. - function burn(address from, uint256 amount) public onlyOwner { - _burn(from, amount); + /// @param _from The address to burn tokens from. + /// @param _amount The amount of tokens to burn. + function burn(address _from, uint256 _amount) public onlyOwner { + _burn(_from, _amount); } /// @notice Creates a new token snapshot. @@ -54,71 +54,71 @@ contract TaikoToken is EssentialContract, ERC20SnapshotUpgradeable, ERC20VotesUp } /// @notice Transfers tokens to a specified address. - /// @param to The address to transfer tokens to. - /// @param amount The amount of tokens to transfer. + /// @param _to The address to transfer tokens to. + /// @param _amount The amount of tokens to transfer. /// @return A boolean indicating whether the transfer was successful or not. - function transfer(address to, uint256 amount) public override returns (bool) { - if (to == address(this)) revert TKO_INVALID_ADDR(); - return super.transfer(to, amount); + function transfer(address _to, uint256 _amount) public override returns (bool) { + if (_to == address(this)) revert TKO_INVALID_ADDR(); + return super.transfer(_to, _amount); } /// @notice Transfers tokens from one address to another. - /// @param from The address to transfer tokens from. - /// @param to The address to transfer tokens to. - /// @param amount The amount of tokens to transfer. + /// @param _from The address to transfer tokens from. + /// @param _to The address to transfer tokens to. + /// @param _amount The amount of tokens to transfer. /// @return A boolean indicating whether the transfer was successful or not. function transferFrom( - address from, - address to, - uint256 amount + address _from, + address _to, + uint256 _amount ) public override returns (bool) { - if (to == address(this)) revert TKO_INVALID_ADDR(); - return super.transferFrom(from, to, amount); + if (_to == address(this)) revert TKO_INVALID_ADDR(); + return super.transferFrom(_from, _to, _amount); } function _beforeTokenTransfer( - address from, - address to, - uint256 amount + address _from, + address _to, + uint256 _amount ) internal override(ERC20Upgradeable, ERC20SnapshotUpgradeable) { - super._beforeTokenTransfer(from, to, amount); + super._beforeTokenTransfer(_from, _to, _amount); } function _afterTokenTransfer( - address from, - address to, - uint256 amount + address _from, + address _to, + uint256 _amount ) internal override(ERC20Upgradeable, ERC20VotesUpgradeable) { - super._afterTokenTransfer(from, to, amount); + super._afterTokenTransfer(_from, _to, _amount); } function _mint( - address to, - uint256 amount + address _to, + uint256 _amount ) internal override(ERC20Upgradeable, ERC20VotesUpgradeable) { - super._mint(to, amount); + super._mint(_to, _amount); } function _burn( - address from, - uint256 amount + address _from, + uint256 _amount ) internal override(ERC20Upgradeable, ERC20VotesUpgradeable) { - super._burn(from, amount); + super._burn(_from, _amount); } } diff --git a/packages/protocol/contracts/L1/gov/TaikoGovernor.sol b/packages/protocol/contracts/L1/gov/TaikoGovernor.sol index 49f70e7746f..f5b6cd2bb6d 100644 --- a/packages/protocol/contracts/L1/gov/TaikoGovernor.sol +++ b/packages/protocol/contracts/L1/gov/TaikoGovernor.sol @@ -46,16 +46,16 @@ contract TaikoGovernor is /// @dev See {IGovernor-propose} function propose( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - string memory description + address[] memory _targets, + uint256[] memory _values, + bytes[] memory _calldatas, + string memory _description ) public override(IGovernorUpgradeable, GovernorUpgradeable, GovernorCompatibilityBravoUpgradeable) returns (uint256) { - return super.propose(targets, values, calldatas, description); + return super.propose(_targets, _values, _calldatas, _description); } /// @notice An overwrite of GovernorCompatibilityBravoUpgradeable's propose() as that one does @@ -66,42 +66,42 @@ contract TaikoGovernor is /// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/0a25c1940ca220686588c4af3ec526f725fe2582/contracts/governance/compatibility/GovernorCompatibilityBravo.sol#L72 /// See {GovernorCompatibilityBravoUpgradeable-propose} function propose( - address[] memory targets, - uint256[] memory values, - string[] memory signatures, - bytes[] memory calldatas, - string memory description + address[] memory _targets, + uint256[] memory _values, + string[] memory _signatures, + bytes[] memory _calldatas, + string memory _description ) public virtual override(GovernorCompatibilityBravoUpgradeable) returns (uint256) { - if (signatures.length != calldatas.length) revert TG_INVALID_SIGNATURES_LENGTH(); + if (_signatures.length != _calldatas.length) revert TG_INVALID_SIGNATURES_LENGTH(); return GovernorCompatibilityBravoUpgradeable.propose( - targets, values, signatures, calldatas, description + _targets, _values, _signatures, _calldatas, _description ); } /// @dev See {GovernorUpgradeable-supportsInterface} - function supportsInterface(bytes4 interfaceId) + function supportsInterface(bytes4 _interfaceId) public view override(GovernorUpgradeable, GovernorTimelockControlUpgradeable, IERC165Upgradeable) returns (bool) { - return super.supportsInterface(interfaceId); + return super.supportsInterface(_interfaceId); } /// @dev See {GovernorUpgradeable-state} - function state(uint256 proposalId) + function state(uint256 _proposalId) public view override(IGovernorUpgradeable, GovernorUpgradeable, GovernorTimelockControlUpgradeable) returns (ProposalState) { - return super.state(proposalId); + return super.state(_proposalId); } /// @notice How long after a proposal is created should voting power be fixed. A @@ -124,29 +124,29 @@ contract TaikoGovernor is } function _execute( - uint256 proposalId, - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash + uint256 _proposalId, + address[] memory _targets, + uint256[] memory _values, + bytes[] memory _calldatas, + bytes32 _descriptionHash ) internal override(GovernorUpgradeable, GovernorTimelockControlUpgradeable) { - super._execute(proposalId, targets, values, calldatas, descriptionHash); + super._execute(_proposalId, _targets, _values, _calldatas, _descriptionHash); } function _cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash + address[] memory _targets, + uint256[] memory _values, + bytes[] memory _calldatas, + bytes32 _descriptionHash ) internal override(GovernorUpgradeable, GovernorTimelockControlUpgradeable) returns (uint256) { - return super._cancel(targets, values, calldatas, descriptionHash); + return super._cancel(_targets, _values, _calldatas, _descriptionHash); } function _executor() diff --git a/packages/protocol/contracts/L1/gov/TaikoTimelockController.sol b/packages/protocol/contracts/L1/gov/TaikoTimelockController.sol index 42331f4e9eb..0b1b9cbe2a3 100644 --- a/packages/protocol/contracts/L1/gov/TaikoTimelockController.sol +++ b/packages/protocol/contracts/L1/gov/TaikoTimelockController.sol @@ -11,16 +11,16 @@ contract TaikoTimelockController is EssentialContract, TimelockControllerUpgrade /// @notice Initializes the contract. /// @param _owner The owner of this contract. msg.sender will be used if this value is zero. - /// @param minDelay The minimal delay. - function init(address _owner, uint256 minDelay) external initializer { + /// @param _minDelay The minimal delay. + function init(address _owner, uint256 _minDelay) external initializer { __Essential_init(_owner); address[] memory nil = new address[](0); - __TimelockController_init(minDelay, nil, nil, owner()); + __TimelockController_init(_minDelay, nil, nil, owner()); } /// @dev Gets the minimum delay for an operation to become valid, allows the admin to get around /// of the min delay. - /// @return uint256 The minimum delay. + /// @return The minimum delay. function getMinDelay() public view override returns (uint256) { return hasRole(TIMELOCK_ADMIN_ROLE, msg.sender) ? 0 : super.getMinDelay(); } diff --git a/packages/protocol/contracts/L1/hooks/AssignmentHook.sol b/packages/protocol/contracts/L1/hooks/AssignmentHook.sol index 475a1337c0c..f0cfb2642f9 100644 --- a/packages/protocol/contracts/L1/hooks/AssignmentHook.sol +++ b/packages/protocol/contracts/L1/hooks/AssignmentHook.sol @@ -60,9 +60,9 @@ contract AssignmentHook is EssentialContract, IHook { /// @inheritdoc IHook function onBlockProposed( - TaikoData.Block memory blk, - TaikoData.BlockMetadata memory meta, - bytes memory data + TaikoData.Block memory _blk, + TaikoData.BlockMetadata memory _meta, + bytes memory _data ) external payable @@ -74,15 +74,15 @@ contract AssignmentHook is EssentialContract, IHook { // - 'block.coinbase' is the L1 block builder // - 'meta.coinbase' is the L2 block proposer - Input memory input = abi.decode(data, (Input)); + Input memory input = abi.decode(_data, (Input)); ProverAssignment memory assignment = input.assignment; // Check assignment validity if ( block.timestamp > assignment.expiry - || assignment.metaHash != 0 && blk.metaHash != assignment.metaHash - || assignment.parentMetaHash != 0 && meta.parentMetaHash != assignment.parentMetaHash - || assignment.maxBlockId != 0 && meta.id > assignment.maxBlockId + || assignment.metaHash != 0 && _blk.metaHash != assignment.metaHash + || assignment.parentMetaHash != 0 && _meta.parentMetaHash != assignment.parentMetaHash + || assignment.maxBlockId != 0 && _meta.id > assignment.maxBlockId || assignment.maxProposedIn != 0 && block.number > assignment.maxProposedIn ) { revert HOOK_ASSIGNMENT_EXPIRED(); @@ -91,28 +91,28 @@ contract AssignmentHook is EssentialContract, IHook { // Hash the assignment with the blobHash, this hash will be signed by // the prover, therefore, we add a string as a prefix. address taikoL1Address = msg.sender; - bytes32 hash = hashAssignment(assignment, taikoL1Address, meta.blobHash); + bytes32 hash = hashAssignment(assignment, taikoL1Address, _meta.blobHash); - if (!blk.assignedProver.isValidSignature(hash, assignment.signature)) { + if (!_blk.assignedProver.isValidSignature(hash, assignment.signature)) { revert HOOK_ASSIGNMENT_INVALID_SIG(); } // Send the liveness bond to the Taiko contract IERC20 tko = IERC20(resolve("taiko_token", false)); - tko.transferFrom(blk.assignedProver, taikoL1Address, blk.livenessBond); + tko.transferFrom(_blk.assignedProver, taikoL1Address, _blk.livenessBond); // Find the prover fee using the minimal tier - uint256 proverFee = _getProverFee(assignment.tierFees, meta.minTier); + uint256 proverFee = _getProverFee(assignment.tierFees, _meta.minTier); // The proposer irrevocably pays a fee to the assigned prover, either in // Ether or ERC20 tokens. if (assignment.feeToken == address(0)) { // Paying Ether - blk.assignedProver.sendEther(proverFee, MAX_GAS_PAYING_PROVER); + _blk.assignedProver.sendEther(proverFee, MAX_GAS_PAYING_PROVER); } else { // Paying ERC20 tokens IERC20(assignment.feeToken).safeTransferFrom( - meta.coinbase, blk.assignedProver, proverFee + _meta.coinbase, _blk.assignedProver, proverFee ); } @@ -126,18 +126,18 @@ contract AssignmentHook is EssentialContract, IHook { taikoL1Address.sendEther(address(this).balance); } - emit BlockAssigned(blk.assignedProver, meta, assignment); + emit BlockAssigned(_blk.assignedProver, _meta, assignment); } /// @notice Hashes the prover assignment. - /// @param assignment The prover assignment. - /// @param taikoL1Address The address of the TaikoL1 contract. - /// @param blobHash The blob hash. + /// @param _assignment The prover assignment. + /// @param _taikoL1Address The address of the TaikoL1 contract. + /// @param _blobHash The blob hash. /// @return The hash of the prover assignment. function hashAssignment( - ProverAssignment memory assignment, - address taikoL1Address, - bytes32 blobHash + ProverAssignment memory _assignment, + address _taikoL1Address, + bytes32 _blobHash ) public view @@ -146,31 +146,31 @@ contract AssignmentHook is EssentialContract, IHook { return keccak256( abi.encode( "PROVER_ASSIGNMENT", - ITaikoL1(taikoL1Address).getConfig().chainId, - taikoL1Address, + ITaikoL1(_taikoL1Address).getConfig().chainId, + _taikoL1Address, address(this), - assignment.metaHash, - assignment.parentMetaHash, - blobHash, - assignment.feeToken, - assignment.expiry, - assignment.maxBlockId, - assignment.maxProposedIn, - assignment.tierFees + _assignment.metaHash, + _assignment.parentMetaHash, + _blobHash, + _assignment.feeToken, + _assignment.expiry, + _assignment.maxBlockId, + _assignment.maxProposedIn, + _assignment.tierFees ) ); } function _getProverFee( - TaikoData.TierFee[] memory tierFees, - uint16 tierId + TaikoData.TierFee[] memory _tierFees, + uint16 _tierId ) private pure returns (uint256) { - for (uint256 i; i < tierFees.length; ++i) { - if (tierFees[i].tier == tierId) return tierFees[i].fee; + for (uint256 i; i < _tierFees.length; ++i) { + if (_tierFees[i].tier == _tierId) return _tierFees[i].fee; } revert HOOK_TIER_NOT_FOUND(); } diff --git a/packages/protocol/contracts/L1/hooks/IHook.sol b/packages/protocol/contracts/L1/hooks/IHook.sol index 2f1e94deff1..48ec6095f18 100644 --- a/packages/protocol/contracts/L1/hooks/IHook.sol +++ b/packages/protocol/contracts/L1/hooks/IHook.sol @@ -7,13 +7,13 @@ import "../TaikoData.sol"; /// @custom:security-contact security@taiko.xyz interface IHook { /// @notice Called when a block is proposed. - /// @param blk The proposed block. - /// @param meta The metadata of the proposed block. - /// @param data The data of the proposed block. + /// @param _blk The proposed block. + /// @param _meta The metadata of the proposed block. + /// @param _data The data of the proposed block. function onBlockProposed( - TaikoData.Block memory blk, - TaikoData.BlockMetadata memory meta, - bytes memory data + TaikoData.Block memory _blk, + TaikoData.BlockMetadata memory _meta, + bytes memory _data ) external payable; diff --git a/packages/protocol/contracts/L1/libs/LibDepositing.sol b/packages/protocol/contracts/L1/libs/LibDepositing.sol index 399f8752c2e..1d4c9fc9696 100644 --- a/packages/protocol/contracts/L1/libs/LibDepositing.sol +++ b/packages/protocol/contracts/L1/libs/LibDepositing.sol @@ -22,36 +22,36 @@ library LibDepositing { error L1_INVALID_ETH_DEPOSIT(); /// @dev Deposits Ether to Layer 2. - /// @param state Current TaikoData.State. - /// @param config Actual TaikoData.Config. - /// @param resolver Address resolver interface. - /// @param recipient The recipient address. + /// @param _state Current TaikoData.State. + /// @param _config Actual TaikoData.Config. + /// @param _resolver Address resolver interface. + /// @param _recipient The recipient address. function depositEtherToL2( - TaikoData.State storage state, - TaikoData.Config memory config, - IAddressResolver resolver, - address recipient + TaikoData.State storage _state, + TaikoData.Config memory _config, + IAddressResolver _resolver, + address _recipient ) internal { - if (!canDepositEthToL2(state, config, msg.value)) { + if (!canDepositEthToL2(_state, _config, msg.value)) { revert L1_INVALID_ETH_DEPOSIT(); } - resolver.resolve("bridge", false).sendEther(msg.value); + _resolver.resolve("bridge", false).sendEther(msg.value); // Append the deposit to the queue. - address _recipient = recipient == address(0) ? msg.sender : recipient; - uint256 slot = state.slotA.numEthDeposits % config.ethDepositRingBufferSize; + address recipient_ = _recipient == address(0) ? msg.sender : _recipient; + uint256 slot = _state.slotA.numEthDeposits % _config.ethDepositRingBufferSize; // range of msg.value is checked by next line. - state.ethDeposits[slot] = _encodeEthDeposit(_recipient, msg.value); + _state.ethDeposits[slot] = _encodeEthDeposit(recipient_, msg.value); emit EthDeposited( TaikoData.EthDeposit({ - recipient: _recipient, + recipient: recipient_, amount: uint96(msg.value), - id: state.slotA.numEthDeposits + id: _state.slotA.numEthDeposits }) ); @@ -59,94 +59,95 @@ library LibDepositing { // - uint64 can store up to ~1.8 * 1e19, which can represent 584K years // if we are depositing at every second unchecked { - state.slotA.numEthDeposits++; + _state.slotA.numEthDeposits++; } } /// @dev Processes the ETH deposits in a batched manner. function processDeposits( - TaikoData.State storage state, - TaikoData.Config memory config, - address feeRecipient + TaikoData.State storage _state, + TaikoData.Config memory _config, + address _feeRecipient ) internal - returns (TaikoData.EthDeposit[] memory deposits) + returns (TaikoData.EthDeposit[] memory deposits_) { // Calculate the number of pending deposits. - uint256 numPending = state.slotA.numEthDeposits - state.slotA.nextEthDepositToProcess; + uint256 numPending = _state.slotA.numEthDeposits - _state.slotA.nextEthDepositToProcess; - if (numPending < config.ethDepositMinCountPerBlock) { - deposits = new TaikoData.EthDeposit[](0); + if (numPending < _config.ethDepositMinCountPerBlock) { + deposits_ = new TaikoData.EthDeposit[](0); } else { - deposits = new TaikoData.EthDeposit[](numPending.min(config.ethDepositMaxCountPerBlock)); - uint96 fee = uint96(config.ethDepositMaxFee.min(block.basefee * config.ethDepositGas)); - uint64 j = state.slotA.nextEthDepositToProcess; + deposits_ = + new TaikoData.EthDeposit[](numPending.min(_config.ethDepositMaxCountPerBlock)); + uint96 fee = uint96(_config.ethDepositMaxFee.min(block.basefee * _config.ethDepositGas)); + uint64 j = _state.slotA.nextEthDepositToProcess; uint96 totalFee; - for (uint256 i; i < deposits.length;) { - uint256 data = state.ethDeposits[j % config.ethDepositRingBufferSize]; - deposits[i] = TaikoData.EthDeposit({ + for (uint256 i; i < deposits_.length;) { + uint256 data = _state.ethDeposits[j % _config.ethDepositRingBufferSize]; + deposits_[i] = TaikoData.EthDeposit({ recipient: address(uint160(data >> 96)), amount: uint96(data), id: j }); - uint96 _fee = deposits[i].amount > fee ? fee : deposits[i].amount; + uint96 _fee = deposits_[i].amount > fee ? fee : deposits_[i].amount; // Unchecked is safe: - // - _fee cannot be bigger than deposits[i].amount + // - _fee cannot be bigger than deposits_[i].amount // - all values are in the same range (uint96) except loop // counter, which obviously cannot be bigger than uint95 // otherwise the function would be gassing out. unchecked { - deposits[i].amount -= _fee; + deposits_[i].amount -= _fee; totalFee += _fee; ++i; ++j; } } - state.slotA.nextEthDepositToProcess = j; + _state.slotA.nextEthDepositToProcess = j; // This is the fee deposit - state.ethDeposits[state.slotA.numEthDeposits % config.ethDepositRingBufferSize] = - _encodeEthDeposit(feeRecipient, totalFee); + _state.ethDeposits[_state.slotA.numEthDeposits % _config.ethDepositRingBufferSize] = + _encodeEthDeposit(_feeRecipient, totalFee); // Unchecked is safe: // - uint64 can store up to ~1.8 * 1e19, which can represent 584K // years if we are depositing at every second unchecked { - state.slotA.numEthDeposits++; + _state.slotA.numEthDeposits++; } } } /// @dev Checks if Ether deposit is allowed for Layer 2. function canDepositEthToL2( - TaikoData.State storage state, - TaikoData.Config memory config, - uint256 amount + TaikoData.State storage _state, + TaikoData.Config memory _config, + uint256 _amount ) internal view returns (bool) { // Unchecked is safe: - // - both numEthDeposits and state.slotA.nextEthDepositToProcess are + // - both numEthDeposits and _state.slotA.nextEthDepositToProcess are // indexes. One is tracking all deposits (numEthDeposits: unprocessed) // and the next to be processed, so nextEthDepositToProcess cannot be // bigger than numEthDeposits // - ethDepositRingBufferSize cannot be 0 by default (validity checked // in LibVerifying) unchecked { - return amount >= config.ethDepositMinAmount && amount <= config.ethDepositMaxAmount - && state.slotA.numEthDeposits - state.slotA.nextEthDepositToProcess - < config.ethDepositRingBufferSize - 1; + return _amount >= _config.ethDepositMinAmount && _amount <= _config.ethDepositMaxAmount + && _state.slotA.numEthDeposits - _state.slotA.nextEthDepositToProcess + < _config.ethDepositRingBufferSize - 1; } } /// @dev Encodes the given deposit into a uint256. - /// @param addr The address of the deposit recipient. - /// @param amount The amount of the deposit. + /// @param _addr The address of the deposit recipient. + /// @param _amount The amount of the deposit. /// @return The encoded deposit. - function _encodeEthDeposit(address addr, uint256 amount) private pure returns (uint256) { - if (amount > type(uint96).max) revert L1_INVALID_ETH_DEPOSIT(); - return (uint256(uint160(addr)) << 96) | amount; + function _encodeEthDeposit(address _addr, uint256 _amount) private pure returns (uint256) { + if (_amount > type(uint96).max) revert L1_INVALID_ETH_DEPOSIT(); + return (uint256(uint160(_addr)) << 96) | _amount; } } diff --git a/packages/protocol/contracts/L1/libs/LibProposing.sol b/packages/protocol/contracts/L1/libs/LibProposing.sol index 9f1387d6888..74123bb4284 100644 --- a/packages/protocol/contracts/L1/libs/LibProposing.sol +++ b/packages/protocol/contracts/L1/libs/LibProposing.sol @@ -57,28 +57,25 @@ library LibProposing { error L1_UNEXPECTED_PARENT(); /// @dev Proposes a Taiko L2 block. - /// @param state Current TaikoData.State. - /// @param config Actual TaikoData.Config. - /// @param resolver Address resolver interface. - /// @param data Encoded data bytes containing the block params. - /// @param txList Transaction list bytes (if not blob). - /// @return meta The constructed block's metadata. - /// @return depositsProcessed The EthDeposit array about processed deposits in this proposed + /// @param _state Current TaikoData.State. + /// @param _config Actual TaikoData.Config. + /// @param _resolver Address resolver interface. + /// @param _data Encoded data bytes containing the block params. + /// @param _txList Transaction list bytes (if not blob). + /// @return meta_ The constructed block's metadata. + /// @return deposits_ The EthDeposit array about processed deposits in this proposed /// block. function proposeBlock( - TaikoData.State storage state, - TaikoData.Config memory config, - IAddressResolver resolver, - bytes calldata data, - bytes calldata txList + TaikoData.State storage _state, + TaikoData.Config memory _config, + IAddressResolver _resolver, + bytes calldata _data, + bytes calldata _txList ) internal - returns ( - TaikoData.BlockMetadata memory meta, - TaikoData.EthDeposit[] memory depositsProcessed - ) + returns (TaikoData.BlockMetadata memory meta_, TaikoData.EthDeposit[] memory deposits_) { - TaikoData.BlockParams memory params = abi.decode(data, (TaikoData.BlockParams)); + TaikoData.BlockParams memory params = abi.decode(_data, (TaikoData.BlockParams)); // We need a prover that will submit proofs after the block has been submitted if (params.assignedProver == address(0)) { @@ -93,18 +90,17 @@ library LibProposing { // However, if the "proposer" address is set to a non-zero value, we // ensure that only that specific address has the authority to propose // blocks. - TaikoData.SlotB memory b = state.slotB; - if (!_isProposerPermitted(b, resolver)) revert L1_UNAUTHORIZED(); + TaikoData.SlotB memory b = _state.slotB; + if (!_isProposerPermitted(b, _resolver)) revert L1_UNAUTHORIZED(); // It's essential to ensure that the ring buffer for proposed blocks // still has space for at least one more block. - - if (b.numBlocks >= b.lastVerifiedBlockId + config.blockMaxProposals + 1) { + if (b.numBlocks >= b.lastVerifiedBlockId + _config.blockMaxProposals + 1) { revert L1_TOO_MANY_BLOCKS(); } bytes32 parentMetaHash = - state.blocks[(b.numBlocks - 1) % config.blockRingBufferSize].metaHash; + _state.blocks[(b.numBlocks - 1) % _config.blockRingBufferSize].metaHash; // Check if parent block has the right meta hash // This is to allow the proposer to make sure the block builds on the expected latest chain @@ -115,59 +111,59 @@ library LibProposing { // Each transaction must handle a specific quantity of L1-to-L2 // Ether deposits. - depositsProcessed = LibDepositing.processDeposits(state, config, params.coinbase); + deposits_ = LibDepositing.processDeposits(_state, _config, params.coinbase); // Initialize metadata to compute a metaHash, which forms a part of // the block data to be stored on-chain for future integrity checks. // If we choose to persist all data fields in the metadata, it will // require additional storage slots. unchecked { - meta = TaikoData.BlockMetadata({ + meta_ = TaikoData.BlockMetadata({ l1Hash: blockhash(block.number - 1), difficulty: 0, // to be initialized below blobHash: 0, // to be initialized below extraData: params.extraData, - depositsHash: keccak256(abi.encode(depositsProcessed)), + depositsHash: keccak256(abi.encode(deposits_)), coinbase: params.coinbase, id: b.numBlocks, - gasLimit: config.blockMaxGasLimit, + gasLimit: _config.blockMaxGasLimit, timestamp: uint64(block.timestamp), l1Height: uint64(block.number - 1), txListByteOffset: 0, // to be initialized below txListByteSize: 0, // to be initialized below minTier: 0, // to be initialized below - blobUsed: txList.length == 0, + blobUsed: _txList.length == 0, parentMetaHash: parentMetaHash }); } // Update certain meta fields - if (meta.blobUsed) { - if (!config.blobAllowedForDA) revert L1_BLOB_FOR_DA_DISABLED(); + if (meta_.blobUsed) { + if (!_config.blobAllowedForDA) revert L1_BLOB_FOR_DA_DISABLED(); if (params.blobHash != 0) { - if (!config.blobReuseEnabled) revert L1_BLOB_REUSE_DISALBED(); + if (!_config.blobReuseEnabled) revert L1_BLOB_REUSE_DISALBED(); // We try to reuse an old blob - if (!isBlobReusable(state, config, params.blobHash)) { + if (!isBlobReusable(_state, _config, params.blobHash)) { revert L1_BLOB_NOT_REUSEABLE(); } - meta.blobHash = params.blobHash; + meta_.blobHash = params.blobHash; } else { // Always use the first blob in this transaction. If the // proposeBlock functions are called more than once in the same // L1 transaction, these multiple L2 blocks will share the same // blob. - meta.blobHash = blobhash(0); + meta_.blobHash = blobhash(0); - if (meta.blobHash == 0) revert L1_BLOB_NOT_FOUND(); + if (meta_.blobHash == 0) revert L1_BLOB_NOT_FOUND(); // Depends on the blob data price, it may not make sense to // cache the blob which costs 20,000 (sstore) + 631 (event) // extra gas. - if (config.blobReuseEnabled && params.cacheBlobForReuse) { - state.reusableBlobs[meta.blobHash] = block.timestamp; - emit BlobCached(meta.blobHash); + if (_config.blobReuseEnabled && params.cacheBlobForReuse) { + _state.reusableBlobs[meta_.blobHash] = block.timestamp; + emit BlobCached(meta_.blobHash); } } @@ -176,8 +172,8 @@ library LibProposing { revert L1_TXLIST_OFFSET(); } - meta.txListByteOffset = params.txListByteOffset; - meta.txListByteSize = params.txListByteSize; + meta_.txListByteOffset = params.txListByteOffset; + meta_.txListByteSize = params.txListByteSize; } else { // The proposer must be an Externally Owned Account (EOA) for // calldata usage. This ensures that the transaction is not an @@ -190,13 +186,13 @@ library LibProposing { revert L1_INVALID_PARAM(); } - meta.blobHash = keccak256(txList); - meta.txListByteOffset = 0; - meta.txListByteSize = uint24(txList.length); + meta_.blobHash = keccak256(_txList); + meta_.txListByteOffset = 0; + meta_.txListByteSize = uint24(_txList.length); } // Check that the tx length is non-zero and within the supported range - if (meta.txListByteSize == 0 || meta.txListByteSize > config.blockMaxTxListBytes) { + if (meta_.txListByteSize == 0 || meta_.txListByteSize > _config.blockMaxTxListBytes) { revert L1_TXLIST_SIZE(); } @@ -205,22 +201,22 @@ library LibProposing { // of multiple Taiko blocks being proposed within a single // Ethereum block, we choose to introduce a salt to this random // number as the L2 mixHash. - meta.difficulty = keccak256(abi.encodePacked(block.prevrandao, b.numBlocks, block.number)); + meta_.difficulty = keccak256(abi.encodePacked(block.prevrandao, b.numBlocks, block.number)); // Use the difficulty as a random number - meta.minTier = ITierProvider(resolver.resolve("tier_provider", false)).getMinTier( - uint256(meta.difficulty) + meta_.minTier = ITierProvider(_resolver.resolve("tier_provider", false)).getMinTier( + uint256(meta_.difficulty) ); // Create the block that will be stored onchain TaikoData.Block memory blk = TaikoData.Block({ - metaHash: keccak256(abi.encode(meta)), + metaHash: keccak256(abi.encode(meta_)), // Safeguard the liveness bond to ensure its preservation, // particularly in scenarios where it might be altered after the // block's proposal but before it has been proven or verified. - livenessBond: config.livenessBond, + livenessBond: _config.livenessBond, blockId: b.numBlocks, - proposedAt: meta.timestamp, + proposedAt: meta_.timestamp, proposedIn: uint64(block.number), // For a new block, the next transition ID is always 1, not 0. nextTransitionId: 1, @@ -230,15 +226,15 @@ library LibProposing { }); // Store the block in the ring buffer - state.blocks[b.numBlocks % config.blockRingBufferSize] = blk; + _state.blocks[b.numBlocks % _config.blockRingBufferSize] = blk; // Increment the counter (cursor) by 1. unchecked { - ++state.slotB.numBlocks; + ++_state.slotB.numBlocks; } { - IERC20 tko = IERC20(resolver.resolve("taiko_token", false)); + IERC20 tko = IERC20(_resolver.resolve("taiko_token", false)); uint256 tkoBalance = tko.balanceOf(address(this)); // Run all hooks. @@ -255,7 +251,7 @@ library LibProposing { // back to this contract for the next hook to use. // Proposers shall choose use extra hooks wisely. IHook(params.hookCalls[i].hook).onBlockProposed{ value: address(this).balance }( - blk, meta, params.hookCalls[i].data + blk, meta_, params.hookCalls[i].data ); prevHook = params.hookCalls[i].hook; @@ -266,10 +262,10 @@ library LibProposing { } // Check that after hooks, the Taiko Token balance of this contract - // have increased by the same amount as config.livenessBond (to prevent) + // have increased by the same amount as _config.livenessBond (to prevent) // multiple draining payments by a malicious proposer nesting the same // hook. - if (tko.balanceOf(address(this)) != tkoBalance + config.livenessBond) { + if (tko.balanceOf(address(this)) != tkoBalance + _config.livenessBond) { revert L1_LIVENESS_BOND_NOT_RECEIVED(); } } @@ -277,46 +273,46 @@ library LibProposing { emit BlockProposed({ blockId: blk.blockId, assignedProver: blk.assignedProver, - livenessBond: config.livenessBond, - meta: meta, - depositsProcessed: depositsProcessed + livenessBond: _config.livenessBond, + meta: meta_, + depositsProcessed: deposits_ }); } /// @notice Checks if a blob is reusable. - /// @param state Current TaikoData.State. - /// @param config The TaikoData.Config. - /// @param blobHash The blob hash - /// @return True if the blob is reusable, false otherwise. + /// @param _state Current TaikoData.State. + /// @param _config The TaikoData.Config. + /// @param _blobHash The blob hash + /// @return true if the blob is reusable, false otherwise. function isBlobReusable( - TaikoData.State storage state, - TaikoData.Config memory config, - bytes32 blobHash + TaikoData.State storage _state, + TaikoData.Config memory _config, + bytes32 _blobHash ) internal view returns (bool) { - return state.reusableBlobs[blobHash] + config.blobExpiry > block.timestamp; + return _state.reusableBlobs[_blobHash] + _config.blobExpiry > block.timestamp; } function _isProposerPermitted( - TaikoData.SlotB memory slotB, - IAddressResolver resolver + TaikoData.SlotB memory _slotB, + IAddressResolver _resolver ) private view returns (bool) { - if (slotB.numBlocks == 1) { + if (_slotB.numBlocks == 1) { // Only proposer_one can propose the first block after genesis - address proposerOne = resolver.resolve("proposer_one", true); + address proposerOne = _resolver.resolve("proposer_one", true); if (proposerOne != address(0) && msg.sender != proposerOne) { return false; } } - address proposer = resolver.resolve("proposer", true); + address proposer = _resolver.resolve("proposer", true); return proposer == address(0) || msg.sender == proposer; } } diff --git a/packages/protocol/contracts/L1/libs/LibProving.sol b/packages/protocol/contracts/L1/libs/LibProving.sol index 19c9b0d7917..f8ae835f877 100644 --- a/packages/protocol/contracts/L1/libs/LibProving.sol +++ b/packages/protocol/contracts/L1/libs/LibProving.sol @@ -68,58 +68,57 @@ library LibProving { error L1_NOT_ASSIGNED_PROVER(); /// @notice Pauses or unpauses the proving process. - /// @param state Current TaikoData.State. - /// @param toPause The pause status. - function pauseProving(TaikoData.State storage state, bool toPause) external { - if (state.slotB.provingPaused == toPause) revert L1_INVALID_PAUSE_STATUS(); - - state.slotB.provingPaused = toPause; - - if (!toPause) { - state.slotB.lastUnpausedAt = uint64(block.timestamp); + /// @param _state Current TaikoData.State. + /// @param _pause The pause status. + function pauseProving(TaikoData.State storage _state, bool _pause) external { + if (_state.slotB.provingPaused == _pause) revert L1_INVALID_PAUSE_STATUS(); + _state.slotB.provingPaused = _pause; + + if (!_pause) { + _state.slotB.lastUnpausedAt = uint64(block.timestamp); } - emit ProvingPaused(toPause); + emit ProvingPaused(_pause); } /// @dev Proves or contests a block transition. - /// @param state Current TaikoData.State. - /// @param config Actual TaikoData.Config. - /// @param resolver Address resolver interface. - /// @param meta The block's metadata. - /// @param tran The transition data. - /// @param proof The proof. - /// @param maxBlocksToVerify The number of blocks to be verified with this transaction. + /// @param _state Current TaikoData.State. + /// @param _config Actual TaikoData.Config. + /// @param _resolver Address resolver interface. + /// @param _meta The block's metadata. + /// @param _tran The transition data. + /// @param _proof The proof. + /// @param maxBlocksToVerify_ The number of blocks to be verified with this transaction. function proveBlock( - TaikoData.State storage state, - TaikoData.Config memory config, - IAddressResolver resolver, - TaikoData.BlockMetadata memory meta, - TaikoData.Transition memory tran, - TaikoData.TierProof memory proof + TaikoData.State storage _state, + TaikoData.Config memory _config, + IAddressResolver _resolver, + TaikoData.BlockMetadata memory _meta, + TaikoData.Transition memory _tran, + TaikoData.TierProof memory _proof ) internal - returns (uint8 maxBlocksToVerify) + returns (uint8 maxBlocksToVerify_) { // Make sure parentHash is not zero // To contest an existing transition, simply use any non-zero value as // the blockHash and stateRoot. - if (tran.parentHash == 0 || tran.blockHash == 0 || tran.stateRoot == 0) { + if (_tran.parentHash == 0 || _tran.blockHash == 0 || _tran.stateRoot == 0) { revert L1_INVALID_TRANSITION(); } // Check that the block has been proposed but has not yet been verified. - TaikoData.SlotB memory b = state.slotB; - if (meta.id <= b.lastVerifiedBlockId || meta.id >= b.numBlocks) { + TaikoData.SlotB memory b = _state.slotB; + if (_meta.id <= b.lastVerifiedBlockId || _meta.id >= b.numBlocks) { revert L1_INVALID_BLOCK_ID(); } - uint64 slot = meta.id % config.blockRingBufferSize; - TaikoData.Block storage blk = state.blocks[slot]; + uint64 slot = _meta.id % _config.blockRingBufferSize; + TaikoData.Block storage blk = _state.blocks[slot]; // Check the integrity of the block data. It's worth noting that in // theory, this check may be skipped, but it's included for added // caution. - if (blk.blockId != meta.id || blk.metaHash != keccak256(abi.encode(meta))) { + if (blk.blockId != _meta.id || blk.metaHash != keccak256(abi.encode(_meta))) { revert L1_BLOCK_MISMATCH(); } @@ -128,21 +127,21 @@ library LibProving { // become available. In cases where a transition with the specified // parentHash does not exist, the transition ID (tid) will be set to 0. (uint32 tid, TaikoData.TransitionState storage ts) = - _createTransition(state, blk, tran, slot); + _createTransition(_state, blk, _tran, slot); // The new proof must meet or exceed the minimum tier required by the // block or the previous proof; it cannot be on a lower tier. - if (proof.tier == 0 || proof.tier < meta.minTier || proof.tier < ts.tier) { + if (_proof.tier == 0 || _proof.tier < _meta.minTier || _proof.tier < ts.tier) { revert L1_INVALID_TIER(); } // Retrieve the tier configurations. If the tier is not supported, the // subsequent action will result in a revert. ITierProvider.Tier memory tier = - ITierProvider(resolver.resolve("tier_provider", false)).getTier(proof.tier); + ITierProvider(_resolver.resolve("tier_provider", false)).getTier(_proof.tier); // Check if this prover is allowed to submit a proof for this block - _checkProverPermission(state, blk, ts, tid, tier); + _checkProverPermission(_state, blk, ts, tid, tier); // We must verify the proof, and any failure in proof verification will // result in a revert. @@ -159,23 +158,23 @@ library LibProving { // It's obvious that proof verification is entirely decoupled from // Taiko's core protocol. { - address verifier = resolver.resolve(tier.verifierName, true); + address verifier = _resolver.resolve(tier.verifierName, true); if (verifier != address(0)) { - bool isContesting = proof.tier == ts.tier && tier.contestBond != 0; + bool isContesting = _proof.tier == ts.tier && tier.contestBond != 0; IVerifier.Context memory ctx = IVerifier.Context({ metaHash: blk.metaHash, - blobHash: meta.blobHash, + blobHash: _meta.blobHash, // Separate msgSender to allow the prover to be any address in the future. prover: msg.sender, msgSender: msg.sender, blockId: blk.blockId, isContesting: isContesting, - blobUsed: meta.blobUsed + blobUsed: _meta.blobUsed }); - IVerifier(verifier).verifyProof(ctx, tran, proof); + IVerifier(verifier).verifyProof(ctx, _tran, _proof); } else if (tier.verifierName != TIER_OP) { // The verifier can be address-zero, signifying that there are no // proof checks for the tier. In practice, this only applies to @@ -185,13 +184,13 @@ library LibProving { } bool isTopTier = tier.contestBond == 0; - IERC20 tko = IERC20(resolver.resolve("taiko_token", false)); + IERC20 tko = IERC20(_resolver.resolve("taiko_token", false)); if (isTopTier) { // A special return value from the top tier prover can signal this // contract to return all liveness bond. - bool returnLivenessBond = blk.livenessBond > 0 && proof.data.length == 32 - && bytes32(proof.data) == RETURN_LIVENESS_BOND; + bool returnLivenessBond = blk.livenessBond > 0 && _proof.data.length == 32 + && bytes32(_proof.data) == RETURN_LIVENESS_BOND; if (returnLivenessBond) { tko.transfer(blk.assignedProver, blk.livenessBond); @@ -199,20 +198,20 @@ library LibProving { } } - bool sameTransition = tran.blockHash == ts.blockHash && tran.stateRoot == ts.stateRoot; + bool sameTransition = _tran.blockHash == ts.blockHash && _tran.stateRoot == ts.stateRoot; - if (proof.tier > ts.tier) { + if (_proof.tier > ts.tier) { // Handles the case when an incoming tier is higher than the current transition's tier. // Reverts when the incoming proof tries to prove the same transition // (L1_ALREADY_PROVED). - _overrideWithHigherProof(ts, tran, proof, tier, tko, sameTransition); + _overrideWithHigherProof(ts, _tran, _proof, tier, tko, sameTransition); emit TransitionProved({ blockId: blk.blockId, - tran: tran, + tran: _tran, prover: msg.sender, validityBond: tier.validityBond, - tier: proof.tier + tier: _proof.tier }); } else { // New transition and old transition on the same tier - and if this transaction tries to @@ -225,15 +224,15 @@ library LibProving { assert(ts.validityBond == 0 && ts.contestBond == 0 && ts.contester == address(0)); ts.prover = msg.sender; - ts.blockHash = tran.blockHash; - ts.stateRoot = tran.stateRoot; + ts.blockHash = _tran.blockHash; + ts.stateRoot = _tran.stateRoot; emit TransitionProved({ blockId: blk.blockId, - tran: tran, + tran: _tran, prover: msg.sender, validityBond: 0, - tier: proof.tier + tier: _proof.tier }); } else { // Contesting but not on the highest tier @@ -254,10 +253,10 @@ library LibProving { emit TransitionContested({ blockId: blk.blockId, - tran: tran, + tran: _tran, contester: msg.sender, contestBond: tier.contestBond, - tier: proof.tier + tier: _proof.tier }); } } @@ -268,17 +267,17 @@ library LibProving { /// @dev Handle the transition initialization logic function _createTransition( - TaikoData.State storage state, - TaikoData.Block storage blk, - TaikoData.Transition memory tran, + TaikoData.State storage _state, + TaikoData.Block storage _blk, + TaikoData.Transition memory _tran, uint64 slot ) private - returns (uint32 tid, TaikoData.TransitionState storage ts) + returns (uint32 tid_, TaikoData.TransitionState storage ts_) { - tid = LibUtils.getTransitionId(state, blk, slot, tran.parentHash); + tid_ = LibUtils.getTransitionId(_state, _blk, slot, _tran.parentHash); - if (tid == 0) { + if (tid_ == 0) { // In cases where a transition with the provided parentHash is not // found, we must essentially "create" one and set it to its initial // state. This initial state can be viewed as a special transition @@ -291,29 +290,29 @@ library LibProving { unchecked { // Unchecked is safe: Not realistic 2**32 different fork choice // per block will be proven and none of them is valid - tid = blk.nextTransitionId++; + tid_ = _blk.nextTransitionId++; } // Keep in mind that state.transitions are also reusable storage // slots, so it's necessary to reinitialize all transition fields // below. - ts = state.transitions[slot][tid]; - ts.blockHash = 0; - ts.stateRoot = 0; - ts.validityBond = 0; - ts.contester = address(0); - ts.contestBond = 1; // to save gas - ts.timestamp = blk.proposedAt; - ts.tier = 0; - ts.contestations = 0; - - if (tid == 1) { + ts_ = _state.transitions[slot][tid_]; + ts_.blockHash = 0; + ts_.stateRoot = 0; + ts_.validityBond = 0; + ts_.contester = address(0); + ts_.contestBond = 1; // to save gas + ts_.timestamp = _blk.proposedAt; + ts_.tier = 0; + ts_.contestations = 0; + + if (tid_ == 1) { // This approach serves as a cost-saving technique for the // majority of blocks, where the first transition is expected to // be the correct one. Writing to `tran` is more economical // since it resides in the ring buffer, whereas writing to // `transitionIds` is not as cost-effective. - ts.key = tran.parentHash; + ts_.key = _tran.parentHash; // In the case of this first transition, the block's assigned // prover has the privilege to re-prove it, but only when the @@ -325,99 +324,99 @@ library LibProving { // // While alternative implementations are possible, introducing // such changes would require additional if-else logic. - ts.prover = blk.assignedProver; + ts_.prover = _blk.assignedProver; } else { // In scenarios where this transition is not the first one, we // straightforwardly reset the transition prover to address // zero. - ts.prover = address(0); + ts_.prover = address(0); // Furthermore, we index the transition for future retrieval. // It's worth emphasizing that this mapping for indexing is not // reusable. However, given that the majority of blocks will // only possess one transition — the correct one — we don't need // to be concerned about the cost in this case. - state.transitionIds[blk.blockId][tran.parentHash] = tid; + _state.transitionIds[_blk.blockId][_tran.parentHash] = tid_; // There is no need to initialize ts.key here because it's only used when tid == 1 } } else { // A transition with the provided parentHash has been located. - ts = state.transitions[slot][tid]; + ts_ = _state.transitions[slot][tid_]; } } /// @dev Handles what happens when there is a higher proof incoming function _overrideWithHigherProof( - TaikoData.TransitionState storage ts, - TaikoData.Transition memory tran, - TaikoData.TierProof memory proof, - ITierProvider.Tier memory tier, - IERC20 tko, - bool sameTransition + TaikoData.TransitionState storage _ts, + TaikoData.Transition memory _tran, + TaikoData.TierProof memory _proof, + ITierProvider.Tier memory _tier, + IERC20 _tko, + bool _sameTransition ) private { // Higher tier proof overwriting lower tier proof uint256 reward; - if (ts.contester != address(0)) { - if (sameTransition) { + if (_ts.contester != address(0)) { + if (_sameTransition) { // The contested transition is proven to be valid, contestor loses the game - reward = ts.contestBond >> 2; - tko.transfer(ts.prover, ts.validityBond + reward); + reward = _ts.contestBond >> 2; + _tko.transfer(_ts.prover, _ts.validityBond + reward); } else { // The contested transition is proven to be invalid, contestor wins the game - reward = ts.validityBond >> 2; - tko.transfer(ts.contester, ts.contestBond + reward); + reward = _ts.validityBond >> 2; + _tko.transfer(_ts.contester, _ts.contestBond + reward); } } else { - if (sameTransition) revert L1_ALREADY_PROVED(); + if (_sameTransition) revert L1_ALREADY_PROVED(); // Contest the existing transition and prove it to be invalid - reward = ts.validityBond >> 1; - ts.contestations += 1; + reward = _ts.validityBond >> 1; + _ts.contestations += 1; } unchecked { - if (reward > tier.validityBond) { - tko.transfer(msg.sender, reward - tier.validityBond); + if (reward > _tier.validityBond) { + _tko.transfer(msg.sender, reward - _tier.validityBond); } else { - tko.transferFrom(msg.sender, address(this), tier.validityBond - reward); + _tko.transferFrom(msg.sender, address(this), _tier.validityBond - reward); } } - ts.validityBond = tier.validityBond; - ts.contestBond = 1; // to save gas - ts.contester = address(0); - ts.prover = msg.sender; - ts.tier = proof.tier; + _ts.validityBond = _tier.validityBond; + _ts.contestBond = 1; // to save gas + _ts.contester = address(0); + _ts.prover = msg.sender; + _ts.tier = _proof.tier; - if (!sameTransition) { - ts.blockHash = tran.blockHash; - ts.stateRoot = tran.stateRoot; + if (!_sameTransition) { + _ts.blockHash = _tran.blockHash; + _ts.stateRoot = _tran.stateRoot; } } /// @dev Check the msg.sender (the new prover) against the block's assigned prover. function _checkProverPermission( - TaikoData.State storage state, - TaikoData.Block storage blk, - TaikoData.TransitionState storage ts, - uint32 tid, - ITierProvider.Tier memory tier + TaikoData.State storage _state, + TaikoData.Block storage _blk, + TaikoData.TransitionState storage _ts, + uint32 _tid, + ITierProvider.Tier memory _tier ) private view { // The highest tier proof can always submit new proofs - if (tier.contestBond == 0) return; + if (_tier.contestBond == 0) return; - bool inProvingWindow = uint256(ts.timestamp).max(state.slotB.lastUnpausedAt) - + tier.provingWindow * 60 >= block.timestamp; - bool isAssignedPover = msg.sender == blk.assignedProver; + bool inProvingWindow = uint256(_ts.timestamp).max(_state.slotB.lastUnpausedAt) + + _tier.provingWindow * 60 >= block.timestamp; + bool isAssignedPover = msg.sender == _blk.assignedProver; // The assigned prover can only submit the very first transition. - if (tid == 1 && ts.tier == 0 && inProvingWindow) { + if (_tid == 1 && _ts.tier == 0 && inProvingWindow) { if (!isAssignedPover) revert L1_NOT_ASSIGNED_PROVER(); } else { // Disallow the same address to prove the block so that we can detect that the diff --git a/packages/protocol/contracts/L1/libs/LibUtils.sol b/packages/protocol/contracts/L1/libs/LibUtils.sol index 759e69d132d..308a481673b 100644 --- a/packages/protocol/contracts/L1/libs/LibUtils.sol +++ b/packages/protocol/contracts/L1/libs/LibUtils.sol @@ -15,52 +15,52 @@ library LibUtils { /// @notice This function will revert if the transition is not found. /// @dev Retrieves the transition with a given parentHash. - /// @param state Current TaikoData.State. - /// @param config Actual TaikoData.Config. - /// @param blockId Id of the block. - /// @param parentHash Parent hash of the block. - /// @return ts The state transition data of the block. + /// @param _state Current TaikoData.State. + /// @param _config Actual TaikoData.Config. + /// @param _blockId Id of the block. + /// @param _parentHash Parent hash of the block. + /// @return The state transition data of the block. function getTransition( - TaikoData.State storage state, - TaikoData.Config memory config, - uint64 blockId, - bytes32 parentHash + TaikoData.State storage _state, + TaikoData.Config memory _config, + uint64 _blockId, + bytes32 _parentHash ) external view - returns (TaikoData.TransitionState storage ts) + returns (TaikoData.TransitionState storage) { - TaikoData.SlotB memory b = state.slotB; - if (blockId < b.lastVerifiedBlockId || blockId >= b.numBlocks) { + TaikoData.SlotB memory b = _state.slotB; + if (_blockId < b.lastVerifiedBlockId || _blockId >= b.numBlocks) { revert L1_INVALID_BLOCK_ID(); } - uint64 slot = blockId % config.blockRingBufferSize; - TaikoData.Block storage blk = state.blocks[slot]; - if (blk.blockId != blockId) revert L1_BLOCK_MISMATCH(); + uint64 slot = _blockId % _config.blockRingBufferSize; + TaikoData.Block storage blk = _state.blocks[slot]; + if (blk.blockId != _blockId) revert L1_BLOCK_MISMATCH(); - uint32 tid = getTransitionId(state, blk, slot, parentHash); + uint32 tid = getTransitionId(_state, blk, slot, _parentHash); if (tid == 0) revert L1_TRANSITION_NOT_FOUND(); - ts = state.transitions[slot][tid]; + return _state.transitions[slot][tid]; } /// @dev Retrieves a block based on its ID. - /// @param state Current TaikoData.State. - /// @param config Actual TaikoData.Config. - /// @param blockId Id of the block. + /// @param _state Current TaikoData.State. + /// @param _config Actual TaikoData.Config. + /// @param _blockId Id of the block. function getBlock( - TaikoData.State storage state, - TaikoData.Config memory config, - uint64 blockId + TaikoData.State storage _state, + TaikoData.Config memory _config, + uint64 _blockId ) external view - returns (TaikoData.Block storage blk, uint64 slot) + returns (TaikoData.Block storage blk_, uint64 slot_) { - slot = blockId % config.blockRingBufferSize; - blk = state.blocks[slot]; - if (blk.blockId != blockId) { + slot_ = _blockId % _config.blockRingBufferSize; + blk_ = _state.blocks[slot_]; + if (blk_.blockId != _blockId) { revert L1_INVALID_BLOCK_ID(); } } @@ -68,21 +68,21 @@ library LibUtils { /// @dev Retrieves the ID of the transition with a given parentHash. /// This function will return 0 if the transtion is not found. function getTransitionId( - TaikoData.State storage state, - TaikoData.Block storage blk, - uint64 slot, - bytes32 parentHash + TaikoData.State storage _state, + TaikoData.Block storage _blk, + uint64 _slot, + bytes32 _parentHash ) internal view - returns (uint32 tid) + returns (uint32 tid_) { - if (state.transitions[slot][1].key == parentHash) { - tid = 1; + if (_state.transitions[_slot][1].key == _parentHash) { + tid_ = 1; } else { - tid = state.transitionIds[blk.blockId][parentHash]; + tid_ = _state.transitionIds[_blk.blockId][_parentHash]; } - if (tid >= blk.nextTransitionId) revert L1_UNEXPECTED_TRANSITION_ID(); + if (tid_ >= _blk.nextTransitionId) revert L1_UNEXPECTED_TRANSITION_ID(); } } diff --git a/packages/protocol/contracts/L1/libs/LibVerifying.sol b/packages/protocol/contracts/L1/libs/LibVerifying.sol index 01406837b75..ce27624e0b0 100644 --- a/packages/protocol/contracts/L1/libs/LibVerifying.sol +++ b/packages/protocol/contracts/L1/libs/LibVerifying.sol @@ -41,32 +41,32 @@ library LibVerifying { error L1_TRANSITION_ID_ZERO(); /// @notice Initializes the Taiko protocol state. - /// @param state The state to initialize. - /// @param config The configuration for the Taiko protocol. - /// @param genesisBlockHash The block hash of the genesis block. + /// @param _state The state to initialize. + /// @param _config The configuration for the Taiko protocol. + /// @param _genesisBlockHash The block hash of the genesis block. function init( - TaikoData.State storage state, - TaikoData.Config memory config, - bytes32 genesisBlockHash + TaikoData.State storage _state, + TaikoData.Config memory _config, + bytes32 _genesisBlockHash ) external { - if (!_isConfigValid(config)) revert L1_INVALID_CONFIG(); + if (!_isConfigValid(_config)) revert L1_INVALID_CONFIG(); // Init state - state.slotA.genesisHeight = uint64(block.number); - state.slotA.genesisTimestamp = uint64(block.timestamp); - state.slotB.numBlocks = 1; + _state.slotA.genesisHeight = uint64(block.number); + _state.slotA.genesisTimestamp = uint64(block.timestamp); + _state.slotB.numBlocks = 1; // Init the genesis block - TaikoData.Block storage blk = state.blocks[0]; + TaikoData.Block storage blk = _state.blocks[0]; blk.nextTransitionId = 2; blk.proposedAt = uint64(block.timestamp); blk.verifiedTransitionId = 1; // Init the first state transition - TaikoData.TransitionState storage ts = state.transitions[0][1]; - ts.blockHash = genesisBlockHash; + TaikoData.TransitionState storage ts = _state.transitions[0][1]; + ts.blockHash = _genesisBlockHash; ts.prover = address(0); ts.timestamp = uint64(block.timestamp); @@ -74,7 +74,7 @@ library LibVerifying { blockId: 0, assignedProver: address(0), prover: address(0), - blockHash: genesisBlockHash, + blockHash: _genesisBlockHash, stateRoot: 0, tier: 0, contestations: 0 @@ -83,25 +83,25 @@ library LibVerifying { /// @dev Verifies up to N blocks. function verifyBlocks( - TaikoData.State storage state, - TaikoData.Config memory config, - IAddressResolver resolver, - uint64 maxBlocksToVerify + TaikoData.State storage _state, + TaikoData.Config memory _config, + IAddressResolver _resolver, + uint64 _maxBlocksToVerify ) internal { - if (maxBlocksToVerify == 0) { + if (_maxBlocksToVerify == 0) { return; } // Retrieve the latest verified block and the associated transition used // for its verification. - TaikoData.SlotB memory b = state.slotB; + TaikoData.SlotB memory b = _state.slotB; uint64 blockId = b.lastVerifiedBlockId; - uint64 slot = blockId % config.blockRingBufferSize; + uint64 slot = blockId % _config.blockRingBufferSize; - TaikoData.Block storage blk = state.blocks[slot]; + TaikoData.Block storage blk = _state.blocks[slot]; if (blk.blockId != blockId) revert L1_BLOCK_MISMATCH(); uint32 tid = blk.verifiedTransitionId; @@ -112,7 +112,7 @@ library LibVerifying { // The `blockHash` variable represents the most recently trusted // blockHash on L2. - bytes32 blockHash = state.transitions[slot][tid].blockHash; + bytes32 blockHash = _state.transitions[slot][tid].blockHash; bytes32 stateRoot; uint64 numBlocksVerified; address tierProvider; @@ -124,20 +124,20 @@ library LibVerifying { unchecked { ++blockId; - while (blockId < b.numBlocks && numBlocksVerified < maxBlocksToVerify) { - slot = blockId % config.blockRingBufferSize; + while (blockId < b.numBlocks && numBlocksVerified < _maxBlocksToVerify) { + slot = blockId % _config.blockRingBufferSize; - blk = state.blocks[slot]; + blk = _state.blocks[slot]; if (blk.blockId != blockId) revert L1_BLOCK_MISMATCH(); - tid = LibUtils.getTransitionId(state, blk, slot, blockHash); + tid = LibUtils.getTransitionId(_state, blk, slot, blockHash); // When `tid` is 0, it indicates that there is no proven // transition with its parentHash equal to the blockHash of the // most recently verified block. if (tid == 0) break; // A transition with the correct `parentHash` has been located. - TaikoData.TransitionState storage ts = state.transitions[slot][tid]; + TaikoData.TransitionState storage ts = _state.transitions[slot][tid]; // It's not possible to verify this block if either the // transition is contested and awaiting higher-tier proof or if @@ -146,11 +146,11 @@ library LibVerifying { break; } else { if (tierProvider == address(0)) { - tierProvider = resolver.resolve("tier_provider", false); + tierProvider = _resolver.resolve("tier_provider", false); } if ( uint256(ITierProvider(tierProvider).getTier(ts.tier).cooldownWindow) * 60 - + uint256(ts.timestamp).max(state.slotB.lastUnpausedAt) > block.timestamp + + uint256(ts.timestamp).max(_state.slotB.lastUnpausedAt) > block.timestamp ) { // If cooldownWindow is 0, the block can theoretically // be proved and verified within the same L1 block. @@ -185,7 +185,7 @@ library LibVerifying { bondToReturn -= blk.livenessBond >> 1; } - IERC20 tko = IERC20(resolver.resolve("taiko_token", false)); + IERC20 tko = IERC20(_resolver.resolve("taiko_token", false)); tko.transfer(ts.prover, bondToReturn); // Note: We exclusively address the bonds linked to the @@ -213,53 +213,53 @@ library LibVerifying { uint64 lastVerifiedBlockId = b.lastVerifiedBlockId + numBlocksVerified; // Update protocol level state variables - state.slotB.lastVerifiedBlockId = lastVerifiedBlockId; + _state.slotB.lastVerifiedBlockId = lastVerifiedBlockId; // sync chain data - _syncChainData(config, resolver, lastVerifiedBlockId, stateRoot); + _syncChainData(_config, _resolver, lastVerifiedBlockId, stateRoot); } } } function _syncChainData( - TaikoData.Config memory config, - IAddressResolver resolver, - uint64 lastVerifiedBlockId, - bytes32 stateRoot + TaikoData.Config memory _config, + IAddressResolver _resolver, + uint64 _lastVerifiedBlockId, + bytes32 _stateRoot ) private { - ISignalService signalService = ISignalService(resolver.resolve("signal_service", false)); + ISignalService signalService = ISignalService(_resolver.resolve("signal_service", false)); (uint64 lastSyncedBlock,) = signalService.getSyncedChainData( - config.chainId, LibSignals.STATE_ROOT, 0 /* latest block Id*/ + _config.chainId, LibSignals.STATE_ROOT, 0 /* latest block Id*/ ); - if (lastVerifiedBlockId > lastSyncedBlock + config.blockSyncThreshold) { + if (_lastVerifiedBlockId > lastSyncedBlock + _config.blockSyncThreshold) { signalService.syncChainData( - config.chainId, LibSignals.STATE_ROOT, lastVerifiedBlockId, stateRoot + _config.chainId, LibSignals.STATE_ROOT, _lastVerifiedBlockId, _stateRoot ); } } - function _isConfigValid(TaikoData.Config memory config) private view returns (bool) { + function _isConfigValid(TaikoData.Config memory _config) private view returns (bool) { if ( - config.chainId <= 1 || config.chainId == block.chainid // - || config.blockMaxProposals == 1 - || config.blockRingBufferSize <= config.blockMaxProposals + 1 - || config.blockMaxGasLimit == 0 || config.blockMaxTxListBytes == 0 - || config.blockMaxTxListBytes > 128 * 1024 // calldata up to 128K - || config.livenessBond == 0 || config.ethDepositRingBufferSize <= 1 - || config.ethDepositMinCountPerBlock == 0 + _config.chainId <= 1 || _config.chainId == block.chainid // + || _config.blockMaxProposals == 1 + || _config.blockRingBufferSize <= _config.blockMaxProposals + 1 + || _config.blockMaxGasLimit == 0 || _config.blockMaxTxListBytes == 0 + || _config.blockMaxTxListBytes > 128 * 1024 // calldata up to 128K + || _config.livenessBond == 0 || _config.ethDepositRingBufferSize <= 1 + || _config.ethDepositMinCountPerBlock == 0 // Audit recommendation, and gas tested. Processing 32 deposits (as initially set in // TaikoL1.sol) costs 72_502 gas. - || config.ethDepositMaxCountPerBlock > 32 - || config.ethDepositMaxCountPerBlock < config.ethDepositMinCountPerBlock - || config.ethDepositMinAmount == 0 - || config.ethDepositMaxAmount <= config.ethDepositMinAmount - || config.ethDepositMaxAmount > type(uint96).max || config.ethDepositGas == 0 - || config.ethDepositMaxFee == 0 - || config.ethDepositMaxFee > type(uint96).max / config.ethDepositMaxCountPerBlock + || _config.ethDepositMaxCountPerBlock > 32 + || _config.ethDepositMaxCountPerBlock < _config.ethDepositMinCountPerBlock + || _config.ethDepositMinAmount == 0 + || _config.ethDepositMaxAmount <= _config.ethDepositMinAmount + || _config.ethDepositMaxAmount > type(uint96).max || _config.ethDepositGas == 0 + || _config.ethDepositMaxFee == 0 + || _config.ethDepositMaxFee > type(uint96).max / _config.ethDepositMaxCountPerBlock ) return false; return true; diff --git a/packages/protocol/contracts/L1/provers/GuardianProver.sol b/packages/protocol/contracts/L1/provers/GuardianProver.sol index 5961ddb5ba0..6ef953849e4 100644 --- a/packages/protocol/contracts/L1/provers/GuardianProver.sol +++ b/packages/protocol/contracts/L1/provers/GuardianProver.sol @@ -27,30 +27,30 @@ contract GuardianProver is Guardians { } /// @dev Called by guardians to approve a guardian proof - /// @param meta The block's metadata. - /// @param tran The valid transition. - /// @param proof The tier proof. - /// @return approved If the minimum number of participants sent the same proof, and proving + /// @param _meta The block's metadata. + /// @param _tran The valid transition. + /// @param _proof The tier proof. + /// @return approved_ If the minimum number of participants sent the same proof, and proving /// transaction is fired away returns true, false otherwise. function approve( - TaikoData.BlockMetadata calldata meta, - TaikoData.Transition calldata tran, - TaikoData.TierProof calldata proof + TaikoData.BlockMetadata calldata _meta, + TaikoData.Transition calldata _tran, + TaikoData.TierProof calldata _proof ) external whenNotPaused nonReentrant - returns (bool approved) + returns (bool approved_) { - if (proof.tier != LibTiers.TIER_GUARDIAN) revert INVALID_PROOF(); - bytes32 hash = keccak256(abi.encode(meta, tran)); - approved = approve(meta.id, hash); + if (_proof.tier != LibTiers.TIER_GUARDIAN) revert INVALID_PROOF(); + bytes32 hash = keccak256(abi.encode(_meta, _tran)); + approved_ = approve(_meta.id, hash); - if (approved) { + if (approved_) { deleteApproval(hash); - ITaikoL1(resolve("taiko", false)).proveBlock(meta.id, abi.encode(meta, tran, proof)); + ITaikoL1(resolve("taiko", false)).proveBlock(_meta.id, abi.encode(_meta, _tran, _proof)); } - emit GuardianApproval(msg.sender, meta.id, tran.blockHash, approved); + emit GuardianApproval(msg.sender, _meta.id, _tran.blockHash, approved_); } } diff --git a/packages/protocol/contracts/L1/provers/Guardians.sol b/packages/protocol/contracts/L1/provers/Guardians.sol index 615d54d78f3..a4daa55379e 100644 --- a/packages/protocol/contracts/L1/provers/Guardians.sol +++ b/packages/protocol/contracts/L1/provers/Guardians.sol @@ -95,39 +95,39 @@ abstract contract Guardians is EssentialContract { emit GuardiansUpdated(version, _newGuardians); } - /// @notice Return if the hash is approved - /// @param hash The hash to check - /// @return True if the hash is approved - function isApproved(bytes32 hash) public view returns (bool) { - return isApproved(_approvals[version][hash]); + /// @notice Returns if the hash is approved + /// @param _hash The hash to check + /// @return true if the hash is approved + function isApproved(bytes32 _hash) public view returns (bool) { + return isApproved(_approvals[version][_hash]); } - /// @notice Return the number of guardians + /// @notice Returns the number of guardians /// @return The number of guardians function numGuardians() public view returns (uint256) { return guardians.length; } - function approve(uint256 operationId, bytes32 hash) internal returns (bool approved) { + function approve(uint256 _operationId, bytes32 _hash) internal returns (bool approved_) { uint256 id = guardianIds[msg.sender]; if (id == 0) revert INVALID_GUARDIAN(); unchecked { - _approvals[version][hash] |= 1 << (id - 1); + _approvals[version][_hash] |= 1 << (id - 1); } - uint256 _approval = _approvals[version][hash]; - approved = isApproved(_approval); - emit Approved(operationId, _approval, approved); + uint256 _approval = _approvals[version][_hash]; + approved_ = isApproved(_approval); + emit Approved(_operationId, _approval, approved_); } - function deleteApproval(bytes32 hash) internal { - delete _approvals[version][hash]; + function deleteApproval(bytes32 _hash) internal { + delete _approvals[version][_hash]; } - function isApproved(uint256 approvalBits) internal view returns (bool) { + function isApproved(uint256 _approvalBits) internal view returns (bool) { uint256 count; - uint256 bits = approvalBits; + uint256 bits = _approvalBits; uint256 guardiansLength = guardians.length; unchecked { for (uint256 i; i < guardiansLength; ++i) { diff --git a/packages/protocol/contracts/L1/tiers/DevnetTierProvider.sol b/packages/protocol/contracts/L1/tiers/DevnetTierProvider.sol index cc4cc608167..f8b251dbf16 100644 --- a/packages/protocol/contracts/L1/tiers/DevnetTierProvider.sol +++ b/packages/protocol/contracts/L1/tiers/DevnetTierProvider.sol @@ -17,8 +17,8 @@ contract DevnetTierProvider is EssentialContract, ITierProvider { } /// @inheritdoc ITierProvider - function getTier(uint16 tierId) public pure override returns (ITierProvider.Tier memory) { - if (tierId == LibTiers.TIER_OPTIMISTIC) { + function getTier(uint16 _tierId) public pure override returns (ITierProvider.Tier memory) { + if (_tierId == LibTiers.TIER_OPTIMISTIC) { return ITierProvider.Tier({ verifierName: "tier_optimistic", validityBond: 250 ether, // TKO @@ -29,7 +29,7 @@ contract DevnetTierProvider is EssentialContract, ITierProvider { }); } - if (tierId == LibTiers.TIER_GUARDIAN) { + if (_tierId == LibTiers.TIER_GUARDIAN) { return ITierProvider.Tier({ verifierName: "tier_guardian", validityBond: 0, // must be 0 for top tier @@ -44,10 +44,10 @@ contract DevnetTierProvider is EssentialContract, ITierProvider { } /// @inheritdoc ITierProvider - function getTierIds() public pure override returns (uint16[] memory tiers) { - tiers = new uint16[](2); - tiers[0] = LibTiers.TIER_OPTIMISTIC; - tiers[1] = LibTiers.TIER_GUARDIAN; + function getTierIds() public pure override returns (uint16[] memory tiers_) { + tiers_ = new uint16[](2); + tiers_[0] = LibTiers.TIER_OPTIMISTIC; + tiers_[1] = LibTiers.TIER_GUARDIAN; } /// @inheritdoc ITierProvider diff --git a/packages/protocol/contracts/L1/tiers/ITierProvider.sol b/packages/protocol/contracts/L1/tiers/ITierProvider.sol index b056d71f2f6..bd0208248e9 100644 --- a/packages/protocol/contracts/L1/tiers/ITierProvider.sol +++ b/packages/protocol/contracts/L1/tiers/ITierProvider.sol @@ -24,12 +24,12 @@ interface ITierProvider { /// @dev Retrieves the IDs of all supported tiers. /// Note that the core protocol requires the number of tiers to be smaller /// than 256. In reality, this number should be much smaller. - /// @return uint16[] struct containing the ids of the tiers. + /// @return The ids of the tiers. function getTierIds() external view returns (uint16[] memory); /// @dev Determines the minimal tier for a block based on a random input. /// @param rand (Semi) random number. - /// @return uint16 Tier id. + /// @return The tier id. function getMinTier(uint256 rand) external view returns (uint16); } diff --git a/packages/protocol/contracts/L1/tiers/MainnetTierProvider.sol b/packages/protocol/contracts/L1/tiers/MainnetTierProvider.sol index 962bf2459e7..062193a6cd2 100644 --- a/packages/protocol/contracts/L1/tiers/MainnetTierProvider.sol +++ b/packages/protocol/contracts/L1/tiers/MainnetTierProvider.sol @@ -17,8 +17,8 @@ contract MainnetTierProvider is EssentialContract, ITierProvider { } /// @inheritdoc ITierProvider - function getTier(uint16 tierId) public pure override returns (ITierProvider.Tier memory) { - if (tierId == LibTiers.TIER_SGX) { + function getTier(uint16 _tierId) public pure override returns (ITierProvider.Tier memory) { + if (_tierId == LibTiers.TIER_SGX) { return ITierProvider.Tier({ verifierName: "tier_sgx", validityBond: 250 ether, // TKO @@ -29,7 +29,7 @@ contract MainnetTierProvider is EssentialContract, ITierProvider { }); } - if (tierId == LibTiers.TIER_SGX_ZKVM) { + if (_tierId == LibTiers.TIER_SGX_ZKVM) { return ITierProvider.Tier({ verifierName: "tier_sgx_zkvm", validityBond: 500 ether, // TKO @@ -40,7 +40,7 @@ contract MainnetTierProvider is EssentialContract, ITierProvider { }); } - if (tierId == LibTiers.TIER_GUARDIAN) { + if (_tierId == LibTiers.TIER_GUARDIAN) { return ITierProvider.Tier({ verifierName: "tier_guardian", validityBond: 0, // must be 0 for top tier @@ -55,17 +55,17 @@ contract MainnetTierProvider is EssentialContract, ITierProvider { } /// @inheritdoc ITierProvider - function getTierIds() public pure override returns (uint16[] memory tiers) { - tiers = new uint16[](3); - tiers[0] = LibTiers.TIER_SGX; - tiers[1] = LibTiers.TIER_SGX_ZKVM; - tiers[2] = LibTiers.TIER_GUARDIAN; + function getTierIds() public pure override returns (uint16[] memory tiers_) { + tiers_ = new uint16[](3); + tiers_[0] = LibTiers.TIER_SGX; + tiers_[1] = LibTiers.TIER_SGX_ZKVM; + tiers_[2] = LibTiers.TIER_GUARDIAN; } /// @inheritdoc ITierProvider - function getMinTier(uint256 rand) public pure override returns (uint16) { + function getMinTier(uint256 _rand) public pure override returns (uint16) { // 0.1% require SGX + ZKVM; all others require SGX - if (rand % 1000 == 0) return LibTiers.TIER_SGX_ZKVM; + if (_rand % 1000 == 0) return LibTiers.TIER_SGX_ZKVM; else return LibTiers.TIER_SGX; } } diff --git a/packages/protocol/contracts/L1/tiers/TestnetTierProvider.sol b/packages/protocol/contracts/L1/tiers/TestnetTierProvider.sol index a1811b72561..c1d03269263 100644 --- a/packages/protocol/contracts/L1/tiers/TestnetTierProvider.sol +++ b/packages/protocol/contracts/L1/tiers/TestnetTierProvider.sol @@ -17,8 +17,8 @@ contract TestnetTierProvider is EssentialContract, ITierProvider { } /// @inheritdoc ITierProvider - function getTier(uint16 tierId) public pure override returns (ITierProvider.Tier memory) { - if (tierId == LibTiers.TIER_OPTIMISTIC) { + function getTier(uint16 _tierId) public pure override returns (ITierProvider.Tier memory) { + if (_tierId == LibTiers.TIER_OPTIMISTIC) { return ITierProvider.Tier({ verifierName: "tier_optimistic", validityBond: 250 ether, // TKO @@ -29,7 +29,7 @@ contract TestnetTierProvider is EssentialContract, ITierProvider { }); } - if (tierId == LibTiers.TIER_SGX) { + if (_tierId == LibTiers.TIER_SGX) { return ITierProvider.Tier({ verifierName: "tier_sgx", validityBond: 500 ether, // TKO @@ -40,7 +40,7 @@ contract TestnetTierProvider is EssentialContract, ITierProvider { }); } - if (tierId == LibTiers.TIER_GUARDIAN) { + if (_tierId == LibTiers.TIER_GUARDIAN) { return ITierProvider.Tier({ verifierName: "tier_guardian", validityBond: 0, // must be 0 for top tier @@ -55,17 +55,17 @@ contract TestnetTierProvider is EssentialContract, ITierProvider { } /// @inheritdoc ITierProvider - function getTierIds() public pure override returns (uint16[] memory tiers) { - tiers = new uint16[](3); - tiers[0] = LibTiers.TIER_OPTIMISTIC; - tiers[1] = LibTiers.TIER_SGX; - tiers[2] = LibTiers.TIER_GUARDIAN; + function getTierIds() public pure override returns (uint16[] memory tiers_) { + tiers_ = new uint16[](3); + tiers_[0] = LibTiers.TIER_OPTIMISTIC; + tiers_[1] = LibTiers.TIER_SGX; + tiers_[2] = LibTiers.TIER_GUARDIAN; } /// @inheritdoc ITierProvider - function getMinTier(uint256 rand) public pure override returns (uint16) { + function getMinTier(uint256 _rand) public pure override returns (uint16) { // 10% will be selected to require SGX proofs. - if (rand % 10 == 0) return LibTiers.TIER_SGX; + if (_rand % 10 == 0) return LibTiers.TIER_SGX; // Other blocks are optimisitc, without validity proofs. return LibTiers.TIER_OPTIMISTIC; } diff --git a/packages/protocol/contracts/L2/CrossChainOwned.sol b/packages/protocol/contracts/L2/CrossChainOwned.sol index 4636c6b342d..1a49d900d84 100644 --- a/packages/protocol/contracts/L2/CrossChainOwned.sol +++ b/packages/protocol/contracts/L2/CrossChainOwned.sol @@ -31,13 +31,13 @@ abstract contract CrossChainOwned is EssentialContract, IMessageInvocable { error XCO_TX_REVERTED(); /// @inheritdoc IMessageInvocable - function onMessageInvocation(bytes calldata data) + function onMessageInvocation(bytes calldata _data) external payable whenNotPaused onlyFromNamed("bridge") { - (uint64 txId, bytes memory txdata) = abi.decode(data, (uint64, bytes)); + (uint64 txId, bytes memory txdata) = abi.decode(_data, (uint64, bytes)); if (txId != nextTxId) revert XCO_INVALID_TX_ID(); IBridge.Context memory ctx = IBridge(msg.sender).context(); diff --git a/packages/protocol/contracts/L2/Lib1559Math.sol b/packages/protocol/contracts/L2/Lib1559Math.sol index 6ddbda5ecb9..efe3da50aea 100644 --- a/packages/protocol/contracts/L2/Lib1559Math.sol +++ b/packages/protocol/contracts/L2/Lib1559Math.sol @@ -11,19 +11,34 @@ library Lib1559Math { error EIP1559_INVALID_PARAMS(); /// @dev eth_qty(excess_gas_issued) / (TARGET * ADJUSTMENT_QUOTIENT) - /// @param adjustmentFactor The product of gasTarget and adjustmentQuotient - function basefee(uint256 gasExcess, uint256 adjustmentFactor) internal pure returns (uint256) { - if (adjustmentFactor == 0) { + /// @param _gasExcess TBD + /// @param _adjustmentFactor The product of gasTarget and adjustmentQuotient + function basefee( + uint256 _gasExcess, + uint256 _adjustmentFactor + ) + internal + pure + returns (uint256) + { + if (_adjustmentFactor == 0) { revert EIP1559_INVALID_PARAMS(); } - return _ethQty(gasExcess, adjustmentFactor) / LibFixedPointMath.SCALING_FACTOR - / adjustmentFactor; + return _ethQty(_gasExcess, _adjustmentFactor) / LibFixedPointMath.SCALING_FACTOR + / _adjustmentFactor; } /// @dev exp(gas_qty / TARGET / ADJUSTMENT_QUOTIENT) - function _ethQty(uint256 gasExcess, uint256 adjustmentFactor) private pure returns (uint256) { - uint256 input = gasExcess * LibFixedPointMath.SCALING_FACTOR / adjustmentFactor; + function _ethQty( + uint256 _gasExcess, + uint256 _adjustmentFactor + ) + private + pure + returns (uint256) + { + uint256 input = _gasExcess * LibFixedPointMath.SCALING_FACTOR / _adjustmentFactor; if (input > LibFixedPointMath.MAX_EXP_INPUT) { input = LibFixedPointMath.MAX_EXP_INPUT; } diff --git a/packages/protocol/contracts/L2/TaikoL2.sol b/packages/protocol/contracts/L2/TaikoL2.sol index 01b3540dc34..bd46830ea82 100644 --- a/packages/protocol/contracts/L2/TaikoL2.sol +++ b/packages/protocol/contracts/L2/TaikoL2.sol @@ -99,23 +99,23 @@ contract TaikoL2 is CrossChainOwned { /// @notice Anchors the latest L1 block details to L2 for cross-layer /// message verification. - /// @param l1BlockHash The latest L1 block hash when this block was + /// @param _l1BlockHash The latest L1 block hash when this block was /// proposed. - /// @param l1StateRoot The latest L1 block's state root. - /// @param l1BlockId The latest L1 block height when this block was proposed. - /// @param parentGasUsed The gas used in the parent block. + /// @param _l1StateRoot The latest L1 block's state root. + /// @param _l1BlockId The latest L1 block height when this block was proposed. + /// @param _parentGasUsed The gas used in the parent block. function anchor( - bytes32 l1BlockHash, - bytes32 l1StateRoot, - uint64 l1BlockId, - uint32 parentGasUsed + bytes32 _l1BlockHash, + bytes32 _l1StateRoot, + uint64 _l1BlockId, + uint32 _parentGasUsed ) external nonReentrant { if ( - l1BlockHash == 0 || l1StateRoot == 0 || l1BlockId == 0 - || (block.number != 1 && parentGasUsed == 0) + _l1BlockHash == 0 || _l1StateRoot == 0 || _l1BlockId == 0 + || (block.number != 1 && _parentGasUsed == 0) ) { revert L2_INVALID_PARAM(); } @@ -137,18 +137,18 @@ contract TaikoL2 is CrossChainOwned { // Verify the base fee per gas is correct uint256 basefee; - (basefee, gasExcess) = _calc1559BaseFee(config, l1BlockId, parentGasUsed); + (basefee, gasExcess) = _calc1559BaseFee(config, _l1BlockId, _parentGasUsed); if (!skipFeeCheck() && block.basefee != basefee) { revert L2_BASEFEE_MISMATCH(); } - if (l1BlockId > lastSyncedBlock + BLOCK_SYNC_THRESHOLD) { + if (_l1BlockId > lastSyncedBlock + BLOCK_SYNC_THRESHOLD) { // Store the L1's state root as a signal to the local signal service to // allow for multi-hop bridging. ISignalService(resolve("signal_service", false)).syncChainData( - ownerChainId, LibSignals.STATE_ROOT, l1BlockId, l1StateRoot + ownerChainId, LibSignals.STATE_ROOT, _l1BlockId, _l1StateRoot ); - lastSyncedBlock = l1BlockId; + lastSyncedBlock = _l1BlockId; } // Update state variables l2Hashes[parentId] = blockhash(parentId); @@ -158,60 +158,60 @@ contract TaikoL2 is CrossChainOwned { } /// @notice Withdraw token or Ether from this address - /// @param token Token address or address(0) if Ether. - /// @param to Withdraw to address. + /// @param _token Token address or address(0) if Ether. + /// @param _to Withdraw to address. function withdraw( - address token, - address to + address _token, + address _to ) external onlyFromOwnerOrNamed("withdrawer") nonReentrant whenNotPaused { - if (to == address(0)) revert L2_INVALID_PARAM(); - if (token == address(0)) { - to.sendEther(address(this).balance); + if (_to == address(0)) revert L2_INVALID_PARAM(); + if (_token == address(0)) { + _to.sendEther(address(this).balance); } else { - IERC20(token).safeTransfer(to, IERC20(token).balanceOf(address(this))); + IERC20(_token).safeTransfer(_to, IERC20(_token).balanceOf(address(this))); } } /// @notice Gets the basefee and gas excess using EIP-1559 configuration for /// the given parameters. - /// @param l1BlockId The synced L1 height in the next Taiko block - /// @param parentGasUsed Gas used in the parent block. - /// @return basefee The calculated EIP-1559 base fee per gas. + /// @param _l1BlockId The synced L1 height in the next Taiko block + /// @param _parentGasUsed Gas used in the parent block. + /// @return basefee_ The calculated EIP-1559 base fee per gas. function getBasefee( - uint64 l1BlockId, - uint32 parentGasUsed + uint64 _l1BlockId, + uint32 _parentGasUsed ) public view - returns (uint256 basefee) + returns (uint256 basefee_) { - (basefee,) = _calc1559BaseFee(getConfig(), l1BlockId, parentGasUsed); + (basefee_,) = _calc1559BaseFee(getConfig(), _l1BlockId, _parentGasUsed); } /// @notice Retrieves the block hash for the given L2 block number. - /// @param blockId The L2 block number to retrieve the block hash for. + /// @param _blockId The L2 block number to retrieve the block hash for. /// @return The block hash for the specified L2 block id, or zero if the /// block id is greater than or equal to the current block number. - function getBlockHash(uint64 blockId) public view returns (bytes32) { - if (blockId >= block.number) return 0; - if (blockId + 256 >= block.number) return blockhash(blockId); - return l2Hashes[blockId]; + function getBlockHash(uint64 _blockId) public view returns (bytes32) { + if (_blockId >= block.number) return 0; + if (_blockId + 256 >= block.number) return blockhash(_blockId); + return l2Hashes[_blockId]; } /// @notice Returns EIP1559 related configurations. - /// @return config struct containing configuration parameters. - function getConfig() public view virtual returns (Config memory config) { + /// @return config_ struct containing configuration parameters. + function getConfig() public view virtual returns (Config memory config_) { // 4x Ethereum gas target, if we assume most of the time, L2 block time // is 3s, and each block is full (gasUsed is 15_000_000), then its // ~60_000_000, if the network is congester than that, the base fee // will increase. - config.gasTargetPerL1Block = 15 * 1e6 * 4; - config.basefeeAdjustmentQuotient = 8; + config_.gasTargetPerL1Block = 15 * 1e6 * 4; + config_.basefeeAdjustmentQuotient = 8; } /// @notice Tells if we need to validate basefee (for simulation). @@ -220,7 +220,7 @@ contract TaikoL2 is CrossChainOwned { return false; } - function _calcPublicInputHash(uint256 blockId) + function _calcPublicInputHash(uint256 _blockId) private view returns (bytes32 publicInputHashOld, bytes32 publicInputHashNew) @@ -231,8 +231,8 @@ contract TaikoL2 is CrossChainOwned { unchecked { // Put the previous 255 blockhashes (excluding the parent's) into a // ring buffer. - for (uint256 i; i < 255 && blockId >= i + 1; ++i) { - uint256 j = blockId - i - 1; + for (uint256 i; i < 255 && _blockId >= i + 1; ++i) { + uint256 j = _blockId - i - 1; inputs[j % 255] = blockhash(j); } } @@ -243,26 +243,26 @@ contract TaikoL2 is CrossChainOwned { publicInputHashOld := keccak256(inputs, 8192 /*mul(256, 32)*/ ) } - inputs[blockId % 255] = blockhash(blockId); + inputs[_blockId % 255] = blockhash(_blockId); assembly { publicInputHashNew := keccak256(inputs, 8192 /*mul(256, 32)*/ ) } } function _calc1559BaseFee( - Config memory config, - uint64 l1BlockId, - uint32 parentGasUsed + Config memory _config, + uint64 _l1BlockId, + uint32 _parentGasUsed ) private view - returns (uint256 _basefee, uint64 _gasExcess) + returns (uint256 basefee_, uint64 gasExcess_) { // gasExcess being 0 indicate the dynamic 1559 base fee is disabled. if (gasExcess > 0) { // We always add the gas used by parent block to the gas excess // value as this has already happend - uint256 excess = uint256(gasExcess) + parentGasUsed; + uint256 excess = uint256(gasExcess) + _parentGasUsed; // Calculate how much more gas to issue to offset gas excess. // after each L1 block time, config.gasTarget more gas is issued, @@ -272,27 +272,27 @@ contract TaikoL2 is CrossChainOwned { // and the difference between the L1 height would be extremely big, // reverting the initial gas excess value back to 0. uint256 numL1Blocks; - if (lastSyncedBlock > 0 && l1BlockId > lastSyncedBlock) { - numL1Blocks = l1BlockId - lastSyncedBlock; + if (lastSyncedBlock > 0 && _l1BlockId > lastSyncedBlock) { + numL1Blocks = _l1BlockId - lastSyncedBlock; } if (numL1Blocks > 0) { - uint256 issuance = numL1Blocks * config.gasTargetPerL1Block; + uint256 issuance = numL1Blocks * _config.gasTargetPerL1Block; excess = excess > issuance ? excess - issuance : 1; } - _gasExcess = uint64(excess.min(type(uint64).max)); + gasExcess_ = uint64(excess.min(type(uint64).max)); // The base fee per gas used by this block is the spot price at the // bonding curve, regardless the actual amount of gas used by this // block, however, this block's gas used will affect the next // block's base fee. - _basefee = Lib1559Math.basefee( - _gasExcess, uint256(config.basefeeAdjustmentQuotient) * config.gasTargetPerL1Block + basefee_ = Lib1559Math.basefee( + gasExcess_, uint256(_config.basefeeAdjustmentQuotient) * _config.gasTargetPerL1Block ); } // Always make sure basefee is nonzero, this is required by the node. - if (_basefee == 0) _basefee = 1; + if (basefee_ == 0) basefee_ = 1; } } diff --git a/packages/protocol/contracts/L2/TaikoL2EIP1559Configurable.sol b/packages/protocol/contracts/L2/TaikoL2EIP1559Configurable.sol index 5edeff9857b..1ae90719fdf 100644 --- a/packages/protocol/contracts/L2/TaikoL2EIP1559Configurable.sol +++ b/packages/protocol/contracts/L2/TaikoL2EIP1559Configurable.sol @@ -20,23 +20,23 @@ contract TaikoL2EIP1559Configurable is TaikoL2 { error L2_INVALID_CONFIG(); /// @notice Sets EIP1559 configuration and gas excess. - /// @param newConfig The new EIP1559 config. - /// @param newGasExcess The new gas excess + /// @param _newConfig The new EIP1559 config. + /// @param _newGasExcess The new gas excess function setConfigAndExcess( - Config memory newConfig, - uint64 newGasExcess + Config memory _newConfig, + uint64 _newGasExcess ) external virtual onlyOwner { - if (newConfig.gasTargetPerL1Block == 0) revert L2_INVALID_CONFIG(); - if (newConfig.basefeeAdjustmentQuotient == 0) revert L2_INVALID_CONFIG(); + if (_newConfig.gasTargetPerL1Block == 0) revert L2_INVALID_CONFIG(); + if (_newConfig.basefeeAdjustmentQuotient == 0) revert L2_INVALID_CONFIG(); - customConfig = newConfig; - gasExcess = newGasExcess; + customConfig = _newConfig; + gasExcess = _newGasExcess; - emit ConfigAndExcessChanged(newConfig, newGasExcess); + emit ConfigAndExcessChanged(_newConfig, _newGasExcess); } /// @inheritdoc TaikoL2 diff --git a/packages/protocol/contracts/SOLIDITY_STYLE_GUIDE.md b/packages/protocol/contracts/SOLIDITY_STYLE_GUIDE.md new file mode 100644 index 00000000000..4c214787f41 --- /dev/null +++ b/packages/protocol/contracts/SOLIDITY_STYLE_GUIDE.md @@ -0,0 +1,36 @@ +# Solidity Style Guide + +This document outlines the coding and naming conventions for Solidity files within our project. It aims to ensure consistency, readability, and maintainability of the codebase. Please note that this guide is subject to updates and improvements over time. + +## Scope + +This style guide applies to all Solidity files in this directory, with the exception of those located within the following directories: + +- `automata-attestation/` +- `thirdparty/` + +These directories may contain externally sourced contracts or those following different conventions. + +## Naming Conventions + +To maintain clarity and consistency across our Solidity codebase, the following naming conventions are to be adhered to: + +- **Function Parameters:** Prefix all function parameters with a leading underscore (`_`) to distinguish them from local and global variables and avoid naming conflicts. + +- **Function Return Values:** Suffix names of function return variables with an underscore (`_`) to clearly differentiate them from other variables and parameters. + +- **Private Functions:** Prefix private function names with a leading underscore (`_`). This convention signals the function's visibility level at a glance. + +- **Private State Variables:** Prefix all private state variable names with a leading underscore (`_`), highlighting their limited scope within the contract. + +## Reserved Storage Slots + +To ensure upgradeability and prevent storage collisions in future contract versions, reserve a fixed number of storage slots at the end of each contract. This is achieved by declaring a placeholder array in the contract's storage layout as follows: + +```solidity +// Reserve 50 storage slots for future use to ensure contract upgradeability. +uint256[50] private __gap; +``` + +Note: Replace `xx` with the actual number of slots you intend to reserve, as shown in the example above. + diff --git a/packages/protocol/contracts/automata-attestation/interfaces/IAttestation.sol b/packages/protocol/contracts/automata-attestation/interfaces/IAttestation.sol index 47cbdeb780f..767ca02f91f 100644 --- a/packages/protocol/contracts/automata-attestation/interfaces/IAttestation.sol +++ b/packages/protocol/contracts/automata-attestation/interfaces/IAttestation.sol @@ -1,5 +1,5 @@ //SPDX-License-Identifier: MIT -pragma solidity >=0.8.0; +pragma solidity 0.8.24; import { V3Struct } from "../lib/QuoteV3Auth/V3Struct.sol"; diff --git a/packages/protocol/contracts/automata-attestation/interfaces/ISigVerifyLib.sol b/packages/protocol/contracts/automata-attestation/interfaces/ISigVerifyLib.sol index ca5f3ef9cbc..44e20cc92ac 100644 --- a/packages/protocol/contracts/automata-attestation/interfaces/ISigVerifyLib.sol +++ b/packages/protocol/contracts/automata-attestation/interfaces/ISigVerifyLib.sol @@ -1,5 +1,5 @@ //SPDX-License-Identifier: MIT -pragma solidity >=0.8.0; +pragma solidity 0.8.24; /// @title ISigVerifyLib /// @custom:security-contact security@taiko.xyz diff --git a/packages/protocol/contracts/automata-attestation/lib/interfaces/IPEMCertChainLib.sol b/packages/protocol/contracts/automata-attestation/lib/interfaces/IPEMCertChainLib.sol index a70fb2cd71f..7f728558bda 100644 --- a/packages/protocol/contracts/automata-attestation/lib/interfaces/IPEMCertChainLib.sol +++ b/packages/protocol/contracts/automata-attestation/lib/interfaces/IPEMCertChainLib.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MIT -pragma solidity >=0.8.0; +pragma solidity 0.8.24; /// @title IPEMCertChainLib /// @custom:security-contact security@taiko.xyz diff --git a/packages/protocol/contracts/automata-attestation/utils/Asn1Decode.sol b/packages/protocol/contracts/automata-attestation/utils/Asn1Decode.sol index 9063d7ae2be..7f93e61d827 100644 --- a/packages/protocol/contracts/automata-attestation/utils/Asn1Decode.sol +++ b/packages/protocol/contracts/automata-attestation/utils/Asn1Decode.sol @@ -93,7 +93,7 @@ library Asn1Decode { * @dev Use for looping through children of a node (either i or j). * @param i Pointer to an ASN1 node * @param j Pointer to another ASN1 node of the same ASN1 structure - * @return True iff j is child of i or i is child of j. + * @return true iff j is child of i or i is child of j. */ function isChildOf(uint256 i, uint256 j) internal pure returns (bool) { return ( diff --git a/packages/protocol/contracts/automata-attestation/utils/BytesUtils.sol b/packages/protocol/contracts/automata-attestation/utils/BytesUtils.sol index 94aae72a433..7bebeb21be4 100644 --- a/packages/protocol/contracts/automata-attestation/utils/BytesUtils.sol +++ b/packages/protocol/contracts/automata-attestation/utils/BytesUtils.sol @@ -111,7 +111,7 @@ library BytesUtils { * @param other The second byte range to compare. * @param otherOffset The offset into the second byte range. * @param len The number of bytes to compare - * @return True if the byte ranges are equal, false otherwise. + * @return true if the byte ranges are equal, false otherwise. */ function equals( bytes memory self, @@ -133,7 +133,7 @@ library BytesUtils { * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @param otherOffset The offset into the second byte range. - * @return True if the byte ranges are equal, false otherwise. + * @return true if the byte ranges are equal, false otherwise. */ function equals( bytes memory self, @@ -155,7 +155,7 @@ library BytesUtils { * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. - * @return True if the byte ranges are equal, false otherwise. + * @return true if the byte ranges are equal, false otherwise. */ function equals( bytes memory self, @@ -173,7 +173,7 @@ library BytesUtils { * @dev Returns true if the two byte ranges are equal. * @param self The first byte range to compare. * @param other The second byte range to compare. - * @return True if the byte ranges are equal, false otherwise. + * @return true if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, bytes memory other) internal pure returns (bool) { return self.length == other.length && equals(self, 0, other, 0, self.length); diff --git a/packages/protocol/contracts/bridge/Bridge.sol b/packages/protocol/contracts/bridge/Bridge.sol index 63d459badb0..695ab7f3fe1 100644 --- a/packages/protocol/contracts/bridge/Bridge.sol +++ b/packages/protocol/contracts/bridge/Bridge.sol @@ -18,25 +18,6 @@ contract Bridge is EssentialContract, IBridge { using LibAddress for address; using LibAddress for address payable; - enum Status { - NEW, - RETRIABLE, - DONE, - FAILED, - RECALLED - } - - // Note that this struct shall take only 1 slot to minimize gas cost - struct ProofReceipt { - // The time a message is marked as received on the destination chain - uint64 receivedAt; - // The address that can execute the message after the invocation delay without an extra - // delay. - // For a failed message, preferredExecutor's value doesn't matter as only the owner can - // invoke the message. - address preferredExecutor; - } - // The slot in transient storage of the call context // This is the keccak256 hash of "bridge.ctx_slot" bytes32 private constant _CTX_SLOT = @@ -53,7 +34,7 @@ contract Bridge is EssentialContract, IBridge { mapping(bytes32 msgHash => Status status) public messageStatus; /// @dev Slots 3, 4, and 5. - Context private _ctx; + Context private __ctx; /// @notice Mapping to store banned addresses. /// @dev Slot 6. @@ -65,44 +46,6 @@ contract Bridge is EssentialContract, IBridge { uint256[43] private __gap; - /// @notice Emitted when a message is sent. - /// @param msgHash The hash of the message. - /// @param message The message. - event MessageSent(bytes32 indexed msgHash, Message message); - - /// @notice Emitted when a message is received. - /// @param msgHash The hash of the message. - /// @param message The message. - /// @param isRecall True if the message is a recall. - event MessageReceived(bytes32 indexed msgHash, Message message, bool isRecall); - - /// @notice Emitted when a message is recalled. - /// @param msgHash The hash of the message. - event MessageRecalled(bytes32 indexed msgHash); - - /// @notice Emitted when a message is executed. - /// @param msgHash The hash of the message. - event MessageExecuted(bytes32 indexed msgHash); - - /// @notice Emitted when a message is retried. - /// @param msgHash The hash of the message. - event MessageRetried(bytes32 indexed msgHash); - - /// @notice Emitted when the status of a message changes. - /// @param msgHash The hash of the message. - /// @param status The new status of the message. - event MessageStatusChanged(bytes32 indexed msgHash, Status status); - - /// @notice Emitted when a message is suspended or unsuspended. - /// @param msgHash The hash of the message. - /// @param suspended True if the message is suspended. - event MessageSuspended(bytes32 msgHash, bool suspended); - - /// @notice Emitted when an address is banned or unbanned. - /// @param addr The address to ban or unban. - /// @param banned True if the address is banned. - event AddressBanned(address indexed addr, bool banned); - error B_INVALID_CHAINID(); error B_INVALID_CONTEXT(); error B_INVALID_GAS_LIMIT(); @@ -117,8 +60,8 @@ contract Bridge is EssentialContract, IBridge { error B_STATUS_MISMATCH(); error B_INVOCATION_TOO_EARLY(); - modifier sameChain(uint64 chainId) { - if (chainId != block.chainid) revert B_INVALID_CHAINID(); + modifier sameChain(uint64 _chainId) { + if (_chainId != block.chainid) revert B_INVALID_CHAINID(); _; } @@ -133,98 +76,91 @@ contract Bridge is EssentialContract, IBridge { } /// @notice Suspend or unsuspend invocation for a list of messages. - /// @param msgHashes The array of msgHashes to be suspended. - /// @param toSuspend True if suspend, false if unsuspend. + /// @param _msgHashes The array of msgHashes to be suspended. + /// @param _suspend True if suspend, false if unsuspend. function suspendMessages( - bytes32[] calldata msgHashes, - bool toSuspend + bytes32[] calldata _msgHashes, + bool _suspend ) external onlyFromOwnerOrNamed("bridge_watchdog") { - uint64 _timestamp = toSuspend ? type(uint64).max : uint64(block.timestamp); - for (uint256 i; i < msgHashes.length; ++i) { - bytes32 msgHash = msgHashes[i]; + uint64 _timestamp = _suspend ? type(uint64).max : uint64(block.timestamp); + for (uint256 i; i < _msgHashes.length; ++i) { + bytes32 msgHash = _msgHashes[i]; proofReceipt[msgHash].receivedAt = _timestamp; - emit MessageSuspended(msgHash, toSuspend); + emit MessageSuspended(msgHash, _suspend); } } /// @notice Ban or unban an address. A banned addresses will not be invoked upon /// with message calls. - /// @param addr The addreess to ban or unban. - /// @param toBan True if ban, false if unban. + /// @param _addr The addreess to ban or unban. + /// @param _ban True if ban, false if unban. function banAddress( - address addr, - bool toBan + address _addr, + bool _ban ) external onlyFromOwnerOrNamed("bridge_watchdog") nonReentrant { - if (addressBanned[addr] == toBan) revert B_INVALID_STATUS(); - addressBanned[addr] = toBan; - emit AddressBanned(addr, toBan); + if (addressBanned[_addr] == _ban) revert B_INVALID_STATUS(); + addressBanned[_addr] = _ban; + emit AddressBanned(_addr, _ban); } - /// @notice Sends a message to the destination chain and takes custody - /// of Ether required in this contract. All extra Ether will be refunded. /// @inheritdoc IBridge - function sendMessage(Message calldata message) + function sendMessage(Message calldata _message) external payable override nonReentrant whenNotPaused - returns (bytes32 msgHash, Message memory _message) + returns (bytes32 msgHash_, Message memory message_) { // Ensure the message owner is not null. - if (message.srcOwner == address(0) || message.destOwner == address(0)) { + if (_message.srcOwner == address(0) || _message.destOwner == address(0)) { revert B_INVALID_USER(); } // Check if the destination chain is enabled. - (bool destChainEnabled,) = isDestChainEnabled(message.destChainId); + (bool destChainEnabled,) = isDestChainEnabled(_message.destChainId); // Verify destination chain and to address. if (!destChainEnabled) revert B_INVALID_CHAINID(); - if (message.destChainId == block.chainid) { + if (_message.destChainId == block.chainid) { revert B_INVALID_CHAINID(); } // Ensure the sent value matches the expected amount. - uint256 expectedAmount = message.value + message.fee; + uint256 expectedAmount = _message.value + _message.fee; if (expectedAmount != msg.value) revert B_INVALID_VALUE(); - _message = message; + message_ = _message; // Configure message details and send signal to indicate message // sending. - _message.id = nextMessageId++; - _message.from = msg.sender; - _message.srcChainId = uint64(block.chainid); + message_.id = nextMessageId++; + message_.from = msg.sender; + message_.srcChainId = uint64(block.chainid); - msgHash = hashMessage(_message); + msgHash_ = hashMessage(message_); - ISignalService(resolve("signal_service", false)).sendSignal(msgHash); - emit MessageSent(msgHash, _message); + ISignalService(resolve("signal_service", false)).sendSignal(msgHash_); + emit MessageSent(msgHash_, message_); } - /// @notice Recalls a failed message on its source chain, releasing - /// associated assets. - /// @dev This function checks if the message failed on the source chain and - /// releases associated Ether or tokens. - /// @param message The message whose associated Ether should be released. - /// @param proof The merkle inclusion proof. + /// @inheritdoc IBridge function recallMessage( - Message calldata message, - bytes calldata proof + Message calldata _message, + bytes calldata _proof ) external nonReentrant whenNotPaused - sameChain(message.srcChainId) + sameChain(_message.srcChainId) { - bytes32 msgHash = hashMessage(message); + bytes32 msgHash = hashMessage(_message); if (messageStatus[msgHash] != Status.NEW) revert B_STATUS_MISMATCH(); @@ -239,7 +175,7 @@ contract Bridge is EssentialContract, IBridge { } bytes32 failureSignal = signalForFailedMessage(msgHash); - if (!_proveSignalReceived(signalService, failureSignal, message.destChainId, proof)) { + if (!_proveSignalReceived(signalService, failureSignal, _message.destChainId, _proof)) { revert B_NOT_FAILED(); } @@ -256,49 +192,38 @@ contract Bridge is EssentialContract, IBridge { // Execute the recall logic based on the contract's support for the // IRecallableSender interface - if (message.from.supportsInterface(type(IRecallableSender).interfaceId)) { - _storeContext({ - msgHash: msgHash, - from: address(this), - srcChainId: message.srcChainId - }); + if (_message.from.supportsInterface(type(IRecallableSender).interfaceId)) { + _storeContext(msgHash, address(this), _message.srcChainId); // Perform recall - IRecallableSender(message.from).onMessageRecalled{ value: message.value }( - message, msgHash + IRecallableSender(_message.from).onMessageRecalled{ value: _message.value }( + _message, msgHash ); // Reset the context after the message call _resetContext(); } else { - message.srcOwner.sendEther(message.value); + _message.srcOwner.sendEther(_message.value); } emit MessageRecalled(msgHash); } else if (!isMessageProven) { - emit MessageReceived(msgHash, message, true); + emit MessageReceived(msgHash, _message, true); } else { revert B_INVOCATION_TOO_EARLY(); } } - /// @notice Processes a bridge message on the destination chain. This - /// function is callable by any address, including the `message.destOwner`. - /// @dev The process begins by hashing the message and checking the message - /// status in the bridge If the status is "NEW", the message is invoked. The - /// status is updated accordingly, and processing fees are refunded as - /// needed. - /// @param message The message to be processed. - /// @param proof The merkle inclusion proof. + /// @inheritdoc IBridge function processMessage( - Message calldata message, - bytes calldata proof + Message calldata _message, + bytes calldata _proof ) external nonReentrant whenNotPaused - sameChain(message.destChainId) + sameChain(_message.destChainId) { - bytes32 msgHash = hashMessage(message); + bytes32 msgHash = hashMessage(_message); if (messageStatus[msgHash] != Status.NEW) revert B_STATUS_MISMATCH(); address signalService = resolve("signal_service", false); @@ -308,7 +233,7 @@ contract Bridge is EssentialContract, IBridge { (uint256 invocationDelay, uint256 invocationExtraDelay) = getInvocationDelays(); if (!isMessageProven) { - if (!_proveSignalReceived(signalService, msgHash, message.srcChainId, proof)) { + if (!_proveSignalReceived(signalService, msgHash, _message.srcChainId, _proof)) { revert B_NOT_RECEIVED(); } @@ -317,7 +242,7 @@ contract Bridge is EssentialContract, IBridge { if (invocationDelay != 0) { proofReceipt[msgHash] = ProofReceipt({ receivedAt: receivedAt, - preferredExecutor: message.gasLimit == 0 ? message.destOwner : msg.sender + preferredExecutor: _message.gasLimit == 0 ? _message.destOwner : msg.sender }); } } @@ -332,7 +257,7 @@ contract Bridge is EssentialContract, IBridge { if (block.timestamp >= invocationDelay + receivedAt) { // If the gas limit is set to zero, only the owner can process the message. - if (message.gasLimit == 0 && msg.sender != message.destOwner) { + if (_message.gasLimit == 0 && msg.sender != _message.destOwner) { revert B_PERMISSION_DENIED(); } @@ -342,19 +267,19 @@ contract Bridge is EssentialContract, IBridge { // Process message differently based on the target address if ( - message.to == address(0) || message.to == address(this) - || message.to == signalService || addressBanned[message.to] + _message.to == address(0) || _message.to == address(this) + || _message.to == signalService || addressBanned[_message.to] ) { // Handle special addresses that don't require actual invocation but // mark message as DONE - refundAmount = message.value; + refundAmount = _message.value; _updateMessageStatus(msgHash, Status.DONE); } else { // Use the specified message gas limit if called by the owner, else // use remaining gas - uint256 gasLimit = msg.sender == message.destOwner ? gasleft() : message.gasLimit; + uint256 gasLimit = msg.sender == _message.destOwner ? gasleft() : _message.gasLimit; - if (_invokeMessageCall(message, msgHash, gasLimit)) { + if (_invokeMessageCall(_message, msgHash, gasLimit)) { _updateMessageStatus(msgHash, Status.DONE); } else { _updateMessageStatus(msgHash, Status.RETRIABLE); @@ -362,131 +287,122 @@ contract Bridge is EssentialContract, IBridge { } // Determine the refund recipient - address refundTo = message.refundTo == address(0) ? message.destOwner : message.refundTo; + address refundTo = + _message.refundTo == address(0) ? _message.destOwner : _message.refundTo; // Refund the processing fee if (msg.sender == refundTo) { - refundTo.sendEther(message.fee + refundAmount); + refundTo.sendEther(_message.fee + refundAmount); } else { // If sender is another address, reward it and refund the rest - msg.sender.sendEther(message.fee); + msg.sender.sendEther(_message.fee); refundTo.sendEther(refundAmount); } emit MessageExecuted(msgHash); } else if (!isMessageProven) { - emit MessageReceived(msgHash, message, false); + emit MessageReceived(msgHash, _message, false); } else { revert B_INVOCATION_TOO_EARLY(); } } - /// @notice Retries to invoke the messageCall after releasing associated - /// Ether and tokens. - /// @dev This function can be called by any address, including the - /// `message.destOwner`. - /// It attempts to invoke the messageCall and updates the message status - /// accordingly. - /// @param message The message to retry. - /// @param isLastAttempt Specifies if this is the last attempt to retry the - /// message. + /// @inheritdoc IBridge function retryMessage( - Message calldata message, - bool isLastAttempt + Message calldata _message, + bool _isLastAttempt ) external nonReentrant whenNotPaused - sameChain(message.destChainId) + sameChain(_message.destChainId) { // If the gasLimit is set to 0 or isLastAttempt is true, the caller must // be the message.destOwner. - if (message.gasLimit == 0 || isLastAttempt) { - if (msg.sender != message.destOwner) revert B_PERMISSION_DENIED(); + if (_message.gasLimit == 0 || _isLastAttempt) { + if (msg.sender != _message.destOwner) revert B_PERMISSION_DENIED(); } - bytes32 msgHash = hashMessage(message); + bytes32 msgHash = hashMessage(_message); if (messageStatus[msgHash] != Status.RETRIABLE) { revert B_NON_RETRIABLE(); } // Attempt to invoke the messageCall. - if (_invokeMessageCall(message, msgHash, gasleft())) { + if (_invokeMessageCall(_message, msgHash, gasleft())) { _updateMessageStatus(msgHash, Status.DONE); - } else if (isLastAttempt) { + } else if (_isLastAttempt) { _updateMessageStatus(msgHash, Status.FAILED); } emit MessageRetried(msgHash); } - /// @notice Checks if the message was sent. - /// @param message The message. - /// @return True if the message was sent. - function isMessageSent(Message calldata message) public view returns (bool) { - if (message.srcChainId != block.chainid) return false; + /// @inheritdoc IBridge + function isMessageSent(Message calldata _message) public view returns (bool) { + if (_message.srcChainId != block.chainid) return false; return ISignalService(resolve("signal_service", false)).isSignalSent({ - app: address(this), - signal: hashMessage(message) + _app: address(this), + _signal: hashMessage(_message) }); } /// @notice Checks if a msgHash has failed on its destination chain. - /// @param message The message. - /// @param proof The merkle inclusion proof. - /// @return Returns true if the message has failed, false otherwise. + /// @param _message The message. + /// @param _proof The merkle inclusion proof. + /// @return true if the message has failed, false otherwise. function proveMessageFailed( - Message calldata message, - bytes calldata proof + Message calldata _message, + bytes calldata _proof ) public view returns (bool) { - if (message.srcChainId != block.chainid) return false; + if (_message.srcChainId != block.chainid) return false; return _proveSignalReceived( resolve("signal_service", false), - signalForFailedMessage(hashMessage(message)), - message.destChainId, - proof + signalForFailedMessage(hashMessage(_message)), + _message.destChainId, + _proof ); } /// @notice Checks if a msgHash has failed on its destination chain. - /// @param message The message. - /// @param proof The merkle inclusion proof. - /// @return Returns true if the message has failed, false otherwise. + /// @param _message The message. + /// @param _proof The merkle inclusion proof. + /// @return true if the message has failed, false otherwise. function proveMessageReceived( - Message calldata message, - bytes calldata proof + Message calldata _message, + bytes calldata _proof ) public view returns (bool) { - if (message.destChainId != block.chainid) return false; + if (_message.destChainId != block.chainid) return false; return _proveSignalReceived( - resolve("signal_service", false), hashMessage(message), message.srcChainId, proof + resolve("signal_service", false), hashMessage(_message), _message.srcChainId, _proof ); } /// @notice Checks if the destination chain is enabled. - /// @param chainId The destination chain ID. - /// @return enabled True if the destination chain is enabled. - /// @return destBridge The bridge of the destination chain. - function isDestChainEnabled(uint64 chainId) + /// @param _chainId The destination chain ID. + /// @return enabled_ True if the destination chain is enabled. + /// @return destBridge_ The bridge of the destination chain. + function isDestChainEnabled(uint64 _chainId) public view - returns (bool enabled, address destBridge) + returns (bool enabled_, address destBridge_) { - destBridge = resolve(chainId, "bridge", true); - enabled = destBridge != address(0); + destBridge_ = resolve(_chainId, "bridge", true); + enabled_ = destBridge_ != address(0); } /// @notice Gets the current context. /// @inheritdoc IBridge - function context() public view returns (Context memory ctx) { - ctx = _loadContext(); - if (ctx.msgHash == 0 || ctx.msgHash == bytes32(PLACEHOLDER)) { + function context() public view returns (Context memory ctx_) { + ctx_ = _loadContext(); + if (ctx_.msgHash == 0 || ctx_.msgHash == bytes32(PLACEHOLDER)) { revert B_INVALID_CONTEXT(); } } @@ -494,15 +410,15 @@ contract Bridge is EssentialContract, IBridge { /// @notice Returns invocation delay values. /// @dev Bridge contract deployed on L1 shall use a non-zero value for better /// security. - /// @return invocationDelay The minimal delay in second before a message can be executed since + /// @return invocationDelay_ The minimal delay in second before a message can be executed since /// and the time it was received on the this chain. - /// @return invocationExtraDelay The extra delay in second (to be added to invocationDelay) if + /// @return invocationExtraDelay_ The extra delay in second (to be added to invocationDelay) if /// the transactor is not the preferredExecutor who proved this message. function getInvocationDelays() public view virtual - returns (uint256 invocationDelay, uint256 invocationExtraDelay) + returns (uint256 invocationDelay_, uint256 invocationExtraDelay_) { if ( block.chainid == 1 // Ethereum mainnet @@ -529,22 +445,20 @@ contract Bridge is EssentialContract, IBridge { } } - /// @notice Hash the message - /// @param message The message struct variable to be hashed. - /// @return bytes32 The hashed message. - function hashMessage(Message memory message) public pure returns (bytes32) { - return keccak256(abi.encode("TAIKO_MESSAGE", message)); + /// @inheritdoc IBridge + function hashMessage(Message memory _message) public pure returns (bytes32) { + return keccak256(abi.encode("TAIKO_MESSAGE", _message)); } /// @notice Returns a signal representing a failed/recalled message. - /// @param msgHash The message hash. - /// @return bytes32 The failed representation of it as bytes32. - function signalForFailedMessage(bytes32 msgHash) public pure returns (bytes32) { - return msgHash ^ bytes32(uint256(Status.FAILED)); + /// @param _msgHash The message hash. + /// @return The failed representation of it as bytes32. + function signalForFailedMessage(bytes32 _msgHash) public pure returns (bytes32) { + return _msgHash ^ bytes32(uint256(Status.FAILED)); } /// @notice Checks if the given address can pause and unpause the bridge. - function _authorizePause(address addr) + function _authorizePause(address) internal view virtual @@ -553,39 +467,39 @@ contract Bridge is EssentialContract, IBridge { { } /// @notice Invokes a call message on the Bridge. - /// @param message The call message to be invoked. - /// @param msgHash The hash of the message. - /// @param gasLimit The gas limit for the message call. - /// @return success A boolean value indicating whether the message call was + /// @param _message The call message to be invoked. + /// @param _msgHash The hash of the message. + /// @param _gasLimit The gas limit for the message call. + /// @return success_ A boolean value indicating whether the message call was /// successful. /// @dev This function updates the context in the state before and after the /// message call. function _invokeMessageCall( - Message calldata message, - bytes32 msgHash, - uint256 gasLimit + Message calldata _message, + bytes32 _msgHash, + uint256 _gasLimit ) private - returns (bool success) + returns (bool success_) { - if (gasLimit == 0) revert B_INVALID_GAS_LIMIT(); - assert(message.from != address(this)); + if (_gasLimit == 0) revert B_INVALID_GAS_LIMIT(); + assert(_message.from != address(this)); - _storeContext({ msgHash: msgHash, from: message.from, srcChainId: message.srcChainId }); + _storeContext(_msgHash, _message.from, _message.srcChainId); if ( - message.data.length >= 4 // msg can be empty - && bytes4(message.data) != IMessageInvocable.onMessageInvocation.selector - && message.to.isContract() + _message.data.length >= 4 // msg can be empty + && bytes4(_message.data) != IMessageInvocable.onMessageInvocation.selector + && _message.to.isContract() ) { - success = false; + success_ = false; } else { - (success,) = ExcessivelySafeCall.excessivelySafeCall( - message.to, - gasLimit, - message.value, + (success_,) = ExcessivelySafeCall.excessivelySafeCall( + _message.to, + _gasLimit, + _message.value, 64, // return max 64 bytes - message.data + _message.data ); } @@ -596,17 +510,17 @@ contract Bridge is EssentialContract, IBridge { /// @notice Updates the status of a bridge message. /// @dev If the new status is different from the current status in the /// mapping, the status is updated and an event is emitted. - /// @param msgHash The hash of the message. - /// @param status The new status of the message. - function _updateMessageStatus(bytes32 msgHash, Status status) private { - if (messageStatus[msgHash] == status) return; + /// @param _msgHash The hash of the message. + /// @param _status The new status of the message. + function _updateMessageStatus(bytes32 _msgHash, Status _status) private { + if (messageStatus[_msgHash] == _status) return; - messageStatus[msgHash] = status; - emit MessageStatusChanged(msgHash, status); + messageStatus[_msgHash] = _status; + emit MessageStatusChanged(_msgHash, _status); - if (status == Status.FAILED) { + if (_status == Status.FAILED) { ISignalService(resolve("signal_service", false)).sendSignal( - signalForFailedMessage(msgHash) + signalForFailedMessage(_msgHash) ); } } @@ -621,15 +535,15 @@ contract Bridge is EssentialContract, IBridge { } /// @notice Stores the call context - function _storeContext(bytes32 msgHash, address from, uint64 srcChainId) private { + function _storeContext(bytes32 _msgHash, address _from, uint64 _srcChainId) private { if (block.chainid == 1) { assembly { - tstore(_CTX_SLOT, msgHash) - tstore(add(_CTX_SLOT, 1), from) - tstore(add(_CTX_SLOT, 2), srcChainId) + tstore(_CTX_SLOT, _msgHash) + tstore(add(_CTX_SLOT, 1), _from) + tstore(add(_CTX_SLOT, 2), _srcChainId) } } else { - _ctx = Context({ msgHash: msgHash, from: from, srcChainId: srcChainId }); + __ctx = Context(_msgHash, _from, _srcChainId); } } @@ -644,32 +558,32 @@ contract Bridge is EssentialContract, IBridge { from := tload(add(_CTX_SLOT, 1)) srcChainId := tload(add(_CTX_SLOT, 2)) } - return Context({ msgHash: msgHash, from: from, srcChainId: srcChainId }); + return Context(msgHash, from, srcChainId); } else { - return _ctx; + return __ctx; } } /// @notice Checks if the signal was received. - /// @param signalService The signalService - /// @param signal The signal. - /// @param chainId The ID of the chain the signal is stored on - /// @param proof The merkle inclusion proof. - /// @return success True if the message was received. + /// @param _signalService The signalService + /// @param _signal The signal. + /// @param _chainId The ID of the chain the signal is stored on + /// @param _proof The merkle inclusion proof. + /// @return success_ True if the message was received. function _proveSignalReceived( - address signalService, - bytes32 signal, - uint64 chainId, - bytes calldata proof + address _signalService, + bytes32 _signal, + uint64 _chainId, + bytes calldata _proof ) private view - returns (bool success) + returns (bool success_) { bytes memory data = abi.encodeCall( ISignalService.proveSignalReceived, - (chainId, resolve(chainId, "bridge", false), signal, proof) + (_chainId, resolve(_chainId, "bridge", false), _signal, _proof) ); - (success,) = signalService.staticcall(data); + (success_,) = _signalService.staticcall(data); } } diff --git a/packages/protocol/contracts/bridge/IBridge.sol b/packages/protocol/contracts/bridge/IBridge.sol index be17e4de432..cf299d82544 100644 --- a/packages/protocol/contracts/bridge/IBridge.sol +++ b/packages/protocol/contracts/bridge/IBridge.sol @@ -6,6 +6,14 @@ pragma solidity 0.8.24; /// @dev Ether is held by Bridges on L1 and L2s. /// @custom:security-contact security@taiko.xyz interface IBridge { + enum Status { + NEW, + RETRIABLE, + DONE, + FAILED, + RECALLED + } + struct Message { // Message ID. uint128 id; @@ -36,6 +44,17 @@ interface IBridge { string memo; } + // Note that this struct shall take only 1 slot to minimize gas cost + struct ProofReceipt { + // The time a message is marked as received on the destination chain + uint64 receivedAt; + // The address that can execute the message after the invocation delay without an extra + // delay. + // For a failed message, preferredExecutor's value doesn't matter as only the owner can + // invoke the message. + address preferredExecutor; + } + // Struct representing the context of a bridge operation. struct Context { bytes32 msgHash; // Message hash. @@ -43,30 +62,107 @@ interface IBridge { uint64 srcChainId; // Source chain ID. } + /// @notice Emitted when a message is sent. + /// @param msgHash The hash of the message. + /// @param message The message. + event MessageSent(bytes32 indexed msgHash, Message message); + + /// @notice Emitted when a message is received. + /// @param msgHash The hash of the message. + /// @param message The message. + /// @param isRecall True if the message is a recall. + event MessageReceived(bytes32 indexed msgHash, Message message, bool isRecall); + + /// @notice Emitted when a message is recalled. + /// @param msgHash The hash of the message. + event MessageRecalled(bytes32 indexed msgHash); + + /// @notice Emitted when a message is executed. + /// @param msgHash The hash of the message. + event MessageExecuted(bytes32 indexed msgHash); + + /// @notice Emitted when a message is retried. + /// @param msgHash The hash of the message. + event MessageRetried(bytes32 indexed msgHash); + + /// @notice Emitted when the status of a message changes. + /// @param msgHash The hash of the message. + /// @param status The new status of the message. + event MessageStatusChanged(bytes32 indexed msgHash, Status status); + + /// @notice Emitted when a message is suspended or unsuspended. + /// @param msgHash The hash of the message. + /// @param suspended True if the message is suspended. + event MessageSuspended(bytes32 msgHash, bool suspended); + + /// @notice Emitted when an address is banned or unbanned. + /// @param addr The address to ban or unban. + /// @param banned True if the address is banned. + event AddressBanned(address indexed addr, bool banned); + /// @notice Sends a message to the destination chain and takes custody /// of Ether required in this contract. All extra Ether will be refunded. - /// @param message The message to be sent. - /// @return msgHash The hash of the sent message. - /// @return updatedMessage The updated message sent. - function sendMessage(Message calldata message) + /// @param _message The message to be sent. + /// @return msgHash_ The hash of the sent message. + /// @return message_ The updated message sent. + function sendMessage(Message calldata _message) external payable - returns (bytes32 msgHash, Message memory updatedMessage); + returns (bytes32 msgHash_, Message memory message_); + + /// @notice Recalls a failed message on its source chain, releasing + /// associated assets. + /// @dev This function checks if the message failed on the source chain and + /// releases associated Ether or tokens. + /// @param _message The message whose associated Ether should be released. + /// @param _proof The merkle inclusion proof. + function recallMessage(Message calldata _message, bytes calldata _proof) external; + + /// @notice Processes a bridge message on the destination chain. This + /// function is callable by any address, including the `message.destOwner`. + /// @dev The process begins by hashing the message and checking the message + /// status in the bridge If the status is "NEW", the message is invoked. The + /// status is updated accordingly, and processing fees are refunded as + /// needed. + /// @param _message The message to be processed. + /// @param _proof The merkle inclusion proof. + function processMessage(Message calldata _message, bytes calldata _proof) external; + + /// @notice Retries to invoke the messageCall after releasing associated + /// Ether and tokens. + /// @dev This function can be called by any address, including the + /// `message.destOwner`. + /// It attempts to invoke the messageCall and updates the message status + /// accordingly. + /// @param _message The message to retry. + /// @param _isLastAttempt Specifies if this is the last attempt to retry the + /// message. + function retryMessage(Message calldata _message, bool _isLastAttempt) external; /// @notice Returns the bridge state context. - /// @return context The context of the current bridge operation. - function context() external view returns (Context memory context); + /// @return ctx_ The context of the current bridge operation. + function context() external view returns (Context memory ctx_); + + /// @notice Checks if the message was sent. + /// @param _message The message. + /// @return true if the message was sent. + function isMessageSent(Message calldata _message) external view returns (bool); + + /// @notice Hash the message + /// @param _message The message struct variable to be hashed. + /// @return The message's hash. + function hashMessage(Message memory _message) external pure returns (bytes32); } /// @title IRecallableSender /// @notice An interface that all recallable message senders shall implement. interface IRecallableSender { /// @notice Called when a message is recalled. - /// @param message The recalled message. - /// @param msgHash The hash of the recalled message. + /// @param _message The recalled message. + /// @param _msgHash The hash of the recalled message. function onMessageRecalled( - IBridge.Message calldata message, - bytes32 msgHash + IBridge.Message calldata _message, + bytes32 _msgHash ) external payable; @@ -76,7 +172,7 @@ interface IRecallableSender { /// @notice An interface that all bridge message receiver shall implement interface IMessageInvocable { /// @notice Called when this contract is the bridge target. - /// @param data The data for this contract to interpret. + /// @param _data The data for this contract to interpret. /// @dev This method should be guarded with `onlyFromNamed("bridge")`. - function onMessageInvocation(bytes calldata data) external payable; + function onMessageInvocation(bytes calldata _data) external payable; } diff --git a/packages/protocol/contracts/common/AddressManager.sol b/packages/protocol/contracts/common/AddressManager.sol index 4a1de273246..89d9fe80fae 100644 --- a/packages/protocol/contracts/common/AddressManager.sol +++ b/packages/protocol/contracts/common/AddressManager.sol @@ -8,7 +8,7 @@ import "./EssentialContract.sol"; /// @notice See the documentation in {IAddressManager}. /// @custom:security-contact security@taiko.xyz contract AddressManager is EssentialContract, IAddressManager { - mapping(uint256 chainId => mapping(bytes32 name => address addr)) private addresses; + mapping(uint256 chainId => mapping(bytes32 name => address addr)) private __addresses; uint256[49] private __gap; /// @notice Emitted when an address is set. @@ -30,27 +30,27 @@ contract AddressManager is EssentialContract, IAddressManager { } /// @notice Sets the address for a specific chainId-name pair. - /// @param chainId The chainId to which the address will be mapped. - /// @param name The name to which the address will be mapped. - /// @param newAddress The Ethereum address to be mapped. + /// @param _chainId The chainId to which the address will be mapped. + /// @param _name The name to which the address will be mapped. + /// @param _newAddress The Ethereum address to be mapped. function setAddress( - uint64 chainId, - bytes32 name, - address newAddress + uint64 _chainId, + bytes32 _name, + address _newAddress ) external virtual onlyOwner { - address oldAddress = addresses[chainId][name]; - if (newAddress == oldAddress) revert AM_INVALID_PARAMS(); - addresses[chainId][name] = newAddress; - emit AddressSet(chainId, name, newAddress, oldAddress); + address oldAddress = __addresses[_chainId][_name]; + if (_newAddress == oldAddress) revert AM_INVALID_PARAMS(); + __addresses[_chainId][_name] = _newAddress; + emit AddressSet(_chainId, _name, _newAddress, oldAddress); } /// @inheritdoc IAddressManager - function getAddress(uint64 chainId, bytes32 name) public view override returns (address) { - return addresses[chainId][name]; + function getAddress(uint64 _chainId, bytes32 _name) public view override returns (address) { + return __addresses[_chainId][_name]; } function _authorizePause(address) internal pure override { diff --git a/packages/protocol/contracts/common/AddressResolver.sol b/packages/protocol/contracts/common/AddressResolver.sol index 7d32889e973..4b89f19cb01 100644 --- a/packages/protocol/contracts/common/AddressResolver.sol +++ b/packages/protocol/contracts/common/AddressResolver.sol @@ -20,37 +20,37 @@ abstract contract AddressResolver is IAddressResolver, Initializable { /// @dev Modifier that ensures the caller is the resolved address of a given /// name. - /// @param name The name to check against. - modifier onlyFromNamed(bytes32 name) { - if (msg.sender != resolve(name, true)) revert RESOLVER_DENIED(); + /// @param _name The name to check against. + modifier onlyFromNamed(bytes32 _name) { + if (msg.sender != resolve(_name, true)) revert RESOLVER_DENIED(); _; } /// @inheritdoc IAddressResolver function resolve( - bytes32 name, - bool allowZeroAddress + bytes32 _name, + bool _allowZeroAddress ) public view virtual - returns (address payable addr) + returns (address payable) { - return _resolve(uint64(block.chainid), name, allowZeroAddress); + return _resolve(uint64(block.chainid), _name, _allowZeroAddress); } /// @inheritdoc IAddressResolver function resolve( - uint64 chainId, - bytes32 name, - bool allowZeroAddress + uint64 _chainId, + bytes32 _name, + bool _allowZeroAddress ) public view virtual - returns (address payable addr) + returns (address payable) { - return _resolve(chainId, name, allowZeroAddress); + return _resolve(_chainId, _name, _allowZeroAddress); } /// @dev Initialization method for setting up AddressManager reference. @@ -64,27 +64,27 @@ abstract contract AddressResolver is IAddressResolver, Initializable { } /// @dev Helper method to resolve name-to-address. - /// @param chainId The chainId of interest. - /// @param name Name whose address is to be resolved. - /// @param allowZeroAddress If set to true, does not throw if the resolved + /// @param _chainId The chainId of interest. + /// @param _name Name whose address is to be resolved. + /// @param _allowZeroAddress If set to true, does not throw if the resolved /// address is `address(0)`. - /// @return addr Address associated with the given name on the specified + /// @return addr_ Address associated with the given name on the specified /// chain. function _resolve( - uint64 chainId, - bytes32 name, - bool allowZeroAddress + uint64 _chainId, + bytes32 _name, + bool _allowZeroAddress ) private view - returns (address payable addr) + returns (address payable addr_) { if (addressManager == address(0)) revert RESOLVER_INVALID_MANAGER(); - addr = payable(IAddressManager(addressManager).getAddress(chainId, name)); + addr_ = payable(IAddressManager(addressManager).getAddress(_chainId, _name)); - if (!allowZeroAddress && addr == address(0)) { - revert RESOLVER_ZERO_ADDR(chainId, name); + if (!_allowZeroAddress && addr_ == address(0)) { + revert RESOLVER_ZERO_ADDR(_chainId, _name); } } } diff --git a/packages/protocol/contracts/common/EssentialContract.sol b/packages/protocol/contracts/common/EssentialContract.sol index f96596bfef4..4dbe1073cec 100644 --- a/packages/protocol/contracts/common/EssentialContract.sol +++ b/packages/protocol/contracts/common/EssentialContract.sol @@ -16,8 +16,8 @@ abstract contract EssentialContract is UUPSUpgradeable, Ownable2StepUpgradeable, bytes32 private constant _REENTRY_SLOT = 0xa5054f728453d3dbe953bdc43e4d0cb97e662ea32d7958190f3dc2da31d9721a; - uint8 private _reentry; // slot 1 - uint8 private _paused; + uint8 private __reentry; // slot 1 + uint8 private __paused; uint256[49] private __gap; /// @notice Emitted when the contract is paused. @@ -33,9 +33,9 @@ abstract contract EssentialContract is UUPSUpgradeable, Ownable2StepUpgradeable, error ZERO_ADDR_MANAGER(); /// @dev Modifier that ensures the caller is the owner or resolved address of a given name. - /// @param name The name to check against. - modifier onlyFromOwnerOrNamed(bytes32 name) { - if (msg.sender != owner() && msg.sender != resolve(name, true)) revert RESOLVER_DENIED(); + /// @param _name The name to check against. + modifier onlyFromOwnerOrNamed(bytes32 _name) { + if (msg.sender != owner() && msg.sender != resolve(_name, true)) revert RESOLVER_DENIED(); _; } @@ -63,7 +63,7 @@ abstract contract EssentialContract is UUPSUpgradeable, Ownable2StepUpgradeable, /// @notice Pauses the contract. function pause() public virtual whenNotPaused { - _paused = _TRUE; + __paused = _TRUE; emit Paused(msg.sender); // We call the authorize function here to avoid: // Warning (5740): Unreachable code. @@ -72,7 +72,7 @@ abstract contract EssentialContract is UUPSUpgradeable, Ownable2StepUpgradeable, /// @notice Unpauses the contract. function unpause() public virtual whenPaused { - _paused = _FALSE; + __paused = _FALSE; emit Unpaused(msg.sender); // We call the authorize function here to avoid: // Warning (5740): Unreachable code. @@ -82,7 +82,7 @@ abstract contract EssentialContract is UUPSUpgradeable, Ownable2StepUpgradeable, /// @notice Returns true if the contract is paused, and false otherwise. /// @return True if paused, false otherwise. function paused() public view returns (bool) { - return _paused == _TRUE; + return __paused == _TRUE; } /// @notice Initializes the contract. @@ -106,31 +106,31 @@ abstract contract EssentialContract is UUPSUpgradeable, Ownable2StepUpgradeable, // solhint-disable-next-line func-name-mixedcase function __Essential_init(address _owner) internal virtual { _transferOwnership(_owner == address(0) ? msg.sender : _owner); - _paused = _FALSE; + __paused = _FALSE; } function _authorizeUpgrade(address) internal virtual override onlyOwner { } function _authorizePause(address) internal virtual onlyOwner { } // Stores the reentry lock - function _storeReentryLock(uint8 reentry) internal virtual { + function _storeReentryLock(uint8 _reentry) internal virtual { if (block.chainid == 1) { assembly { - tstore(_REENTRY_SLOT, reentry) + tstore(_REENTRY_SLOT, _reentry) } } else { - _reentry = reentry; + __reentry = _reentry; } } // Loads the reentry lock - function _loadReentryLock() internal view virtual returns (uint8 reentry) { + function _loadReentryLock() internal view virtual returns (uint8 reentry_) { if (block.chainid == 1) { assembly { - reentry := tload(_REENTRY_SLOT) + reentry_ := tload(_REENTRY_SLOT) } } else { - reentry = _reentry; + reentry_ = __reentry; } } diff --git a/packages/protocol/contracts/common/IAddressManager.sol b/packages/protocol/contracts/common/IAddressManager.sol index 211ca7cd0fe..f88933462fe 100644 --- a/packages/protocol/contracts/common/IAddressManager.sol +++ b/packages/protocol/contracts/common/IAddressManager.sol @@ -8,8 +8,8 @@ interface IAddressManager { /// @notice Gets the address mapped to a specific chainId-name pair. /// @dev Note that in production, this method shall be a pure function /// without any storage access. - /// @param chainId The chainId for which the address needs to be fetched. - /// @param name The name for which the address needs to be fetched. + /// @param _chainId The chainId for which the address needs to be fetched. + /// @param _name The name for which the address needs to be fetched. /// @return Address associated with the chainId-name pair. - function getAddress(uint64 chainId, bytes32 name) external view returns (address); + function getAddress(uint64 _chainId, bytes32 _name) external view returns (address); } diff --git a/packages/protocol/contracts/common/IAddressResolver.sol b/packages/protocol/contracts/common/IAddressResolver.sol index 2b3b391bb1e..886e123e1ba 100644 --- a/packages/protocol/contracts/common/IAddressResolver.sol +++ b/packages/protocol/contracts/common/IAddressResolver.sol @@ -12,31 +12,31 @@ pragma solidity 0.8.24; /// @custom:security-contact security@taiko.xyz interface IAddressResolver { /// @notice Resolves a name to its address deployed on this chain. - /// @param name Name whose address is to be resolved. - /// @param allowZeroAddress If set to true, does not throw if the resolved + /// @param _name Name whose address is to be resolved. + /// @param _allowZeroAddress If set to true, does not throw if the resolved /// address is `address(0)`. - /// @return addr Address associated with the given name. + /// @return Address associated with the given name. function resolve( - bytes32 name, - bool allowZeroAddress + bytes32 _name, + bool _allowZeroAddress ) external view - returns (address payable addr); + returns (address payable); /// @notice Resolves a name to its address deployed on a specified chain. - /// @param chainId The chainId of interest. - /// @param name Name whose address is to be resolved. - /// @param allowZeroAddress If set to true, does not throw if the resolved + /// @param _chainId The chainId of interest. + /// @param _name Name whose address is to be resolved. + /// @param _allowZeroAddress If set to true, does not throw if the resolved /// address is `address(0)`. - /// @return addr Address associated with the given name on the specified + /// @return Address associated with the given name on the specified /// chain. function resolve( - uint64 chainId, - bytes32 name, - bool allowZeroAddress + uint64 _chainId, + bytes32 _name, + bool _allowZeroAddress ) external view - returns (address payable addr); + returns (address payable); } diff --git a/packages/protocol/contracts/libs/Lib4844.sol b/packages/protocol/contracts/libs/Lib4844.sol index 2bf79bf6348..83ab5c1888d 100644 --- a/packages/protocol/contracts/libs/Lib4844.sol +++ b/packages/protocol/contracts/libs/Lib4844.sol @@ -22,26 +22,26 @@ library Lib4844 { error POINT_Y_TOO_LARGE(); /// @notice Evaluates the 4844 point using the precompile. - /// @param blobHash The versioned hash - /// @param x The evaluation point - /// @param y The expected output - /// @param commitment The input kzg point - /// @param pointProof The quotient kzg + /// @param _blobHash The versioned hash + /// @param _x The evaluation point + /// @param _y The expected output + /// @param _commitment The input kzg point + /// @param _pointProof The quotient kzg function evaluatePoint( - bytes32 blobHash, - uint256 x, - uint256 y, - bytes1[48] memory commitment, - bytes1[48] memory pointProof + bytes32 _blobHash, + uint256 _x, + uint256 _y, + bytes1[48] memory _commitment, + bytes1[48] memory _pointProof ) internal view { - if (x >= BLS_MODULUS) revert POINT_X_TOO_LARGE(); - if (y >= BLS_MODULUS) revert POINT_Y_TOO_LARGE(); + if (_x >= BLS_MODULUS) revert POINT_X_TOO_LARGE(); + if (_y >= BLS_MODULUS) revert POINT_Y_TOO_LARGE(); (bool ok, bytes memory ret) = POINT_EVALUATION_PRECOMPILE_ADDRESS.staticcall( - abi.encodePacked(blobHash, x, y, commitment, pointProof) + abi.encodePacked(_blobHash, _x, _y, _commitment, _pointProof) ); if (!ok) revert EVAL_FAILED_1(); diff --git a/packages/protocol/contracts/libs/LibAddress.sol b/packages/protocol/contracts/libs/LibAddress.sol index d3de8ef558d..0219d78bfb7 100644 --- a/packages/protocol/contracts/libs/LibAddress.sol +++ b/packages/protocol/contracts/libs/LibAddress.sol @@ -11,23 +11,23 @@ import "../thirdparty/nomad-xyz/ExcessivelySafeCall.sol"; /// @dev Provides utilities for address-related operations. /// @custom:security-contact security@taiko.xyz library LibAddress { - bytes4 private constant EIP1271_MAGICVALUE = 0x1626ba7e; + bytes4 private constant _EIP1271_MAGICVALUE = 0x1626ba7e; error ETH_TRANSFER_FAILED(); /// @dev Sends Ether to the specified address. - /// @param to The recipient address. - /// @param amount The amount of Ether to send in wei. - /// @param gasLimit The max amount gas to pay for this transaction. - function sendEther(address to, uint256 amount, uint256 gasLimit) internal { + /// @param _to The recipient address. + /// @param _amount The amount of Ether to send in wei. + /// @param _gasLimit The max amount gas to pay for this transaction. + function sendEther(address _to, uint256 _amount, uint256 _gasLimit) internal { // Check for zero-address transactions - if (to == address(0)) revert ETH_TRANSFER_FAILED(); + if (_to == address(0)) revert ETH_TRANSFER_FAILED(); // Attempt to send Ether to the recipient address (bool success,) = ExcessivelySafeCall.excessivelySafeCall( - to, - gasLimit, - amount, + _to, + _gasLimit, + _amount, 64, // return max 64 bytes "" ); @@ -37,40 +37,40 @@ library LibAddress { } /// @dev Sends Ether to the specified address. - /// @param to The recipient address. - /// @param amount The amount of Ether to send in wei. - function sendEther(address to, uint256 amount) internal { - sendEther(to, amount, gasleft()); + /// @param _to The recipient address. + /// @param _amount The amount of Ether to send in wei. + function sendEther(address _to, uint256 _amount) internal { + sendEther(_to, _amount, gasleft()); } function supportsInterface( - address addr, - bytes4 interfaceId + address _addr, + bytes4 _interfaceId ) internal view - returns (bool result) + returns (bool result_) { - if (!Address.isContract(addr)) return false; + if (!Address.isContract(_addr)) return false; - try IERC165(addr).supportsInterface(interfaceId) returns (bool _result) { - result = _result; + try IERC165(_addr).supportsInterface(_interfaceId) returns (bool _result) { + result_ = _result; } catch { } } function isValidSignature( - address addr, - bytes32 hash, - bytes memory sig + address _addr, + bytes32 _hash, + bytes memory _sig ) internal view - returns (bool valid) + returns (bool) { - if (Address.isContract(addr)) { - return IERC1271(addr).isValidSignature(hash, sig) == EIP1271_MAGICVALUE; + if (Address.isContract(_addr)) { + return IERC1271(_addr).isValidSignature(_hash, _sig) == _EIP1271_MAGICVALUE; } else { - return ECDSA.recover(hash, sig) == addr; + return ECDSA.recover(_hash, _sig) == _addr; } } diff --git a/packages/protocol/contracts/libs/LibMath.sol b/packages/protocol/contracts/libs/LibMath.sol index 3d53a1926dc..cbdda81a3ff 100644 --- a/packages/protocol/contracts/libs/LibMath.sol +++ b/packages/protocol/contracts/libs/LibMath.sol @@ -6,18 +6,18 @@ pragma solidity 0.8.24; /// @custom:security-contact security@taiko.xyz library LibMath { /// @dev Returns the smaller of the two given values. - /// @param a The first number to compare. - /// @param b The second number to compare. + /// @param _a The first number to compare. + /// @param _b The second number to compare. /// @return The smaller of the two numbers. - function min(uint256 a, uint256 b) internal pure returns (uint256) { - return a > b ? b : a; + function min(uint256 _a, uint256 _b) internal pure returns (uint256) { + return _a > _b ? _b : _a; } /// @dev Returns the larger of the two given values. - /// @param a The first number to compare. - /// @param b The second number to compare. + /// @param _a The first number to compare. + /// @param _b The second number to compare. /// @return The larger of the two numbers. - function max(uint256 a, uint256 b) internal pure returns (uint256) { - return a > b ? a : b; + function max(uint256 _a, uint256 _b) internal pure returns (uint256) { + return _a > _b ? _a : _b; } } diff --git a/packages/protocol/contracts/libs/LibTrieProof.sol b/packages/protocol/contracts/libs/LibTrieProof.sol index ac86586943e..f28476318c8 100644 --- a/packages/protocol/contracts/libs/LibTrieProof.sol +++ b/packages/protocol/contracts/libs/LibTrieProof.sol @@ -15,50 +15,50 @@ import "../thirdparty/optimism/trie/SecureMerkleTrie.sol"; library LibTrieProof { // The consensus format representing account is RLP encoded in the // following order: nonce, balance, storageHash, codeHash. - uint256 private constant ACCOUNT_FIELD_INDEX_STORAGE_HASH = 2; + uint256 private constant _ACCOUNT_FIELD_INDEX_STORAGE_HASH = 2; error LTP_INVALID_ACCOUNT_PROOF(); error LTP_INVALID_INCLUSION_PROOF(); /// @notice Verifies that the value of a slot in the storage of an account is value. /// - /// @param rootHash The merkle root of state tree or the account tree. If accountProof's length + /// @param _rootHash The merkle root of state tree or the account tree. If accountProof's length /// is zero, it is used as the account's storage root, otherwise it will be used as the state /// root. - /// @param addr The address of contract. - /// @param slot The slot in the contract. - /// @param value The value to be verified. - /// @param accountProof The account proof - /// @param storageProof The storage proof - /// @return storageRoot The account's storage root + /// @param _addr The address of contract. + /// @param _slot The slot in the contract. + /// @param _value The value to be verified. + /// @param _accountProof The account proof + /// @param _storageProof The storage proof + /// @return storageRoot_ The account's storage root function verifyMerkleProof( - bytes32 rootHash, - address addr, - bytes32 slot, - bytes32 value, - bytes[] memory accountProof, - bytes[] memory storageProof + bytes32 _rootHash, + address _addr, + bytes32 _slot, + bytes32 _value, + bytes[] memory _accountProof, + bytes[] memory _storageProof ) internal pure - returns (bytes32 storageRoot) + returns (bytes32 storageRoot_) { - if (accountProof.length != 0) { + if (_accountProof.length != 0) { bytes memory rlpAccount = - SecureMerkleTrie.get(abi.encodePacked(addr), accountProof, rootHash); + SecureMerkleTrie.get(abi.encodePacked(_addr), _accountProof, _rootHash); if (rlpAccount.length == 0) revert LTP_INVALID_ACCOUNT_PROOF(); RLPReader.RLPItem[] memory accountState = RLPReader.readList(rlpAccount); - storageRoot = - bytes32(RLPReader.readBytes(accountState[ACCOUNT_FIELD_INDEX_STORAGE_HASH])); + storageRoot_ = + bytes32(RLPReader.readBytes(accountState[_ACCOUNT_FIELD_INDEX_STORAGE_HASH])); } else { - storageRoot = rootHash; + storageRoot_ = _rootHash; } bool verified = SecureMerkleTrie.verifyInclusionProof( - bytes.concat(slot), RLPWriter.writeUint(uint256(value)), storageProof, storageRoot + bytes.concat(_slot), RLPWriter.writeUint(uint256(_value)), _storageProof, storageRoot_ ); if (!verified) revert LTP_INVALID_INCLUSION_PROOF(); diff --git a/packages/protocol/contracts/signal/ISignalService.sol b/packages/protocol/contracts/signal/ISignalService.sol index 1537e3ee37a..6bdf463eb93 100644 --- a/packages/protocol/contracts/signal/ISignalService.sol +++ b/packages/protocol/contracts/signal/ISignalService.sol @@ -10,6 +10,22 @@ pragma solidity 0.8.24; /// a merkle proof. /// @custom:security-contact security@taiko.xyz interface ISignalService { + enum CacheOption { + CACHE_NOTHING, + CACHE_SIGNAL_ROOT, + CACHE_STATE_ROOT, + CACHE_BOTH + } + + struct HopProof { + uint64 chainId; + uint64 blockId; + bytes32 rootHash; + CacheOption cacheOption; + bytes[] accountProof; + bytes[] storageProof; + } + /// @notice Emitted when a remote chain's state root or signal root is /// synced locally as a signal. /// @param chainId The remote chainId. @@ -25,93 +41,105 @@ interface ISignalService { bytes32 signal ); + /// @notice Emitted when a signal is sent. + /// @param app The address that initiated the signal. + /// @param signal The signal (message) that was sent. + /// @param slot The location in storage where this signal is stored. + /// @param value The value of the signal. + event SignalSent(address app, bytes32 signal, bytes32 slot, bytes32 value); + + /// @notice Emitted when an address is authorized or deauthorized. + /// @param addr The address to be authorized or deauthorized. + /// @param authrized True if authorized, false otherwise. + event Authorized(address indexed addr, bool authrized); + /// @notice Send a signal (message) by setting the storage slot to a value of 1. - /// @param signal The signal (message) to send. - /// @return slot The location in storage where this signal is stored. - function sendSignal(bytes32 signal) external returns (bytes32 slot); + /// @param _signal The signal (message) to send. + /// @return slot_ The location in storage where this signal is stored. + function sendSignal(bytes32 _signal) external returns (bytes32 slot_); /// @notice Sync a data from a remote chain locally as a signal. The signal is calculated /// uniquely from chainId, kind, and data. - /// @param chainId The remote chainId. - /// @param kind A value to mark the data type. - /// @param blockId The chain data's corresponding blockId - /// @param chainData The remote data. - /// @return signal The signal for this chain data. + /// @param _chainId The remote chainId. + /// @param _kind A value to mark the data type. + /// @param _blockId The chain data's corresponding blockId + /// @param _chainData The remote data. + /// @return signal_ The signal for this chain data. function syncChainData( - uint64 chainId, - bytes32 kind, - uint64 blockId, - bytes32 chainData + uint64 _chainId, + bytes32 _kind, + uint64 _blockId, + bytes32 _chainData ) external - returns (bytes32 signal); + returns (bytes32 signal_); /// @notice Verifies if a signal has been received on the target chain. - /// @param chainId The identifier for the source chain from which the + /// @param _chainId The identifier for the source chain from which the /// signal originated. - /// @param app The address that initiated the signal. - /// @param signal The signal (message) to send. - /// @param proof Merkle proof that the signal was persisted on the + /// @param _app The address that initiated the signal. + /// @param _signal The signal (message) to send. + /// @param _proof Merkle proof that the signal was persisted on the /// source chain. function proveSignalReceived( - uint64 chainId, - address app, - bytes32 signal, - bytes calldata proof + uint64 _chainId, + address _app, + bytes32 _signal, + bytes calldata _proof ) external; /// @notice Verifies if a particular signal has already been sent. - /// @param app The address that initiated the signal. - /// @param signal The signal (message) that was sent. - /// @return True if the signal has been sent, otherwise false. - function isSignalSent(address app, bytes32 signal) external view returns (bool); + /// @param _app The address that initiated the signal. + /// @param _signal The signal (message) that was sent. + /// @return true if the signal has been sent, otherwise false. + function isSignalSent(address _app, bytes32 _signal) external view returns (bool); /// @notice Checks if a chain data has been synced. /// uniquely from chainId, kind, and data. - /// @param chainId The remote chainId. - /// @param kind A value to mark the data type. - /// @param blockId The chain data's corresponding blockId - /// @param chainData The remote data. - /// @return True if the data has been synced, otherwise false. + /// @param _chainId The remote chainId. + /// @param _kind A value to mark the data type. + /// @param _blockId The chain data's corresponding blockId + /// @param _chainData The remote data. + /// @return true if the data has been synced, otherwise false. function isChainDataSynced( - uint64 chainId, - bytes32 kind, - uint64 blockId, - bytes32 chainData + uint64 _chainId, + bytes32 _kind, + uint64 _blockId, + bytes32 _chainData ) external view returns (bool); /// @notice Returns the given block's chain data. - /// @param chainId Indenitifer of the chainId. - /// @param kind A value to mark the data type. - /// @param blockId The chain data's corresponding block id. If this value is 0, use the top + /// @param _chainId Indenitifer of the chainId. + /// @param _kind A value to mark the data type. + /// @param _blockId The chain data's corresponding block id. If this value is 0, use the top /// block id. - /// @return _blockId The actual block id. - /// @return _chainData The synced chain data. + /// @return blockId_ The actual block id. + /// @return chainData_ The synced chain data. function getSyncedChainData( - uint64 chainId, - bytes32 kind, - uint64 blockId + uint64 _chainId, + bytes32 _kind, + uint64 _blockId ) external view - returns (uint64 _blockId, bytes32 _chainData); + returns (uint64 blockId_, bytes32 chainData_); /// @notice Returns the data to be used for caching slot generation. - /// @param chainId Indenitifer of the chainId. - /// @param kind A value to mark the data type. - /// @param blockId The chain data's corresponding block id. If this value is 0, use the top + /// @param _chainId Indenitifer of the chainId. + /// @param _kind A value to mark the data type. + /// @param _blockId The chain data's corresponding block id. If this value is 0, use the top /// block id. - /// @return signal The signal used for caching slot creation. + /// @return signal_ The signal used for caching slot creation. function signalForChainData( - uint64 chainId, - bytes32 kind, - uint64 blockId + uint64 _chainId, + bytes32 _kind, + uint64 _blockId ) external pure - returns (bytes32 signal); + returns (bytes32 signal_); } diff --git a/packages/protocol/contracts/signal/SignalService.sol b/packages/protocol/contracts/signal/SignalService.sol index 783d1a0b608..499d49632e6 100644 --- a/packages/protocol/contracts/signal/SignalService.sol +++ b/packages/protocol/contracts/signal/SignalService.sol @@ -12,22 +12,6 @@ import "./LibSignals.sol"; /// @dev Labeled in AddressResolver as "signal_service". /// @custom:security-contact security@taiko.xyz contract SignalService is EssentialContract, ISignalService { - enum CacheOption { - CACHE_NOTHING, - CACHE_SIGNAL_ROOT, - CACHE_STATE_ROOT, - CACHE_BOTH - } - - struct HopProof { - uint64 chainId; - uint64 blockId; - bytes32 rootHash; - CacheOption cacheOption; - bytes[] accountProof; - bytes[] storageProof; - } - /// @notice Mapping to store the top blockId. /// @dev Slot 1. mapping(uint64 chainId => mapping(bytes32 kind => uint64 blockId)) public topBlockId; @@ -38,18 +22,6 @@ contract SignalService is EssentialContract, ISignalService { uint256[48] private __gap; - /// @notice Emitted when a signal is sent. - /// @param app The address that initiated the signal. - /// @param signal The signal (message) that was sent. - /// @param slot The location in storage where this signal is stored. - /// @param value The value of the signal. - event SignalSent(address app, bytes32 signal, bytes32 slot, bytes32 value); - - /// @notice Emitted when an address is authorized or deauthorized. - /// @param addr The address to be authorized or deauthorized. - /// @param authrized True if authorized, false otherwise. - event Authorized(address indexed addr, bool authrized); - error SS_EMPTY_PROOF(); error SS_INVALID_SENDER(); error SS_INVALID_LAST_HOP_CHAINID(); @@ -60,13 +32,13 @@ contract SignalService is EssentialContract, ISignalService { error SS_UNAUTHORIZED(); error SS_UNSUPPORTED(); - modifier validSender(address app) { - if (app == address(0)) revert SS_INVALID_SENDER(); + modifier validSender(address _app) { + if (_app == address(0)) revert SS_INVALID_SENDER(); _; } - modifier nonZeroValue(bytes32 input) { - if (input == 0) revert SS_INVALID_VALUE(); + modifier nonZeroValue(bytes32 _input) { + if (_input == 0) revert SS_INVALID_VALUE(); _; } @@ -79,181 +51,180 @@ contract SignalService is EssentialContract, ISignalService { /// @dev Authorize or deauthorize an address for calling syncChainData. /// @dev Note that addr is supposed to be TaikoL1 and TaikoL1 contracts deployed locally. - /// @param addr The address to be authorized or deauthorized. - /// @param toAuthorize True if authorize, false otherwise. - function authorize(address addr, bool toAuthorize) external onlyOwner { - if (isAuthorized[addr] == toAuthorize) revert SS_INVALID_STATE(); - isAuthorized[addr] = toAuthorize; - emit Authorized(addr, toAuthorize); + /// @param _addr The address to be authorized or deauthorized. + /// @param _authorize True if authorize, false otherwise. + function authorize(address _addr, bool _authorize) external onlyOwner { + if (isAuthorized[_addr] == _authorize) revert SS_INVALID_STATE(); + isAuthorized[_addr] = _authorize; + emit Authorized(_addr, _authorize); } /// @inheritdoc ISignalService - function sendSignal(bytes32 signal) external returns (bytes32 slot) { - return _sendSignal(msg.sender, signal, signal); + function sendSignal(bytes32 _signal) external returns (bytes32) { + return _sendSignal(msg.sender, _signal, _signal); } /// @inheritdoc ISignalService function syncChainData( - uint64 chainId, - bytes32 kind, - uint64 blockId, - bytes32 chainData + uint64 _chainId, + bytes32 _kind, + uint64 _blockId, + bytes32 _chainData ) external - returns (bytes32 signal) + returns (bytes32) { if (!isAuthorized[msg.sender]) revert SS_UNAUTHORIZED(); - return _syncChainData(chainId, kind, blockId, chainData); + return _syncChainData(_chainId, _kind, _blockId, _chainData); } /// @inheritdoc ISignalService /// @dev This function may revert. function proveSignalReceived( - uint64 chainId, - address app, - bytes32 signal, - bytes calldata proof + uint64 _chainId, + address _app, + bytes32 _signal, + bytes calldata _proof ) public virtual - validSender(app) - nonZeroValue(signal) + validSender(_app) + nonZeroValue(_signal) { - HopProof[] memory _hopProofs = abi.decode(proof, (HopProof[])); - if (_hopProofs.length == 0) revert SS_EMPTY_PROOF(); + HopProof[] memory hopProofs = abi.decode(_proof, (HopProof[])); + if (hopProofs.length == 0) revert SS_EMPTY_PROOF(); - uint64 _chainId = chainId; - address _app = app; - bytes32 _signal = signal; - bytes32 _value = signal; - address _signalService = resolve(_chainId, "signal_service", false); + uint64 chainId = _chainId; + address app = _app; + bytes32 signal = _signal; + bytes32 value = _signal; + address signalService = resolve(chainId, "signal_service", false); HopProof memory hop; - for (uint256 i; i < _hopProofs.length; ++i) { - hop = _hopProofs[i]; + for (uint256 i; i < hopProofs.length; ++i) { + hop = hopProofs[i]; - bytes32 signalRoot = - _verifyHopProof(_chainId, _app, _signal, _value, hop, _signalService); - bool isLastHop = i == _hopProofs.length - 1; + bytes32 signalRoot = _verifyHopProof(chainId, app, signal, value, hop, signalService); + bool isLastHop = i == hopProofs.length - 1; if (isLastHop) { if (hop.chainId != block.chainid) revert SS_INVALID_LAST_HOP_CHAINID(); - _signalService = address(this); + signalService = address(this); } else { if (hop.chainId == 0 || hop.chainId == block.chainid) { revert SS_INVALID_MID_HOP_CHAINID(); } - _signalService = resolve(hop.chainId, "signal_service", false); + signalService = resolve(hop.chainId, "signal_service", false); } bool isFullProof = hop.accountProof.length > 0; - _cacheChainData(hop, _chainId, hop.blockId, signalRoot, isFullProof, isLastHop); + _cacheChainData(hop, chainId, hop.blockId, signalRoot, isFullProof, isLastHop); bytes32 kind = isFullProof ? LibSignals.STATE_ROOT : LibSignals.SIGNAL_ROOT; - _signal = signalForChainData(_chainId, kind, hop.blockId); - _value = hop.rootHash; - _chainId = hop.chainId; - _app = _signalService; + signal = signalForChainData(chainId, kind, hop.blockId); + value = hop.rootHash; + chainId = hop.chainId; + app = signalService; } - if (_value == 0 || _value != _loadSignalValue(address(this), _signal)) { + if (value == 0 || value != _loadSignalValue(address(this), signal)) { revert SS_SIGNAL_NOT_FOUND(); } } /// @inheritdoc ISignalService function isChainDataSynced( - uint64 chainId, - bytes32 kind, - uint64 blockId, - bytes32 chainData + uint64 _chainId, + bytes32 _kind, + uint64 _blockId, + bytes32 _chainData ) public view - nonZeroValue(chainData) + nonZeroValue(_chainData) returns (bool) { - bytes32 signal = signalForChainData(chainId, kind, blockId); - return _loadSignalValue(address(this), signal) == chainData; + bytes32 signal = signalForChainData(_chainId, _kind, _blockId); + return _loadSignalValue(address(this), signal) == _chainData; } /// @inheritdoc ISignalService - function isSignalSent(address app, bytes32 signal) public view returns (bool) { - return _loadSignalValue(app, signal) != 0; + function isSignalSent(address _app, bytes32 _signal) public view returns (bool) { + return _loadSignalValue(_app, _signal) != 0; } /// @inheritdoc ISignalService function getSyncedChainData( - uint64 chainId, - bytes32 kind, - uint64 blockId + uint64 _chainId, + bytes32 _kind, + uint64 _blockId ) public view - returns (uint64 _blockId, bytes32 _chainData) + returns (uint64 blockId_, bytes32 chainData_) { - _blockId = blockId != 0 ? blockId : topBlockId[chainId][kind]; + blockId_ = _blockId != 0 ? _blockId : topBlockId[_chainId][_kind]; - if (_blockId != 0) { - bytes32 signal = signalForChainData(chainId, kind, _blockId); - _chainData = _loadSignalValue(address(this), signal); - if (_chainData == 0) revert SS_SIGNAL_NOT_FOUND(); + if (blockId_ != 0) { + bytes32 signal = signalForChainData(_chainId, _kind, blockId_); + chainData_ = _loadSignalValue(address(this), signal); + if (chainData_ == 0) revert SS_SIGNAL_NOT_FOUND(); } } /// @inheritdoc ISignalService function signalForChainData( - uint64 chainId, - bytes32 kind, - uint64 blockId + uint64 _chainId, + bytes32 _kind, + uint64 _blockId ) public pure returns (bytes32) { - return keccak256(abi.encode(chainId, kind, blockId)); + return keccak256(abi.encode(_chainId, _kind, _blockId)); } /// @notice Returns the slot for a signal. - /// @param chainId The chainId of the signal. - /// @param app The address that initiated the signal. - /// @param signal The signal (message) that was sent. - /// @return slot The slot for the signal. + /// @param _chainId The chainId of the signal. + /// @param _app The address that initiated the signal. + /// @param _signal The signal (message) that was sent. + /// @return The slot for the signal. function getSignalSlot( - uint64 chainId, - address app, - bytes32 signal + uint64 _chainId, + address _app, + bytes32 _signal ) public pure returns (bytes32) { - return keccak256(abi.encodePacked("SIGNAL", chainId, app, signal)); + return keccak256(abi.encodePacked("SIGNAL", _chainId, _app, _signal)); } function _verifyHopProof( - uint64 chainId, - address app, - bytes32 signal, - bytes32 value, - HopProof memory hop, - address signalService + uint64 _chainId, + address _app, + bytes32 _signal, + bytes32 _value, + HopProof memory _hop, + address _signalService ) internal virtual - validSender(app) - nonZeroValue(signal) - nonZeroValue(value) - returns (bytes32 signalRoot) + validSender(_app) + nonZeroValue(_signal) + nonZeroValue(_value) + returns (bytes32) { return LibTrieProof.verifyMerkleProof( - hop.rootHash, - signalService, - getSignalSlot(chainId, app, signal), - value, - hop.accountProof, - hop.storageProof + _hop.rootHash, + _signalService, + getSignalSlot(_chainId, _app, _signal), + _value, + _hop.accountProof, + _hop.storageProof ); } @@ -262,81 +233,81 @@ contract SignalService is EssentialContract, ISignalService { } function _syncChainData( - uint64 chainId, - bytes32 kind, - uint64 blockId, - bytes32 chainData + uint64 _chainId, + bytes32 _kind, + uint64 _blockId, + bytes32 _chainData ) private - returns (bytes32 signal) + returns (bytes32 signal_) { - signal = signalForChainData(chainId, kind, blockId); - _sendSignal(address(this), signal, chainData); + signal_ = signalForChainData(_chainId, _kind, _blockId); + _sendSignal(address(this), signal_, _chainData); - if (topBlockId[chainId][kind] < blockId) { - topBlockId[chainId][kind] = blockId; + if (topBlockId[_chainId][_kind] < _blockId) { + topBlockId[_chainId][_kind] = _blockId; } - emit ChainDataSynced(chainId, blockId, kind, chainData, signal); + emit ChainDataSynced(_chainId, _blockId, _kind, _chainData, signal_); } function _sendSignal( - address app, - bytes32 signal, - bytes32 value + address _app, + bytes32 _signal, + bytes32 _value ) private - validSender(app) - nonZeroValue(signal) - nonZeroValue(value) - returns (bytes32 slot) + validSender(_app) + nonZeroValue(_signal) + nonZeroValue(_value) + returns (bytes32 slot_) { - slot = getSignalSlot(uint64(block.chainid), app, signal); + slot_ = getSignalSlot(uint64(block.chainid), _app, _signal); assembly { - sstore(slot, value) + sstore(slot_, _value) } - emit SignalSent(app, signal, slot, value); + emit SignalSent(_app, _signal, slot_, _value); } function _cacheChainData( - HopProof memory hop, - uint64 chainId, - uint64 blockId, - bytes32 signalRoot, - bool isFullProof, - bool isLastHop + HopProof memory _hop, + uint64 _chainId, + uint64 _blockId, + bytes32 _signalRoot, + bool _isFullProof, + bool _isLastHop ) private { // cache state root - bool cacheStateRoot = hop.cacheOption == CacheOption.CACHE_BOTH - || hop.cacheOption == CacheOption.CACHE_STATE_ROOT; + bool cacheStateRoot = _hop.cacheOption == CacheOption.CACHE_BOTH + || _hop.cacheOption == CacheOption.CACHE_STATE_ROOT; - if (cacheStateRoot && isFullProof && !isLastHop) { - _syncChainData(chainId, LibSignals.STATE_ROOT, blockId, hop.rootHash); + if (cacheStateRoot && _isFullProof && !_isLastHop) { + _syncChainData(_chainId, LibSignals.STATE_ROOT, _blockId, _hop.rootHash); } // cache signal root - bool cacheSignalRoot = hop.cacheOption == CacheOption.CACHE_BOTH - || hop.cacheOption == CacheOption.CACHE_SIGNAL_ROOT; + bool cacheSignalRoot = _hop.cacheOption == CacheOption.CACHE_BOTH + || _hop.cacheOption == CacheOption.CACHE_SIGNAL_ROOT; - if (cacheSignalRoot && (!isLastHop || isFullProof)) { - _syncChainData(chainId, LibSignals.SIGNAL_ROOT, blockId, signalRoot); + if (cacheSignalRoot && (_isFullProof || !_isLastHop)) { + _syncChainData(_chainId, LibSignals.SIGNAL_ROOT, _blockId, _signalRoot); } } function _loadSignalValue( - address app, - bytes32 signal + address _app, + bytes32 _signal ) private view - validSender(app) - nonZeroValue(signal) - returns (bytes32 value) + validSender(_app) + nonZeroValue(_signal) + returns (bytes32 value_) { - bytes32 slot = getSignalSlot(uint64(block.chainid), app, signal); + bytes32 slot = getSignalSlot(uint64(block.chainid), _app, _signal); assembly { - value := sload(slot) + value_ := sload(slot) } } } diff --git a/packages/protocol/contracts/team/TimelockTokenPool.sol b/packages/protocol/contracts/team/TimelockTokenPool.sol index dbe05faad54..44850abfc1a 100644 --- a/packages/protocol/contracts/team/TimelockTokenPool.sol +++ b/packages/protocol/contracts/team/TimelockTokenPool.sol @@ -130,31 +130,31 @@ contract TimelockTokenPool is EssentialContract { /// @notice Gives a grant to a address with its own unlock schedule. /// This transaction should happen on a regular basis, e.g., quarterly. - /// @param recipient The grant recipient address. - /// @param g The grant struct. - function grant(address recipient, Grant memory g) external onlyOwner { - if (recipient == address(0)) revert INVALID_PARAM(); - if (recipients[recipient].grant.amount != 0) revert ALREADY_GRANTED(); + /// @param _recipient The grant recipient address. + /// @param _grant The grant struct. + function grant(address _recipient, Grant memory _grant) external onlyOwner { + if (_recipient == address(0)) revert INVALID_PARAM(); + if (recipients[_recipient].grant.amount != 0) revert ALREADY_GRANTED(); - _validateGrant(g); + _validateGrant(_grant); - totalAmountGranted += g.amount; - recipients[recipient].grant = g; - emit Granted(recipient, g); + totalAmountGranted += _grant.amount; + recipients[_recipient].grant = _grant; + emit Granted(_recipient, _grant); } /// @notice Puts a stop to all grants for a given recipient. Tokens already /// granted to the recipient will NOT be voided but are subject to the /// original unlock schedule. - /// @param recipient The grant recipient address. - function void(address recipient) external onlyOwner { - Recipient storage r = recipients[recipient]; + /// @param _recipient The grant recipient address. + function void(address _recipient) external onlyOwner { + Recipient storage r = recipients[_recipient]; uint128 amountVoided = _voidGrant(r.grant); if (amountVoided == 0) revert NOTHING_TO_VOID(); totalAmountVoided += amountVoided; - emit Voided(recipient, amountVoided); + emit Voided(_recipient, amountVoided); } /// @notice Withdraws all withdrawable tokens. @@ -163,23 +163,17 @@ contract TimelockTokenPool is EssentialContract { } /// @notice Withdraws all withdrawable tokens. - /// @param to The address where the granted and unlocked tokens shall be sent to. - /// @param sig Signature provided by the grant recipient. - function withdraw(address to, bytes memory sig) external { - if (to == address(0)) revert INVALID_PARAM(); - bytes32 hash = keccak256(abi.encodePacked("Withdraw unlocked Taiko token to: ", to)); - address recipient = ECDSA.recover(hash, sig); - _withdraw(recipient, to); + /// @param _to The address where the granted and unlocked tokens shall be sent to. + /// @param _sig Signature provided by the grant recipient. + function withdraw(address _to, bytes memory _sig) external { + if (_to == address(0)) revert INVALID_PARAM(); + bytes32 hash = keccak256(abi.encodePacked("Withdraw unlocked Taiko token to: ", _to)); + address recipient = ECDSA.recover(hash, _sig); + _withdraw(recipient, _to); } /// @notice Returns the summary of the grant for a given recipient. - /// @param recipient The grant recipient address. - /// @return amountOwned The amount of tokens owned. - /// @return amountUnlocked The amount of tokens unlocked. - /// @return amountWithdrawn The amount of tokens withdrawn. - /// @return amountToWithdraw The amount of tokens to withdraw. - /// @return costToWithdraw The cost to withdraw. - function getMyGrantSummary(address recipient) + function getMyGrantSummary(address _recipient) public view returns ( @@ -190,7 +184,7 @@ contract TimelockTokenPool is EssentialContract { uint128 costToWithdraw ) { - Recipient storage r = recipients[recipient]; + Recipient storage r = recipients[_recipient]; amountOwned = _getAmountOwned(r.grant); amountUnlocked = _getAmountUnlocked(r.grant); @@ -205,16 +199,16 @@ contract TimelockTokenPool is EssentialContract { } /// @notice Returns the grant for a given recipient. - /// @param recipient The grant recipient address. + /// @param _recipient The grant recipient address. /// @return The grant. - function getMyGrant(address recipient) public view returns (Grant memory) { - return recipients[recipient].grant; + function getMyGrant(address _recipient) public view returns (Grant memory) { + return recipients[_recipient].grant; } - function _withdraw(address recipient, address to) private { - Recipient storage r = recipients[recipient]; + function _withdraw(address _recipient, address _to) private { + Recipient storage r = recipients[_recipient]; - (,,, uint128 amountToWithdraw, uint128 costToWithdraw) = getMyGrantSummary(recipient); + (,,, uint128 amountToWithdraw, uint128 costToWithdraw) = getMyGrantSummary(_recipient); r.amountWithdrawn += amountToWithdraw; r.costPaid += costToWithdraw; @@ -222,64 +216,66 @@ contract TimelockTokenPool is EssentialContract { totalAmountWithdrawn += amountToWithdraw; totalCostPaid += costToWithdraw; - IERC20(taikoToken).transferFrom(sharedVault, to, amountToWithdraw); - IERC20(costToken).safeTransferFrom(recipient, sharedVault, costToWithdraw); + IERC20(taikoToken).transferFrom(sharedVault, _to, amountToWithdraw); + IERC20(costToken).safeTransferFrom(_recipient, sharedVault, costToWithdraw); - emit Withdrawn(recipient, to, amountToWithdraw, costToWithdraw); + emit Withdrawn(_recipient, _to, amountToWithdraw, costToWithdraw); } - function _voidGrant(Grant storage g) private returns (uint128 amountVoided) { - uint128 amountOwned = _getAmountOwned(g); + function _voidGrant(Grant storage _grant) private returns (uint128 amountVoided) { + uint128 amountOwned = _getAmountOwned(_grant); - amountVoided = g.amount - amountOwned; - g.amount = amountOwned; + amountVoided = _grant.amount - amountOwned; + _grant.amount = amountOwned; - g.grantStart = 0; - g.grantPeriod = 0; + _grant.grantStart = 0; + _grant.grantPeriod = 0; } - function _getAmountOwned(Grant memory g) private view returns (uint128) { - return _calcAmount(g.amount, g.grantStart, g.grantCliff, g.grantPeriod); + function _getAmountOwned(Grant memory _grant) private view returns (uint128) { + return _calcAmount(_grant.amount, _grant.grantStart, _grant.grantCliff, _grant.grantPeriod); } - function _getAmountUnlocked(Grant memory g) private view returns (uint128) { - return _calcAmount(_getAmountOwned(g), g.unlockStart, g.unlockCliff, g.unlockPeriod); + function _getAmountUnlocked(Grant memory _grant) private view returns (uint128) { + return _calcAmount( + _getAmountOwned(_grant), _grant.unlockStart, _grant.unlockCliff, _grant.unlockPeriod + ); } function _calcAmount( - uint128 amount, - uint64 start, - uint64 cliff, - uint64 period + uint128 _amount, + uint64 _start, + uint64 _cliff, + uint64 _period ) private view returns (uint128) { - if (amount == 0) return 0; - if (start == 0) return amount; - if (block.timestamp <= start) return 0; + if (_amount == 0) return 0; + if (_start == 0) return _amount; + if (block.timestamp <= _start) return 0; - if (period == 0) return amount; - if (block.timestamp >= start + period) return amount; + if (_period == 0) return _amount; + if (block.timestamp >= _start + _period) return _amount; - if (block.timestamp <= cliff) return 0; + if (block.timestamp <= _cliff) return 0; - return amount * uint64(block.timestamp - start) / period; + return _amount * uint64(block.timestamp - _start) / _period; } - function _validateGrant(Grant memory g) private pure { - if (g.amount == 0) revert INVALID_GRANT(); - _validateCliff(g.grantStart, g.grantCliff, g.grantPeriod); - _validateCliff(g.unlockStart, g.unlockCliff, g.unlockPeriod); + function _validateGrant(Grant memory _grant) private pure { + if (_grant.amount == 0) revert INVALID_GRANT(); + _validateCliff(_grant.grantStart, _grant.grantCliff, _grant.grantPeriod); + _validateCliff(_grant.unlockStart, _grant.unlockCliff, _grant.unlockPeriod); } - function _validateCliff(uint64 start, uint64 cliff, uint32 period) private pure { - if (start == 0 || period == 0) { - if (cliff > 0) revert INVALID_GRANT(); + function _validateCliff(uint64 _start, uint64 _cliff, uint32 _period) private pure { + if (_start == 0 || _period == 0) { + if (_cliff > 0) revert INVALID_GRANT(); } else { - if (cliff > 0 && cliff <= start) revert INVALID_GRANT(); - if (cliff >= start + period) revert INVALID_GRANT(); + if (_cliff > 0 && _cliff <= _start) revert INVALID_GRANT(); + if (_cliff >= _start + _period) revert INVALID_GRANT(); } } } diff --git a/packages/protocol/contracts/thirdparty/optimism/Bytes.sol b/packages/protocol/contracts/thirdparty/optimism/Bytes.sol index d0f8c8d5d84..3886dd59022 100644 --- a/packages/protocol/contracts/thirdparty/optimism/Bytes.sol +++ b/packages/protocol/contracts/thirdparty/optimism/Bytes.sol @@ -145,7 +145,7 @@ library Bytes { /// @notice Compares two byte arrays by comparing their keccak256 hashes. /// @param _bytes First byte array to compare. /// @param _other Second byte array to compare. - /// @return True if the two byte arrays are equal, false otherwise. + /// @return true if the two byte arrays are equal, false otherwise. function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) { return keccak256(_bytes) == keccak256(_other); } diff --git a/packages/protocol/contracts/tokenvault/BaseNFTVault.sol b/packages/protocol/contracts/tokenvault/BaseNFTVault.sol index 123e8135ae0..8e0e691ea0a 100644 --- a/packages/protocol/contracts/tokenvault/BaseNFTVault.sol +++ b/packages/protocol/contracts/tokenvault/BaseNFTVault.sol @@ -137,16 +137,16 @@ abstract contract BaseNFTVault is BaseVault { error VAULT_TOKEN_ARRAY_MISMATCH(); error VAULT_MAX_TOKEN_PER_TXN_EXCEEDED(); - modifier withValidOperation(BridgeTransferOp memory op) { - if (op.tokenIds.length != op.amounts.length) { + modifier withValidOperation(BridgeTransferOp memory _op) { + if (_op.tokenIds.length != _op.amounts.length) { revert VAULT_TOKEN_ARRAY_MISMATCH(); } - if (op.tokenIds.length > MAX_TOKEN_PER_TXN) { + if (_op.tokenIds.length > MAX_TOKEN_PER_TXN) { revert VAULT_MAX_TOKEN_PER_TXN_EXCEEDED(); } - if (op.token == address(0)) revert VAULT_INVALID_TOKEN(); + if (_op.token == address(0)) revert VAULT_INVALID_TOKEN(); _; } } diff --git a/packages/protocol/contracts/tokenvault/BaseVault.sol b/packages/protocol/contracts/tokenvault/BaseVault.sol index 6d4012dc5bd..859fcea2d6c 100644 --- a/packages/protocol/contracts/tokenvault/BaseVault.sol +++ b/packages/protocol/contracts/tokenvault/BaseVault.sol @@ -34,10 +34,10 @@ abstract contract BaseVault is } /// @notice Checks if the contract supports the given interface. - /// @param interfaceId The interface identifier. - /// @return True if the contract supports the interface, false otherwise. - function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { - return interfaceId == type(IRecallableSender).interfaceId; + /// @param _interfaceId The interface identifier. + /// @return true if the contract supports the interface, false otherwise. + function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) { + return _interfaceId == type(IRecallableSender).interfaceId; } /// @notice Returns the name of the vault. @@ -48,20 +48,20 @@ abstract contract BaseVault is internal view onlyFromBridge - returns (IBridge.Context memory ctx) + returns (IBridge.Context memory ctx_) { - ctx = IBridge(msg.sender).context(); - address selfOnSourceChain = resolve(ctx.srcChainId, name(), false); - if (ctx.from != selfOnSourceChain) revert VAULT_PERMISSION_DENIED(); + ctx_ = IBridge(msg.sender).context(); + address selfOnSourceChain = resolve(ctx_.srcChainId, name(), false); + if (ctx_.from != selfOnSourceChain) revert VAULT_PERMISSION_DENIED(); } function checkRecallMessageContext() internal view onlyFromBridge - returns (IBridge.Context memory ctx) + returns (IBridge.Context memory ctx_) { - ctx = IBridge(msg.sender).context(); - if (ctx.from != msg.sender) revert VAULT_PERMISSION_DENIED(); + ctx_ = IBridge(msg.sender).context(); + if (ctx_.from != msg.sender) revert VAULT_PERMISSION_DENIED(); } } diff --git a/packages/protocol/contracts/tokenvault/BridgedERC1155.sol b/packages/protocol/contracts/tokenvault/BridgedERC1155.sol index 6b3ff909f82..c3ff41dbe06 100644 --- a/packages/protocol/contracts/tokenvault/BridgedERC1155.sol +++ b/packages/protocol/contracts/tokenvault/BridgedERC1155.sol @@ -19,10 +19,10 @@ contract BridgedERC1155 is EssentialContract, IERC1155MetadataURIUpgradeable, ER uint256 public srcChainId; /// @dev Symbol of the bridged token. - string private symbol_; + string private __symbol; /// @dev Name of the bridged token. - string private name_; + string private __name; uint256[46] private __gap; @@ -55,86 +55,86 @@ contract BridgedERC1155 is EssentialContract, IERC1155MetadataURIUpgradeable, ER srcToken = _srcToken; srcChainId = _srcChainId; - symbol_ = _symbol; - name_ = _name; + __symbol = _symbol; + __name = _name; } /// @dev Mints tokens. - /// @param to Address to receive the minted tokens. - /// @param tokenId ID of the token to mint. - /// @param amount Amount of tokens to mint. + /// @param _to Address to receive the minted tokens. + /// @param _tokenId ID of the token to mint. + /// @param _amount Amount of tokens to mint. function mint( - address to, - uint256 tokenId, - uint256 amount + address _to, + uint256 _tokenId, + uint256 _amount ) public nonReentrant whenNotPaused onlyFromNamed("erc1155_vault") { - _mint(to, tokenId, amount, ""); + _mint(_to, _tokenId, _amount, ""); } /// @dev Mints tokens. - /// @param to Address to receive the minted tokens. - /// @param tokenIds ID of the token to mint. - /// @param amounts Amount of tokens to mint. + /// @param _to Address to receive the minted tokens. + /// @param _tokenIds ID of the token to mint. + /// @param _amounts Amount of tokens to mint. function mintBatch( - address to, - uint256[] memory tokenIds, - uint256[] memory amounts + address _to, + uint256[] memory _tokenIds, + uint256[] memory _amounts ) public nonReentrant whenNotPaused onlyFromNamed("erc1155_vault") { - _mintBatch(to, tokenIds, amounts, ""); + _mintBatch(_to, _tokenIds, _amounts, ""); } /// @dev Burns tokens. - /// @param account Address from which tokens are burned. - /// @param tokenId ID of the token to burn. - /// @param amount Amount of tokens to burn. + /// @param _account Address from which tokens are burned. + /// @param _tokenId ID of the token to burn. + /// @param _amount Amount of tokens to burn. function burn( - address account, - uint256 tokenId, - uint256 amount + address _account, + uint256 _tokenId, + uint256 _amount ) public nonReentrant whenNotPaused onlyFromNamed("erc1155_vault") { - _burn(account, tokenId, amount); + _burn(_account, _tokenId, _amount); } /// @notice Gets the name of the bridged token. /// @return The name. function name() public view returns (string memory) { - return LibBridgedToken.buildName(name_, srcChainId); + return LibBridgedToken.buildName(__name, srcChainId); } /// @notice Gets the symbol of the bridged token. /// @return The symbol. function symbol() public view returns (string memory) { - return LibBridgedToken.buildSymbol(symbol_); + return LibBridgedToken.buildSymbol(__symbol); } function _beforeTokenTransfer( - address, /*operator*/ - address, /*from*/ - address to, - uint256[] memory, /*ids*/ - uint256[] memory, /*amounts*/ - bytes memory /*data*/ + address, /*_operator*/ + address, /*_from*/ + address _to, + uint256[] memory, /*_ids*/ + uint256[] memory, /*_amounts*/ + bytes memory /*_data*/ ) internal virtual override { - if (to == address(this)) revert BTOKEN_CANNOT_RECEIVE(); + if (_to == address(this)) revert BTOKEN_CANNOT_RECEIVE(); if (paused()) revert INVALID_PAUSE_STATUS(); } } diff --git a/packages/protocol/contracts/tokenvault/BridgedERC20.sol b/packages/protocol/contracts/tokenvault/BridgedERC20.sol index 97cc5c480a0..19d01c38549 100644 --- a/packages/protocol/contracts/tokenvault/BridgedERC20.sol +++ b/packages/protocol/contracts/tokenvault/BridgedERC20.sol @@ -21,7 +21,7 @@ contract BridgedERC20 is /// @dev Slot 1. address public srcToken; - uint8 private srcDecimals; + uint8 private __srcDecimals; /// @dev Slot 2. uint256 public srcChainId; @@ -64,7 +64,7 @@ contract BridgedERC20 is // Check if provided parameters are valid LibBridgedToken.validateInputs(_srcToken, _srcChainId, _symbol, _name); __Essential_init(_owner, _addressManager); - __ERC20_init({ name_: _name, symbol_: _symbol }); + __ERC20_init(_name, _symbol); __ERC20Snapshot_init(); __ERC20Votes_init(); __ERC20Permit_init(_name); @@ -72,7 +72,7 @@ contract BridgedERC20 is // Set contract properties srcToken = _srcToken; srcChainId = _srcChainId; - srcDecimals = _decimals; + __srcDecimals = _decimals; } /// @notice Set the snapshoter address. @@ -116,67 +116,67 @@ contract BridgedERC20 is override(ERC20Upgradeable, IERC20MetadataUpgradeable) returns (uint8) { - return srcDecimals; + return __srcDecimals; } /// @notice Gets the canonical token's address and chain ID. - /// @return address The canonical token's address. - /// @return uint256 The canonical token's chain ID. + /// @return The canonical token's address. + /// @return The canonical token's chain ID. function canonical() public view returns (address, uint256) { return (srcToken, srcChainId); } - function _mintToken(address account, uint256 amount) internal override { - _mint(account, amount); + function _mintToken(address _account, uint256 _amount) internal override { + _mint(_account, _amount); } - function _burnToken(address from, uint256 amount) internal override { - _burn(from, amount); + function _burnToken(address _from, uint256 _amount) internal override { + _burn(_from, _amount); } /// @dev For ERC20SnapshotUpgradeable and ERC20VotesUpgradeable, need to implement the following /// functions function _beforeTokenTransfer( - address from, - address to, - uint256 amount + address _from, + address _to, + uint256 _amount ) internal override(ERC20Upgradeable, ERC20SnapshotUpgradeable) { - if (to == address(this)) revert BTOKEN_CANNOT_RECEIVE(); + if (_to == address(this)) revert BTOKEN_CANNOT_RECEIVE(); if (paused()) revert INVALID_PAUSE_STATUS(); - super._beforeTokenTransfer(from, to, amount); + super._beforeTokenTransfer(_from, _to, _amount); } function _afterTokenTransfer( - address from, - address to, - uint256 amount + address _from, + address _to, + uint256 _amount ) internal override(ERC20Upgradeable, ERC20VotesUpgradeable) { - super._afterTokenTransfer(from, to, amount); + super._afterTokenTransfer(_from, _to, _amount); } function _mint( - address to, - uint256 amount + address _to, + uint256 _amount ) internal override(ERC20Upgradeable, ERC20VotesUpgradeable) { - super._mint(to, amount); + super._mint(_to, _amount); } function _burn( - address from, - uint256 amount + address _from, + uint256 _amount ) internal override(ERC20Upgradeable, ERC20VotesUpgradeable) { - super._burn(from, amount); + super._burn(_from, _amount); } } diff --git a/packages/protocol/contracts/tokenvault/BridgedERC20Base.sol b/packages/protocol/contracts/tokenvault/BridgedERC20Base.sol index 2179c776204..73cb27f4255 100644 --- a/packages/protocol/contracts/tokenvault/BridgedERC20Base.sol +++ b/packages/protocol/contracts/tokenvault/BridgedERC20Base.sol @@ -52,51 +52,51 @@ abstract contract BridgedERC20Base is EssentialContract, IBridgedERC20 { } /// @notice Mints tokens to the specified account. - /// @param account The address of the account to receive the tokens. - /// @param amount The amount of tokens to mint. - function mint(address account, uint256 amount) public nonReentrant whenNotPaused { + /// @param _account The address of the account to receive the tokens. + /// @param _amount The amount of tokens to mint. + function mint(address _account, uint256 _amount) public nonReentrant whenNotPaused { // mint is disabled while migrating outbound. if (_isMigratingOut()) revert BB_MINT_DISALLOWED(); if (msg.sender == migratingAddress) { // Inbound migration - emit MigratedTo(migratingAddress, account, amount); + emit MigratedTo(migratingAddress, _account, _amount); } else if (msg.sender != resolve("erc20_vault", true)) { // Bridging from vault revert BB_PERMISSION_DENIED(); } - _mintToken(account, amount); + _mintToken(_account, _amount); } /// @notice Burns tokens from the specified account. - /// @param account The address of the account to burn the tokens from. - /// @param amount The amount of tokens to burn. - function burn(address account, uint256 amount) public nonReentrant whenNotPaused { + /// @param _account The address of the account to burn the tokens from. + /// @param _amount The amount of tokens to burn. + function burn(address _account, uint256 _amount) public nonReentrant whenNotPaused { if (_isMigratingOut()) { // Only the owner of the tokens himself can migrate out - if (msg.sender != account) revert BB_PERMISSION_DENIED(); + if (msg.sender != _account) revert BB_PERMISSION_DENIED(); // Outbound migration - emit MigratedTo(migratingAddress, account, amount); + emit MigratedTo(migratingAddress, _account, _amount); // Ask the new bridged token to mint token for the user. - IBridgedERC20(migratingAddress).mint(account, amount); + IBridgedERC20(migratingAddress).mint(_account, _amount); } else if (msg.sender != resolve("erc20_vault", true)) { // Only the vault can burn tokens when not migrating out revert RESOLVER_DENIED(); } - _burnToken(account, amount); + _burnToken(_account, _amount); } /// @notice Returns the owner. - /// @return address The address of the owner. + /// @return The address of the owner. function owner() public view override(IBridgedERC20, OwnableUpgradeable) returns (address) { return super.owner(); } - function _mintToken(address account, uint256 amount) internal virtual; + function _mintToken(address _account, uint256 _amount) internal virtual; - function _burnToken(address from, uint256 amount) internal virtual; + function _burnToken(address _from, uint256 _amount) internal virtual; function _isMigratingOut() internal view returns (bool) { return migratingAddress != address(0) && !migratingInbound; diff --git a/packages/protocol/contracts/tokenvault/BridgedERC721.sol b/packages/protocol/contracts/tokenvault/BridgedERC721.sol index 881bbc4963d..824403fd402 100644 --- a/packages/protocol/contracts/tokenvault/BridgedERC721.sol +++ b/packages/protocol/contracts/tokenvault/BridgedERC721.sol @@ -49,26 +49,26 @@ contract BridgedERC721 is EssentialContract, ERC721Upgradeable { } /// @dev Mints tokens. - /// @param account Address to receive the minted token. - /// @param tokenId ID of the token to mint. + /// @param _account Address to receive the minted token. + /// @param _tokenId ID of the token to mint. function mint( - address account, - uint256 tokenId + address _account, + uint256 _tokenId ) public nonReentrant whenNotPaused onlyFromNamed("erc721_vault") { - _safeMint(account, tokenId); + _safeMint(_account, _tokenId); } /// @dev Burns tokens. - /// @param account Address from which the token is burned. - /// @param tokenId ID of the token to burn. + /// @param _account Address from which the token is burned. + /// @param _tokenId ID of the token to burn. function burn( - address account, - uint256 tokenId + address _account, + uint256 _tokenId ) public nonReentrant @@ -76,10 +76,10 @@ contract BridgedERC721 is EssentialContract, ERC721Upgradeable { onlyFromNamed("erc721_vault") { // Check if the caller is the owner of the token. - if (ownerOf(tokenId) != account) { + if (ownerOf(_tokenId) != _account) { revert BTOKEN_INVALID_BURN(); } - _burn(tokenId); + _burn(_tokenId); } /// @notice Gets the name of the token. @@ -95,34 +95,34 @@ contract BridgedERC721 is EssentialContract, ERC721Upgradeable { } /// @notice Gets the source token and source chain ID being bridged. - /// @return address The source token's address. - /// @return uint256 The source token's chain ID. + /// @return The source token's address. + /// @return The source token's chain ID. function source() public view returns (address, uint256) { return (srcToken, srcChainId); } /// @notice Returns the token URI. - /// @param tokenId The token id. - /// @return string The token uri following eip-681. - function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { + /// @param _tokenId The token id. + /// @return The token URI following EIP-681. + function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { return string( abi.encodePacked( - LibBridgedToken.buildURI(srcToken, srcChainId), Strings.toString(tokenId) + LibBridgedToken.buildURI(srcToken, srcChainId), Strings.toString(_tokenId) ) ); } function _beforeTokenTransfer( - address, /*from*/ - address to, - uint256, /*firstTokenId*/ - uint256 /*batchSize*/ + address, /*_from*/ + address _to, + uint256, /*_firstTokenId*/ + uint256 /*_batchSize*/ ) internal virtual override { - if (to == address(this)) revert BTOKEN_CANNOT_RECEIVE(); + if (_to == address(this)) revert BTOKEN_CANNOT_RECEIVE(); if (paused()) revert INVALID_PAUSE_STATUS(); } } diff --git a/packages/protocol/contracts/tokenvault/ERC1155Vault.sol b/packages/protocol/contracts/tokenvault/ERC1155Vault.sol index b5bf4e1a840..812f19ae7fb 100644 --- a/packages/protocol/contracts/tokenvault/ERC1155Vault.sol +++ b/packages/protocol/contracts/tokenvault/ERC1155Vault.sol @@ -34,54 +34,54 @@ contract ERC1155Vault is BaseNFTVault, ERC1155ReceiverUpgradeable { /// @notice Transfers ERC1155 tokens to this vault and sends a message to /// the destination chain so the user can receive the same (bridged) tokens /// by invoking the message call. - /// @param op Option for sending the ERC1155 token. - /// @return _message The constructed message. - function sendToken(BridgeTransferOp memory op) + /// @param _op Option for sending the ERC1155 token. + /// @return message_ The constructed message. + function sendToken(BridgeTransferOp memory _op) external payable nonReentrant whenNotPaused - withValidOperation(op) - returns (IBridge.Message memory _message) + withValidOperation(_op) + returns (IBridge.Message memory message_) { - for (uint256 i; i < op.amounts.length; ++i) { - if (op.amounts[i] == 0) revert VAULT_INVALID_AMOUNT(); + for (uint256 i; i < _op.amounts.length; ++i) { + if (_op.amounts[i] == 0) revert VAULT_INVALID_AMOUNT(); } // Check token interface support - if (!op.token.supportsInterface(ERC1155_INTERFACE_ID)) { + if (!_op.token.supportsInterface(ERC1155_INTERFACE_ID)) { revert VAULT_INTERFACE_NOT_SUPPORTED(); } - (bytes memory data, CanonicalNFT memory ctoken) = _handleMessage(msg.sender, op); + (bytes memory data, CanonicalNFT memory ctoken) = _handleMessage(msg.sender, _op); // Create a message to send to the destination chain IBridge.Message memory message; - message.destChainId = op.destChainId; + message.destChainId = _op.destChainId; message.data = data; message.srcOwner = msg.sender; - message.destOwner = op.destOwner != address(0) ? op.destOwner : msg.sender; + message.destOwner = _op.destOwner != address(0) ? _op.destOwner : msg.sender; message.to = resolve(message.destChainId, name(), false); - message.gasLimit = op.gasLimit; - message.value = msg.value - op.fee; - message.fee = op.fee; - message.refundTo = op.refundTo; - message.memo = op.memo; + message.gasLimit = _op.gasLimit; + message.value = msg.value - _op.fee; + message.fee = _op.fee; + message.refundTo = _op.refundTo; + message.memo = _op.memo; // Send the message and obtain the message hash bytes32 msgHash; - (msgHash, _message) = + (msgHash, message_) = IBridge(resolve("bridge", false)).sendMessage{ value: msg.value }(message); // Emit TokenSent event emit TokenSent({ msgHash: msgHash, - from: _message.srcOwner, - to: op.to, - destChainId: _message.destChainId, + from: message_.srcOwner, + to: _op.to, + destChainId: message_.destChainId, ctoken: ctoken.addr, - token: op.token, - tokenIds: op.tokenIds, - amounts: op.amounts + token: _op.token, + tokenIds: _op.tokenIds, + amounts: _op.amounts }); } @@ -133,9 +133,9 @@ contract ERC1155Vault is BaseNFTVault, ERC1155ReceiverUpgradeable { // `onlyFromBridge` checked in checkRecallMessageContext checkRecallMessageContext(); - (bytes memory _data) = abi.decode(message.data[4:], (bytes)); + (bytes memory data) = abi.decode(message.data[4:], (bytes)); (CanonicalNFT memory ctoken,,, uint256[] memory tokenIds, uint256[] memory amounts) = - abi.decode(_data, (CanonicalNFT, address, address, uint256[], uint256[])); + abi.decode(data, (CanonicalNFT, address, address, uint256[], uint256[])); // Transfer the ETH and tokens back to the owner address token = _transferTokens(ctoken, message.srcOwner, tokenIds, amounts); @@ -184,7 +184,7 @@ contract ERC1155Vault is BaseNFTVault, ERC1155ReceiverUpgradeable { /// @dev See {BaseVault-supportsInterface}. /// @param interfaceId The interface identifier. - /// @return bool True if supports, else otherwise. + /// @return true if supports, else otherwise. function supportsInterface(bytes4 interfaceId) public view @@ -229,90 +229,90 @@ contract ERC1155Vault is BaseNFTVault, ERC1155ReceiverUpgradeable { /// @dev Handles the message on the source chain and returns the encoded /// call on the destination call. - /// @param user The user's address. - /// @param op BridgeTransferOp data. - /// @return msgData Encoded message data. - /// @return ctoken The canonical token. + /// @param _user The user's address. + /// @param _op BridgeTransferOp data. + /// @return msgData_ Encoded message data. + /// @return ctoken_ The canonical token. function _handleMessage( - address user, - BridgeTransferOp memory op + address _user, + BridgeTransferOp memory _op ) private - returns (bytes memory msgData, CanonicalNFT memory ctoken) + returns (bytes memory msgData_, CanonicalNFT memory ctoken_) { unchecked { // is a btoken, meaning, it does not live on this chain - if (bridgedToCanonical[op.token].addr != address(0)) { - ctoken = bridgedToCanonical[op.token]; - for (uint256 i; i < op.tokenIds.length; ++i) { - BridgedERC1155(op.token).burn(user, op.tokenIds[i], op.amounts[i]); + if (bridgedToCanonical[_op.token].addr != address(0)) { + ctoken_ = bridgedToCanonical[_op.token]; + for (uint256 i; i < _op.tokenIds.length; ++i) { + BridgedERC1155(_op.token).burn(_user, _op.tokenIds[i], _op.amounts[i]); } } else { // is a ctoken token, meaning, it lives on this chain - ctoken = CanonicalNFT({ + ctoken_ = CanonicalNFT({ chainId: uint64(block.chainid), - addr: op.token, + addr: _op.token, symbol: "", name: "" }); - IERC1155NameAndSymbol t = IERC1155NameAndSymbol(op.token); + IERC1155NameAndSymbol t = IERC1155NameAndSymbol(_op.token); try t.name() returns (string memory _name) { - ctoken.name = _name; + ctoken_.name = _name; } catch { } try t.symbol() returns (string memory _symbol) { - ctoken.symbol = _symbol; + ctoken_.symbol = _symbol; } catch { } - for (uint256 i; i < op.tokenIds.length; ++i) { - IERC1155(op.token).safeTransferFrom({ + for (uint256 i; i < _op.tokenIds.length; ++i) { + IERC1155(_op.token).safeTransferFrom({ from: msg.sender, to: address(this), - id: op.tokenIds[i], - amount: op.amounts[i], + id: _op.tokenIds[i], + amount: _op.amounts[i], data: "" }); } } } - msgData = abi.encodeCall( - this.onMessageInvocation, abi.encode(ctoken, user, op.to, op.tokenIds, op.amounts) + msgData_ = abi.encodeCall( + this.onMessageInvocation, abi.encode(ctoken_, _user, _op.to, _op.tokenIds, _op.amounts) ); } /// @dev Retrieve or deploy a bridged ERC1155 token contract. - /// @param ctoken CanonicalNFT data. - /// @return btoken Address of the bridged token contract. - function _getOrDeployBridgedToken(CanonicalNFT memory ctoken) + /// @param _ctoken CanonicalNFT data. + /// @return btoken_ Address of the bridged token contract. + function _getOrDeployBridgedToken(CanonicalNFT memory _ctoken) private - returns (address btoken) + returns (address btoken_) { - btoken = canonicalToBridged[ctoken.chainId][ctoken.addr]; - if (btoken == address(0)) { - btoken = _deployBridgedToken(ctoken); + btoken_ = canonicalToBridged[_ctoken.chainId][_ctoken.addr]; + if (btoken_ == address(0)) { + btoken_ = _deployBridgedToken(_ctoken); } } /// @dev Deploy a new BridgedNFT contract and initialize it. /// This must be called before the first time a bridged token is sent to /// this chain. - /// @param ctoken CanonicalNFT data. - /// @return btoken Address of the deployed bridged token contract. - function _deployBridgedToken(CanonicalNFT memory ctoken) private returns (address btoken) { + /// @param _ctoken CanonicalNFT data. + /// @return btoken_ Address of the deployed bridged token contract. + function _deployBridgedToken(CanonicalNFT memory _ctoken) private returns (address btoken_) { bytes memory data = abi.encodeCall( BridgedERC1155.init, - (owner(), addressManager, ctoken.addr, ctoken.chainId, ctoken.symbol, ctoken.name) + (owner(), addressManager, _ctoken.addr, _ctoken.chainId, _ctoken.symbol, _ctoken.name) ); - btoken = address(new ERC1967Proxy(resolve("bridged_erc1155", false), data)); + btoken_ = address(new ERC1967Proxy(resolve("bridged_erc1155", false), data)); - bridgedToCanonical[btoken] = ctoken; - canonicalToBridged[ctoken.chainId][ctoken.addr] = btoken; + bridgedToCanonical[btoken_] = _ctoken; + canonicalToBridged[_ctoken.chainId][_ctoken.addr] = btoken_; emit BridgedTokenDeployed({ - chainId: ctoken.chainId, - ctoken: ctoken.addr, - btoken: btoken, - ctokenSymbol: ctoken.symbol, - ctokenName: ctoken.name + chainId: _ctoken.chainId, + ctoken: _ctoken.addr, + btoken: btoken_, + ctokenSymbol: _ctoken.symbol, + ctokenName: _ctoken.name }); } } diff --git a/packages/protocol/contracts/tokenvault/ERC20Vault.sol b/packages/protocol/contracts/tokenvault/ERC20Vault.sol index 5e64629810a..a3848b83c85 100644 --- a/packages/protocol/contracts/tokenvault/ERC20Vault.sol +++ b/packages/protocol/contracts/tokenvault/ERC20Vault.sol @@ -142,114 +142,119 @@ contract ERC20Vault is BaseVault { error VAULT_NOT_SAME_OWNER(); /// @notice Change bridged token. - /// @param ctoken The canonical token. - /// @param btokenNew The new bridged token address. + /// @param _ctoken The canonical token. + /// @param _btokenNew The new bridged token address. + /// @return btokenOld_ The old bridged token address. function changeBridgedToken( - CanonicalERC20 calldata ctoken, - address btokenNew + CanonicalERC20 calldata _ctoken, + address _btokenNew ) external nonReentrant whenNotPaused onlyOwner - returns (address btokenOld) + returns (address btokenOld_) { - if (btokenNew == address(0) || bridgedToCanonical[btokenNew].addr != address(0)) { + if (_btokenNew == address(0) || bridgedToCanonical[_btokenNew].addr != address(0)) { revert VAULT_INVALID_NEW_BTOKEN(); } - if (btokenBlacklist[btokenNew]) revert VAULT_BTOKEN_BLACKLISTED(); + if (btokenBlacklist[_btokenNew]) revert VAULT_BTOKEN_BLACKLISTED(); - if (IBridgedERC20(btokenNew).owner() != owner()) { + if (IBridgedERC20(_btokenNew).owner() != owner()) { revert VAULT_NOT_SAME_OWNER(); } - btokenOld = canonicalToBridged[ctoken.chainId][ctoken.addr]; + btokenOld_ = canonicalToBridged[_ctoken.chainId][_ctoken.addr]; - if (btokenOld != address(0)) { - CanonicalERC20 memory _ctoken = bridgedToCanonical[btokenOld]; + if (btokenOld_ != address(0)) { + CanonicalERC20 memory ctoken = bridgedToCanonical[btokenOld_]; // The ctoken must match the saved one. if ( - _ctoken.decimals != ctoken.decimals - || keccak256(bytes(_ctoken.symbol)) != keccak256(bytes(ctoken.symbol)) - || keccak256(bytes(_ctoken.name)) != keccak256(bytes(ctoken.name)) + ctoken.decimals != _ctoken.decimals + || keccak256(bytes(ctoken.symbol)) != keccak256(bytes(_ctoken.symbol)) + || keccak256(bytes(ctoken.name)) != keccak256(bytes(_ctoken.name)) ) revert VAULT_CTOKEN_MISMATCH(); - delete bridgedToCanonical[btokenOld]; - btokenBlacklist[btokenOld] = true; + delete bridgedToCanonical[_btokenNew]; + btokenBlacklist[btokenOld_] = true; // Start the migration - IBridgedERC20(btokenOld).changeMigrationStatus(btokenNew, false); - IBridgedERC20(btokenNew).changeMigrationStatus(btokenOld, true); + IBridgedERC20(btokenOld_).changeMigrationStatus(_btokenNew, false); + IBridgedERC20(_btokenNew).changeMigrationStatus(btokenOld_, true); } - bridgedToCanonical[btokenNew] = ctoken; - canonicalToBridged[ctoken.chainId][ctoken.addr] = btokenNew; + bridgedToCanonical[_btokenNew] = _ctoken; + canonicalToBridged[_ctoken.chainId][_ctoken.addr] = _btokenNew; emit BridgedTokenChanged({ - srcChainId: ctoken.chainId, - ctoken: ctoken.addr, - btokenOld: btokenOld, - btokenNew: btokenNew, - ctokenSymbol: ctoken.symbol, - ctokenName: ctoken.name, - ctokenDecimal: ctoken.decimals + srcChainId: _ctoken.chainId, + ctoken: _ctoken.addr, + btokenOld: btokenOld_, + btokenNew: _btokenNew, + ctokenSymbol: _ctoken.symbol, + ctokenName: _ctoken.name, + ctokenDecimal: _ctoken.decimals }); } /// @notice Transfers ERC20 tokens to this vault and sends a message to the /// destination chain so the user can receive the same amount of tokens by /// invoking the message call. - /// @param op Option for sending ERC20 tokens. - /// @return _message The constructed message. - function sendToken(BridgeTransferOp calldata op) + /// @param _op Option for sending ERC20 tokens. + /// @return message_ The constructed message. + function sendToken(BridgeTransferOp calldata _op) external payable nonReentrant whenNotPaused - returns (IBridge.Message memory _message) + returns (IBridge.Message memory message_) { - if (op.amount == 0) revert VAULT_INVALID_AMOUNT(); - if (op.token == address(0)) revert VAULT_INVALID_TOKEN(); - if (btokenBlacklist[op.token]) revert VAULT_BTOKEN_BLACKLISTED(); + if (_op.amount == 0) revert VAULT_INVALID_AMOUNT(); + if (_op.token == address(0)) revert VAULT_INVALID_TOKEN(); + if (btokenBlacklist[_op.token]) revert VAULT_BTOKEN_BLACKLISTED(); uint256 _amount; IBridge.Message memory message; CanonicalERC20 memory ctoken; - (message.data, ctoken, _amount) = - _handleMessage({ user: msg.sender, token: op.token, amount: op.amount, to: op.to }); + (message.data, ctoken, _amount) = _handleMessage(msg.sender, _op.token, _op.to, _op.amount); - message.destChainId = op.destChainId; + message.destChainId = _op.destChainId; message.srcOwner = msg.sender; - message.destOwner = op.destOwner != address(0) ? op.destOwner : msg.sender; - message.to = resolve(op.destChainId, name(), false); - message.gasLimit = op.gasLimit; - message.value = msg.value - op.fee; - message.fee = op.fee; - message.refundTo = op.refundTo; - message.memo = op.memo; + message.destOwner = _op.destOwner != address(0) ? _op.destOwner : msg.sender; + message.to = resolve(_op.destChainId, name(), false); + message.gasLimit = _op.gasLimit; + message.value = msg.value - _op.fee; + message.fee = _op.fee; + message.refundTo = _op.refundTo; + message.memo = _op.memo; bytes32 msgHash; - (msgHash, _message) = + (msgHash, message_) = IBridge(resolve("bridge", false)).sendMessage{ value: msg.value }(message); emit TokenSent({ msgHash: msgHash, - from: _message.srcOwner, - to: op.to, - destChainId: op.destChainId, + from: message_.srcOwner, + to: _op.to, + destChainId: _op.destChainId, ctoken: ctoken.addr, - token: op.token, + token: _op.token, amount: _amount }); } /// @inheritdoc IMessageInvocable - function onMessageInvocation(bytes calldata data) external payable nonReentrant whenNotPaused { + function onMessageInvocation(bytes calldata _data) + external + payable + nonReentrant + whenNotPaused + { (CanonicalERC20 memory ctoken, address from, address to, uint256 amount) = - abi.decode(data, (CanonicalERC20, address, address, uint256)); + abi.decode(_data, (CanonicalERC20, address, address, uint256)); // `onlyFromBridge` checked in checkProcessMessageContext IBridge.Context memory ctx = checkProcessMessageContext(); @@ -275,8 +280,8 @@ contract ERC20Vault is BaseVault { /// @inheritdoc IRecallableSender function onMessageRecalled( - IBridge.Message calldata message, - bytes32 msgHash + IBridge.Message calldata _message, + bytes32 _msgHash ) external payable @@ -287,17 +292,17 @@ contract ERC20Vault is BaseVault { // `onlyFromBridge` checked in checkRecallMessageContext checkRecallMessageContext(); - (bytes memory _data) = abi.decode(message.data[4:], (bytes)); + (bytes memory data) = abi.decode(_message.data[4:], (bytes)); (CanonicalERC20 memory ctoken,,, uint256 amount) = - abi.decode(_data, (CanonicalERC20, address, address, uint256)); + abi.decode(data, (CanonicalERC20, address, address, uint256)); // Transfer the ETH and tokens back to the owner - address token = _transferTokens(ctoken, message.srcOwner, amount); - message.srcOwner.sendEther(message.value); + address token = _transferTokens(ctoken, _message.srcOwner, amount); + _message.srcOwner.sendEther(_message.value); emit TokenReleased({ - msgHash: msgHash, - from: message.srcOwner, + msgHash: _msgHash, + from: _message.srcOwner, ctoken: ctoken.addr, token: token, amount: amount @@ -310,53 +315,53 @@ contract ERC20Vault is BaseVault { } function _transferTokens( - CanonicalERC20 memory ctoken, - address to, - uint256 amount + CanonicalERC20 memory _ctoken, + address _to, + uint256 _amount ) private - returns (address token) + returns (address token_) { - if (ctoken.chainId == block.chainid) { - token = ctoken.addr; - IERC20(token).safeTransfer(to, amount); + if (_ctoken.chainId == block.chainid) { + token_ = _ctoken.addr; + IERC20(token_).safeTransfer(_to, _amount); } else { - token = _getOrDeployBridgedToken(ctoken); - IBridgedERC20(token).mint(to, amount); + token_ = _getOrDeployBridgedToken(_ctoken); + IBridgedERC20(token_).mint(_to, _amount); } } /// @dev Handles the message on the source chain and returns the encoded /// call on the destination call. - /// @param user The user's address. - /// @param token The token address. - /// @param to To address. - /// @param amount Amount to be sent. - /// @return msgData Encoded message data. - /// @return ctoken The canonical token. - /// @return balanceChange User token balance actual change after the token + /// @param _user The user's address. + /// @param _token The token address. + /// @param _to To address. + /// @param _amount Amount to be sent. + /// @return msgData_ Encoded message data. + /// @return ctoken_ The canonical token. + /// @return balanceChange_ User token balance actual change after the token /// transfer. This value is calculated so we do not assume token balance /// change is the amount of token transfered away. function _handleMessage( - address user, - address token, - address to, - uint256 amount + address _user, + address _token, + address _to, + uint256 _amount ) private - returns (bytes memory msgData, CanonicalERC20 memory ctoken, uint256 balanceChange) + returns (bytes memory msgData_, CanonicalERC20 memory ctoken_, uint256 balanceChange_) { // If it's a bridged token - if (bridgedToCanonical[token].addr != address(0)) { - ctoken = bridgedToCanonical[token]; - IBridgedERC20(token).burn(msg.sender, amount); - balanceChange = amount; + if (bridgedToCanonical[_token].addr != address(0)) { + ctoken_ = bridgedToCanonical[_token]; + IBridgedERC20(_token).burn(msg.sender, _amount); + balanceChange_ = _amount; } else { // If it's a canonical token - IERC20Metadata meta = IERC20Metadata(token); - ctoken = CanonicalERC20({ + IERC20Metadata meta = IERC20Metadata(_token); + ctoken_ = CanonicalERC20({ chainId: uint64(block.chainid), - addr: token, + addr: _token, decimals: meta.decimals(), symbol: meta.symbol(), name: meta.name() @@ -366,14 +371,15 @@ contract ERC20Vault is BaseVault { // token transferred into this address, this is more accurate than // simply using `amount` -- some contract may deduct a fee from the // transferred amount. - IERC20 t = IERC20(token); + IERC20 t = IERC20(_token); uint256 _balance = t.balanceOf(address(this)); - t.safeTransferFrom({ from: msg.sender, to: address(this), value: amount }); - balanceChange = t.balanceOf(address(this)) - _balance; + t.safeTransferFrom({ from: msg.sender, to: address(this), value: _amount }); + balanceChange_ = t.balanceOf(address(this)) - _balance; } - msgData = - abi.encodeCall(this.onMessageInvocation, abi.encode(ctoken, user, to, balanceChange)); + msgData_ = abi.encodeCall( + this.onMessageInvocation, abi.encode(ctoken_, _user, _to, balanceChange_) + ); } /// @dev Retrieve or deploy a bridged ERC20 token contract. diff --git a/packages/protocol/contracts/tokenvault/ERC721Vault.sol b/packages/protocol/contracts/tokenvault/ERC721Vault.sol index 941cffb4e09..449478b90a5 100644 --- a/packages/protocol/contracts/tokenvault/ERC721Vault.sol +++ b/packages/protocol/contracts/tokenvault/ERC721Vault.sol @@ -21,58 +21,63 @@ contract ERC721Vault is BaseNFTVault, IERC721Receiver { /// @notice Transfers ERC721 tokens to this vault and sends a message to the /// destination chain so the user can receive the same (bridged) tokens /// by invoking the message call. - /// @param op Option for sending the ERC721 token. - /// @return _message The constructed message. - function sendToken(BridgeTransferOp memory op) + /// @param _op Option for sending the ERC721 token. + /// @return message_ The constructed message. + function sendToken(BridgeTransferOp memory _op) external payable nonReentrant whenNotPaused - withValidOperation(op) - returns (IBridge.Message memory _message) + withValidOperation(_op) + returns (IBridge.Message memory message_) { - for (uint256 i; i < op.tokenIds.length; ++i) { - if (op.amounts[i] != 0) revert VAULT_INVALID_AMOUNT(); + for (uint256 i; i < _op.tokenIds.length; ++i) { + if (_op.amounts[i] != 0) revert VAULT_INVALID_AMOUNT(); } - if (!op.token.supportsInterface(ERC721_INTERFACE_ID)) { + if (!_op.token.supportsInterface(ERC721_INTERFACE_ID)) { revert VAULT_INTERFACE_NOT_SUPPORTED(); } - (bytes memory data, CanonicalNFT memory ctoken) = _handleMessage(msg.sender, op); + (bytes memory data, CanonicalNFT memory ctoken) = _handleMessage(msg.sender, _op); IBridge.Message memory message; - message.destChainId = op.destChainId; + message.destChainId = _op.destChainId; message.data = data; message.srcOwner = msg.sender; - message.destOwner = op.destOwner != address(0) ? op.destOwner : msg.sender; + message.destOwner = _op.destOwner != address(0) ? _op.destOwner : msg.sender; message.to = resolve(message.destChainId, name(), false); - message.gasLimit = op.gasLimit; - message.value = msg.value - op.fee; - message.fee = op.fee; - message.refundTo = op.refundTo; - message.memo = op.memo; + message.gasLimit = _op.gasLimit; + message.value = msg.value - _op.fee; + message.fee = _op.fee; + message.refundTo = _op.refundTo; + message.memo = _op.memo; bytes32 msgHash; - (msgHash, _message) = + (msgHash, message_) = IBridge(resolve("bridge", false)).sendMessage{ value: msg.value }(message); emit TokenSent({ msgHash: msgHash, - from: _message.srcOwner, - to: op.to, - destChainId: _message.destChainId, + from: message_.srcOwner, + to: _op.to, + destChainId: message_.destChainId, ctoken: ctoken.addr, - token: op.token, - tokenIds: op.tokenIds, - amounts: op.amounts + token: _op.token, + tokenIds: _op.tokenIds, + amounts: _op.amounts }); } /// @inheritdoc IMessageInvocable - function onMessageInvocation(bytes calldata data) external payable nonReentrant whenNotPaused { + function onMessageInvocation(bytes calldata _data) + external + payable + nonReentrant + whenNotPaused + { (CanonicalNFT memory ctoken, address from, address to, uint256[] memory tokenIds) = - abi.decode(data, (CanonicalNFT, address, address, uint256[])); + abi.decode(_data, (CanonicalNFT, address, address, uint256[])); // `onlyFromBridge` checked in checkProcessMessageContext IBridge.Context memory ctx = checkProcessMessageContext(); @@ -99,8 +104,8 @@ contract ERC721Vault is BaseNFTVault, IERC721Receiver { /// @inheritdoc IRecallableSender function onMessageRecalled( - IBridge.Message calldata message, - bytes32 msgHash + IBridge.Message calldata _message, + bytes32 _msgHash ) external payable @@ -111,17 +116,17 @@ contract ERC721Vault is BaseNFTVault, IERC721Receiver { // `onlyFromBridge` checked in checkRecallMessageContext checkRecallMessageContext(); - (bytes memory _data) = abi.decode(message.data[4:], (bytes)); + (bytes memory data) = abi.decode(_message.data[4:], (bytes)); (CanonicalNFT memory ctoken,,, uint256[] memory tokenIds) = - abi.decode(_data, (CanonicalNFT, address, address, uint256[])); + abi.decode(data, (CanonicalNFT, address, address, uint256[])); // Transfer the ETH and tokens back to the owner - address token = _transferTokens(ctoken, message.srcOwner, tokenIds); - message.srcOwner.sendEther(message.value); + address token = _transferTokens(ctoken, _message.srcOwner, tokenIds); + _message.srcOwner.sendEther(_message.value); emit TokenReleased({ - msgHash: msgHash, - from: message.srcOwner, + msgHash: _msgHash, + from: _message.srcOwner, ctoken: ctoken.addr, token: token, tokenIds: tokenIds, @@ -149,100 +154,101 @@ contract ERC721Vault is BaseNFTVault, IERC721Receiver { } function _transferTokens( - CanonicalNFT memory ctoken, - address to, - uint256[] memory tokenIds + CanonicalNFT memory _ctoken, + address _to, + uint256[] memory _tokenIds ) private - returns (address token) + returns (address token_) { - if (ctoken.chainId == block.chainid) { - token = ctoken.addr; - for (uint256 i; i < tokenIds.length; ++i) { - IERC721(token).safeTransferFrom({ from: address(this), to: to, tokenId: tokenIds[i] }); + if (_ctoken.chainId == block.chainid) { + token_ = _ctoken.addr; + for (uint256 i; i < _tokenIds.length; ++i) { + IERC721(token_).safeTransferFrom(address(this), _to, _tokenIds[i]); } } else { - token = _getOrDeployBridgedToken(ctoken); - for (uint256 i; i < tokenIds.length; ++i) { - BridgedERC721(token).mint(to, tokenIds[i]); + token_ = _getOrDeployBridgedToken(_ctoken); + for (uint256 i; i < _tokenIds.length; ++i) { + BridgedERC721(token_).mint(_to, _tokenIds[i]); } } } /// @dev Handles the message on the source chain and returns the encoded /// call on the destination call. - /// @param user The user's address. - /// @param op BridgeTransferOp data. - /// @return msgData Encoded message data. - /// @return ctoken The canonical token. + /// @param _user The user's address. + /// @param _op BridgeTransferOp data. + /// @return msgData_ Encoded message data. + /// @return ctoken_ The canonical token. function _handleMessage( - address user, - BridgeTransferOp memory op + address _user, + BridgeTransferOp memory _op ) private - returns (bytes memory msgData, CanonicalNFT memory ctoken) + returns (bytes memory msgData_, CanonicalNFT memory ctoken_) { unchecked { - if (bridgedToCanonical[op.token].addr != address(0)) { - ctoken = bridgedToCanonical[op.token]; - for (uint256 i; i < op.tokenIds.length; ++i) { - BridgedERC721(op.token).burn(user, op.tokenIds[i]); + if (bridgedToCanonical[_op.token].addr != address(0)) { + ctoken_ = bridgedToCanonical[_op.token]; + for (uint256 i; i < _op.tokenIds.length; ++i) { + BridgedERC721(_op.token).burn(_user, _op.tokenIds[i]); } } else { - ERC721Upgradeable t = ERC721Upgradeable(op.token); + ERC721Upgradeable t = ERC721Upgradeable(_op.token); - ctoken = CanonicalNFT({ + ctoken_ = CanonicalNFT({ chainId: uint64(block.chainid), - addr: op.token, + addr: _op.token, symbol: t.symbol(), name: t.name() }); - for (uint256 i; i < op.tokenIds.length; ++i) { - t.safeTransferFrom(user, address(this), op.tokenIds[i]); + for (uint256 i; i < _op.tokenIds.length; ++i) { + t.safeTransferFrom(_user, address(this), _op.tokenIds[i]); } } } - msgData = - abi.encodeCall(this.onMessageInvocation, abi.encode(ctoken, user, op.to, op.tokenIds)); + msgData_ = abi.encodeCall( + this.onMessageInvocation, abi.encode(ctoken_, _user, _op.to, _op.tokenIds) + ); } /// @dev Retrieve or deploy a bridged ERC721 token contract. - /// @param ctoken CanonicalNFT data. - /// @return btoken Address of the bridged token contract. - function _getOrDeployBridgedToken(CanonicalNFT memory ctoken) + /// @param _ctoken CanonicalNFT data. + /// @return btoken_ Address of the bridged token contract. + function _getOrDeployBridgedToken(CanonicalNFT memory _ctoken) private - returns (address btoken) + returns (address btoken_) { - btoken = canonicalToBridged[ctoken.chainId][ctoken.addr]; + btoken_ = canonicalToBridged[_ctoken.chainId][_ctoken.addr]; - if (btoken == address(0)) { - btoken = _deployBridgedToken(ctoken); + if (btoken_ == address(0)) { + btoken_ = _deployBridgedToken(_ctoken); } } /// @dev Deploy a new BridgedNFT contract and initialize it. /// This must be called before the first time a bridged token is sent to /// this chain. - /// @param ctoken CanonicalNFT data. - /// @return btoken Address of the deployed bridged token contract. - function _deployBridgedToken(CanonicalNFT memory ctoken) private returns (address btoken) { + /// @param _ctoken CanonicalNFT data. + /// @return btoken_ Address of the deployed bridged token contract. + function _deployBridgedToken(CanonicalNFT memory _ctoken) private returns (address btoken_) { bytes memory data = abi.encodeCall( BridgedERC721.init, - (owner(), addressManager, ctoken.addr, ctoken.chainId, ctoken.symbol, ctoken.name) + (owner(), addressManager, _ctoken.addr, _ctoken.chainId, _ctoken.symbol, _ctoken.name) ); - btoken = address(new ERC1967Proxy(resolve("bridged_erc721", false), data)); - bridgedToCanonical[btoken] = ctoken; - canonicalToBridged[ctoken.chainId][ctoken.addr] = btoken; + btoken_ = address(new ERC1967Proxy(resolve("bridged_erc721", false), data)); + bridgedToCanonical[btoken_] = _ctoken; + canonicalToBridged[_ctoken.chainId][_ctoken.addr] = btoken_; emit BridgedTokenDeployed({ - chainId: ctoken.chainId, - ctoken: ctoken.addr, - btoken: btoken, - ctokenSymbol: ctoken.symbol, - ctokenName: ctoken.name + chainId: _ctoken.chainId, + ctoken: _ctoken.addr, + btoken: btoken_, + ctokenSymbol: _ctoken.symbol, + ctokenName: _ctoken.name }); } } diff --git a/packages/protocol/contracts/tokenvault/IBridgedERC20.sol b/packages/protocol/contracts/tokenvault/IBridgedERC20.sol index af93b7c425d..98b13cedcbd 100644 --- a/packages/protocol/contracts/tokenvault/IBridgedERC20.sol +++ b/packages/protocol/contracts/tokenvault/IBridgedERC20.sol @@ -9,21 +9,21 @@ pragma solidity 0.8.24; /// @custom:security-contact security@taiko.xyz interface IBridgedERC20 { /// @notice Mints `amount` tokens and assigns them to the `account` address. - /// @param account The account to receive the minted tokens. - /// @param amount The amount of tokens to mint. - function mint(address account, uint256 amount) external; + /// @param _account The account to receive the minted tokens. + /// @param _amount The amount of tokens to mint. + function mint(address _account, uint256 _amount) external; /// @notice Burns `amount` tokens from the `from` address. - /// @param from The account from which the tokens will be burned. - /// @param amount The amount of tokens to burn. - function burn(address from, uint256 amount) external; + /// @param _from The account from which the tokens will be burned. + /// @param _amount The amount of tokens to burn. + function burn(address _from, uint256 _amount) external; /// @notice Start or stop migration to/from a specified contract. - /// @param addr The address migrating 'to' or 'from'. - /// @param inbound If false then signals migrating 'from', true if migrating 'into'. - function changeMigrationStatus(address addr, bool inbound) external; + /// @param _addr The address migrating 'to' or 'from'. + /// @param _inbound If false then signals migrating 'from', true if migrating 'into'. + function changeMigrationStatus(address _addr, bool _inbound) external; /// @notice Returns the owner. - /// @return address The address of the owner. + /// @return The address of the owner. function owner() external view returns (address); } diff --git a/packages/protocol/contracts/tokenvault/LibBridgedToken.sol b/packages/protocol/contracts/tokenvault/LibBridgedToken.sol index 61114c61e33..ad5944587a9 100644 --- a/packages/protocol/contracts/tokenvault/LibBridgedToken.sol +++ b/packages/protocol/contracts/tokenvault/LibBridgedToken.sol @@ -26,29 +26,36 @@ library LibBridgedToken { } function buildName( - string memory name, - uint256 srcChainId + string memory _name, + uint256 _srcChainId ) internal pure returns (string memory) { - return string.concat("Bridged ", name, unicode" (⭀", Strings.toString(srcChainId), ")"); + return string.concat("Bridged ", _name, unicode" (⭀", Strings.toString(_srcChainId), ")"); } - function buildSymbol(string memory symbol) internal pure returns (string memory) { - return string.concat(symbol, ".t"); + function buildSymbol(string memory _symbol) internal pure returns (string memory) { + return string.concat(_symbol, ".t"); } - function buildURI(address srcToken, uint256 srcChainId) internal pure returns (string memory) { + function buildURI( + address _srcToken, + uint256 _srcChainId + ) + internal + pure + returns (string memory) + { // Creates a base URI in the format specified by EIP-681: // https://eips.ethereum.org/EIPS/eip-681 return string( abi.encodePacked( "ethereum:", - Strings.toHexString(uint160(srcToken), 20), + Strings.toHexString(uint160(_srcToken), 20), "@", - Strings.toString(srcChainId), + Strings.toString(_srcChainId), "/tokenURI?uint256=" ) ); diff --git a/packages/protocol/contracts/tokenvault/adapters/USDCAdapter.sol b/packages/protocol/contracts/tokenvault/adapters/USDCAdapter.sol index e63c847f9ea..9a9c9fbc489 100644 --- a/packages/protocol/contracts/tokenvault/adapters/USDCAdapter.sol +++ b/packages/protocol/contracts/tokenvault/adapters/USDCAdapter.sol @@ -7,20 +7,20 @@ import "../BridgedERC20Base.sol"; /// @custom:security-contact security@taiko.xyz interface IUSDC { /// @notice Burns a specific amount of tokens. - /// @param amount The amount of token to be burned. - function burn(uint256 amount) external; + /// @param _amount The amount of token to be burned. + function burn(uint256 _amount) external; /// @notice Mints a specific amount of new tokens to an address. - /// @param to The address that will receive the minted tokens. - /// @param amount The amount of tokens to mint. - function mint(address to, uint256 amount) external; + /// @param _to The address that will receive the minted tokens. + /// @param _amount The amount of tokens to mint. + function mint(address _to, uint256 _amount) external; /// @notice Transfers tokens from one address to another. /// @param from The address which you want to send tokens from. - /// @param to The address which you want to transfer to. - /// @param value The amount of tokens to be transferred. - /// @return True if the transfer was successful, otherwise false. - function transferFrom(address from, address to, uint256 value) external returns (bool); + /// @param _to The address which you want to transfer to. + /// @param _amount The amount of tokens to be transferred. + /// @return true if the transfer was successful, otherwise false. + function transferFrom(address from, address _to, uint256 _amount) external returns (bool); } /// @title USDCAdapter @@ -40,12 +40,12 @@ contract USDCAdapter is BridgedERC20Base { usdc = _usdc; } - function _mintToken(address account, uint256 amount) internal override { - usdc.mint(account, amount); + function _mintToken(address _account, uint256 _amount) internal override { + usdc.mint(_account, _amount); } - function _burnToken(address from, uint256 amount) internal override { - usdc.transferFrom(from, address(this), amount); - usdc.burn(amount); + function _burnToken(address _from, uint256 _amount) internal override { + usdc.transferFrom(_from, address(this), _amount); + usdc.burn(_amount); } } diff --git a/packages/protocol/contracts/verifiers/GuardianVerifier.sol b/packages/protocol/contracts/verifiers/GuardianVerifier.sol index aaa5ea3277c..d8cba1800d3 100644 --- a/packages/protocol/contracts/verifiers/GuardianVerifier.sol +++ b/packages/protocol/contracts/verifiers/GuardianVerifier.sol @@ -21,14 +21,14 @@ contract GuardianVerifier is EssentialContract, IVerifier { /// @inheritdoc IVerifier function verifyProof( - Context calldata ctx, + Context calldata _ctx, TaikoData.Transition calldata, TaikoData.TierProof calldata ) external view { - if (ctx.msgSender != resolve("guardian_prover", false)) { + if (_ctx.msgSender != resolve("guardian_prover", false)) { revert PERMISSION_DENIED(); } } diff --git a/packages/protocol/contracts/verifiers/IVerifier.sol b/packages/protocol/contracts/verifiers/IVerifier.sol index 22ac6f47c8a..a3e0091fcd2 100644 --- a/packages/protocol/contracts/verifiers/IVerifier.sol +++ b/packages/protocol/contracts/verifiers/IVerifier.sol @@ -18,13 +18,13 @@ interface IVerifier { } /// @notice Verifies a proof. - /// @param ctx The context of the proof verification. - /// @param tran The transition to verify. - /// @param proof The proof to verify. + /// @param _ctx The context of the proof verification. + /// @param _tran The transition to verify. + /// @param _proof The proof to verify. function verifyProof( - Context calldata ctx, - TaikoData.Transition calldata tran, - TaikoData.TierProof calldata proof + Context calldata _ctx, + TaikoData.Transition calldata _tran, + TaikoData.TierProof calldata _proof ) external; } diff --git a/packages/protocol/contracts/verifiers/SgxVerifier.sol b/packages/protocol/contracts/verifiers/SgxVerifier.sol index bf238a4f680..8ea73fc0cbb 100644 --- a/packages/protocol/contracts/verifiers/SgxVerifier.sol +++ b/packages/protocol/contracts/verifiers/SgxVerifier.sol @@ -86,13 +86,13 @@ contract SgxVerifier is EssentialContract, IVerifier { /// @notice Adds trusted SGX instances to the registry. /// @param _instances The address array of trusted SGX instances. - /// @return ids The respective instanceId array per addresses. + /// @return The respective instanceId array per addresses. function addInstances(address[] calldata _instances) external onlyOwner - returns (uint256[] memory ids) + returns (uint256[] memory) { - ids = _addInstances(_instances, true); + return _addInstances(_instances, true); } /// @notice Deletes SGX instances from the registry. @@ -113,9 +113,9 @@ contract SgxVerifier is EssentialContract, IVerifier { } /// @notice Adds an SGX instance after the attestation is verified - /// @param attestation The parsed attestation quote. - /// @return id The respective instanceId - function registerInstance(V3Struct.ParsedV3QuoteStruct calldata attestation) + /// @param _attestation The parsed attestation quote. + /// @return The respective instanceId + function registerInstance(V3Struct.ParsedV3QuoteStruct calldata _attestation) external returns (uint256) { @@ -125,58 +125,58 @@ contract SgxVerifier is EssentialContract, IVerifier { revert SGX_RA_NOT_SUPPORTED(); } - (bool verified,) = IAttestation(automataDcapAttestation).verifyParsedQuote(attestation); + (bool verified,) = IAttestation(automataDcapAttestation).verifyParsedQuote(_attestation); if (!verified) revert SGX_INVALID_ATTESTATION(); address[] memory _address = new address[](1); - _address[0] = address(bytes20(attestation.localEnclaveReport.reportData)); + _address[0] = address(bytes20(_attestation.localEnclaveReport.reportData)); return _addInstances(_address, false)[0]; } /// @inheritdoc IVerifier function verifyProof( - Context calldata ctx, - TaikoData.Transition calldata tran, - TaikoData.TierProof calldata proof + Context calldata _ctx, + TaikoData.Transition calldata _tran, + TaikoData.TierProof calldata _proof ) external onlyFromNamed("taiko") { // Do not run proof verification to contest an existing proof - if (ctx.isContesting) return; + if (_ctx.isContesting) return; // Size is: 89 bytes // 4 bytes + 20 bytes + 65 bytes (signature) = 89 - if (proof.data.length != 89) revert SGX_INVALID_PROOF(); + if (_proof.data.length != 89) revert SGX_INVALID_PROOF(); - uint32 id = uint32(bytes4(Bytes.slice(proof.data, 0, 4))); - address newInstance = address(bytes20(Bytes.slice(proof.data, 4, 20))); - bytes memory signature = Bytes.slice(proof.data, 24); + uint32 id = uint32(bytes4(Bytes.slice(_proof.data, 0, 4))); + address newInstance = address(bytes20(Bytes.slice(_proof.data, 4, 20))); + bytes memory signature = Bytes.slice(_proof.data, 24); address oldInstance = - ECDSA.recover(getSignedHash(tran, newInstance, ctx.prover, ctx.metaHash), signature); + ECDSA.recover(getSignedHash(_tran, newInstance, _ctx.prover, _ctx.metaHash), signature); if (!_isInstanceValid(id, oldInstance)) revert SGX_INVALID_INSTANCE(); _replaceInstance(id, oldInstance, newInstance); } /// @notice Gets the signed hash for the proof verification. - /// @param tran The transition to verify. - /// @param newInstance The new instance address. - /// @param prover The prover address. - /// @param metaHash The meta hash. - /// @return signedHash The signed hash. + /// @param _tran The transition to verify. + /// @param _newInstance The new instance address. + /// @param _prover The prover address. + /// @param _metaHash The meta hash. + /// @return The signed hash. function getSignedHash( - TaikoData.Transition memory tran, - address newInstance, - address prover, - bytes32 metaHash + TaikoData.Transition memory _tran, + address _newInstance, + address _prover, + bytes32 _metaHash ) public view - returns (bytes32 signedHash) + returns (bytes32) { address taikoL1 = resolve("taiko", false); return keccak256( @@ -184,10 +184,10 @@ contract SgxVerifier is EssentialContract, IVerifier { "VERIFY_PROOF", ITaikoL1(taikoL1).getConfig().chainId, address(this), - tran, - newInstance, - prover, - metaHash + _tran, + _newInstance, + _prover, + _metaHash ) ); } diff --git a/packages/protocol/test/L2/Lib1559Math.t.sol b/packages/protocol/test/L2/Lib1559Math.t.sol index 9689d37e675..a4edccf67ad 100644 --- a/packages/protocol/test/L2/Lib1559Math.t.sol +++ b/packages/protocol/test/L2/Lib1559Math.t.sol @@ -13,24 +13,24 @@ contract TestLib1559Math is TaikoTest { // The expected values are calculated in eip1559_util.py _assertAmostEq( 999_999_916, - Lib1559Math.basefee({ gasExcess: 49_954_623_777, adjustmentFactor: adjustmentFactor }) + Lib1559Math.basefee({ _gasExcess: 49_954_623_777, _adjustmentFactor: adjustmentFactor }) ); _assertAmostEq( 48_246_703_821_869_050_543_408_253_349_256_099_602_613_005_189_120, Lib1559Math.basefee({ - gasExcess: LibFixedPointMath.MAX_EXP_INPUT * adjustmentFactor + _gasExcess: LibFixedPointMath.MAX_EXP_INPUT * adjustmentFactor / LibFixedPointMath.SCALING_FACTOR, - adjustmentFactor: adjustmentFactor + _adjustmentFactor: adjustmentFactor }) ); } // Assert the different between two number is smaller than 1/1000000 - function _assertAmostEq(uint256 a, uint256 b) private { - uint256 min = a.min(b); - uint256 max = a.max(b); + function _assertAmostEq(uint256 _a, uint256 _b) private { + uint256 min = _a.min(_b); + uint256 max = _a.max(_b); assertTrue(max > 0 && ((max - min) * 1_000_000) / max <= 1); - console2.log(a, " <> ", b); + console2.log(_a, " <> ", _b); } } diff --git a/packages/protocol/test/automata-attestation/utils/DcapTestUtils.t.sol b/packages/protocol/test/automata-attestation/utils/DcapTestUtils.t.sol index fd53b999d65..a859d73a30e 100644 --- a/packages/protocol/test/automata-attestation/utils/DcapTestUtils.t.sol +++ b/packages/protocol/test/automata-attestation/utils/DcapTestUtils.t.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MIT -pragma solidity ^0.8.13; +pragma solidity 0.8.24; import { TCBInfoStruct } from "../../../contracts/automata-attestation/lib/TCBInfoStruct.sol"; import { EnclaveIdStruct } from "../../../contracts/automata-attestation/lib/EnclaveIdStruct.sol"; diff --git a/packages/protocol/test/automata-attestation/utils/V3QuoteParseUtils.t.sol b/packages/protocol/test/automata-attestation/utils/V3QuoteParseUtils.t.sol index 1e01cda5c6c..472a4421a76 100644 --- a/packages/protocol/test/automata-attestation/utils/V3QuoteParseUtils.t.sol +++ b/packages/protocol/test/automata-attestation/utils/V3QuoteParseUtils.t.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MIT -pragma solidity ^0.8.13; +pragma solidity 0.8.24; import { V3Struct } from "../../../contracts/automata-attestation/lib/QuoteV3Auth/V3Struct.sol"; import { V3Parser } from "../../../contracts/automata-attestation/lib/QuoteV3Auth/V3Parser.sol"; diff --git a/packages/protocol/test/bridge/Bridge.t.sol b/packages/protocol/test/bridge/Bridge.t.sol index 05209e8f1a0..bd235a09452 100644 --- a/packages/protocol/test/bridge/Bridge.t.sol +++ b/packages/protocol/test/bridge/Bridge.t.sol @@ -144,9 +144,9 @@ contract BridgeTest is TaikoTest { vm.prank(Bob, Bob); destChainBridge.processMessage(message, proof); - Bridge.Status status = destChainBridge.messageStatus(msgHash); + IBridge.Status status = destChainBridge.messageStatus(msgHash); - assertEq(status == Bridge.Status.DONE, true); + assertEq(status == IBridge.Status.DONE, true); // Alice has 100 ether + 1000 wei balance, because we did not use the // 'sendMessage' // since we mocking the proof, so therefore the 1000 wei @@ -183,9 +183,9 @@ contract BridgeTest is TaikoTest { vm.prank(Bob, Bob); dest2StepBridge.processMessage(message, proof); - Bridge.Status status = dest2StepBridge.messageStatus(msgHash); + IBridge.Status status = dest2StepBridge.messageStatus(msgHash); // Still new ! Because of the delay, no processing happened - assertEq(status == Bridge.Status.NEW, true); + assertEq(status == IBridge.Status.NEW, true); // Alice has 100 ether assertEq(Alice.balance, 100_000_000_000_000_000_000); @@ -240,9 +240,9 @@ contract BridgeTest is TaikoTest { vm.prank(Bob, Bob); dest2StepBridge.processMessage(message, proof); - Bridge.Status status = dest2StepBridge.messageStatus(msgHash); + IBridge.Status status = dest2StepBridge.messageStatus(msgHash); // Still new ! Because of the delay, no processing happened - assertEq(status == Bridge.Status.NEW, true); + assertEq(status == IBridge.Status.NEW, true); // Alice has 100 ether assertEq(Alice.balance, 100_000_000_000_000_000_000); @@ -292,9 +292,9 @@ contract BridgeTest is TaikoTest { vm.prank(Bob, Bob); destChainBridge.processMessage(message, proof); - Bridge.Status status = destChainBridge.messageStatus(msgHash); + IBridge.Status status = destChainBridge.messageStatus(msgHash); - assertEq(status == Bridge.Status.DONE, true); + assertEq(status == IBridge.Status.DONE, true); // Bob (relayer) and goodContract has 1000 wei balance assertEq(address(goodReceiver).balance, 1000); @@ -330,9 +330,9 @@ contract BridgeTest is TaikoTest { vm.prank(Bob, Bob); destChainBridge.processMessage(message, proof); - Bridge.Status status = destChainBridge.messageStatus(msgHash); + IBridge.Status status = destChainBridge.messageStatus(msgHash); - assertEq(status == Bridge.Status.DONE, true); + assertEq(status == IBridge.Status.DONE, true); // Carol and goodContract has 500 wei balance assertEq(address(goodReceiver).balance, 500); @@ -560,9 +560,9 @@ contract BridgeTest is TaikoTest { destChainBridge.processMessage(message, proof); - Bridge.Status status = destChainBridge.messageStatus(msgHash); + IBridge.Status status = destChainBridge.messageStatus(msgHash); - assertEq(status == Bridge.Status.DONE, true); + assertEq(status == IBridge.Status.DONE, true); } // test with a known good merkle proof / message since we cant generate @@ -580,21 +580,21 @@ contract BridgeTest is TaikoTest { destChainBridge.processMessage(message, proof); - Bridge.Status status = destChainBridge.messageStatus(msgHash); + IBridge.Status status = destChainBridge.messageStatus(msgHash); - assertEq(status == Bridge.Status.RETRIABLE, true); + assertEq(status == IBridge.Status.RETRIABLE, true); vm.stopPrank(); vm.prank(message.destOwner); destChainBridge.retryMessage(message, false); - Bridge.Status postRetryStatus = destChainBridge.messageStatus(msgHash); - assertEq(postRetryStatus == Bridge.Status.RETRIABLE, true); + IBridge.Status postRetryStatus = destChainBridge.messageStatus(msgHash); + assertEq(postRetryStatus == IBridge.Status.RETRIABLE, true); vm.prank(message.destOwner); destChainBridge.retryMessage(message, true); postRetryStatus = destChainBridge.messageStatus(msgHash); - assertEq(postRetryStatus == Bridge.Status.FAILED, true); + assertEq(postRetryStatus == IBridge.Status.FAILED, true); } function retry_message_reverts_when_status_non_retriable() public { diff --git a/packages/protocol/test/signal/SignalService.t.sol b/packages/protocol/test/signal/SignalService.t.sol index 8e8a75e5044..02c291dc4e3 100644 --- a/packages/protocol/test/signal/SignalService.t.sol +++ b/packages/protocol/test/signal/SignalService.t.sol @@ -115,19 +115,19 @@ contract TestSignalService is TaikoTest { // app being address(0) will revert vm.expectRevert(SignalService.SS_INVALID_SENDER.selector); signalService.proveSignalReceived({ - chainId: 1, - app: address(0), - signal: randBytes32(), - proof: abi.encode(proofs) + _chainId: 1, + _app: address(0), + _signal: randBytes32(), + _proof: abi.encode(proofs) }); // signal being 0 will revert vm.expectRevert(SignalService.SS_INVALID_VALUE.selector); signalService.proveSignalReceived({ - chainId: uint64(block.chainid), - app: randAddress(), - signal: 0, - proof: abi.encode(proofs) + _chainId: uint64(block.chainid), + _app: randAddress(), + _signal: 0, + _proof: abi.encode(proofs) }); } @@ -135,10 +135,10 @@ contract TestSignalService is TaikoTest { // "undecodable proof" is not decodeable into SignalService.HopProof[] memory vm.expectRevert(); signalService.proveSignalReceived({ - chainId: 0, - app: randAddress(), - signal: randBytes32(), - proof: "undecodable proof" + _chainId: 0, + _app: randAddress(), + _signal: randBytes32(), + _proof: "undecodable proof" }); } @@ -161,10 +161,10 @@ contract TestSignalService is TaikoTest { ) ); signalService.proveSignalReceived({ - chainId: srcChainId, - app: randAddress(), - signal: randBytes32(), - proof: abi.encode(proofs) + _chainId: srcChainId, + _app: randAddress(), + _signal: randBytes32(), + _proof: abi.encode(proofs) }); } @@ -179,10 +179,10 @@ contract TestSignalService is TaikoTest { vm.expectRevert(SignalService.SS_EMPTY_PROOF.selector); signalService.proveSignalReceived({ - chainId: srcChainId, - app: randAddress(), - signal: randBytes32(), - proof: abi.encode(proofs) + _chainId: srcChainId, + _app: randAddress(), + _signal: randBytes32(), + _proof: abi.encode(proofs) }); } @@ -200,10 +200,10 @@ contract TestSignalService is TaikoTest { vm.expectRevert(SignalService.SS_INVALID_LAST_HOP_CHAINID.selector); signalService.proveSignalReceived({ - chainId: srcChainId, - app: randAddress(), - signal: randBytes32(), - proof: abi.encode(proofs) + _chainId: srcChainId, + _app: randAddress(), + _signal: randBytes32(), + _proof: abi.encode(proofs) }); } @@ -221,10 +221,10 @@ contract TestSignalService is TaikoTest { vm.expectRevert(SignalService.SS_INVALID_MID_HOP_CHAINID.selector); signalService.proveSignalReceived({ - chainId: srcChainId, - app: randAddress(), - signal: randBytes32(), - proof: abi.encode(proofs) + _chainId: srcChainId, + _app: randAddress(), + _signal: randBytes32(), + _proof: abi.encode(proofs) }); } @@ -249,10 +249,10 @@ contract TestSignalService is TaikoTest { ); signalService.proveSignalReceived({ - chainId: srcChainId, - app: randAddress(), - signal: randBytes32(), - proof: abi.encode(proofs) + _chainId: srcChainId, + _app: randAddress(), + _signal: randBytes32(), + _proof: abi.encode(proofs) }); } @@ -273,10 +273,10 @@ contract TestSignalService is TaikoTest { vm.expectRevert(SignalService.SS_SIGNAL_NOT_FOUND.selector); signalService.proveSignalReceived({ - chainId: srcChainId, - app: randAddress(), - signal: randBytes32(), - proof: abi.encode(proofs) + _chainId: srcChainId, + _app: randAddress(), + _signal: randBytes32(), + _proof: abi.encode(proofs) }); // the proof is a full proof @@ -284,10 +284,10 @@ contract TestSignalService is TaikoTest { vm.expectRevert(SignalService.SS_SIGNAL_NOT_FOUND.selector); signalService.proveSignalReceived({ - chainId: srcChainId, - app: randAddress(), - signal: randBytes32(), - proof: abi.encode(proofs) + _chainId: srcChainId, + _app: randAddress(), + _signal: randBytes32(), + _proof: abi.encode(proofs) }); } @@ -309,10 +309,10 @@ contract TestSignalService is TaikoTest { vm.expectRevert(SignalService.SS_SIGNAL_NOT_FOUND.selector); signalService.proveSignalReceived({ - chainId: srcChainId, - app: randAddress(), - signal: randBytes32(), - proof: abi.encode(proofs) + _chainId: srcChainId, + _app: randAddress(), + _signal: randBytes32(), + _proof: abi.encode(proofs) }); // relay the signal root @@ -321,10 +321,10 @@ contract TestSignalService is TaikoTest { srcChainId, LibSignals.SIGNAL_ROOT, proofs[0].blockId, proofs[0].rootHash ); signalService.proveSignalReceived({ - chainId: srcChainId, - app: randAddress(), - signal: randBytes32(), - proof: abi.encode(proofs) + _chainId: srcChainId, + _app: randAddress(), + _signal: randBytes32(), + _proof: abi.encode(proofs) }); vm.prank(Alice); @@ -355,10 +355,10 @@ contract TestSignalService is TaikoTest { vm.expectRevert(SignalService.SS_SIGNAL_NOT_FOUND.selector); signalService.proveSignalReceived({ - chainId: srcChainId, - app: randAddress(), - signal: randBytes32(), - proof: abi.encode(proofs) + _chainId: srcChainId, + _app: randAddress(), + _signal: randBytes32(), + _proof: abi.encode(proofs) }); // relay the state root @@ -369,10 +369,10 @@ contract TestSignalService is TaikoTest { // Should not revert signalService.proveSignalReceived({ - chainId: srcChainId, - app: randAddress(), - signal: randBytes32(), - proof: abi.encode(proofs) + _chainId: srcChainId, + _app: randAddress(), + _signal: randBytes32(), + _proof: abi.encode(proofs) }); assertEq( @@ -421,10 +421,10 @@ contract TestSignalService is TaikoTest { ) ); signalService.proveSignalReceived({ - chainId: srcChainId, - app: randAddress(), - signal: randBytes32(), - proof: abi.encode(proofs) + _chainId: srcChainId, + _app: randAddress(), + _signal: randBytes32(), + _proof: abi.encode(proofs) }); // Add two trusted hop relayers @@ -435,10 +435,10 @@ contract TestSignalService is TaikoTest { vm.expectRevert(SignalService.SS_SIGNAL_NOT_FOUND.selector); signalService.proveSignalReceived({ - chainId: srcChainId, - app: randAddress(), - signal: randBytes32(), - proof: abi.encode(proofs) + _chainId: srcChainId, + _app: randAddress(), + _signal: randBytes32(), + _proof: abi.encode(proofs) }); vm.prank(taiko); @@ -447,10 +447,10 @@ contract TestSignalService is TaikoTest { ); signalService.proveSignalReceived({ - chainId: srcChainId, - app: randAddress(), - signal: randBytes32(), - proof: abi.encode(proofs) + _chainId: srcChainId, + _app: randAddress(), + _signal: randBytes32(), + _proof: abi.encode(proofs) }); } @@ -466,7 +466,7 @@ contract TestSignalService is TaikoTest { proofs[0].rootHash = randBytes32(); proofs[0].accountProof = new bytes[](1); proofs[0].storageProof = new bytes[](10); - proofs[0].cacheOption = SignalService.CacheOption.CACHE_NOTHING; + proofs[0].cacheOption = ISignalService.CacheOption.CACHE_NOTHING; // hop 2: full merkle proof, CACHE_STATE_ROOT proofs[1].chainId = nextChainId++; @@ -474,7 +474,7 @@ contract TestSignalService is TaikoTest { proofs[1].rootHash = randBytes32(); proofs[1].accountProof = new bytes[](1); proofs[1].storageProof = new bytes[](10); - proofs[1].cacheOption = SignalService.CacheOption.CACHE_STATE_ROOT; + proofs[1].cacheOption = ISignalService.CacheOption.CACHE_STATE_ROOT; // hop 3: full merkle proof, CACHE_SIGNAL_ROOT proofs[2].chainId = nextChainId++; @@ -482,7 +482,7 @@ contract TestSignalService is TaikoTest { proofs[2].rootHash = randBytes32(); proofs[2].accountProof = new bytes[](1); proofs[2].storageProof = new bytes[](10); - proofs[2].cacheOption = SignalService.CacheOption.CACHE_SIGNAL_ROOT; + proofs[2].cacheOption = ISignalService.CacheOption.CACHE_SIGNAL_ROOT; // hop 4: full merkle proof, CACHE_BOTH proofs[3].chainId = nextChainId++; @@ -490,7 +490,7 @@ contract TestSignalService is TaikoTest { proofs[3].rootHash = randBytes32(); proofs[3].accountProof = new bytes[](1); proofs[3].storageProof = new bytes[](10); - proofs[3].cacheOption = SignalService.CacheOption.CACHE_BOTH; + proofs[3].cacheOption = ISignalService.CacheOption.CACHE_BOTH; // hop 5: storage merkle proof, CACHE_NOTHING proofs[4].chainId = nextChainId++; @@ -498,7 +498,7 @@ contract TestSignalService is TaikoTest { proofs[4].rootHash = randBytes32(); proofs[4].accountProof = new bytes[](0); proofs[4].storageProof = new bytes[](10); - proofs[4].cacheOption = SignalService.CacheOption.CACHE_NOTHING; + proofs[4].cacheOption = ISignalService.CacheOption.CACHE_NOTHING; // hop 6: storage merkle proof, CACHE_STATE_ROOT proofs[5].chainId = nextChainId++; @@ -506,7 +506,7 @@ contract TestSignalService is TaikoTest { proofs[5].rootHash = randBytes32(); proofs[5].accountProof = new bytes[](0); proofs[5].storageProof = new bytes[](10); - proofs[5].cacheOption = SignalService.CacheOption.CACHE_STATE_ROOT; + proofs[5].cacheOption = ISignalService.CacheOption.CACHE_STATE_ROOT; // hop 7: storage merkle proof, CACHE_SIGNAL_ROOT proofs[6].chainId = nextChainId++; @@ -514,7 +514,7 @@ contract TestSignalService is TaikoTest { proofs[6].rootHash = randBytes32(); proofs[6].accountProof = new bytes[](0); proofs[6].storageProof = new bytes[](10); - proofs[6].cacheOption = SignalService.CacheOption.CACHE_SIGNAL_ROOT; + proofs[6].cacheOption = ISignalService.CacheOption.CACHE_SIGNAL_ROOT; // hop 8: storage merkle proof, CACHE_BOTH proofs[7].chainId = nextChainId++; @@ -522,7 +522,7 @@ contract TestSignalService is TaikoTest { proofs[7].rootHash = randBytes32(); proofs[7].accountProof = new bytes[](0); proofs[7].storageProof = new bytes[](10); - proofs[7].cacheOption = SignalService.CacheOption.CACHE_BOTH; + proofs[7].cacheOption = ISignalService.CacheOption.CACHE_BOTH; // last hop, 9: full merkle proof, CACHE_BOTH proofs[8].chainId = uint64(block.chainid); @@ -530,7 +530,7 @@ contract TestSignalService is TaikoTest { proofs[8].rootHash = randBytes32(); proofs[8].accountProof = new bytes[](1); proofs[8].storageProof = new bytes[](10); - proofs[8].cacheOption = SignalService.CacheOption.CACHE_BOTH; + proofs[8].cacheOption = ISignalService.CacheOption.CACHE_BOTH; // Add two trusted hop relayers vm.startPrank(Alice); @@ -548,10 +548,10 @@ contract TestSignalService is TaikoTest { ); signalService.proveSignalReceived({ - chainId: srcChainId, - app: randAddress(), - signal: randBytes32(), - proof: abi.encode(proofs) + _chainId: srcChainId, + _app: randAddress(), + _signal: randBytes32(), + _proof: abi.encode(proofs) }); // hop 1: full merkle proof, CACHE_NOTHING diff --git a/packages/protocol/utils/generate_genesis/taikoL2.ts b/packages/protocol/utils/generate_genesis/taikoL2.ts index b1d1c1cc3ad..c0fda6f3b04 100644 --- a/packages/protocol/utils/generate_genesis/taikoL2.ts +++ b/packages/protocol/utils/generate_genesis/taikoL2.ts @@ -240,7 +240,7 @@ async function generateContractConfigs( // Ownable2Upgradeable _owner: ownerSecurityCouncil, // AddressManager - addresses: { + __addresses: { [chainId]: { [ethers.utils.hexlify( ethers.utils.toUtf8Bytes("bridge"), @@ -296,8 +296,8 @@ async function generateContractConfigs( _initialized: 1, _initializing: false, // ReentrancyGuardUpgradeable - _reentry: 1, // _FALSE - _paused: 1, // _FALSE + __reentry: 1, // _FALSE + __paused: 1, // _FALSE // Ownable2Upgradeable _owner: ownerSecurityCouncil, // AddressResolver @@ -331,8 +331,8 @@ async function generateContractConfigs( _initialized: 1, _initializing: false, // ReentrancyGuardUpgradeable - _reentry: 1, // _FALSE - _paused: 1, // _FALSE + __reentry: 1, // _FALSE + __paused: 1, // _FALSE // Ownable2Upgradeable _owner: ownerSecurityCouncil, // AddressResolver @@ -366,8 +366,8 @@ async function generateContractConfigs( _initialized: 1, _initializing: false, // ReentrancyGuardUpgradeable - _reentry: 1, // _FALSE - _paused: 1, // _FALSE + __reentry: 1, // _FALSE + __paused: 1, // _FALSE // Ownable2Upgradeable _owner: ownerSecurityCouncil, // AddressResolver @@ -401,8 +401,8 @@ async function generateContractConfigs( _initialized: 1, _initializing: false, // ReentrancyGuardUpgradeable - _reentry: 1, // _FALSE - _paused: 1, // _FALSE + __reentry: 1, // _FALSE + __paused: 1, // _FALSE // Ownable2Upgradeable _owner: ownerSecurityCouncil, // AddressResolver @@ -460,8 +460,8 @@ async function generateContractConfigs( _initialized: 1, _initializing: false, // ReentrancyGuardUpgradeable - _reentry: 1, // _FALSE - _paused: 1, // _FALSE + __reentry: 1, // _FALSE + __paused: 1, // _FALSE // Ownable2Upgradeable _owner: ownerSecurityCouncil, // AddressResolver @@ -545,7 +545,7 @@ async function generateContractConfigs( // Ownable2Upgradeable _owner: ownerSecurityCouncil, // AddressManager - addresses: { + __addresses: { [chainId]: { [ethers.utils.hexlify( ethers.utils.toUtf8Bytes("taiko"),