Source Code
Overview
ETH Balance
0 ETH
More Info
ContractCreator
Multichain Info
N/A
View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Loading...
Loading
Contract Name:
ValidatorManager
Compiler Version
v0.8.15+commit.e14f2714
Optimization Enabled:
Yes with 10000 runs
Other Settings:
london EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; import { Atan2 } from "../libraries/Atan2.sol"; import { BalancedWeightTree } from "../libraries/BalancedWeightTree.sol"; import { Constants } from "../libraries/Constants.sol"; import { Types } from "../libraries/Types.sol"; import { Uint128Math } from "../libraries/Uint128Math.sol"; import { ISemver } from "../universal/ISemver.sol"; import { AssetManager } from "./AssetManager.sol"; import { IValidatorManager } from "./interfaces/IValidatorManager.sol"; import { L2OutputOracle } from "./L2OutputOracle.sol"; /** * @custom:proxied * @title ValidatorManager * @notice The ValidatorManager manages validator set and determines the next validator who can * submit the checkpoint output to L2OutputOracle. */ contract ValidatorManager is ISemver, IValidatorManager { using BalancedWeightTree for BalancedWeightTree.Tree; using Uint128Math for uint128; using Math for uint256; /** * @notice The denominator for the commission rate. */ uint128 public constant COMMISSION_RATE_DENOM = 100; /** * @notice The numerator for the boosted reward. */ uint128 public constant BOOSTED_REWARD_NUMERATOR = 40; /** * @notice The denominator for the boosted reward. */ uint128 public constant BOOSTED_REWARD_DENOM = 100; /** * @notice Address of the L2OutputOracle contract. Can be updated via upgrade. */ L2OutputOracle public immutable L2_ORACLE; /** * @notice The address of AssetManager contract. Can be updated via upgrade. */ AssetManager public immutable ASSET_MANAGER; /** * @notice The address of the trusted validator. */ address public immutable TRUSTED_VALIDATOR; /** * @notice Minimum amount to register as a validator. It should be equal or more than * ASSET_MANAGER.BOND_AMOUNT. */ uint128 public immutable MIN_REGISTER_AMOUNT; /** * @notice Minimum amount to activate a validator and add it to the validator tree. * Note that only the active validators can submit outputs. */ uint128 public immutable MIN_ACTIVATE_AMOUNT; /** * @notice The delay to finalize the commission rate change of the validator (in seconds). */ uint128 public immutable COMMISSION_CHANGE_DELAY_SECONDS; /** * @notice The duration of a submission round for one output (in seconds). * Note that there are two submission rounds for an output: PRIORITY ROUND and PUBLIC * ROUND. */ uint128 public immutable ROUND_DURATION_SECONDS; /** * @notice The minimum duration to get out of jail in output non-submissions penalty (in seconds). */ uint128 public immutable SOFT_JAIL_PERIOD_SECONDS; /** * @notice The maximum duration to get out of jail in slashing penalty (in seconds). */ uint128 public immutable HARD_JAIL_PERIOD_SECONDS; /** * @notice Maximum allowed number of output non-submissions in priority round before the * validator goes to jail. */ uint128 public immutable JAIL_THRESHOLD; /** * @notice The max number of outputs to be finalized at once when distributing rewards. */ uint128 public immutable MAX_OUTPUT_FINALIZATIONS; /** * @notice Amount of base reward for the validator. */ uint128 public immutable BASE_REWARD; /** * @notice Address of the next validator with priority for submitting output. */ address internal _nextPriorityValidator; /** * @notice Weighted tree to store and calculate the probability to be selected as an output submitter. */ BalancedWeightTree.Tree internal _validatorTree; /** * @notice A mapping of the validator to the validator information. */ mapping(address => Validator) internal _validatorInfo; /** * @notice A mapping of the jailed validator to the jail expiration timestamp. */ mapping(address => uint128) internal _jail; /** * @notice A mapping of output index challenged successfully to pending challenge rewards. */ mapping(uint256 => uint128) internal _pendingChallengeReward; /** * @notice A modifier that only allows L2OutputOracle contract to call. */ modifier onlyL2OutputOracle() { if (msg.sender != address(L2_ORACLE)) revert NotAllowedCaller(); _; } /** * @notice A modifier that only allows Colosseum contract to call. */ modifier onlyColosseum() { if (msg.sender != L2_ORACLE.COLOSSEUM()) revert NotAllowedCaller(); _; } /** * @notice A modifier that only allows AssetManager contract to call. */ modifier onlyAssetManager() { if (msg.sender != address(ASSET_MANAGER)) revert NotAllowedCaller(); _; } /** * @notice Semantic version. * @custom:semver 1.0.0 */ string public constant version = "1.0.0"; /** * @notice Constructs the ValidatorManager contract. * * @param _constructorParams The constructor parameters. */ constructor(ConstructorParams memory _constructorParams) { if (_constructorParams._minRegisterAmount > _constructorParams._minActivateAmount) revert InvalidConstructorParams(); L2_ORACLE = _constructorParams._l2Oracle; ASSET_MANAGER = _constructorParams._assetManager; TRUSTED_VALIDATOR = _constructorParams._trustedValidator; MIN_REGISTER_AMOUNT = _constructorParams._minRegisterAmount; MIN_ACTIVATE_AMOUNT = _constructorParams._minActivateAmount; COMMISSION_CHANGE_DELAY_SECONDS = _constructorParams._commissionChangeDelaySeconds; // Note that this value MUST be (SUBMISSION_INTERVAL * L2_BLOCK_TIME) / 2. ROUND_DURATION_SECONDS = _constructorParams._roundDurationSeconds; SOFT_JAIL_PERIOD_SECONDS = _constructorParams._softJailPeriodSeconds; HARD_JAIL_PERIOD_SECONDS = _constructorParams._hardJailPeriodSeconds; JAIL_THRESHOLD = _constructorParams._jailThreshold; MAX_OUTPUT_FINALIZATIONS = _constructorParams._maxOutputFinalizations; BASE_REWARD = _constructorParams._baseReward; } /** * @inheritdoc IValidatorManager */ function registerValidator( uint128 assets, uint8 commissionRate, address withdrawAccount ) external { if (msg.sender.code.length > 0 || msg.sender != tx.origin) revert NotAllowedCaller(); if (getStatus(msg.sender) != ValidatorStatus.NONE) revert ImproperValidatorStatus(); if (assets < MIN_REGISTER_AMOUNT) revert InsufficientAsset(); if (commissionRate > COMMISSION_RATE_DENOM) revert MaxCommissionRateExceeded(); Validator storage validatorInfo = _validatorInfo[msg.sender]; validatorInfo.isInitiated = true; validatorInfo.commissionRate = commissionRate; ASSET_MANAGER.depositToRegister(msg.sender, assets, withdrawAccount); bool ready = assets >= MIN_ACTIVATE_AMOUNT; if (ready) { _activateValidator(msg.sender); } emit ValidatorRegistered(msg.sender, ready, commissionRate, assets); } /** * @inheritdoc IValidatorManager */ function activateValidator() external { if (getStatus(msg.sender) != ValidatorStatus.READY || inJail(msg.sender)) revert ImproperValidatorStatus(); _activateValidator(msg.sender); } /** * @inheritdoc IValidatorManager */ function tryActivateValidator(address validator) external onlyAssetManager { if (getStatus(validator) == ValidatorStatus.READY && !inJail(validator)) _activateValidator(validator); } /** * @inheritdoc IValidatorManager */ function afterSubmitL2Output(uint256 outputIndex) external onlyL2OutputOracle { _distributeReward(); // Bond validator KRO to reserve slashing amount. address submitter = L2_ORACLE.getSubmitter(outputIndex); ASSET_MANAGER.bondValidatorKro(submitter); if (submitter == _nextPriorityValidator) { _resetNoSubmissionCount(submitter); } else { _tryJail(); } // Select the next priority validator. _updatePriorityValidator(); } /** * @inheritdoc IValidatorManager */ function initCommissionChange(uint8 newCommissionRate) external { if (getStatus(msg.sender) < ValidatorStatus.REGISTERED || inJail(msg.sender)) revert ImproperValidatorStatus(); if (newCommissionRate > COMMISSION_RATE_DENOM) revert MaxCommissionRateExceeded(); Validator storage validatorInfo = _validatorInfo[msg.sender]; uint8 oldCommissionRate = validatorInfo.commissionRate; if (newCommissionRate == oldCommissionRate) revert SameCommissionRate(); validatorInfo.pendingCommissionRate = newCommissionRate; validatorInfo.commissionChangeInitiatedAt = uint128(block.timestamp); emit ValidatorCommissionChangeInitiated(msg.sender, oldCommissionRate, newCommissionRate); } /** * @inheritdoc IValidatorManager */ function finalizeCommissionChange() external { if (getStatus(msg.sender) < ValidatorStatus.REGISTERED || inJail(msg.sender)) revert ImproperValidatorStatus(); uint128 canFinalizeAt = canFinalizeCommissionChangeAt(msg.sender); if (canFinalizeAt == COMMISSION_CHANGE_DELAY_SECONDS) revert NotInitiatedCommissionChange(); if (block.timestamp < canFinalizeAt) revert NotElapsedCommissionChangeDelay(); Validator storage validatorInfo = _validatorInfo[msg.sender]; uint8 oldCommissionRate = validatorInfo.commissionRate; uint8 newCommissionRate = validatorInfo.pendingCommissionRate; validatorInfo.commissionRate = newCommissionRate; validatorInfo.pendingCommissionRate = 0; validatorInfo.commissionChangeInitiatedAt = 0; emit ValidatorCommissionChangeFinalized(msg.sender, oldCommissionRate, newCommissionRate); } /** * @inheritdoc IValidatorManager */ function tryUnjail() external { if (!inJail(msg.sender)) revert ImproperValidatorStatus(); if (_jail[msg.sender] > block.timestamp) revert NotElapsedJailPeriod(); _resetNoSubmissionCount(msg.sender); delete _jail[msg.sender]; emit ValidatorUnjailed(msg.sender); if (getStatus(msg.sender) == ValidatorStatus.READY) { _activateValidator(msg.sender); } } /** * @inheritdoc IValidatorManager */ function bondValidatorKro(address validator) external onlyColosseum { ASSET_MANAGER.bondValidatorKro(validator); } /** * @inheritdoc IValidatorManager */ function unbondValidatorKro(address validator) external onlyColosseum { ASSET_MANAGER.unbondValidatorKro(validator); } /** * @inheritdoc IValidatorManager */ function slash(uint256 outputIndex, address winner, address loser) external onlyColosseum { uint128 challengeReward = ASSET_MANAGER.decreaseBalanceWithChallenge(loser); emit Slashed(outputIndex, loser, challengeReward); _sendToJail(loser, false); if (L2_ORACLE.nextFinalizeOutputIndex() <= outputIndex) { // If output is not rewarded yet, add slashing asset to the pending challenge reward. unchecked { _pendingChallengeReward[outputIndex] += challengeReward; } } else { // If output is already rewarded, add slashing asset to the winner's asset directly. challengeReward = ASSET_MANAGER.increaseBalanceWithChallenge(winner, challengeReward); updateValidatorTree(winner, false); emit ChallengeRewardDistributed(outputIndex, winner, challengeReward); } } /** * @inheritdoc IValidatorManager */ function revertSlash(uint256 outputIndex, address loser) external onlyColosseum { uint128 challengeReward = ASSET_MANAGER.revertDecreaseBalanceWithChallenge(loser); unchecked { _pendingChallengeReward[outputIndex] -= challengeReward; } emit SlashReverted(outputIndex, loser, challengeReward); if (inJail(loser)) { // Revert jail expiration timestamp of the original loser. uint128 expiresAt = _jail[loser] - HARD_JAIL_PERIOD_SECONDS; if (block.timestamp < expiresAt) { _jail[loser] = expiresAt; emit ValidatorJailed(loser, expiresAt); } else { delete _jail[loser]; emit ValidatorUnjailed(loser); if (getStatus(loser) == ValidatorStatus.READY) { _activateValidator(loser); } } } } /** * @inheritdoc IValidatorManager */ function checkSubmissionEligibility(address validator) external view onlyL2OutputOracle { address _nextValidator = nextValidator(); if ( _nextValidator != Constants.VALIDATOR_PUBLIC_ROUND_ADDRESS && validator != _nextValidator ) revert NotSelectedPriorityValidator(); if (!isActive(validator)) revert ImproperValidatorStatus(); } /** * @inheritdoc IValidatorManager */ function getCommissionRate(address validator) external view returns (uint8) { return _validatorInfo[validator].commissionRate; } /** * @inheritdoc IValidatorManager */ function getPendingCommissionRate(address validator) external view returns (uint8) { return _validatorInfo[validator].pendingCommissionRate; } /** * @inheritdoc IValidatorManager */ function activatedValidatorCount() external view returns (uint32) { return _validatorTree.counter - _validatorTree.removed; } /** * @inheritdoc IValidatorManager */ function getWeight(address validator) external view returns (uint120) { return _validatorTree.nodes[_validatorTree.nodeMap[validator]].weight; } /** * @inheritdoc IValidatorManager */ function jailExpiresAt(address validator) external view returns (uint128) { return _jail[validator]; } /** * @inheritdoc IValidatorManager */ function updateValidatorTree(address validator, bool tryRemove) public { ValidatorStatus status = getStatus(validator); if (tryRemove && (status == ValidatorStatus.EXITED || status == ValidatorStatus.INACTIVE)) { if (_validatorTree.remove(validator)) emit ValidatorStopped(validator, block.timestamp); } else if (status >= ValidatorStatus.INACTIVE) { _validatorTree.update(validator, uint120(ASSET_MANAGER.reflectiveWeight(validator))); } } /** * @inheritdoc IValidatorManager */ function nextValidator() public view returns (address) { if (_nextPriorityValidator != address(0)) { uint256 l2Timestamp = L2_ORACLE.nextOutputMinL2Timestamp(); if (block.timestamp >= l2Timestamp) { uint256 elapsed = block.timestamp - l2Timestamp; // If the current time exceeds one round time, it is a public round. if (elapsed > ROUND_DURATION_SECONDS) { return Constants.VALIDATOR_PUBLIC_ROUND_ADDRESS; } } return _nextPriorityValidator; } else { return TRUSTED_VALIDATOR; } } /** * @inheritdoc IValidatorManager */ function getStatus(address validator) public view returns (ValidatorStatus) { if (!_validatorInfo[validator].isInitiated) { return ValidatorStatus.NONE; } if (ASSET_MANAGER.totalValidatorKro(validator) < MIN_REGISTER_AMOUNT) { return ValidatorStatus.EXITED; } bool activated = _validatorTree.nodeMap[validator] > 0; if (ASSET_MANAGER.reflectiveWeight(validator) < MIN_ACTIVATE_AMOUNT) { if (!activated) { return ValidatorStatus.REGISTERED; } return ValidatorStatus.INACTIVE; } if (!activated) { return ValidatorStatus.READY; } return ValidatorStatus.ACTIVE; } /** * @inheritdoc IValidatorManager */ function inJail(address validator) public view returns (bool) { return _jail[validator] != 0; } /** * @inheritdoc IValidatorManager */ function isActive(address validator) public view returns (bool) { if (getStatus(validator) == ValidatorStatus.ACTIVE) return true; return false; } /** * @inheritdoc IValidatorManager */ function noSubmissionCount(address validator) public view returns (uint8) { return _validatorInfo[validator].noSubmissionCount; } /** * @inheritdoc IValidatorManager */ function canFinalizeCommissionChangeAt(address validator) public view returns (uint128) { return _validatorInfo[validator].commissionChangeInitiatedAt + COMMISSION_CHANGE_DELAY_SECONDS; } /** * @inheritdoc IValidatorManager */ function activatedValidatorTotalWeight() public view returns (uint120) { return _validatorTree.nodes[_validatorTree.root].weightSum; } /** * @notice Private function to activate a validator and adds the validator to validator tree. * * @param validator Address of the validator. */ function _activateValidator(address validator) private { _validatorTree.insert(validator, uint120(ASSET_MANAGER.reflectiveWeight(validator))); emit ValidatorActivated(validator, block.timestamp); } /** * @notice Private function to add output submission rewards to the vaults of finalized output * submitters. * * @return Whether the reward distribution is done at least once or not. */ function _distributeReward() private returns (bool) { uint256 outputIndex = L2_ORACLE.nextFinalizeOutputIndex(); uint256 latestOutputIndex = L2_ORACLE.latestOutputIndex(); if (!L2_ORACLE.VALIDATOR_POOL().isTerminated(outputIndex)) { return false; } uint128 finalizedOutputNum = 0; address submitter; while (finalizedOutputNum < MAX_OUTPUT_FINALIZATIONS && outputIndex <= latestOutputIndex) { if (L2_ORACLE.isFinalized(outputIndex)) { submitter = L2_ORACLE.getSubmitter(outputIndex); ( uint128 baseReward, uint128 boostedReward, uint128 validatorReward ) = _calculateReward(submitter); ASSET_MANAGER.increaseBalanceWithReward( submitter, baseReward, boostedReward, validatorReward ); emit RewardDistributed( outputIndex, submitter, validatorReward, baseReward, boostedReward ); uint128 challengeReward = _pendingChallengeReward[outputIndex]; if (challengeReward > 0) { challengeReward = ASSET_MANAGER.increaseBalanceWithChallenge( submitter, challengeReward ); delete _pendingChallengeReward[outputIndex]; emit ChallengeRewardDistributed(outputIndex, submitter, challengeReward); } updateValidatorTree(submitter, false); unchecked { ++outputIndex; ++finalizedOutputNum; } } else { break; } } if (finalizedOutputNum > 0) { L2_ORACLE.setNextFinalizeOutputIndex(outputIndex); return true; } return false; } /** * @notice Internal function to get the boosted reward with the number of KGH. * * @param validator Address of the validator. * * @return The boosted reward with the number of KGH. */ function _getBoostedReward(address validator) internal view returns (uint128) { uint128 numKgh = ASSET_MANAGER.totalKghNum(validator); uint128 coefficient = BASE_REWARD.mulDiv(BOOSTED_REWARD_NUMERATOR, BOOSTED_REWARD_DENOM); return uint128(Atan2.atan2(numKgh, 100).mulDiv(coefficient, 1 << 40)); } /** * @notice Internal function to calculate the reward of the validator when distributing reward. * * @param validator Address of the validator. * * @return The amount of base reward, excluding base reward for the validator. * @return The amount of boosted reward. * @return The amount of reward from commission and base reward for the validator. */ function _calculateReward(address validator) internal view returns (uint128, uint128, uint128) { if (validator == ASSET_MANAGER.SECURITY_COUNCIL()) { return (0, 0, BASE_REWARD); } uint128 commissionRate = _validatorInfo[validator].commissionRate; uint128 boostedReward = _getBoostedReward(validator); uint128 baseReward; uint128 validatorReward; unchecked { validatorReward = (BASE_REWARD + boostedReward).mulDiv( commissionRate, COMMISSION_RATE_DENOM ); baseReward = BASE_REWARD.mulDiv( COMMISSION_RATE_DENOM - commissionRate, COMMISSION_RATE_DENOM ); boostedReward = boostedReward.mulDiv( COMMISSION_RATE_DENOM - commissionRate, COMMISSION_RATE_DENOM ); uint128 validatorKro = ASSET_MANAGER.totalValidatorKro(validator); uint128 totalKro = ASSET_MANAGER.totalKroAssets(validator); uint128 validatorBaseReward = baseReward.mulDiv(validatorKro, totalKro + validatorKro); // Exclude the base reward for the validator from total base reward given to KRO delegators. baseReward -= validatorBaseReward; validatorReward += validatorBaseReward; } return (baseReward, boostedReward, validatorReward); } /** * @notice Updates next priority validator address. Validators with more delegation tokens have * a higher probability of being selected. The random weight selection is based on the * last finalized output root. */ function _updatePriorityValidator() private { uint120 weightSum = activatedValidatorTotalWeight(); uint256 nextFinalizeOutputIndex = L2_ORACLE.nextFinalizeOutputIndex(); if (weightSum > 0 && nextFinalizeOutputIndex > 0) { Types.CheckpointOutput memory output = L2_ORACLE.getL2Output( nextFinalizeOutputIndex - 1 ); uint120 weight = uint120( uint256( keccak256( abi.encodePacked( output.outputRoot, block.number, block.coinbase, block.difficulty, blockhash(block.number - 1) ) ) ) ) % weightSum; _nextPriorityValidator = _validatorTree.select(weight); } else { _nextPriorityValidator = address(0); } } /** * @notice Attempts to jail a validator who was selected as a priority validator for this * submission round but did not submit the output. The period to get out of jail is * SOFT_JAIL_PERIOD_SECONDS. */ function _tryJail() private { if (_nextPriorityValidator == address(0)) return; if (_validatorInfo[_nextPriorityValidator].noSubmissionCount >= JAIL_THRESHOLD) { _sendToJail(_nextPriorityValidator, true); } else { unchecked { _validatorInfo[_nextPriorityValidator].noSubmissionCount++; } } } /** * @notice Send the given validator to the jail and remove from the validator tree. * * @param validator Address of the validator. * @param isSoft Whether the jail is soft or hard. */ function _sendToJail(address validator, bool isSoft) private { uint128 jailSeconds = isSoft ? SOFT_JAIL_PERIOD_SECONDS : HARD_JAIL_PERIOD_SECONDS; uint128 expiresAt = _jail[validator].max(uint128(block.timestamp)) + jailSeconds; _jail[validator] = expiresAt; emit ValidatorJailed(validator, expiresAt); if (_validatorTree.remove(validator)) emit ValidatorStopped(validator, block.timestamp); } /** * @notice Attempts to reset non-submission count of a validator. * * @param validator Address of the validator. */ function _resetNoSubmissionCount(address validator) private { if (noSubmissionCount(validator) > 0) { _validatorInfo[validator].noSubmissionCount = 0; } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { enum Rounding { Down, // Toward negative infinity Up, // Toward infinity Zero // Toward zero } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) * with further edits by Uniswap Labs also under MIT license. */ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1, "Math: mulDiv overflow"); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 twos = denominator & (~denominator + 1); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2, rounded down, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10, rounded down, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0); } } /** * @dev Return the log in base 256, rounded down, of a positive value. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0); } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; /** * @title Atan2 * @notice A library for calculating the arctangent of a fraction y / x. Based on fixed-point * math library, it provides 1E-12 precision with 40 fractional bits. * Originally from https://github.com/NovakDistributed/macroverse. */ library Atan2 { /** * @notice The value of pi/2 in radians, represented as a fixed-point number. */ uint256 internal constant REAL_HALF_PI = 1727108826179; /** * @notice Calculate atan(y / x). * @dev Uses the Chebyshev polynomial approach to approximate arctan(x) where x is [0, 1]. * @dev 0.999974x-0.332568x^3+0.193235x^5-0.115729x^7+0.0519505x^9-0.0114658x^11 * * @param real_y The numerator of the fraction y / x. * @param real_x The denominator of the fraction y / x. * * @return result The angle in radians of the fraction y / x. */ function atan2(uint256 real_y, uint256 real_x) internal pure returns (uint256 result) { assembly { let frac switch lt(real_x, real_y) case 0 { frac := div(mul(real_y, shl(40, 1)), real_x) } case 1 { frac := div(mul(real_x, shl(40, 1)), real_y) } // Initialize variables to be used in the polynomial. let frac_squared := shr(40, mul(frac, frac)) let frac_cubed := shr(40, mul(frac_squared, frac)) let frac_five_squared := shr(40, mul(frac_squared, frac_cubed)) let frac_seven_squared := shr(40, mul(frac_squared, frac_five_squared)) let frac_nine_squared := shr(40, mul(frac_squared, frac_seven_squared)) let frac_eleven_squared := shr(40, mul(frac_squared, frac_nine_squared)) // Calculate the polynomial using unsigned integers. // Start with the x^1 term, and then subtract or add the other terms based on the coefficient signs. result := shr(40, mul(1099483040474, frac)) // x^1 term // x^5 term result := add(result, shr(40, mul(212464129393, frac_five_squared))) // x^9 term result := add(result, shr(40, mul(57120178819, frac_nine_squared))) // x^3 term, subtract because original coefficient is negative result := sub(result, shr(40, mul(365662383026, frac_cubed))) // x^7 term, subtract because original coefficient is negative result := sub(result, shr(40, mul(127245381171, frac_seven_squared))) // x^11 term, subtract because original coefficient is negative result := sub(result, shr(40, mul(12606780422, frac_eleven_squared))) if gt(real_y, real_x) { result := sub(REAL_HALF_PI, result) } } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; /** * @title BalancedWeightTree * @notice A self-balancing tree (balancing the weights) holds the keys and their weights and the * weight sum of each child. A random integer smaller than the weight sum is taken and the * tree is traversed to find the matching key. * See https://github.com/yasharpm/Solidity-Weighted-Random-List. */ library BalancedWeightTree { /** * @notice Struct representing a node that constructs the tree. * * @custom:field addr The address that owns the node. * @custom:field parent The index of parent node. * @custom:field leftChild The index of left child node. * @custom:field rightChild The index of right child node. * @custom:field isLeftChild If the node is left child node of its parent node. * @custom:field weight The weight of the node. * @custom:field weightSum The weight sum of the node and its child nodes. */ struct Node { address addr; uint32 parent; uint32 leftChild; uint32 rightChild; bool isLeftChild; uint120 weight; uint120 weightSum; } /** * @notice Struct representing a tree. * * @custom:field counter A counter used to assign a unique index to each node. The node index * starts with 1 and counter only increments. * @custom:field removed The cumulative number of removed nodes. * @custom:field root The index of root node. * @custom:field nodes A mapping of node index to node struct. * @custom:field nodeMap A mapping of owner address to node index. */ struct Tree { uint32 counter; uint32 removed; uint32 root; mapping(uint32 => Node) nodes; mapping(address => uint32) nodeMap; } /** * @notice Inserts new node with the specified address and weight inside the tree. * * @param _tree The tree to insert the new node. * @param _addr The address that owns the new node. * @param _weight The weight of the new node. */ function insert(Tree storage _tree, address _addr, uint120 _weight) internal { require(_addr != address(0), "BalancedWeightTree: zero address not allowed"); require(_tree.nodeMap[_addr] == 0, "BalancedWeightTree: node already existing"); Node memory newNode = Node({ addr: _addr, weight: _weight, weightSum: _weight, parent: 0, leftChild: 0, rightChild: 0, isLeftChild: true }); unchecked { _tree.counter++; } uint32 newNodeIndex = _tree.counter; _tree.nodes[newNodeIndex] = newNode; _tree.nodeMap[_addr] = newNodeIndex; if (_tree.root == 0) { _tree.root = newNodeIndex; return; } uint32 index = _tree.root; while (true) { Node storage node = _tree.nodes[index]; unchecked { node.weightSum += _weight; } if (node.leftChild == 0) { _tree.nodes[newNodeIndex].parent = index; node.leftChild = newNodeIndex; _promote(_tree, newNodeIndex); return; } else if (node.rightChild == 0) { _tree.nodes[newNodeIndex].parent = index; _tree.nodes[newNodeIndex].isLeftChild = false; node.rightChild = newNodeIndex; _promote(_tree, newNodeIndex); return; } else if ( _tree.nodes[node.leftChild].weightSum > _tree.nodes[node.rightChild].weightSum ) { index = node.rightChild; } else { index = node.leftChild; } } } /** * @notice Updates the weight of the node with the specified address. Returns true if the weight * is updated, false if the node with specified address doesn't exist. * * @param _tree The tree that includes the node to update. * @param _addr The address that owns the node to update. * @param _weight The new weight to be assigned. * * @return If the weight is updated. */ function update(Tree storage _tree, address _addr, uint120 _weight) internal returns (bool) { uint32 index = _tree.nodeMap[_addr]; if (index == 0) { return false; } uint120 oldWeight = _tree.nodes[index].weight; _tree.nodes[index].weight = _weight; uint32 parentIndex = _tree.nodes[index].parent; if (_weight > oldWeight) { unchecked { uint120 weightDiff = _weight - oldWeight; _tree.nodes[index].weightSum += weightDiff; while (parentIndex != 0) { _tree.nodes[parentIndex].weightSum += weightDiff; parentIndex = _tree.nodes[parentIndex].parent; } } _promote(_tree, index); } else { unchecked { uint120 weightDiff = oldWeight - _weight; _tree.nodes[index].weightSum -= weightDiff; while (parentIndex != 0) { _tree.nodes[parentIndex].weightSum -= weightDiff; parentIndex = _tree.nodes[parentIndex].parent; } } _demote(_tree, index); } return true; } /** * @notice Removes the node with specified address from the tree. Returns true is the node is * removed, false if it doesn't exist in the tree. * * @param _tree The tree that includes the node to remove. * @param _addr The address that owns the node to remove. * * @return If the node is removed. */ function remove(Tree storage _tree, address _addr) internal returns (bool) { uint32 index = _tree.nodeMap[_addr]; if (index == 0) { return false; } delete _tree.nodeMap[_addr]; uint32 parentIndex = _tree.nodes[index].parent; uint120 weight = _tree.nodes[index].weight; while (parentIndex != 0) { unchecked { _tree.nodes[parentIndex].weightSum -= weight; } parentIndex = _tree.nodes[parentIndex].parent; } _pullUp(_tree, index); unchecked { ++_tree.removed; } return true; } /** * @notice Performs a weighted selection among the stored nodes. Returns the address of the * selected node. If _weight is equal or greater than the weight sum of the tree, it * returns zero address. * * @param _tree The tree that includes the nodes to select. * @param _weight The random weight to be used for selection. * * @return The address of the selected node. */ function select(Tree storage _tree, uint120 _weight) internal view returns (address) { uint32 index = _tree.root; while (true) { if (_tree.nodes[_tree.nodes[index].leftChild].weightSum > _weight) { index = _tree.nodes[index].leftChild; continue; } unchecked { _weight -= _tree.nodes[_tree.nodes[index].leftChild].weightSum; } if (_tree.nodes[index].weight > _weight) { return _tree.nodes[index].addr; } unchecked { _weight -= _tree.nodes[index].weight; } if (_tree.nodes[_tree.nodes[index].rightChild].weightSum > _weight) { index = _tree.nodes[index].rightChild; } else { return address(0); } } return address(0); } /** * @notice Promotes the node with higher weight to higher level of the tree. It is because to * reduce the average number of traverses required since these nodes are more likely to * be randomly selected. * * @param _tree The tree that includes the node to promote. * @param _index The initial index of the target node to promote. */ function _promote(Tree storage _tree, uint32 _index) private { Node storage node = _tree.nodes[_index]; Node storage parentNode = _tree.nodes[node.parent]; while (node.parent != 0 && node.weight > parentNode.weight) { address nodeAddr = node.addr; node.addr = parentNode.addr; parentNode.addr = nodeAddr; uint120 nodeWeight = node.weight; uint120 parentWeight = parentNode.weight; node.weight = parentWeight; parentNode.weight = nodeWeight; unchecked { node.weightSum -= nodeWeight - parentWeight; } _tree.nodeMap[node.addr] = _index; _tree.nodeMap[parentNode.addr] = node.parent; _index = node.parent; node = _tree.nodes[_index]; parentNode = _tree.nodes[node.parent]; } } /** * @notice Demotes the node with lower weight to lower level of the tree. It is because to * reduce the average number of traverses required since these nodes are less likely to * be randomly selected. * * @param _tree The tree that includes the node to demote. * @param _index The initial index of the target node to demote. */ function _demote(Tree storage _tree, uint32 _index) private { while (true) { Node storage node = _tree.nodes[_index]; if (_tree.nodes[node.leftChild].weight > _tree.nodes[node.rightChild].weight) { if (_tree.nodes[node.leftChild].weight > node.weight) { address nodeAddr = node.addr; node.addr = _tree.nodes[node.leftChild].addr; _tree.nodes[node.leftChild].addr = nodeAddr; uint120 nodeWeight = node.weight; uint120 leftChildWeight = _tree.nodes[node.leftChild].weight; node.weight = leftChildWeight; _tree.nodes[node.leftChild].weight = nodeWeight; unchecked { _tree.nodes[node.leftChild].weightSum -= leftChildWeight - nodeWeight; } _tree.nodeMap[node.addr] = _index; _tree.nodeMap[_tree.nodes[node.leftChild].addr] = node.leftChild; _index = node.leftChild; continue; } return; } else if (_tree.nodes[node.rightChild].weight > node.weight) { address nodeAddr = node.addr; node.addr = _tree.nodes[node.rightChild].addr; _tree.nodes[node.rightChild].addr = nodeAddr; uint120 nodeWeight = node.weight; uint120 rightChildWeight = _tree.nodes[node.rightChild].weight; node.weight = rightChildWeight; _tree.nodes[node.rightChild].weight = nodeWeight; unchecked { _tree.nodes[node.rightChild].weightSum -= rightChildWeight - nodeWeight; } _tree.nodeMap[node.addr] = _index; _tree.nodeMap[_tree.nodes[node.rightChild].addr] = node.rightChild; _index = node.rightChild; continue; } return; } } /** * @notice When removing a node, pulls up the remaining nodes with higher weight to higher level * of the tree. * * @param _tree The tree that includes the node to remove. * @param _index The initial index of the target node to remove. */ function _pullUp(Tree storage _tree, uint32 _index) private { while (true) { Node storage node = _tree.nodes[_index]; require(node.addr != address(0), "BalancedWeightTree: node not exists"); if (node.leftChild == 0) { if (node.rightChild == 0) { if (node.parent == 0) { _tree.root = 0; } else if (node.isLeftChild) { _tree.nodes[node.parent].leftChild = 0; } else { _tree.nodes[node.parent].rightChild = 0; } delete _tree.nodes[_index]; return; } else { node.addr = _tree.nodes[node.rightChild].addr; node.weight = _tree.nodes[node.rightChild].weight; node.weightSum = _tree.nodes[node.rightChild].weightSum; _tree.nodeMap[_tree.nodes[node.rightChild].addr] = _index; _index = node.rightChild; } } else if (node.rightChild == 0) { node.addr = _tree.nodes[node.leftChild].addr; node.weight = _tree.nodes[node.leftChild].weight; node.weightSum = _tree.nodes[node.leftChild].weightSum; _tree.nodeMap[_tree.nodes[node.leftChild].addr] = _index; _index = node.leftChild; } else if (_tree.nodes[node.leftChild].weight > _tree.nodes[node.rightChild].weight) { node.addr = _tree.nodes[node.leftChild].addr; node.weight = _tree.nodes[node.leftChild].weight; unchecked { node.weightSum = _tree.nodes[node.leftChild].weightSum + _tree.nodes[node.rightChild].weightSum; } _tree.nodeMap[_tree.nodes[node.leftChild].addr] = _index; _index = node.leftChild; } else { node.addr = _tree.nodes[node.rightChild].addr; node.weight = _tree.nodes[node.rightChild].weight; unchecked { node.weightSum = _tree.nodes[node.leftChild].weightSum + _tree.nodes[node.rightChild].weightSum; } _tree.nodeMap[_tree.nodes[node.rightChild].addr] = _index; _index = node.rightChild; } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { ResourceMetering } from "../L1/ResourceMetering.sol"; /** * @title Constants * @notice Constants is a library for storing constants. Simple! Don't put everything in here, just * the stuff used in multiple contracts. Constants that only apply to a single contract * should be defined in that contract instead. */ library Constants { /** * @notice Special address to be used as the tx origin for gas estimation calls in the * KromaPortal and CrossDomainMessenger calls. You only need to use this address if * the minimum gas limit specified by the user is not actually enough to execute the * given message and you're attempting to estimate the actual necessary gas limit. We * use address(1) because it's the ecrecover precompile and therefore guaranteed to * never have any code on any EVM chain. */ address internal constant ESTIMATION_ADDRESS = address(1); /** * @notice Value used for the L2 sender storage slot in both the KromaPortal and the * CrossDomainMessenger contracts before an actual sender is set. This value is * non-zero to reduce the gas cost of message passing transactions. */ address internal constant DEFAULT_L2_SENDER = 0x000000000000000000000000000000000000dEaD; /** * @notice Returns the default values for the ResourceConfig. These are the recommended values * for a production network. */ function DEFAULT_RESOURCE_CONFIG() internal pure returns (ResourceMetering.ResourceConfig memory) { ResourceMetering.ResourceConfig memory config = ResourceMetering.ResourceConfig({ maxResourceLimit: 20_000_000, elasticityMultiplier: 10, baseFeeMaxChangeDenominator: 8, minimumBaseFee: 1 gwei, systemTxMaxGas: 1_000_000, maximumBaseFee: type(uint128).max }); return config; } /** * @notice The denominator of the validator reward. * DO NOT change this value if the L2 chain is already operational. */ uint256 internal constant VALIDATOR_REWARD_DENOMINATOR = 10000; /** * @notice An address that identifies that current submission round is a public round. */ address internal constant VALIDATOR_PUBLIC_ROUND_ADDRESS = address(type(uint160).max); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title Types * @notice Contains various types used throughout the Kroma contract system. */ library Types { /** * @notice CheckpointOutput represents a commitment to the state of L2 checkpoint. The timestamp * is the L1 timestamp that the output root is posted. This timestamp is used to verify * that the finalization period has passed since the output root was submitted. * * @custom:field submitter Address of the output submitter. * @custom:field outputRoot Hash of the L2 output. * @custom:field timestamp Timestamp of the L1 block that the output root was submitted in. * @custom:field l2BlockNumber L2 block number that the output corresponds to. */ struct CheckpointOutput { address submitter; bytes32 outputRoot; uint128 timestamp; uint128 l2BlockNumber; } /** * @notice Struct representing the elements that are hashed together to generate an output root * which itself represents a snapshot of the L2 state. * * @custom:field version Version of the output root. * @custom:field stateRoot Root of the state trie at the block of this output. * @custom:field messagePasserStorageRoot Root of the message passer storage trie. * @custom:field blockHash Hash of the block this output was generated from. * @custom:field nextBlockHash Hash of the next block. */ struct OutputRootProof { bytes32 version; bytes32 stateRoot; bytes32 messagePasserStorageRoot; bytes32 blockHash; bytes32 nextBlockHash; } /** * @notice Struct representing the elements that are hashed together to generate a public input. * * @custom:field blockHash The hash of the block. * @custom:field parentHash The hash of the previous block. * @custom:field timestamp The block time. * @custom:field number The block number. * @custom:field gasLimit Maximum gas allowed. * @custom:field baseFee The base fee per gas. * @custom:field transactionsRoot Root hash of the transactions. * @custom:field stateRoot Root hash of the state trie. * @custom:field withdrawalsRoot Root hash of the withdrawals. * @custom:field txHashes Array of hash of the transaction. * @custom:field blobGasUsed The total amount of blob gas consumed by the transactions within the block. * @custom:field excessBlobGas A total of blob gas consumed in excess of the target, prior to the block. * @custom:field parentBeaconRoot Root hash of the parent beacon block. */ struct PublicInput { bytes32 blockHash; bytes32 parentHash; uint64 timestamp; uint64 number; uint64 gasLimit; uint256 baseFee; bytes32 transactionsRoot; bytes32 stateRoot; bytes32 withdrawalsRoot; bytes32[] txHashes; uint64 blobGasUsed; uint64 excessBlobGas; bytes32 parentBeaconRoot; } /** * @notice Struct representing the elements that are hashed together to generate a block hash. * Some of fields that are contained in PublicInput are omitted. * * @custom:field uncleHash RLP encoded uncle hash. * @custom:field coinbase RLP encoded coinbase. * @custom:field receiptsRoot RLP encoded receipts root. * @custom:field logsBloom RLP encoded logs bloom. * @custom:field difficulty RLP encoded difficulty. * @custom:field gasUsed RLP encoded gas used. * @custom:field extraData RLP encoded extra data. * @custom:field mixHash RLP encoded mix hash. * @custom:field nonce RLP encoded nonce. */ struct BlockHeaderRLP { bytes uncleHash; bytes coinbase; bytes receiptsRoot; bytes logsBloom; bytes difficulty; bytes gasUsed; bytes extraData; bytes mixHash; bytes nonce; } /** * @notice Struct representing a deposit transaction (L1 => L2 transaction) created by an end * user (as opposed to a system deposit transaction generated by the system). * * @custom:field from Address of the sender of the transaction. * @custom:field to Address of the recipient of the transaction. * @custom:field isCreation True if the transaction is a contract creation. * @custom:field value Value to send to the recipient. * @custom:field mint Amount of ETH to mint. * @custom:field gasLimit Gas limit of the transaction. * @custom:field data Data of the transaction. * @custom:field l1BlockHash Hash of the block the transaction was submitted in. * @custom:field logIndex Index of the log in the block the transaction was submitted in. */ struct UserDepositTransaction { address from; address to; bool isCreation; uint256 value; uint256 mint; uint64 gasLimit; bytes data; bytes32 l1BlockHash; uint64 logIndex; } /** * @notice Struct representing a withdrawal transaction. * * @custom:field nonce Nonce of the withdrawal transaction * @custom:field sender Address of the sender of the transaction. * @custom:field target Address of the recipient of the transaction. * @custom:field value Value to send to the recipient. * @custom:field gasLimit Gas limit of the transaction. * @custom:field data Data of the transaction. */ struct WithdrawalTransaction { uint256 nonce; address sender; address target; uint256 value; uint256 gasLimit; bytes data; } /** * @notice Struct representing a challenge. * * @custom:field turn The current turn. * @custom:field timeoutAt Timeout timestamp of the next turn. * @custom:field asserter Address of the asserter. * @custom:field challenger Address of the challenger. * @custom:field segments Array of the segment. * @custom:field segStart The L2 block number of the first segment. * @custom:field segSize The number of L2 blocks. */ struct Challenge { uint8 turn; uint64 timeoutAt; address asserter; address challenger; bytes32[] segments; uint256 segSize; uint256 segStart; } /** * @notice Struct representing a validator's bond. * * @custom:field amount Amount of the lock. * @custom:field expiresAt The expiration timestamp of bond. */ struct Bond { uint128 amount; uint128 expiresAt; } /** * @notice Struct representing multisig transaction data. * * @custom:field target The destination address to run the transaction. * @custom:field executed Record whether a transaction was executed or not. * @custom:field value The value passed in while executing the transaction. * @custom:field data Calldata for transaction. */ struct MultiSigTransaction { address target; bool executed; uint256 value; bytes data; } /** * @notice Struct representing multisig confirmation data. * * @custom:field confirmationCount The sum of confirmations. * @custom:field confirmedBy Map data that stores whether confirmation is performed by account. */ struct MultiSigConfirmation { uint256 confirmationCount; mapping(address => bool) confirmedBy; } /** * @notice Struct representing the data for verifying the public input. * * @custom:field srcOutputRootProof Proof of the source output root. * @custom:field dstOutputRootProof Proof of the destination output root. * @custom:field publicInput Ingredients to compute the public input used by ZK proof verification. * @custom:field rlps Pre-encoded RLPs to compute the next block hash * of the source output root proof. * @custom:field l2ToL1MessagePasserBalance Balance of the L2ToL1MessagePasser account. * @custom:field l2ToL1MessagePasserCodeHash Codehash of the L2ToL1MessagePasser account. * @custom:field merkleProof Merkle proof of L2ToL1MessagePasser account against the state root. */ struct PublicInputProof { OutputRootProof srcOutputRootProof; OutputRootProof dstOutputRootProof; PublicInput publicInput; BlockHeaderRLP rlps; bytes32 l2ToL1MessagePasserBalance; bytes32 l2ToL1MessagePasserCodeHash; bytes[] merkleProof; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; /** * @title Uint128Math * @notice A library for handling overflow-safe math on uint128, especially for mulDiv operations. * This library is motivated from the open-source Openzeppelin's Math library. */ library Uint128Math { /** * @dev Returns the largest of two numbers. */ function max(uint128 a, uint128 b) internal pure returns (uint128) { return a > b ? a : b; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint128 or denominator == 0 * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) * with further edits by Uniswap Labs and Openzeppelin also under MIT license. */ function mulDiv( uint128 x, uint128 y, uint128 denominator ) internal pure returns (uint128 result) { unchecked { uint256 prod; assembly { prod := mul(x, y) } // Make sure the result is less than 2^128. require(denominator > (prod >> 128), "Uint128Math: mulDiv overflow"); // Direct division as fallback since we can't guarantee not exceeding 128 bits without further checks. result = uint128(prod / uint256(denominator)); return result; } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title ISemver /// @notice ISemver is a simple contract for ensuring that contracts are /// versioned using semantic versioning. interface ISemver { /// @notice Getter for the semantic version of the contract. This is not /// meant to be used onchain but instead meant to be used by offchain /// tooling. /// @return Semver contract version as a string. function version() external view returns (string memory); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import { IERC721Receiver } from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import { Uint128Math } from "../libraries/Uint128Math.sol"; import { ISemver } from "../universal/ISemver.sol"; import { IAssetManager } from "./interfaces/IAssetManager.sol"; import { IValidatorManager } from "./interfaces/IValidatorManager.sol"; /** * @title AssetManager * @notice AssetManager is a contract that handles (un)delegations of KRO and KGH, and the * distribution of rewards to the delegators and the validator. */ contract AssetManager is ISemver, IERC721Receiver, IAssetManager { using SafeERC20 for IERC20; using Uint128Math for uint128; /** * @notice The numerator of the tax. */ uint128 public constant TAX_NUMERATOR = 20; /** * @notice The denominator of the tax. */ uint128 public constant TAX_DENOMINATOR = 100; /** * @notice Decimals offset for the KRO shares. */ uint128 public constant DECIMAL_OFFSET = 10 ** 6; /** * @notice Address of the KRO token contract. */ IERC20 public immutable ASSET_TOKEN; /** * @notice Address of the KGH token contract. */ IERC721 public immutable KGH; /** * @notice The address of the SecurityCouncil contract. Can be updated via upgrade. */ address public immutable SECURITY_COUNCIL; /** * @notice The address of Validator Reward Vault. Can be updated via upgrade. */ address public immutable VALIDATOR_REWARD_VAULT; /** * @notice Address of ValidatorManager contract. Can be updated via upgrade. */ IValidatorManager public immutable VALIDATOR_MANAGER; /** * @notice Minimum delegation period. Can be updated via upgrade. */ uint128 public immutable MIN_DELEGATION_PERIOD; /** * @notice The amount to bond. */ uint128 public immutable BOND_AMOUNT; /** * @notice A mapping of validator address to the vault. */ mapping(address => Vault) internal _vaults; /** * @notice Modifier to check if the caller is the ValidatorManager contract. */ modifier onlyValidatorManager() { if (msg.sender != address(VALIDATOR_MANAGER)) revert NotAllowedCaller(); _; } /** * @notice Modifier to check if the validator is registered and not in jail. */ modifier isRegistered(address validator) { if ( VALIDATOR_MANAGER.getStatus(validator) < IValidatorManager.ValidatorStatus.REGISTERED || VALIDATOR_MANAGER.inJail(validator) ) revert ImproperValidatorStatus(); _; } /** * @notice Modifier to check if the caller is the withdraw account of the validator. */ modifier onlyWithdrawAccount(address validator) { if (msg.sender != _vaults[validator].withdrawAccount) revert NotAllowedCaller(); _; } /** * @notice Semantic version. * @custom:semver 1.0.0 */ string public constant version = "1.0.0"; /** * @notice Constructs the AssetManager contract. * * @param _assetToken Address of the KRO token. * @param _kgh Address of the KGH token. * @param _securityCouncil Address of the SecurityCouncil contract. * @param _validatorRewardVault Address of the Validator Reward Vault. * @param _validatorManager Address of the ValidatorManager contract. * @param _minDelegationPeriod Minimum delegation period. * @param _bondAmount Amount to bond. */ constructor( IERC20 _assetToken, IERC721 _kgh, address _securityCouncil, address _validatorRewardVault, IValidatorManager _validatorManager, uint128 _minDelegationPeriod, uint128 _bondAmount ) { ASSET_TOKEN = _assetToken; KGH = _kgh; SECURITY_COUNCIL = _securityCouncil; VALIDATOR_REWARD_VAULT = _validatorRewardVault; VALIDATOR_MANAGER = _validatorManager; MIN_DELEGATION_PERIOD = _minDelegationPeriod; BOND_AMOUNT = _bondAmount; } /** * @inheritdoc IAssetManager */ function getKroTotalShareBalance( address validator, address delegator ) external view returns (uint128) { return _vaults[validator].kroDelegators[delegator].shares; } /** * @inheritdoc IAssetManager */ function getKroAssets(address validator, address delegator) external view returns (uint128) { return _convertToKroAssets(validator, _vaults[validator].kroDelegators[delegator].shares); } /** * @inheritdoc IAssetManager */ function getKghNum(address validator, address delegator) external view returns (uint128) { return _vaults[validator].kghDelegators[delegator].kghNum; } /** * @inheritdoc IAssetManager */ function previewDelegate(address validator, uint128 assets) external view returns (uint128) { return _convertToKroShares(validator, assets); } /** * @inheritdoc IAssetManager */ function previewUndelegate(address validator, uint128 shares) external view returns (uint128) { return _convertToKroAssets(validator, shares); } /** * @inheritdoc IAssetManager */ function canUndelegateKroAt( address validator, address delegator ) public view returns (uint128) { return _vaults[validator].kroDelegators[delegator].lastDelegatedAt + MIN_DELEGATION_PERIOD; } /** * @inheritdoc IAssetManager */ function canUndelegateKghAt( address validator, address delegator, uint256 tokenId ) public view returns (uint128) { return _vaults[validator].kghDelegators[delegator].delegatedAt[tokenId] + MIN_DELEGATION_PERIOD; } /** * @inheritdoc IAssetManager */ function canWithdrawAt(address validator) public view returns (uint128) { return _vaults[validator].lastDepositedAt + MIN_DELEGATION_PERIOD; } /** * @inheritdoc IAssetManager */ function getKghReward(address validator, address delegator) external view returns (uint128) { Vault storage vault = _vaults[validator]; KghDelegator storage kghDelegator = vault.kghDelegators[delegator]; uint128 rewardPerKghStored = vault.asset.rewardPerKghStored; uint128 totalBoostedReward = kghDelegator.kghNum * (rewardPerKghStored - kghDelegator.rewardPerKghPaid); return totalBoostedReward; } /** * @inheritdoc IAssetManager */ function getWithdrawAccount(address validator) external view returns (address) { return _vaults[validator].withdrawAccount; } /** * @inheritdoc IAssetManager */ function totalKroAssets(address validator) public view returns (uint128) { return _vaults[validator].asset.totalKro; } /** * @inheritdoc IAssetManager */ function totalKghNum(address validator) external view returns (uint128) { return _vaults[validator].asset.totalKgh; } /** * @inheritdoc IAssetManager */ function totalValidatorKro(address validator) external view returns (uint128) { return _vaults[validator].asset.validatorKro; } /** * @inheritdoc IAssetManager */ function totalValidatorKroBonded(address validator) external view returns (uint128) { return _vaults[validator].asset.validatorKroBonded; } /** * @inheritdoc IAssetManager */ function totalValidatorKroNotBonded(address validator) external view returns (uint128) { return _vaults[validator].asset.validatorKro - _vaults[validator].asset.validatorKroBonded; } /** * @notice Returns the reflective weight of given validator. * * @param validator Address of the validator. * * @return The reflective weight of given validator. */ function reflectiveWeight(address validator) external view returns (uint128) { return _vaults[validator].asset.totalKro + _vaults[validator].asset.validatorKro; } /** * @notice Deposit KRO to register as a validator. This function is only called by the * ValidatorManager contract. * * @param validator Address of the validator. * @param assets The amount of KRO to deposit. * @param withdrawAccount An account where assets can be withdrawn to. Only this account can * withdraw the assets. */ function depositToRegister( address validator, uint128 assets, address withdrawAccount ) external onlyValidatorManager { if (withdrawAccount == address(0)) revert ZeroAddress(); _vaults[validator].withdrawAccount = withdrawAccount; _deposit(validator, assets, false); emit Deposited(validator, assets); } /** * @inheritdoc IAssetManager */ function deposit(uint128 assets) external { if (assets == 0) revert NotAllowedZeroInput(); if (VALIDATOR_MANAGER.getStatus(msg.sender) == IValidatorManager.ValidatorStatus.NONE) revert ImproperValidatorStatus(); _deposit(msg.sender, assets, true); emit Deposited(msg.sender, assets); VALIDATOR_MANAGER.tryActivateValidator(msg.sender); } /** * @inheritdoc IAssetManager */ function withdraw(address validator, uint128 assets) external onlyWithdrawAccount(validator) { if (assets == 0) revert NotAllowedZeroInput(); if (canWithdrawAt(validator) > block.timestamp) { revert NotElapsedMinDelegationPeriod(); } if (VALIDATOR_MANAGER.jailExpiresAt(validator) > block.timestamp) revert ImproperValidatorStatus(); _withdraw(validator, assets); VALIDATOR_MANAGER.updateValidatorTree(validator, true); ASSET_TOKEN.safeTransfer(_vaults[validator].withdrawAccount, assets); emit Withdrawn(validator, assets); } /** * @inheritdoc IAssetManager */ function delegate( address validator, uint128 assets ) external isRegistered(validator) returns (uint128) { if (assets == 0) revert NotAllowedZeroInput(); ASSET_TOKEN.safeTransferFrom(msg.sender, address(this), assets); uint128 shares = _convertToKroShares(validator, assets); _delegate(validator, msg.sender, assets, shares); VALIDATOR_MANAGER.updateValidatorTree(validator, false); emit KroDelegated(validator, msg.sender, assets, shares); return shares; } /** * @inheritdoc IAssetManager */ function delegateKgh(address validator, uint256 tokenId) external isRegistered(validator) { // claim boosted reward uint128 boostedReward = _claimBoostedReward(validator, msg.sender); if (boostedReward > 0) { ASSET_TOKEN.safeTransfer(msg.sender, boostedReward); emit KghRewardClaimed(validator, msg.sender, boostedReward); } KGH.safeTransferFrom(msg.sender, address(this), tokenId); _delegateKgh(validator, msg.sender, tokenId); emit KghDelegated(validator, msg.sender, tokenId); } /** * @inheritdoc IAssetManager */ function delegateKghBatch( address validator, uint256[] calldata tokenIds ) external isRegistered(validator) { if (tokenIds.length == 0) revert NotAllowedZeroInput(); // claim boosted reward uint128 boostedReward = _claimBoostedReward(validator, msg.sender); if (boostedReward > 0) { ASSET_TOKEN.safeTransfer(msg.sender, boostedReward); emit KghRewardClaimed(validator, msg.sender, boostedReward); } KghDelegator storage kghDelegator = _vaults[validator].kghDelegators[msg.sender]; for (uint256 i = 0; i < tokenIds.length; ) { KGH.safeTransferFrom(msg.sender, address(this), tokenIds[i]); kghDelegator.delegatedAt[tokenIds[i]] = uint128(block.timestamp); unchecked { ++i; } } _delegateKghBatch(validator, msg.sender, uint128(tokenIds.length)); emit KghBatchDelegated(validator, msg.sender, tokenIds); } /** * @inheritdoc IAssetManager */ function undelegate(address validator, uint128 assets) external { if (assets == 0) revert NotAllowedZeroInput(); uint128 shares = _convertToKroShares(validator, assets); if (shares == 0) revert InsufficientShare(); if (shares > _vaults[validator].kroDelegators[msg.sender].shares) revert InsufficientShare(); if (canUndelegateKroAt(validator, msg.sender) > block.timestamp) revert NotElapsedMinDelegationPeriod(); _undelegate(validator, msg.sender, assets, shares); VALIDATOR_MANAGER.updateValidatorTree(validator, true); ASSET_TOKEN.safeTransfer(msg.sender, assets); emit KroUndelegated(validator, msg.sender, assets, shares); } /** * @inheritdoc IAssetManager */ function undelegateKgh(address validator, uint256 tokenId) external { KghDelegator storage kghDelegator = _vaults[validator].kghDelegators[msg.sender]; if (kghDelegator.delegatedAt[tokenId] == 0) revert InvalidTokenIdsInput(); if (canUndelegateKghAt(validator, msg.sender, tokenId) > block.timestamp) revert NotElapsedMinDelegationPeriod(); // boosted reward of KGH uint128 boostedReward = _claimBoostedReward(validator, msg.sender); // update storage _undelegateKgh(validator, msg.sender, tokenId); // transfer KGH KGH.safeTransferFrom(address(this), msg.sender, tokenId); // transfer KRO if (boostedReward > 0) { ASSET_TOKEN.safeTransfer(msg.sender, boostedReward); } emit KghUndelegated(validator, msg.sender, tokenId, boostedReward); } /** * @inheritdoc IAssetManager */ function undelegateKghBatch(address validator, uint256[] calldata tokenIds) external { if (tokenIds.length == 0) revert NotAllowedZeroInput(); KghDelegator storage kghDelegator = _vaults[validator].kghDelegators[msg.sender]; for (uint256 i = 0; i < tokenIds.length; ) { if (kghDelegator.delegatedAt[tokenIds[i]] == 0) revert InvalidTokenIdsInput(); if (canUndelegateKghAt(validator, msg.sender, tokenIds[i]) > block.timestamp) revert NotElapsedMinDelegationPeriod(); delete kghDelegator.delegatedAt[tokenIds[i]]; unchecked { ++i; } } // boosted reward of KGHs uint128 boostedReward = _claimBoostedReward(validator, msg.sender); // update storage _undelegateKghBatch(validator, msg.sender, uint128(tokenIds.length)); // transfer KGHs for (uint256 i = 0; i < tokenIds.length; ) { KGH.safeTransferFrom(address(this), msg.sender, tokenIds[i]); unchecked { ++i; } } // transfer KRO if (boostedReward > 0) { ASSET_TOKEN.safeTransfer(msg.sender, boostedReward); } emit KghBatchUndelegated(validator, msg.sender, tokenIds, boostedReward); } /** * @inheritdoc IAssetManager */ function claimKghReward(address validator) external { uint128 boostedReward = _claimBoostedReward(validator, msg.sender); if (boostedReward == 0) revert InsufficientAsset(); ASSET_TOKEN.safeTransfer(msg.sender, boostedReward); emit KghRewardClaimed(validator, msg.sender, boostedReward); } /** * @notice Bond KRO from validator KRO during output submission or challenge creation. This * function is only called by the ValidatorManager contract. * * @param validator Address of the validator. */ function bondValidatorKro(address validator) external onlyValidatorManager { Asset storage asset = _vaults[validator].asset; uint128 remainder = asset.validatorKro - asset.validatorKroBonded; if (remainder < BOND_AMOUNT) revert InsufficientAsset(); unchecked { asset.validatorKroBonded += BOND_AMOUNT; } emit ValidatorKroBonded(validator, BOND_AMOUNT, remainder - BOND_AMOUNT); } /** * @notice Unbond KRO from validator KRO during output finalization or challenge slashing. This * function is only called by the ValidatorManager contract. * * @param validator Address of the validator. */ function unbondValidatorKro(address validator) external onlyValidatorManager { Asset storage asset = _vaults[validator].asset; unchecked { asset.validatorKroBonded -= BOND_AMOUNT; } emit ValidatorKroUnbonded( validator, BOND_AMOUNT, asset.validatorKro - asset.validatorKroBonded ); } /** * @notice Update the vault of validator with the distributed reward. This function is only * called by the ValidatorManager contract. * * @param validator Address of the validator. * @param baseReward The base reward to distribute. * @param boostedReward The boosted reward to distribute. * @param validatorReward The validator reward to distribute. */ function increaseBalanceWithReward( address validator, uint128 baseReward, uint128 boostedReward, uint128 validatorReward ) external onlyValidatorManager { // Distribute the reward from a designated vault to the AssetManager contract. ASSET_TOKEN.safeTransferFrom( VALIDATOR_REWARD_VAULT, address(this), baseReward + boostedReward + validatorReward ); // If reward is distributed to SECURITY_COUNCIL, transfer it directly. if (validator == SECURITY_COUNCIL) { ASSET_TOKEN.safeTransfer( SECURITY_COUNCIL, baseReward + boostedReward + validatorReward ); } else { Asset storage asset = _vaults[validator].asset; unchecked { asset.totalKro += baseReward; asset.validatorKro += validatorReward; if (asset.totalKgh != 0) { asset.rewardPerKghStored += boostedReward / asset.totalKgh; } asset.validatorKroBonded -= BOND_AMOUNT; } emit ValidatorKroUnbonded( validator, BOND_AMOUNT, asset.validatorKro - asset.validatorKroBonded ); } } /** * @notice Update the vault of challenge winner with the challenge reward. This function is only * called by the ValidatorManager contract. * * @param winner Address of the challenge winner. * @param challengeReward The challenge reward to be added to the winner's asset after excluding * tax. * * @return The challenge reward added to winner's asset. */ function increaseBalanceWithChallenge( address winner, uint128 challengeReward ) external onlyValidatorManager returns (uint128) { Asset storage asset = _vaults[winner].asset; // If challenge reward is distributed to SECURITY_COUNCIL, transfer it directly. if (winner == SECURITY_COUNCIL) { ASSET_TOKEN.safeTransfer(SECURITY_COUNCIL, challengeReward); return challengeReward; } uint128 tax = challengeReward.mulDiv(TAX_NUMERATOR, TAX_DENOMINATOR); ASSET_TOKEN.safeTransfer(SECURITY_COUNCIL, tax); unchecked { challengeReward -= tax; asset.validatorKro += challengeReward; } return challengeReward; } /** * @notice Update the vault of challenge loser with the challenge reward. This function is only * called by the ValidatorManager contract. * * @param loser Address of the challenge loser. * * @return The challenge reward slashed from loser's asset. */ function decreaseBalanceWithChallenge( address loser ) external onlyValidatorManager returns (uint128) { Asset storage asset = _vaults[loser].asset; unchecked { asset.validatorKroBonded -= BOND_AMOUNT; asset.validatorKro -= BOND_AMOUNT; } return BOND_AMOUNT; } /** * @notice Revert the changes of decreaseBalanceWithChallenge. This function is only called by * the ValidatorManager contract. * * @param loser Address of the challenge original loser. * * @return The challenge reward refunded to loser's asset. */ function revertDecreaseBalanceWithChallenge( address loser ) external onlyValidatorManager returns (uint128) { Asset storage asset = _vaults[loser].asset; unchecked { asset.validatorKroBonded += BOND_AMOUNT; asset.validatorKro += BOND_AMOUNT; } return BOND_AMOUNT; } /** * @notice Returns the total amount of KRO shares held by the vault. * * @param validator Address of the validator. * * @return The total amount of shares held by the validator vault. */ function _totalKroShares(address validator) internal view returns (uint128) { return _vaults[validator].asset.totalKroShares; } /** * @notice Internal conversion function for KRO (from assets to shares). * * @param validator Address of the validator. * @param assets The amount of assets to convert to shares. */ function _convertToKroShares( address validator, uint128 assets ) internal view returns (uint128) { return assets.mulDiv( _totalKroShares(validator) + DECIMAL_OFFSET, totalKroAssets(validator) + 1 ); } /** * @notice Internal conversion function for KRO (from shares to assets). * * @param validator Address of the validator. * @param shares The amount of shares to convert to assets. */ function _convertToKroAssets( address validator, uint128 shares ) internal view returns (uint128) { return shares.mulDiv( totalKroAssets(validator) + 1, _totalKroShares(validator) + DECIMAL_OFFSET ); } /** * @notice Internal function to deposit KRO by the validator. * * @param validator Address of the validator. * @param assets The amount of KRO to deposit. * @param updateTree Flag to update the validator tree. */ function _deposit(address validator, uint128 assets, bool updateTree) internal { Vault storage vault = _vaults[validator]; ASSET_TOKEN.safeTransferFrom(validator, address(this), assets); unchecked { vault.asset.validatorKro += assets; vault.lastDepositedAt = uint128(block.timestamp); } if (updateTree) { VALIDATOR_MANAGER.updateValidatorTree(validator, false); } } /** * @notice Internal function to withdraw KRO by the validator. * * @param validator Address of the validator. * @param assets The amount of KRO to withdraw. */ function _withdraw(address validator, uint128 assets) internal { Asset storage asset = _vaults[validator].asset; if (assets > asset.validatorKro - asset.validatorKroBonded) revert InsufficientAsset(); unchecked { asset.validatorKro -= assets; } } /** * @notice Internal function to delegate KRO to the validator. * * @param validator Address of the validator. * @param delegator Address of the delegator. * @param assets The amount of KRO to delegate. * @param shares The amount of shares to delegate. */ function _delegate( address validator, address delegator, uint128 assets, uint128 shares ) internal { Vault storage vault = _vaults[validator]; unchecked { vault.asset.totalKro += assets; vault.asset.totalKroShares += shares; vault.kroDelegators[delegator].shares += shares; vault.kroDelegators[delegator].lastDelegatedAt = uint128(block.timestamp); } } /** * @notice Internal function to delegate KGH to the validator. * * @param validator Address of the validator. * @param delegator Address of the delegator. * @param tokenId Token Id of the KGH. */ function _delegateKgh(address validator, address delegator, uint256 tokenId) internal { Vault storage vault = _vaults[validator]; KghDelegator storage kghDelegator = vault.kghDelegators[delegator]; unchecked { vault.asset.totalKgh += 1; ++kghDelegator.kghNum; kghDelegator.delegatedAt[tokenId] = uint128(block.timestamp); } } /** * @notice Internal function to delegate KGHs to the validator. * * @param validator Address of the validator. * @param delegator Address of the delegator. * @param kghCount The number of KGHs to delegate. */ function _delegateKghBatch(address validator, address delegator, uint128 kghCount) internal { Vault storage vault = _vaults[validator]; unchecked { // asset vault.asset.totalKgh += kghCount; // delegator vault.kghDelegators[delegator].kghNum += kghCount; } } /** * @notice Internal function to undelegate KRO from the validator. * * @param validator Address of the validator. * @param delegator Address of the delegator. * @param assets The amount of KRO to undelegate. * @param shares The amount of shares to undelegate. */ function _undelegate( address validator, address delegator, uint128 assets, uint128 shares ) internal { Vault storage vault = _vaults[validator]; unchecked { vault.asset.totalKroShares -= shares; vault.asset.totalKro -= assets; vault.kroDelegators[delegator].shares -= shares; } } /** * @notice Internal function to undelegate KGH from the validator. * * @param validator Address of the validator. * @param delegator Address of the delegator. * @param tokenId Token Id of the KGH. */ function _undelegateKgh(address validator, address delegator, uint256 tokenId) internal { Vault storage vault = _vaults[validator]; KghDelegator storage kghDelegator = vault.kghDelegators[delegator]; unchecked { // asset vault.asset.totalKgh -= 1; // delegator kghDelegator.kghNum -= 1; delete kghDelegator.delegatedAt[tokenId]; } } /** * @notice Internal function to undelegate KGHs from the validator. * * @param validator Address of the validator. * @param delegator Address of the delegator. * @param kghCount The number of KGH token to undelegate. */ function _undelegateKghBatch(address validator, address delegator, uint128 kghCount) internal { Vault storage vault = _vaults[validator]; unchecked { // asset vault.asset.totalKgh -= kghCount; // delegator vault.kghDelegators[delegator].kghNum -= kghCount; } } /** * @notice Internal function to claim the boosted reward of the delegator. * * @param validator Address of the validator. * @param delegator Address of the delegator. * * @return The amount of the claimed boosted reward. */ function _claimBoostedReward(address validator, address delegator) internal returns (uint128) { Vault storage vault = _vaults[validator]; KghDelegator storage kghDelegator = vault.kghDelegators[delegator]; uint128 rewardPerKghStored = vault.asset.rewardPerKghStored; uint128 totalBoostedReward = kghDelegator.kghNum * (rewardPerKghStored - kghDelegator.rewardPerKghPaid); kghDelegator.rewardPerKghPaid = rewardPerKghStored; return totalBoostedReward; } /** * @inheritdoc IERC721Receiver */ function onERC721Received( address /* operator */, address /* from */, uint256 /* tokenId */, bytes calldata /* data */ ) external pure returns (bytes4) { return IERC721Receiver.onERC721Received.selector; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { AssetManager } from "../AssetManager.sol"; import { L2OutputOracle } from "../L2OutputOracle.sol"; /** * @title IValidatorManager * @notice Interface for ValidatorManager contract. */ interface IValidatorManager { /** * @notice Enum of the status of a validator. * * Below is the possible conditions of each status. "initiated" means the validator has been * initiated at least once, "activated" means the validator has been activated and added to the * validator tree. "MIN_REGISTER_AMOUNT" means the total assets of the validator exceeds * MIN_REGISTER_AMOUNT, "MIN_ACTIVATE_AMOUNT" means the same. * * +------------+-----------+-----------+---------------------+---------------------+ * | Status | initiated | activated | MIN_REGISTER_AMOUNT | MIN_ACTIVATE_AMOUNT | * +------------+-----------+-----------+---------------------+---------------------+ * | NONE | X | X | X | X | * | EXITED | O | O/X | X | O/X | * | REGISTERED | O | X | O | X | * | READY | O | X | O | O | * | INACTIVE | O | O | O | X | * | ACTIVE | O | O | O | O | * +------------+-----------+-----------+---------------------+---------------------+ */ enum ValidatorStatus { NONE, EXITED, REGISTERED, READY, INACTIVE, ACTIVE } /** * @notice Constructs the constructor parameters of ValidatorManager contract. * * @custom:field _l2Oracle Address of the L2OutputOracle contract. * @custom:field _assetManager Address of the AssetManager contract. * @custom:field _trustedValidator Address of the trusted validator. * @custom:field _commissionChangeDelaySeconds The delay to finalize the commission rate change * in seconds. * @custom:field _roundDurationSeconds The duration of one submission round in seconds. * @custom:field _softJailPeriodSeconds The minimum duration to get out of jail in * seconds in output non-submissions penalty. * @custom:field _hardJailPeriodSeconds The minimum duration to get out of jail in * seconds in slashing penalty. * @custom:field _jailThreshold The maximum allowed number of output * non-submissions before jailed. * @custom:field _maxOutputFinalizations Max number of finalized outputs. * @custom:field _baseReward Base reward for the validator. * @custom:field _minRegisterAmount Minimum amount to register as a validator. * @custom:field _minActivateAmount Minimum amount to activate a validator. */ struct ConstructorParams { L2OutputOracle _l2Oracle; AssetManager _assetManager; address _trustedValidator; uint128 _commissionChangeDelaySeconds; uint128 _roundDurationSeconds; uint128 _softJailPeriodSeconds; uint128 _hardJailPeriodSeconds; uint128 _jailThreshold; uint128 _maxOutputFinalizations; uint128 _baseReward; uint128 _minRegisterAmount; uint128 _minActivateAmount; } /** * @notice Constructs the information of a validator. * * @custom:field isInitiated Whether the validator is initiated. * @custom:field noSubmissionCount Number of counts that the validator did not submit * the output in priority round. * @custom:field commissionRate Commission rate of validator. * @custom:field pendingCommissionRate Pending commission rate of validator. * @custom:field commissionChangeInitiatedAt Timestamp of commission change initialization. */ struct Validator { bool isInitiated; uint8 noSubmissionCount; uint8 commissionRate; uint8 pendingCommissionRate; uint128 commissionChangeInitiatedAt; } /** * @notice Emitted when registers as a validator. * * @param validator Address of the validator. * @param activated If the validator is activated or not. * @param commissionRate The commission rate the validator sets. * @param assets The number of assets the validator deposits. */ event ValidatorRegistered( address indexed validator, bool activated, uint8 commissionRate, uint128 assets ); /** * @notice Emitted when a validator activated, which means added to the validator tree. * * @param validator Address of the validator. * @param activatedAt The timestamp when the validator activated. */ event ValidatorActivated(address indexed validator, uint256 activatedAt); /** * @notice Emitted when a validator stops, which means removed from the validator tree. * * @param validator Address of the validator. * @param stopsAt The timestamp when the validator stops. */ event ValidatorStopped(address indexed validator, uint256 stopsAt); /** * @notice Emitted when a validator initiated commission rate change. * * @param validator Address of the validator. * @param oldCommissionRate The old commission rate. * @param newCommissionRate The new commission rate. */ event ValidatorCommissionChangeInitiated( address indexed validator, uint8 oldCommissionRate, uint8 newCommissionRate ); /** * @notice Emitted when a validator finalized commission rate change. * * @param validator Address of the validator. * @param oldCommissionRate The old commission rate. * @param newCommissionRate The new commission rate. */ event ValidatorCommissionChangeFinalized( address indexed validator, uint8 oldCommissionRate, uint8 newCommissionRate ); /** * @notice Emitted when a validator is jailed. * * @param validator Address of the validator. * @param expiresAt The expiration timestamp of the jail. */ event ValidatorJailed(address indexed validator, uint128 expiresAt); /** * @notice Emitted when a validator is unjailed. * * @param validator Address of the validator. */ event ValidatorUnjailed(address indexed validator); /** * @notice Emitted when the output reward is distributed. * * @param outputIndex Index of the L2 checkpoint output. * @param validator Address of the validator whose vault is rewarded. * @param validatorReward The amount of validator reward. * @param baseReward The amount of base reward for KRO delegators. * @param boostedReward The amount of boosted reward for KGH delegators. */ event RewardDistributed( uint256 indexed outputIndex, address indexed validator, uint128 validatorReward, uint128 baseReward, uint128 boostedReward ); /** * @notice Emitted when challenge reward for challenge winner is distributed. * * @param outputIndex Index of the L2 checkpoint output. * @param recipient Address of the reward recipient. * @param amount The amount of challenge reward. */ event ChallengeRewardDistributed( uint256 indexed outputIndex, address indexed recipient, uint128 amount ); /** * @notice Emitted when the validator is slashed. * * @param outputIndex Index of the L2 checkpoint output. * @param loser Address of the challenge loser. * @param amount The amount of KRO slashed. */ event Slashed(uint256 indexed outputIndex, address indexed loser, uint128 amount); /** * @notice Emitted when the slash is reverted. * * @param outputIndex Index of the L2 checkpoint output. * @param loser Address of the challenge original loser. * @param amount The amount of KRO refunded to the loser. */ event SlashReverted(uint256 indexed outputIndex, address indexed loser, uint128 amount); /** * @notice Reverts when caller is not allowed. */ error NotAllowedCaller(); /** * @notice Reverts when constructor parameters are invalid. */ error InvalidConstructorParams(); /** * @notice Reverts when the status of validator is improper. */ error ImproperValidatorStatus(); /** * @notice Reverts when the asset is insufficient. */ error InsufficientAsset(); /** * @notice Reverts when the commission rate exceeds the max value. */ error MaxCommissionRateExceeded(); /** * @notice Reverts when try to change commission rate with same value as previous. */ error SameCommissionRate(); /** * @notice Reverts when the commission rate change has not been initiated. */ error NotInitiatedCommissionChange(); /** * @notice Reverts when the delay of commission rate change finalization has not elapsed. */ error NotElapsedCommissionChangeDelay(); /** * @notice Reverts when try to unjail before jail period elapsed. */ error NotElapsedJailPeriod(); /** * @notice Reverts if the validator is not selected priority validator. */ error NotSelectedPriorityValidator(); /** * @notice Registers as a validator with assets at least MIN_REGISTER_AMOUNT. The validator with * assets more than MIN_ACTIVATE_AMOUNT can be activated at the same time. * * @param assets The amount of assets to deposit. * @param commissionRate The commission rate the validator sets. * @param withdrawAccount An account where assets can be withdrawn to. Only this account can * withdraw the assets. */ function registerValidator( uint128 assets, uint8 commissionRate, address withdrawAccount ) external; /** * @notice Activates a validator and adds the validator to validator tree. To submit outputs, * the validator should be activated. */ function activateValidator() external; /** * @notice Tries to activate a validator and adds the validator to validator tree. To submit * outputs, the validator should be activated. This function can only be called by * AssetManager. * * @param validator Address of the validator. */ function tryActivateValidator(address validator) external; /** * @notice Handles some essential actions such as reward distribution, jail handling, next * priority validator selection after output submission. This function can only be * called by L2OutputOracle. * * @param outputIndex Index of the L2 checkpoint output submitted. */ function afterSubmitL2Output(uint256 outputIndex) external; /** * @notice Initiates the commission rate change of a validator. An exited or jailed validator * cannot initiate it. * * @param newCommissionRate The new commission rate to apply. */ function initCommissionChange(uint8 newCommissionRate) external; /** * @notice Finalizes the commission rate change of a validator. An exited or jailed validator * cannot finalize it, and a validator can finalize it after * COMMISION_CHANGE_DELAY_SECONDS elapsed since the initialization of commission change. */ function finalizeCommissionChange() external; /** * @notice Attempts to unjail a validator. Only the validator who wants to unjail can call * itself. */ function tryUnjail() external; /** * @notice Call ASSET_MANAGER.bondValidatorKro(). This function is only called by the Colosseum * contract. * * @param validator Address of the validator. */ function bondValidatorKro(address validator) external; /** * @notice Call ASSET_MANAGER.unbondValidatorKro(). This function is only called by the * Colosseum contract. * * @param validator Address of the validator. */ function unbondValidatorKro(address validator) external; /** * @notice Slash KRO from the vault of the challenge loser and move the slashing asset to * pending challenge reward before output rewarded, after directly to winner's asset. * Since the behavior could threaten the security of the chain, the loser is sent to * jail for HARD_JAIL_PERIOD_SECONDS. This function is only called by the Colosseum * contract. * * @param outputIndex The index of output challenged. * @param winner Address of the challenge winner. * @param loser Address of the challenge loser. */ function slash(uint256 outputIndex, address winner, address loser) external; /** * @notice Revert slash. This function is only called by the Colosseum contract. * * @param outputIndex The index of output challenged. * @param loser Address of the challenge loser. */ function revertSlash(uint256 outputIndex, address loser) external; /** * @notice Updates the validator tree. * * @param validator Address of the validator. * @param tryRemove Flag to try remove the validator from validator tree. */ function updateValidatorTree(address validator, bool tryRemove) external; /** * @notice Returns the no submission count of given validator. * * @param validator Address of the validator. * * @return The no submission count of given validator. */ function noSubmissionCount(address validator) external view returns (uint8); /** * @notice Returns the commission rate of given validator. * * @param validator Address of the validator. * * @return The commission rate of given validator. */ function getCommissionRate(address validator) external view returns (uint8); /** * @notice Returns the pending commission rate of given validator. * * @param validator Address of the validator. * * @return The pending commission rate of given validator. */ function getPendingCommissionRate(address validator) external view returns (uint8); /** * @notice Returns when commission change of given validator can be finalized. * * @param validator Address of the validator. * * @return When commission change of given validator can be finalized. */ function canFinalizeCommissionChangeAt(address validator) external view returns (uint128); /** * @notice Checks the eligibility to submit L2 checkpoint output during output submission. * Note that only the validator whose status is ACTIVE can submit output. This function * can only be called by L2OutputOracle during output submission. * * @param validator Address of the output submitter. */ function checkSubmissionEligibility(address validator) external view; /** * @notice Determines who can submit the L2 checkpoint output for the current round. * * @return Address of the validator who can submit the L2 checkpoint output for the current * round. */ function nextValidator() external view returns (address); /** * @notice Returns the status of the validator corresponding to the given address. * * @param validator Address of the validator. * * @return The status of the validator corresponding to the given address. */ function getStatus(address validator) external view returns (ValidatorStatus); /** * @notice Returns if the given validator is in jail or not. * * @param validator Address of the validator. * * @return If the given validator is in jail or not. */ function inJail(address validator) external view returns (bool); /** * @notice Returns the jail expiration timestamp of given validator. * * @param validator Address of the jailed validator. * * @return The jail expiration timestamp of given validator. */ function jailExpiresAt(address validator) external view returns (uint128); /** * @notice Returns if the status of the given validator is active. * * @param validator Address of the validator. * * @return If the status of the given validator is active. */ function isActive(address validator) external view returns (bool); /** * @notice Returns the weight of given validator. It not activated, returns 0. * Note that `weight / activatedValidatorTotalWeight()` is the probability that the * validator is selected as a priority validator. * * @param validator Address of the validator. * * @return The weight of given validator. */ function getWeight(address validator) external view returns (uint120); /** * @notice Returns the number of activated validators. * * @return The number of activated validators. */ function activatedValidatorCount() external view returns (uint32); /** * @notice Returns the total weight of activated validators. * * @return The total weight of activated validators. */ function activatedValidatorTotalWeight() external view returns (uint120); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { Initializable } from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import { Constants } from "../libraries/Constants.sol"; import { Types } from "../libraries/Types.sol"; import { ISemver } from "../universal/ISemver.sol"; import { IValidatorManager } from "./interfaces/IValidatorManager.sol"; import { ValidatorPool } from "./ValidatorPool.sol"; /** * @custom:proxied * @title L2OutputOracle * @notice The L2OutputOracle contains an array of L2 state outputs, where each output is a * commitment to the state of the L2 chain. Other contracts like the KromaPortal use * these outputs to verify information about the state of L2. */ contract L2OutputOracle is Initializable, ISemver { /** * @notice The address of the validator pool contract. Can be updated via upgrade. */ ValidatorPool public immutable VALIDATOR_POOL; /** * @notice The address of the validator manager contract. Can be updated via upgrade. */ IValidatorManager public immutable VALIDATOR_MANAGER; /** * @notice The address of the colosseum contract. Can be updated via upgrade. */ address public immutable COLOSSEUM; /** * @notice The interval in L2 blocks at which checkpoints must be submitted. Although this is * immutable, it can be modified by upgrading the implementation contract. * Note that nodes that fetch and use this value need to restart when it is modified. */ uint256 public immutable SUBMISSION_INTERVAL; /** * @notice The time between L2 blocks in seconds. Once set, this value MUST NOT be modified. */ uint256 public immutable L2_BLOCK_TIME; /** * @notice Minimum time (in seconds) that must elapse before a withdrawal can be finalized. */ uint256 public immutable FINALIZATION_PERIOD_SECONDS; /** * @notice The number of the first L2 block recorded in this contract. */ uint256 public startingBlockNumber; /** * @notice The timestamp of the first L2 block recorded in this contract. */ uint256 public startingTimestamp; /** * @notice Array of L2 checkpoint outputs. */ Types.CheckpointOutput[] internal l2Outputs; /** * @notice The output index of the next finalization target output. */ uint256 public nextFinalizeOutputIndex; /** * @notice Emitted when an output is submitted. * * @param outputRoot The output root. * @param l2OutputIndex The index of the output in the l2Outputs array. * @param l2BlockNumber The L2 block number of the output root. * @param l1Timestamp The L1 timestamp when submitted. */ event OutputSubmitted( bytes32 indexed outputRoot, uint256 indexed l2OutputIndex, uint256 indexed l2BlockNumber, uint256 l1Timestamp ); /** * @notice Emitted when an output is replaced. * * @param outputIndex Replaced L2 output index. * @param newSubmitter Output submitter after replacement. * @param newOutputRoot L2 output root after replacement. */ event OutputReplaced( uint256 indexed outputIndex, address indexed newSubmitter, bytes32 newOutputRoot ); /** * @notice Semantic version. * @custom:semver 1.1.0 */ string public constant version = "1.1.0"; /** * @notice Constructs the L2OutputOracle contract. * * @param _validatorPool The address of the ValidatorPool contract. * @param _validatorManager The address of the ValidatorManager contract. * @param _colosseum The address of the Colosseum contract. * @param _submissionInterval Interval in blocks at which checkpoints must be submitted. * @param _l2BlockTime The time per L2 block, in seconds. * @param _startingBlockNumber The number of the first L2 block. * @param _startingTimestamp The timestamp of the first L2 block. * @param _finalizationPeriodSeconds Output finalization time in seconds. */ constructor( ValidatorPool _validatorPool, IValidatorManager _validatorManager, address _colosseum, uint256 _submissionInterval, uint256 _l2BlockTime, uint256 _startingBlockNumber, uint256 _startingTimestamp, uint256 _finalizationPeriodSeconds ) { require(_l2BlockTime > 0, "L2OutputOracle: L2 block time must be greater than 0"); require( _submissionInterval > 0, "L2OutputOracle: submission interval must be greater than 0" ); VALIDATOR_POOL = _validatorPool; VALIDATOR_MANAGER = _validatorManager; COLOSSEUM = _colosseum; SUBMISSION_INTERVAL = _submissionInterval; L2_BLOCK_TIME = _l2BlockTime; FINALIZATION_PERIOD_SECONDS = _finalizationPeriodSeconds; initialize(_startingBlockNumber, _startingTimestamp); } /** * @notice Initializer. * * @param _startingBlockNumber Block number for the first recorded L2 block. * @param _startingTimestamp Timestamp for the first recorded L2 block. */ function initialize( uint256 _startingBlockNumber, uint256 _startingTimestamp ) public initializer { require( _startingTimestamp <= block.timestamp, "L2OutputOracle: starting L2 timestamp must be less than current time" ); startingTimestamp = _startingTimestamp; startingBlockNumber = _startingBlockNumber; } /** * @notice Replaces the output that corresponds to the given output index. * Only the Colosseum contract can replace an output. * * @param _l2OutputIndex Index of the L2 output to be replaced. * @param _newOutputRoot The L2 output root to replace the existing one. * @param _submitter Address of the L2 output submitter. */ function replaceL2Output( uint256 _l2OutputIndex, bytes32 _newOutputRoot, address _submitter ) external { require( msg.sender == COLOSSEUM, "L2OutputOracle: only the colosseum contract can replace an output" ); require(_submitter != address(0), "L2OutputOracle: submitter address cannot be zero"); // Make sure we're not *increasing* the length of the array. require( _l2OutputIndex < l2Outputs.length, "L2OutputOracle: cannot replace an output after the latest output index" ); Types.CheckpointOutput storage output = l2Outputs[_l2OutputIndex]; // Do not allow replacing any outputs that have already been finalized. require( block.timestamp - output.timestamp < FINALIZATION_PERIOD_SECONDS, "L2OutputOracle: cannot replace an output that has already been finalized" ); output.outputRoot = _newOutputRoot; output.submitter = _submitter; emit OutputReplaced(_l2OutputIndex, _submitter, _newOutputRoot); } /** * @notice Accepts an outputRoot and the block number of the corresponding L2 block. * The block number must be equal to the current value returned by `nextBlockNumber()` * in order to be accepted. This function may only be called by the validator. * * @param _outputRoot The L2 output of the checkpoint block. * @param _l2BlockNumber The L2 block number that resulted in _outputRoot. * @param _l1BlockHash A block hash which must be included in the current chain. * @param _l1BlockNumber The block number with the specified block hash. */ function submitL2Output( bytes32 _outputRoot, uint256 _l2BlockNumber, bytes32 _l1BlockHash, uint256 _l1BlockNumber ) external payable { uint256 outputIndex = nextOutputIndex(); // Upgrade validator system after validator pool contract is terminated. bool isValidatorPoolTerminated = VALIDATOR_POOL.isTerminated(outputIndex); address nextValidator; if (isValidatorPoolTerminated) { VALIDATOR_MANAGER.checkSubmissionEligibility(msg.sender); } else { nextValidator = VALIDATOR_POOL.nextValidator(); } // If it's not a public round, only selected validators can submit output. if ( !isValidatorPoolTerminated && nextValidator != Constants.VALIDATOR_PUBLIC_ROUND_ADDRESS ) { require( msg.sender == nextValidator, "L2OutputOracle: only the next selected validator can submit output" ); } require( _l2BlockNumber == nextBlockNumber(), "L2OutputOracle: block number must be equal to next expected block number" ); require( nextOutputMinL2Timestamp() <= block.timestamp, "L2OutputOracle: cannot submit L2 output in the future" ); require( _outputRoot != bytes32(0), "L2OutputOracle: L2 checkpoint output cannot be the zero hash" ); if (_l1BlockHash != bytes32(0) && blockhash(_l1BlockNumber) != bytes32(0)) { // This check allows the validator to submit an output based on a given L1 block, // without fear that it will be reorged out. // It will be skipped if the blockheight provided is more than 256 blocks behind the // chain tip (as the hash will return as zero). require( blockhash(_l1BlockNumber) == _l1BlockHash, "L2OutputOracle: block hash does not match the hash at the expected height" ); } l2Outputs.push( Types.CheckpointOutput({ submitter: msg.sender, outputRoot: _outputRoot, timestamp: uint128(block.timestamp), l2BlockNumber: uint128(_l2BlockNumber) }) ); emit OutputSubmitted(_outputRoot, outputIndex, _l2BlockNumber, block.timestamp); if (isValidatorPoolTerminated) { VALIDATOR_MANAGER.afterSubmitL2Output(outputIndex); } else { VALIDATOR_POOL.createBond( outputIndex, uint128(block.timestamp + FINALIZATION_PERIOD_SECONDS) ); } } /** * @notice Updates the next output index to be finalized. This function may only be called by * the validator pool contract before terminated, after that by the validator manager * contract. * * @param _outputIndex Index of the next output to be finalized. */ function setNextFinalizeOutputIndex(uint256 _outputIndex) external { if (VALIDATOR_POOL.isTerminated(_outputIndex - 1)) { require( msg.sender == address(VALIDATOR_MANAGER), "L2OutputOracle: only the validator manager contract can set next finalize output index" ); } else { require( msg.sender == address(VALIDATOR_POOL), "L2OutputOracle: only the validator pool contract can set next finalize output index" ); } nextFinalizeOutputIndex = _outputIndex; } /** * @notice Returns an output by index. Reverts if output is not found at the given index. * * @param _l2OutputIndex Index of the output to return. * * @return The output at the given index. */ function getL2Output( uint256 _l2OutputIndex ) external view returns (Types.CheckpointOutput memory) { return l2Outputs[_l2OutputIndex]; } /** * @notice Returns the index of the L2 output that checkpoints a given L2 block number. Uses a * binary search to find the first output greater than or equal to the given block. * * @param _l2BlockNumber L2 block number to find a checkpoint for. * * @return Index of the first checkpoint that commits to the given L2 block number. */ function getL2OutputIndexAfter(uint256 _l2BlockNumber) public view returns (uint256) { // Make sure an output for this block number has actually been submitted. require( _l2BlockNumber <= latestBlockNumber(), "L2OutputOracle: cannot get output for a block that has not been submitted" ); // Make sure there's at least one output submitted. require( l2Outputs.length > 0, "L2OutputOracle: cannot get output as no outputs have been submitted yet" ); // Find the output via binary search, guaranteed to exist. uint256 lo = 0; uint256 hi = l2Outputs.length; while (lo < hi) { uint256 mid = (lo + hi) / 2; if (l2Outputs[mid].l2BlockNumber < _l2BlockNumber) { lo = mid + 1; } else { hi = mid; } } return lo; } /** * @notice Returns the L2 checkpoint output that checkpoints a given L2 block number. * * @param _l2BlockNumber L2 block number to find a checkpoint for. * * @return First checkpoint that commits to the given L2 block number. */ function getL2OutputAfter( uint256 _l2BlockNumber ) external view returns (Types.CheckpointOutput memory) { return l2Outputs[getL2OutputIndexAfter(_l2BlockNumber)]; } /** * @notice Returns the index of the latest submitted output. Will revert if no outputs * have been submitted yet. * * @return The index of the latest submitted output. */ function latestOutputIndex() external view returns (uint256) { return l2Outputs.length - 1; } /** * @notice Returns the index of the next output to be submitted. * * @return The index of the next output to be submitted. */ function nextOutputIndex() public view returns (uint256) { return l2Outputs.length; } /** * @notice Returns the block number of the latest submitted L2 checkpoint output. If no outputs * have been submitted yet then this function will return the starting block number. * * @return Latest submitted L2 block number. */ function latestBlockNumber() public view returns (uint256) { return l2Outputs.length == 0 ? startingBlockNumber : l2Outputs[l2Outputs.length - 1].l2BlockNumber; } /** * @notice Computes the block number of the next L2 block that needs to be checkpointed. If no * outputs have been submitted yet then this function will return the latest block * number, which is the starting block number. * * @return Next L2 block number. */ function nextBlockNumber() public view returns (uint256) { return l2Outputs.length == 0 ? latestBlockNumber() : latestBlockNumber() + SUBMISSION_INTERVAL; } /** * @notice Returns the L2 timestamp corresponding to a given L2 block number. * * @param _l2BlockNumber The L2 block number of the target block. * * @return L2 timestamp of the given block. */ function computeL2Timestamp(uint256 _l2BlockNumber) public view returns (uint256) { return startingTimestamp + ((_l2BlockNumber - startingBlockNumber) * L2_BLOCK_TIME); } /** * @notice Returns the L2 timestamp corresponding to the right next block of the block that * needs to be checkpointed. * Note that the added one is because of the existence of next block hash in the output. * * @return L2 timestamp of the right next block of the block that needs to be checkpointed. */ function nextOutputMinL2Timestamp() public view returns (uint256) { return computeL2Timestamp(nextBlockNumber() + 1); } /** * @notice Returns the address of the L2 output submitter. * * @param _outputIndex Index of an output. * * @return Address of the submitter. */ function getSubmitter(uint256 _outputIndex) external view returns (address) { return l2Outputs[_outputIndex].submitter; } /** * @notice Returns if the output of given index is finalized. * * @param _outputIndex Index of an output. * * @return If the given output is finalized or not. */ function isFinalized(uint256 _outputIndex) external view returns (bool) { return finalizedAt(_outputIndex) <= block.timestamp; } /** * @notice Returns the finalization time of given output index. * * @param _outputIndex Index of an output. * * @return The finalization time of given output index. */ function finalizedAt(uint256 _outputIndex) public view returns (uint256) { return l2Outputs[_outputIndex].timestamp + FINALIZATION_PERIOD_SECONDS; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { Initializable } from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; import { Arithmetic } from "../libraries/Arithmetic.sol"; import { Burn } from "../libraries/Burn.sol"; /** * @custom:upgradeable * @title ResourceMetering * @notice ResourceMetering implements an EIP-1559 style resource metering system where pricing * updates automatically based on current demand. */ abstract contract ResourceMetering is Initializable { /** * @notice Represents the various parameters that control the way in which resources are * metered. Corresponds to the EIP-1559 resource metering system. * * @custom:field prevBaseFee Base fee from the previous block(s). * @custom:field prevBoughtGas Amount of gas bought so far in the current block. * @custom:field prevBlockNum Last block number that the base fee was updated. */ struct ResourceParams { uint128 prevBaseFee; uint64 prevBoughtGas; uint64 prevBlockNum; } /** * @notice Represents the configuration for the EIP-1559 based curve for the deposit gas * market. These values should be set with care as it is possible to set them in * a way that breaks the deposit gas market. The target resource limit is defined as * maxResourceLimit / elasticityMultiplier. This struct was designed to fit within a * single word. There is additional space for additions in the future. * * @custom:field maxResourceLimit Represents the maximum amount of deposit gas that * can be purchased per block. * @custom:field elasticityMultiplier Determines the target resource limit along with * the resource limit. * @custom:field baseFeeMaxChangeDenominator Determines max change on fee per block. * @custom:field minimumBaseFee The min deposit base fee, it is clamped to this * value. * @custom:field systemTxMaxGas The amount of gas supplied to the system * transaction. This should be set to the same number * that the kroma-node sets as the gas limit for the * system transaction. * @custom:field maximumBaseFee The max deposit base fee, it is clamped to this * value. */ struct ResourceConfig { uint32 maxResourceLimit; uint8 elasticityMultiplier; uint8 baseFeeMaxChangeDenominator; uint32 minimumBaseFee; uint32 systemTxMaxGas; uint128 maximumBaseFee; } /** * @notice EIP-1559 style gas parameters. */ ResourceParams public params; /** * @notice Reserve extra slots (to a total of 50) in the storage layout for future upgrades. */ uint256[48] private __gap; /** * @notice Meters access to a function based an amount of a requested resource. * * @param _amount Amount of the resource requested. */ modifier metered(uint64 _amount) { // Record initial gas amount so we can refund for it later. uint256 initialGas = gasleft(); // Run the underlying function. _; // Run the metering function. _metered(_amount, initialGas); } /** * @notice An internal function that holds all of the logic for metering a resource. * * @param _amount Amount of the resource requested. * @param _initialGas The amount of gas before any modifier execution. */ function _metered(uint64 _amount, uint256 _initialGas) internal { // Update block number and base fee if necessary. uint256 blockDiff = block.number - params.prevBlockNum; ResourceConfig memory config = _resourceConfig(); int256 targetResourceLimit = int256(uint256(config.maxResourceLimit)) / int256(uint256(config.elasticityMultiplier)); if (blockDiff > 0) { // Handle updating EIP-1559 style gas parameters. We use EIP-1559 to restrict the rate // at which deposits can be created and therefore limit the potential for deposits to // spam the L2 system. Fee scheme is very similar to EIP-1559 with minor changes. int256 gasUsedDelta = int256(uint256(params.prevBoughtGas)) - targetResourceLimit; int256 baseFeeDelta = (int256(uint256(params.prevBaseFee)) * gasUsedDelta) / (targetResourceLimit * int256(uint256(config.baseFeeMaxChangeDenominator))); // Update base fee by adding the base fee delta and clamp the resulting value between // min and max. int256 newBaseFee = Arithmetic.clamp({ _value: int256(uint256(params.prevBaseFee)) + baseFeeDelta, _min: int256(uint256(config.minimumBaseFee)), _max: int256(uint256(config.maximumBaseFee)) }); // If we skipped more than one block, we also need to account for every empty block. // Empty block means there was no demand for deposits in that block, so we should // reflect this lack of demand in the fee. if (blockDiff > 1) { // Update the base fee by repeatedly applying the exponent 1-(1/change_denominator) // blockDiff - 1 times. Simulates multiple empty blocks. Clamp the resulting value // between min and max. newBaseFee = Arithmetic.clamp({ _value: Arithmetic.cdexp({ _coefficient: newBaseFee, _denominator: int256(uint256(config.baseFeeMaxChangeDenominator)), _exponent: int256(blockDiff - 1) }), _min: int256(uint256(config.minimumBaseFee)), _max: int256(uint256(config.maximumBaseFee)) }); } // Update new base fee, reset bought gas, and update block number. params.prevBaseFee = uint128(uint256(newBaseFee)); params.prevBoughtGas = 0; params.prevBlockNum = uint64(block.number); } // Make sure we can actually buy the resource amount requested by the user. params.prevBoughtGas += _amount; require( int256(uint256(params.prevBoughtGas)) <= int256(uint256(config.maxResourceLimit)), "ResourceMetering: cannot buy more gas than available gas limit" ); // Determine the amount of ETH to be paid. uint256 resourceCost = uint256(_amount) * uint256(params.prevBaseFee); // We currently charge for this ETH amount as an L1 gas burn, so we convert the ETH amount // into gas by dividing by the L1 base fee. We assume a minimum base fee of 1 gwei to avoid // division by zero for L1s that don't support 1559 or to avoid excessive gas burns during // periods of extremely low L1 demand. One-day average gas fee hasn't dipped below 1 gwei // during any 1 day period in the last 5 years, so should be fine. uint256 gasCost = resourceCost / Math.max(block.basefee, 1 gwei); // Give the user a refund based on the amount of gas they used to do all of the work up to // this point. Since we're at the end of the modifier, this should be pretty accurate. Acts // effectively like a dynamic stipend (with a minimum value). uint256 usedGas = _initialGas - gasleft(); if (gasCost > usedGas) { Burn.gas(gasCost - usedGas); } } /** * @notice Virtual function that returns the resource config. Contracts that inherit this * contract must implement this function. * * @return ResourceConfig */ function _resourceConfig() internal virtual returns (ResourceConfig memory); /** * @notice Sets initial resource parameter values. This function must either be called by the * initializer function of an upgradeable child contract. */ // solhint-disable-next-line func-name-mixedcase function __ResourceMetering_init() internal onlyInitializing { params = ResourceParams({ prevBaseFee: 1 gwei, prevBoughtGas: 0, prevBlockNum: uint64(block.number) }); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 amount) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../extensions/IERC20Permit.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; /** * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } /** * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful. */ function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } /** * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 oldAllowance = token.allowance(address(this), spender); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value)); } /** * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value)); } } /** * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval * to be set to zero before setting it to a non-zero value, such as USDT. */ function forceApprove(IERC20 token, address spender, uint256 value) internal { bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, approvalCall); } } /** * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`. * Revert on invalid signature. */ function safePermit( IERC20Permit token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). * * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead. */ function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false // and not revert is the subcall reverts. (bool success, bytes memory returndata) = address(token).call(data); return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721 * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must * understand this adds an external call which potentially creates a reentrancy vulnerability. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; /** * @title IAssetManager * @notice Interface for AssetManager contract. */ interface IAssetManager { /** * @notice Represents the asset information of the vault of a validator. * * @custom:field validatorKro Total amount of KRO that deposited by the validator and * accumulated as validator reward (including validatorKroBonded). * @custom:field validatorKroBonded Total amount of validator KRO that bonded during output * submission or challenge creation. * @custom:field totalKro Total amount of KRO that delegated by the delegators and * accumulated as KRO delegation reward. * @custom:field totalKroShares Total shares for KRO delegation in the vault. * @custom:field totalKgh Total number of KGH in the vault. * @custom:field rewardPerKghStored Accumulated boosted reward per 1 KGH. */ struct Asset { uint128 validatorKro; uint128 validatorKroBonded; uint128 totalKro; uint128 totalKroShares; uint128 totalKgh; uint128 rewardPerKghStored; } /** * @notice Constructs the delegator of KRO in the vault of a validator. * * @custom:field shares Amount of shares for KRO delegation. * @custom:field lastDelegatedAt Last timestamp when the delegator delegated. The delegator can * undelegate after MIN_DELEGATION_PERIOD elapsed. */ struct KroDelegator { uint128 shares; uint128 lastDelegatedAt; } /** * @notice Constructs the delegator of KGH in the vault of a validator. * * @custom:field rewardPerKghPaid Accumulated paid boosted reward per 1 KGH. * @custom:field kghNum Total number of KGH delegated. * @custom:field delegatedAt A mapping of tokenId to the delegation timestamp. The * delegator can undelegate after MIN_DELEGATION_PERIOD * elapsed from each delegation timestamp. */ struct KghDelegator { uint128 rewardPerKghPaid; uint128 kghNum; mapping(uint256 => uint128) delegatedAt; } /** * @notice Constructs the vault of a validator. * * @custom:field withdrawAccount An account where assets can be withdrawn to. Only this account * can withdraw the assets. * @custom:field lastDepositedAt Last timestamp when the validator deposited. The validator can * withdraw after MIN_DELEGATION_PERIOD elapsed. * @custom:field asset Asset information of the vault. * @custom:field kroDelegators A mapping of validator address to KRO delegator struct. * @custom:field kghDelegators A mapping of validator address to KGH delegator struct. */ struct Vault { address withdrawAccount; uint128 lastDepositedAt; Asset asset; mapping(address => KroDelegator) kroDelegators; mapping(address => KghDelegator) kghDelegators; } /** * @notice Emitted when validator deposited KROs. * * @param validator Address of the validator. * @param amount The amount of KRO deposited. */ event Deposited(address indexed validator, uint128 amount); /** * @notice Emitted when KROs are delegated. * * @param validator Address of the validator. * @param delegator Address of the delegator. * @param amount The amount of KRO delegated. * @param shares The amount of shares received. */ event KroDelegated( address indexed validator, address indexed delegator, uint128 amount, uint128 shares ); /** * @notice Emitted when a KGH is delegated. * * @param validator Address of the validator. * @param delegator Address of the delegator. * @param tokenId Token id of the KGH. */ event KghDelegated(address indexed validator, address indexed delegator, uint256 tokenId); /** * @notice Emitted when KGHs are delegated in batch. * * @param validator Address of the validator. * @param delegator Address of the delegator. * @param tokenIds Array of token ids of the KGHs. */ event KghBatchDelegated( address indexed validator, address indexed delegator, uint256[] tokenIds ); /** * @notice Emitted when validator withdrew KRO. * * @param validator Address of the validator. * @param amount The amount of KRO the validator withdrew. */ event Withdrawn(address indexed validator, uint128 amount); /** * @notice Emitted when KRO is undelegated. * * @param validator Address of the validator. * @param delegator Address of the delegator. * @param amount The amount of KRO to undelegate. * @param shares The amount of shares to be burnt. */ event KroUndelegated( address indexed validator, address indexed delegator, uint128 amount, uint128 shares ); /** * @notice Emitted when KGH is undelegated. * * @param validator Address of the validator. * @param delegator Address of the delegator. * @param tokenId Token id of the KGH. * @param amount The amount of KRO claimed as boosted reward. */ event KghUndelegated( address indexed validator, address indexed delegator, uint256 tokenId, uint128 amount ); /** * @notice Emitted when KGHs are undelegated in batch. * * @param validator Address of the validator. * @param delegator Address of the delegator. * @param tokenIds Array of token ids of the KGHs. * @param amount The amount of KRO claimed as boosted reward. */ event KghBatchUndelegated( address indexed validator, address indexed delegator, uint256[] tokenIds, uint128 amount ); /** * @notice Emitted when accumulated rewards of KGH delegation are claimed. * * @param validator Address of the validator. * @param delegator Address of the delegator. * @param amount The amount of KRO claimed as boosted reward. */ event KghRewardClaimed(address indexed validator, address indexed delegator, uint128 amount); /** * @notice Emitted when validator KRO is bonded during output submission or challenge creation. * * @param validator Address of the validator. * @param amount The amount of KRO bonded. * @param remainder The remaining amount of validator KRO excluding bonded KRO. */ event ValidatorKroBonded(address indexed validator, uint128 amount, uint128 remainder); /** * @notice Emitted when validator KRO is unbonded during output finalization or slashing. * * @param validator Address of the validator. * @param amount The amount of KRO unbonded. * @param remainder The remaining amount of validator KRO excluding bonded KRO. */ event ValidatorKroUnbonded(address indexed validator, uint128 amount, uint128 remainder); /** * @notice Reverts when caller is not allowed. */ error NotAllowedCaller(); /** * @notice Reverts when the status of validator is improper. */ error ImproperValidatorStatus(); /** * @notice Reverts when try to input zero. */ error NotAllowedZeroInput(); /** * @notice Reverts when the address is zero address. */ error ZeroAddress(); /** * @notice Reverts when the asset is insufficient. */ error InsufficientAsset(); /** * @notice Reverts when the share is insufficient. */ error InsufficientShare(); /** * @notice Reverts when the minimum delegation period is not elapsed. */ error NotElapsedMinDelegationPeriod(); /** * @notice Reverts when the given token ids are invalid. */ error InvalidTokenIdsInput(); /** * @notice Returns the address of withdraw account of given validator. * * @param validator Address of the validator. * * @return The address of withdraw account of given validator. */ function getWithdrawAccount(address validator) external view returns (address); /** * @notice Returns when the validator can withdraw KRO. The validator can withdraw after * MIN_DELEGATION_PERIOD elapsed from lastDepositedAt. * * @param validator Address of the validator. * * @return When the validator can withdraw KRO. */ function canWithdrawAt(address validator) external view returns (uint128); /** * @notice Returns the total amount of KRO a validator has deposited and been rewarded. * * @param validator Address of the validator. * * @return The total amount of KRO a validator has deposited and been rewarded. */ function totalValidatorKro(address validator) external view returns (uint128); /** * @notice Returns the total amount of validator KRO that bonded during output submission or * challenge creation. * * @param validator Address of the validator. * * @return The total amount of validator KRO bonded. */ function totalValidatorKroBonded(address validator) external view returns (uint128); /** * @notice Returns the total amount of validator balance excluding the bond amount. * * @param validator Address of the validator. * * @return The total amount of validator balance excluding the bond amount. */ function totalValidatorKroNotBonded(address validator) external view returns (uint128); /** * @notice Returns the total amount of KRO that delegated by the delegators and accumulated as * KRO delegation reward. * * @param validator Address of the validator. * * @return The total amount of KRO that delegated by the delegators and accumulated as KRO * delegation reward. */ function totalKroAssets(address validator) external view returns (uint128); /** * @notice Returns the total number of KGHs held by the vault. * * @param validator Address of the validator. * * @return The total number of KGHs held by the vault. */ function totalKghNum(address validator) external view returns (uint128); /** * @notice Returns the amount of KRO shares that the KRO delegator has. * * @param validator Address of the validator. * @param delegator Address of the delegator. * * @return The amount of KRO shares that the KRO delegator has. */ function getKroTotalShareBalance( address validator, address delegator ) external view returns (uint128); /** * @notice Returns the amount of KRO assets delegated to the given validator by the delegator. * * @param validator Address of the validator. * @param delegator Address of the delegator. * * @return The amount of KRO assets that the delegator delegated to the validator. */ function getKroAssets(address validator, address delegator) external view returns (uint128); /** * @notice Returns when the KRO delegators can undelegate KRO. The delegators can undelegate * after MIN_DELEGATION_PERIOD elapsed from lastDelegatedAt. * * @param validator Address of the validator. * @param delegator Address of the KRO delegator. * * @return When the KRO delegators can undelegate KRO. */ function canUndelegateKroAt( address validator, address delegator ) external view returns (uint128); /** * @notice Returns the number of KGH delegated by the given delegator. * * @param validator Address of the validator. * @param delegator Address of the delegator. * * @return The number of KGH delegated by the given delegator. */ function getKghNum(address validator, address delegator) external view returns (uint128); /** * @notice Returns when the KGH delegators can undelegate KGH. The delegators can undelegate KGH * for the given token id after MIN_DELEGATION_PERIOD elapsed from delegation * timestamp. * * @param validator Address of the validator. * @param delegator Address of the KGH delegator. * @param tokenId The token id of KGH to undelegate. * * @return When the KGH delegators can undelegate KGH for the given token id. */ function canUndelegateKghAt( address validator, address delegator, uint256 tokenId ) external view returns (uint128); /** * @notice Allows an on-chain or off-chain user to simulate the effects of their KRO delegation * at the current block. * * @param validator Address of the validator. * @param assets The amount of assets to delegate. * * @return The amount of shares that the Vault would exchange for the amount of assets provided. */ function previewDelegate(address validator, uint128 assets) external view returns (uint128); /** * @notice Allows an on-chain or off-chain user to simulate the effects of their KRO * undelegation at the current block. * * @param validator The address of the validator. * @param shares The amount of shares to undelegate. * * @return The amount of assets that the Vault would exchange for the amount of shares provided. */ function previewUndelegate(address validator, uint128 shares) external view returns (uint128); /** * @notice Returns the claimable reward of KGH delegation. * * @param validator The address of the validator. * @param delegator The address of the delegator. * * @return The amount of claimable reward of KGH delegation. */ function getKghReward(address validator, address delegator) external view returns (uint128); /** * @notice Deposit KRO. To deposit KRO, the validator should be initiated. * * @param assets The amount of KRO to deposit. */ function deposit(uint128 assets) external; /** * @notice Withdraw KRO. To withdraw KRO, the validator should be initiated and MIN_DELEGATION_PERIOD * should be passed after the last deposit time. Only withdrawAccount of the validator can call * this function. * * @param validator Address of the validator. * @param assets The amount of KRO to withdraw. */ function withdraw(address validator, uint128 assets) external; /** * @notice Delegate KRO to the validator and returns the amount of shares that the vault would * exchange. * * @param validator Address of the validator. * @param assets The amount of KRO to delegate. * * @return The amount of shares that the Vault would exchange for the amount of assets provided. */ function delegate(address validator, uint128 assets) external returns (uint128); /** * @notice Delegate KGH to the validator. * * @param validator Address of the validator. * @param tokenId The token id of KGH to delegate. */ function delegateKgh(address validator, uint256 tokenId) external; /** * @notice Delegate KGHs to the validator. * * @param validator Address of the validator. * @param tokenIds The token ids of KGHs to delegate. */ function delegateKghBatch(address validator, uint256[] calldata tokenIds) external; /** * @notice Undelegate the KRO of given assets for the given validator. * * @param validator Address of the validator. * @param assets The amount of assets to undelegate. */ function undelegate(address validator, uint128 assets) external; /** * @notice Undelegate KGH for given validator and tokenId. * * @param validator Address of the validator. * @param tokenId Token id of KGH to undelegate. */ function undelegateKgh(address validator, uint256 tokenId) external; /** * @notice Undelegate KGHs for given validator and token ids. * * @param validator Address of the validator. * @param tokenIds Array of token ids of KGHs to undelegate. */ function undelegateKghBatch(address validator, uint256[] calldata tokenIds) external; /** * @notice Claim the boosted reward of the KGH delegator from the given validator vault. * * @param validator Address of the validator. */ function claimKghReward(address validator) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ```solidity * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a * constructor. * * Emits an {Initialized} event. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: setting the version to 255 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized != type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint8) { return _initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _initializing; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import { Constants } from "../libraries/Constants.sol"; import { Predeploys } from "../libraries/Predeploys.sol"; import { SafeCall } from "../libraries/SafeCall.sol"; import { Types } from "../libraries/Types.sol"; import { ISemver } from "../universal/ISemver.sol"; import { ValidatorRewardVault } from "../L2/ValidatorRewardVault.sol"; import { KromaPortal } from "./KromaPortal.sol"; import { L2OutputOracle } from "./L2OutputOracle.sol"; /** * @custom:proxied * @title ValidatorPool * @notice The ValidatorPool determines whether the validator is present and manages the validator's deposit. */ contract ValidatorPool is ReentrancyGuardUpgradeable, ISemver { /** * @notice The gas limit to use when rewarding validator in the ValidatorRewardVault on L2. * This value is measured through simulation. */ uint64 public constant VAULT_REWARD_GAS_LIMIT = 100000; /** * @notice The numerator of the tax. */ uint128 public constant TAX_NUMERATOR = 20; /** * @notice The denominator of the tax. */ uint128 public constant TAX_DENOMINATOR = 100; /** * @notice The address of the L2OutputOracle contract. Can be updated via upgrade. */ L2OutputOracle public immutable L2_ORACLE; /** * @notice The address of the KromaPortal contract. Can be updated via upgrade. */ KromaPortal public immutable PORTAL; /** * @notice The address of the SecurityCouncil contract. Can be updated via upgrade. */ address public immutable SECURITY_COUNCIL; /** * @notice The address of the trusted validator. Can be updated via upgrade. */ address public immutable TRUSTED_VALIDATOR; /** * @notice The required bond amount. Can be updated via upgrade. */ uint128 public immutable REQUIRED_BOND_AMOUNT; /** * @notice The max number of unbonds when trying unbond. */ uint256 public immutable MAX_UNBOND; /** * @notice The duration of a submission round for one output (in seconds). * Note that there are two submission rounds for an output: PRIORITY ROUND and PUBLIC ROUND. */ uint256 public immutable ROUND_DURATION; /** * @notice The output index where ValidatorPool is terminated after. Validator system is * upgraded to ValidatorManager. */ uint256 public immutable TERMINATE_OUTPUT_INDEX; /** * @notice A mapping of balances. */ mapping(address => uint256) internal balances; /** * @notice The bond corresponding to a specific output index. */ mapping(uint256 => Types.Bond) internal bonds; /** * @notice The output index to unbond next. */ uint256 internal nextUnbondOutputIndex; /** * @notice An array of validator addresses. */ address[] internal validators; /** * @notice The index of the specific address in the validator array. */ mapping(address => uint256) internal validatorIndexes; /** * @notice Address of the next validator with priority for submitting output. */ address internal nextPriorityValidator; /** * @notice A mapping of pending bonds that have not yet been included in a bond. */ mapping(uint256 => mapping(address => uint128)) internal pendingBonds; /** * @notice Emitted when a validator bonds. * * @param submitter Address of submitter. * @param outputIndex Index of the L2 checkpoint output index. * @param amount Amount of bonded. * @param expiresAt The expiration timestamp of bond. */ event Bonded( address indexed submitter, uint256 indexed outputIndex, uint128 amount, uint128 expiresAt ); /** * @notice Emitted when the pending bond is added. * * @param outputIndex Index of the L2 checkpoint output. * @param challenger Address of the challenger. * @param amount Amount of bond added. */ event PendingBondAdded(uint256 indexed outputIndex, address indexed challenger, uint128 amount); /** * @notice Emitted when the bond is increased. * * @param outputIndex Index of the L2 checkpoint output. * @param challenger Address of the challenger. * @param amount Amount of bond increased. */ event BondIncreased(uint256 indexed outputIndex, address indexed challenger, uint128 amount); /** * @notice Emitted when the pending bond is released(refunded). * * @param outputIndex Index of the L2 checkpoint output. * @param challenger Address of the challenger. * @param recipient Address to receive amount from a pending bond. * @param amount Amount of bond released. */ event PendingBondReleased( uint256 indexed outputIndex, address indexed challenger, address indexed recipient, uint128 amount ); /** * @notice Emitted when a validator unbonds. * * @param outputIndex Index of the L2 checkpoint output. * @param recipient Address of the recipient. * @param amount Amount of unbonded. */ event Unbonded(uint256 indexed outputIndex, address indexed recipient, uint128 amount); /** * @notice A modifier that only allows the Colosseum contract to call */ modifier onlyColosseum() { require(msg.sender == L2_ORACLE.COLOSSEUM(), "ValidatorPool: sender is not Colosseum"); _; } /** * @notice Semantic version. * @custom:semver 1.1.0 */ string public constant version = "1.1.0"; /** * @notice Constructs the ValidatorPool contract. * * @param _l2OutputOracle Address of the L2OutputOracle. * @param _portal Address of the KromaPortal. * @param _securityCouncil Address of the security council. * @param _trustedValidator Address of the trusted validator. * @param _requiredBondAmount The required bond amount. * @param _maxUnbond The max number of unbonds when trying unbond. * @param _roundDuration The duration of one submission round in seconds. * @param _terminateOutputIndex The output index where ValidatorPool is terminated after. */ constructor( L2OutputOracle _l2OutputOracle, KromaPortal _portal, address _securityCouncil, address _trustedValidator, uint256 _requiredBondAmount, uint256 _maxUnbond, uint256 _roundDuration, uint256 _terminateOutputIndex ) { L2_ORACLE = _l2OutputOracle; PORTAL = _portal; SECURITY_COUNCIL = _securityCouncil; TRUSTED_VALIDATOR = _trustedValidator; REQUIRED_BOND_AMOUNT = uint128(_requiredBondAmount); MAX_UNBOND = _maxUnbond; TERMINATE_OUTPUT_INDEX = _terminateOutputIndex; // Note that this value MUST be (SUBMISSION_INTERVAL * L2_BLOCK_TIME) / 2. ROUND_DURATION = _roundDuration; initialize(); } /** * @notice Initializer. */ function initialize() public initializer { __ReentrancyGuard_init_unchained(); } /** * @notice Deposit ETH to be used as bond. Note that deposit after termination is not allowed. */ function deposit() external payable { require( L2_ORACLE.nextOutputIndex() < TERMINATE_OUTPUT_INDEX + 1, "ValidatorPool: only can deposit to ValidatorPool before terminated" ); _increaseBalance(msg.sender, msg.value); } /** * @notice Withdraw a given amount. * * @param _amount Amount to withdraw. */ function withdraw(uint256 _amount) external nonReentrant { _decreaseBalance(msg.sender, _amount); bool success = SafeCall.call(msg.sender, gasleft(), _amount, ""); require(success, "ValidatorPool: ETH transfer failed"); } /** * @notice Withdraw a given amount. * * @param _to Address to withdraw asset to. * @param _amount Amount to withdraw. */ function withdrawTo(address _to, uint256 _amount) external nonReentrant { require(_to != address(0), "ValidatorPool: cannot withdraw to the zero address"); _decreaseBalance(msg.sender, _amount); bool success = SafeCall.call(_to, gasleft(), _amount, ""); require(success, "ValidatorPool: ETH transfer failed"); } /** * @notice Bond asset corresponding to the given output index. * This function is called when submitting output. * * @param _outputIndex Index of the L2 checkpoint output. * @param _expiresAt The expiration timestamp of bond. */ function createBond(uint256 _outputIndex, uint128 _expiresAt) external { require(msg.sender == address(L2_ORACLE), "ValidatorPool: sender is not L2OutputOracle"); Types.Bond storage bond = bonds[_outputIndex]; require( bond.expiresAt == 0, "ValidatorPool: bond of the given output index already exists" ); // Unbond the bond of nextUnbondOutputIndex if available. _tryUnbond(); address submitter = L2_ORACLE.getSubmitter(_outputIndex); _decreaseBalance(submitter, REQUIRED_BOND_AMOUNT); bond.amount = REQUIRED_BOND_AMOUNT; bond.expiresAt = _expiresAt; emit Bonded(submitter, _outputIndex, REQUIRED_BOND_AMOUNT, _expiresAt); // Select the next priority validator _updatePriorityValidator(); } /** * @notice Adds a pending bond to the challenge corresponding to the given output index and challenger address. * The pending bond is added to the bond when the challenge is proven or challenger is timed out, * or refunded when the challenge is canceled. * * @param _outputIndex Index of the L2 checkpoint output. * @param _challenger Address of the challenger. */ function addPendingBond(uint256 _outputIndex, address _challenger) external onlyColosseum { Types.Bond storage bond = bonds[_outputIndex]; require( bond.expiresAt >= block.timestamp, "ValidatorPool: the output is already finalized" ); _decreaseBalance(_challenger, REQUIRED_BOND_AMOUNT); pendingBonds[_outputIndex][_challenger] = REQUIRED_BOND_AMOUNT; emit PendingBondAdded(_outputIndex, _challenger, REQUIRED_BOND_AMOUNT); } /** * @notice Releases the corresponding pending bond to the given output index and challenger address * if a challenge is canceled. * * @param _outputIndex Index of the L2 checkpoint output. * @param _challenger Address of the challenger. * @param _recipient Address to receive amount from a pending bond. */ function releasePendingBond( uint256 _outputIndex, address _challenger, address _recipient ) external onlyColosseum { uint128 bonded = pendingBonds[_outputIndex][_challenger]; require(bonded > 0, "ValidatorPool: the pending bond does not exist"); delete pendingBonds[_outputIndex][_challenger]; _increaseBalance(_recipient, bonded); emit PendingBondReleased(_outputIndex, _challenger, _recipient, bonded); } /** * @notice Increases the bond amount corresponding to the given output index by the pending bond amount. * This is when taxes are charged, and note that taxes are a means of preventing collusive attacks by * the asserter and challenger. * * @param _outputIndex Index of the L2 checkpoint output. * @param _challenger Address of the challenger. */ function increaseBond(uint256 _outputIndex, address _challenger) external onlyColosseum { Types.Bond storage bond = bonds[_outputIndex]; require( bond.expiresAt >= block.timestamp, "ValidatorPool: the output is already finalized" ); uint128 pendingBond = pendingBonds[_outputIndex][_challenger]; require(pendingBond > 0, "ValidatorPool: the pending bond does not exist"); uint128 tax = (pendingBond * TAX_NUMERATOR) / TAX_DENOMINATOR; uint128 increased = pendingBond - tax; delete pendingBonds[_outputIndex][_challenger]; unchecked { bond.amount += increased; balances[SECURITY_COUNCIL] += tax; } emit BondIncreased(_outputIndex, _challenger, increased); } /** * @notice Attempt to unbond. Reverts if unbond is not possible. */ function unbond() external { bool released = _tryUnbond(); require(released, "ValidatorPool: no bond that can be unbond"); } /** * @notice Attempts to unbond starting from nextUnbondOutputIndex and returns whether at least * one unbond is executed. Tries unbond at most MAX_UNBOND number of bonds and sends * a reward message to L2 for each unbond. * * @return Whether at least one unbond is executed. */ function _tryUnbond() private returns (bool) { uint256 outputIndex = nextUnbondOutputIndex; uint128 bondAmount; Types.Bond storage bond; Types.CheckpointOutput memory output; uint256 unbondedNum = 0; for (; unbondedNum < MAX_UNBOND; ) { bond = bonds[outputIndex]; bondAmount = bond.amount; if (block.timestamp >= bond.expiresAt && bondAmount > 0) { delete bonds[outputIndex]; output = L2_ORACLE.getL2Output(outputIndex); _increaseBalance(output.submitter, bondAmount); emit Unbonded(outputIndex, output.submitter, bondAmount); // Send reward message to L2 ValidatorRewardVault. _sendRewardMessageToL2Vault(output); unchecked { ++unbondedNum; ++outputIndex; } } else { break; } } if (unbondedNum > 0) { unchecked { nextUnbondOutputIndex = outputIndex; } // Set the next output index to be finalized in L2OutputOracle. L2_ORACLE.setNextFinalizeOutputIndex(outputIndex); return true; } return false; } /** * @notice Updates next priority validator address. */ function _updatePriorityValidator() private { uint256 len = validators.length; if (len > 0 && nextUnbondOutputIndex > 0) { // TODO(pangssu): improve next validator selection Types.CheckpointOutput memory output = L2_ORACLE.getL2Output(nextUnbondOutputIndex - 1); uint256 validatorIndex = uint256( keccak256( abi.encodePacked( output.outputRoot, block.number, block.coinbase, block.difficulty, blockhash(block.number - 1) ) ) ) % len; nextPriorityValidator = validators[validatorIndex]; } else { nextPriorityValidator = address(0); } } /** * @notice Sends reward message to ValidatorRewardVault contract on L2 using Portal. * * @param _output The finalized output. */ function _sendRewardMessageToL2Vault(Types.CheckpointOutput memory _output) private { // Pay out rewards via L2 Vault now that the output is finalized. PORTAL.depositTransactionByValidatorPool( Predeploys.VALIDATOR_REWARD_VAULT, VAULT_REWARD_GAS_LIMIT, abi.encodeWithSelector( ValidatorRewardVault.reward.selector, _output.submitter, _output.l2BlockNumber ) ); } /** * @notice Increases the balance of the given address. If the balance is greater than the required bond amount, * add the given address to the validator set. * * @param _validator Address to increase the balance. * @param _amount Amount of balance increased. */ function _increaseBalance(address _validator, uint256 _amount) private { uint256 balance = balances[_validator] + _amount; if (balance >= REQUIRED_BOND_AMOUNT && !isValidator(_validator)) { if (_validator != SECURITY_COUNCIL) { validatorIndexes[_validator] = validators.length; validators.push(_validator); } } balances[_validator] = balance; } /** * @notice Deceases the balance of the given address. If the balance is less than the required bond amount, * remove the given address from the validator set. * * @param _validator Address to decrease the balance. * @param _amount Amount of balance decreased. */ function _decreaseBalance(address _validator, uint256 _amount) private { uint256 balance = balances[_validator]; require(balance >= _amount, "ValidatorPool: insufficient balances"); balance = balance - _amount; if (balance < REQUIRED_BOND_AMOUNT && isValidator(_validator)) { uint256 lastValidatorIndex = validators.length - 1; if (lastValidatorIndex > 0) { uint256 validatorIndex = validatorIndexes[_validator]; address lastValidator = validators[lastValidatorIndex]; validators[validatorIndex] = lastValidator; validatorIndexes[lastValidator] = validatorIndex; } delete validatorIndexes[_validator]; validators.pop(); } balances[_validator] = balance; } /** * @notice Returns the bond corresponding to the output index. Reverts if the bond does not exist. * * @param _outputIndex Index of the L2 checkpoint output. * * @return The bond data. */ function getBond(uint256 _outputIndex) external view returns (Types.Bond memory) { Types.Bond storage bond = bonds[_outputIndex]; require(bond.amount > 0 && bond.expiresAt > 0, "ValidatorPool: the bond does not exist"); return bond; } /** * @notice Returns the pending bond corresponding to the output index and challenger address. * Reverts if the pending bond does not exist. * * @param _outputIndex Index of the L2 checkpoint output. * @param _challenger Address of the challenger. * * @return Amount of the pending bond. */ function getPendingBond( uint256 _outputIndex, address _challenger ) external view returns (uint128) { uint128 pendingBond = pendingBonds[_outputIndex][_challenger]; require(pendingBond > 0, "ValidatorPool: the pending bond does not exist"); return pendingBond; } /** * @notice Returns the balance of given address. * * @param _addr Address of validator. * * @return Balance of given address. */ function balanceOf(address _addr) external view returns (uint256) { return balances[_addr]; } /** * @notice Determines whether the given address is an active validator. * * @param _addr Address of validator. * * @return Whether the given address is an active validator. */ function isValidator(address _addr) public view returns (bool) { if (validators.length == 0) { return false; } else if (_addr == address(0)) { return false; } uint256 index = validatorIndexes[_addr]; return validators[index] == _addr; } /** * @notice Returns the number of validators. * * @return The number of validators. */ function validatorCount() external view returns (uint256) { return validators.length; } /** * @notice Determines who can submit the L2 output next. * * @return The address of the validator. */ function nextValidator() public view returns (address) { if (nextPriorityValidator != address(0)) { uint256 l2Timestamp = L2_ORACLE.nextOutputMinL2Timestamp(); if (block.timestamp >= l2Timestamp) { uint256 elapsed = block.timestamp - l2Timestamp; // If the current time exceeds one round time, it is a public round. if (elapsed > ROUND_DURATION) { return Constants.VALIDATOR_PUBLIC_ROUND_ADDRESS; } } return nextPriorityValidator; } else { return TRUSTED_VALIDATOR; } } /** * @notice Determines whether the given output index must not interact with ValidatorPool. * * @param _outputIndex Index of the L2 checkpoint output. * * @return Whether the given output index must not interact with ValidatorPool. */ function isTerminated(uint256 _outputIndex) external view returns (bool) { return _outputIndex > TERMINATE_OUTPUT_INDEX; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; import { SignedMath } from "@openzeppelin/contracts/utils/math/SignedMath.sol"; import { FixedPointMathLib } from "@rari-capital/solmate/src/utils/FixedPointMathLib.sol"; /** * @title Arithmetic * @notice Even more math than before. */ library Arithmetic { /** * @notice Clamps a value between a minimum and maximum. * * @param _value The value to clamp. * @param _min The minimum value. * @param _max The maximum value. * * @return The clamped value. */ function clamp( int256 _value, int256 _min, int256 _max ) internal pure returns (int256) { return SignedMath.min(SignedMath.max(_value, _min), _max); } /** * @notice Clamps a value between a minimum and maximum. * * @param _value The value to clamp. * @param _min The minimum value. * @param _max The maximum value. * * @return The clamped value. */ function clamp( uint256 _value, uint256 _min, uint256 _max ) internal pure returns (uint256) { return Math.min(Math.max(_value, _min), _max); } /** * @notice (c)oefficient (d)enominator (exp)onentiation function. * Returns the result of: c * (1 - 1/d)^exp. * * @param _coefficient Coefficient of the function. * @param _denominator Fractional denominator. * @param _exponent Power function exponent. * * @return Result of c * (1 - 1/d)^exp. */ function cdexp( int256 _coefficient, int256 _denominator, int256 _exponent ) internal pure returns (int256) { return (_coefficient * (FixedPointMathLib.powWad(1e18 - (1e18 / _denominator), _exponent * 1e18))) / 1e18; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { SafeCall } from "./SafeCall.sol"; /** * @title Burn * @notice Utilities for burning stuff. */ library Burn { /** * Burns a given amount of ETH. * Note that execution engine of Kroma does not support SELFDESTRUCT opcode, so it sends ETH to zero address. * * @param _amount Amount of ETH to burn. */ function eth(uint256 _amount) internal { SafeCall.call(address(0), gasleft(), _amount, ""); } /** * Burns a given amount of gas. * * @param _amount Amount of gas to burn. */ function gas(uint256 _amount) internal view { uint256 i = 0; uint256 initialGas = gasleft(); while (initialGas - gasleft() < _amount) { ++i; } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * * Furthermore, `isContract` will also return true if the target contract within * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, * which only has an effect at the end of a transaction. * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { _nonReentrantBefore(); _; _nonReentrantAfter(); } function _nonReentrantBefore() private { // On the first call to nonReentrant, _status will be _NOT_ENTERED require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _nonReentrantAfter() private { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a * `nonReentrant` function in the call stack. */ function _reentrancyGuardEntered() internal view returns (bool) { return _status == _ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Predeploys * @notice Contains constant addresses for contracts that are pre-deployed to the L2 system. */ library Predeploys { /** * @notice Address of the ProxyAdmin predeploy. */ address internal constant PROXY_ADMIN = 0x4200000000000000000000000000000000000000; /** * @notice Address of the L1Block predeploy. */ address internal constant L1_BLOCK_ATTRIBUTES = 0x4200000000000000000000000000000000000002; /** * @notice Address of the L2ToL1MessagePasser predeploy. */ address internal constant L2_TO_L1_MESSAGE_PASSER = 0x4200000000000000000000000000000000000003; /** * @notice Address of the L2CrossDomainMessenger predeploy. */ address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000004; /** * @notice Address of the GasPriceOracle predeploy. Includes fee information * and helpers for computing the L1 portion of the transaction fee. */ address internal constant GAS_PRICE_ORACLE = 0x4200000000000000000000000000000000000005; /** * @notice Address of the ProtocolVault predeploy. */ address internal constant PROTOCOL_VAULT = 0x4200000000000000000000000000000000000006; /** * @notice Address of the L1FeeVault predeploy. */ address internal constant L1_FEE_VAULT = 0x4200000000000000000000000000000000000007; /** * @notice Address of the ValidatorRewardVault predeploy. */ address internal constant VALIDATOR_REWARD_VAULT = 0x4200000000000000000000000000000000000008; /** * @notice Address of the L2StandardBridge predeploy. */ address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000009; /** * @notice Address of the L2ERC721Bridge predeploy. */ address internal constant L2_ERC721_BRIDGE = 0x420000000000000000000000000000000000000A; /** * @notice Address of the KromaMintableERC20Factory predeploy. */ address internal constant KROMA_MINTABLE_ERC20_FACTORY = 0x420000000000000000000000000000000000000B; /** * @notice Address of the KromaMintableERC721Factory predeploy. */ address internal constant KROMA_MINTABLE_ERC721_FACTORY = 0x420000000000000000000000000000000000000c; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; /** * @title SafeCall * @notice Perform low level safe calls */ library SafeCall { /** * @notice Perform a low level call without copying any returndata * * @param _target Address to call * @param _gas Amount of gas to pass to the call * @param _value Amount of value to pass to the call * @param _calldata Calldata to pass to the call */ function call( address _target, uint256 _gas, uint256 _value, bytes memory _calldata ) internal returns (bool) { bool _success; assembly { _success := call( _gas, // gas _target, // recipient _value, // ether value add(_calldata, 32), // inloc mload(_calldata), // inlen 0, // outloc 0 // outlen ) } return _success; } /** * @notice Helper function to determine if there is sufficient gas remaining within the context * to guarantee that the minimum gas requirement for a call will be met as well as * optionally reserving a specified amount of gas for after the call has concluded. * * @param _minGas The minimum amount of gas that may be passed to the target context. * @param _reservedGas Optional amount of gas to reserve for the caller after the execution * of the target context. * * @return `true` if there is enough gas remaining to safely supply `_minGas` to the target * context as well as reserve `_reservedGas` for the caller after the execution of * the target context. * * @dev !!!!! FOOTGUN ALERT !!!!! * 1.) The 40_000 base buffer is to account for the worst case of the dynamic cost of the * `CALL` opcode's `address_access_cost`, `positive_value_cost`, and * `value_to_empty_account_cost` factors with an added buffer of 5,700 gas. It is * still possible to self-rekt by initiating a withdrawal with a minimum gas limit * that does not account for the `memory_expansion_cost` & `code_execution_cost` * factors of the dynamic cost of the `CALL` opcode. * 2.) This function should *directly* precede the external call if possible. There is an * added buffer to account for gas consumed between this check and the call, but it * is only 5,700 gas. * 3.) Because EIP-150 ensures that a maximum of 63/64ths of the remaining gas in the call * frame may be passed to a subcontext, we need to ensure that the gas will not be * truncated. * 4.) Use wisely. This function is not a silver bullet. */ function hasMinGas(uint256 _minGas, uint256 _reservedGas) internal view returns (bool) { bool _hasMinGas; assembly { // Equation: gas × 63 ≥ minGas × 64 + 63(40_000 + reservedGas) _hasMinGas := iszero( lt(mul(gas(), 63), add(mul(_minGas, 64), mul(add(40000, _reservedGas), 63))) ) } return _hasMinGas; } /** * @notice Perform a low level call without copying any returndata. This function * will revert if the call cannot be performed with the specified minimum * gas. * * @param _target Address to call * @param _minGas The minimum amount of gas that may be passed to the call * @param _value Amount of value to pass to the call * @param _calldata Calldata to pass to the call */ function callWithMinGas( address _target, uint256 _minGas, uint256 _value, bytes memory _calldata ) internal returns (bool) { bool _success; bool _hasMinGas = hasMinGas(_minGas, 0); assembly { // Assertion: gasleft() >= (_minGas * 64) / 63 + 40_000 if iszero(_hasMinGas) { // Store the "Error(string)" selector in scratch space. mstore(0, 0x08c379a0) // Store the pointer to the string length in scratch space. mstore(32, 32) // Store the string. // // SAFETY: // - We pad the beginning of the string with two zero bytes as well as the // length (24) to ensure that we override the free memory pointer at offset // 0x40. This is necessary because the free memory pointer is likely to // be greater than 1 byte when this function is called, but it is incredibly // unlikely that it will be greater than 3 bytes. As for the data within // 0x60, it is ensured that it is 0 due to 0x60 being the zero offset. // - It's fine to clobber the free memory pointer, we're reverting. mstore(88, 0x0000185361666543616c6c3a204e6f7420656e6f75676820676173) // Revert with 'Error("SafeCall: Not enough gas")' revert(28, 100) } // The call will be supplied at least ((_minGas * 64) / 63 + 40_000 - 49) gas due to the // above assertion. This ensures that, in all circumstances (except for when the // `_minGas` does not account for the `memory_expansion_cost` and `code_execution_cost` // factors of the dynamic cost of the `CALL` opcode), the call will receive at least // the minimum amount of gas specified. _success := call( gas(), // gas _target, // recipient _value, // ether value add(_calldata, 32), // inloc mload(_calldata), // inlen 0x00, // outloc 0x00 // outlen ) } return _success; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { L2StandardBridge } from "../L2/L2StandardBridge.sol"; import { Predeploys } from "../libraries/Predeploys.sol"; import { SafeCall } from "../libraries/SafeCall.sol"; import { FeeVault } from "../universal/FeeVault.sol"; import { ISemver } from "../universal/ISemver.sol"; import { AddressAliasHelper } from "../vendor/AddressAliasHelper.sol"; /** * @custom:proxied * @custom:predeploy 0x4200000000000000000000000000000000000008 * @title ValidatorRewardVault * @notice The ValidatorRewardVault accumulates transaction fees and pays rewards to validators. */ contract ValidatorRewardVault is FeeVault, ISemver { /** * @notice Address of the ValidatorPool contract on L1. */ address public immutable VALIDATOR_POOL; /** * @notice A value to divide the vault balance by when determining the reward amount. */ uint256 public immutable REWARD_DIVIDER; /** * @notice The reward balance that the validator is eligible to receive. */ mapping(address => uint256) internal rewards; /** * @notice A mapping of whether the reward corresponding to the L2 block number has been paid. */ mapping(uint256 => bool) internal isPaid; /** * @notice The amount of determined as rewards. */ uint256 public totalReserved; /** * @notice Emitted when the balance of a validator has increased. * * @param validator Address of the validator. * @param l2BlockNumber The L2 block number of the output root. * @param amount Amount of the reward. */ event Rewarded(address indexed validator, uint256 indexed l2BlockNumber, uint256 amount); /** * @notice Semantic version. * @custom:semver 1.0.0 */ string public constant version = "1.0.0"; /** * @notice Constructs the ValidatorRewardVault contract. * * @param _validatorPool Address of the ValidatorPool contract on L1. * @param _rewardDivider A value to divide the vault balance by when determining the reward amount. */ constructor(address _validatorPool, uint256 _rewardDivider) FeeVault(address(0), 0) { VALIDATOR_POOL = _validatorPool; REWARD_DIVIDER = _rewardDivider; } /** * @notice Rewards the validator for submitting the output. * ValidatorPool contract on L1 calls this function over the portal when output is finalized. * * @param _validator Address of the validator. * @param _l2BlockNumber The L2 block number of the output root. */ function reward(address _validator, uint256 _l2BlockNumber) external { require( AddressAliasHelper.undoL1ToL2Alias(msg.sender) == VALIDATOR_POOL, "ValidatorRewardVault: function can only be called from the ValidatorPool" ); require(_validator != address(0), "ValidatorRewardVault: validator address cannot be 0"); require( !isPaid[_l2BlockNumber], "ValidatorRewardVault: the reward has already been paid for the L2 block number" ); uint256 amount = _determineRewardAmount(); unchecked { totalReserved += amount; rewards[_validator] += amount; } isPaid[_l2BlockNumber] = true; emit Rewarded(_validator, _l2BlockNumber, amount); } /** * @notice Checks if the withdrawal is possible, and returns the withdrawal amount. * When a withdrawal is available, it resets the balance and updates the total processed amount. */ function _processWithdrawal() internal override returns (uint256) { uint256 amount = rewards[msg.sender]; require( amount >= MIN_WITHDRAWAL_AMOUNT, "ValidatorRewardVault: withdrawal amount must be greater than minimum withdrawal amount" ); rewards[msg.sender] = 0; unchecked { totalReserved -= amount; totalProcessed += amount; } emit Withdrawal(amount, msg.sender, msg.sender); return amount; } /** * @notice Withdraws all of the sender's balance. * Reverts if the balance is less than the minimum withdrawal amount. */ function withdraw() external override { uint256 amount = _processWithdrawal(); L2StandardBridge(payable(Predeploys.L2_STANDARD_BRIDGE)).bridgeETHTo{ value: amount }( msg.sender, WITHDRAWAL_MIN_GAS, bytes("") ); } /** * @notice Withdraws all of the sender's balance to L2. * Reverts if the balance is less than the minimum withdrawal amount. */ function withdrawToL2() external override { uint256 amount = _processWithdrawal(); bool success = SafeCall.call(msg.sender, gasleft(), amount, bytes("")); require(success, "ValidatorRewardVault: ETH transfer failed"); } /** * @notice Determines the reward amount. * * @return Amount of the reward. */ function _determineRewardAmount() internal view returns (uint256) { return (address(this).balance - totalReserved) / REWARD_DIVIDER; } /** * @notice Returns the reward balance of the given address. * * @param _addr Address to lookup. * * @return The reward balance of the given address. */ function balanceOf(address _addr) external view returns (uint256) { return rewards[_addr]; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { Initializable } from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import { Constants } from "../libraries/Constants.sol"; import { Hashing } from "../libraries/Hashing.sol"; import { SafeCall } from "../libraries/SafeCall.sol"; import { Types } from "../libraries/Types.sol"; import { ISemver } from "../universal/ISemver.sol"; import { AddressAliasHelper } from "../vendor/AddressAliasHelper.sol"; import { L2OutputOracle } from "./L2OutputOracle.sol"; import { ResourceMetering } from "./ResourceMetering.sol"; import { SystemConfig } from "./SystemConfig.sol"; import { ZKMerkleTrie } from "./ZKMerkleTrie.sol"; /** * @custom:proxied * @title KromaPortal * @notice The KromaPortal is a low-level contract responsible for passing messages between L1 * and L2. Messages sent directly to the KromaPortal have no form of replayability. * Users are encouraged to use the L1CrossDomainMessenger for a higher-level interface. */ contract KromaPortal is Initializable, ResourceMetering, ISemver { /** * @notice Represents a proven withdrawal. * * @custom:field outputRoot Root of the L2 output this was proven against. * @custom:field timestamp Timestamp at whcih the withdrawal was proven. * @custom:field l2OutputIndex Index of the output this was proven against. */ struct ProvenWithdrawal { bytes32 outputRoot; uint128 timestamp; uint128 l2OutputIndex; } /** * @notice Version of the deposit event. */ uint256 internal constant DEPOSIT_VERSION = 0; /** * @notice The L2 gas limit set when eth is deposited using the receive() function. */ uint64 internal constant RECEIVE_DEFAULT_GAS_LIMIT = 100_000; /** * @notice Address of the L2OutputOracle contract. */ L2OutputOracle public immutable L2_ORACLE; /** * @notice Address of the ValidatorPool contract. */ address public immutable VALIDATOR_POOL; /** /** * @notice Address of the SystemConfig contract. */ SystemConfig public immutable SYSTEM_CONFIG; /** * @notice MultiSig wallet address that has the ability to pause and unpause withdrawals. */ address public immutable GUARDIAN; /** * @notice Address of the ZKMerkleTrie. */ ZKMerkleTrie public immutable ZK_MERKLE_TRIE; /** * @notice Address of the L2 account which initiated a withdrawal in this transaction. If the * of this variable is the default L2 sender address, then we are NOT inside of a call * to finalizeWithdrawalTransaction. */ address public l2Sender; /** * @notice A list of withdrawal hashes which have been successfully finalized. */ mapping(bytes32 => bool) public finalizedWithdrawals; /** * @notice A mapping of withdrawal hashes to `ProvenWithdrawal` data. */ mapping(bytes32 => ProvenWithdrawal) public provenWithdrawals; /** * @notice Determines if cross domain messaging is paused. When set to true, * withdrawals are paused. This may be removed in the future. */ bool public paused; /** * @notice Emitted when a transaction is deposited from L1 to L2. The parameters of this event * are read by the rollup node and used to derive deposit transactions on L2. * * @param from Address that triggered the deposit transaction. * @param to Address that the deposit transaction is directed to. * @param version Version of this deposit transaction event. * @param opaqueData ABI encoded deposit data to be parsed off-chain. */ event TransactionDeposited( address indexed from, address indexed to, uint256 indexed version, bytes opaqueData ); /** * @notice Emitted when a withdrawal transaction is proven. * * @param withdrawalHash Hash of the withdrawal transaction. */ event WithdrawalProven( bytes32 indexed withdrawalHash, address indexed from, address indexed to ); /** * @notice Emitted when a withdrawal transaction is finalized. * * @param withdrawalHash Hash of the withdrawal transaction. * @param success Whether the withdrawal transaction was successful. */ event WithdrawalFinalized(bytes32 indexed withdrawalHash, bool success); /** * @notice Emitted when the pause is triggered. * * @param account Address of the account triggering the pause. */ event Paused(address account); /** * @notice Emitted when the pause is lifted. * * @param account Address of the account triggering the unpause. */ event Unpaused(address account); /** * @notice Reverts when paused. */ modifier whenNotPaused() { require(paused == false, "KromaPortal: paused"); _; } /** * @notice Semantic version. * @custom:semver 1.0.0 */ string public constant version = "1.0.0"; /** * @notice Constructs the KromaPortal contract. * * @param _l2Oracle Address of the L2OutputOracle contract. * @param _validatorPool Address of the ValidatorPool contract. * @param _guardian MultiSig wallet address that can pause deposits and withdrawals. * @param _paused Sets the contract's pausability state. * @param _config Address of the SystemConfig contract. * @param _zkMerkleTrie Address of the ZKMerkleTrie contract. */ constructor( L2OutputOracle _l2Oracle, address _validatorPool, address _guardian, bool _paused, SystemConfig _config, ZKMerkleTrie _zkMerkleTrie ) { L2_ORACLE = _l2Oracle; VALIDATOR_POOL = _validatorPool; GUARDIAN = _guardian; SYSTEM_CONFIG = _config; ZK_MERKLE_TRIE = _zkMerkleTrie; initialize(_paused); } /** * @notice Initializer. */ function initialize(bool _paused) public initializer { l2Sender = Constants.DEFAULT_L2_SENDER; paused = _paused; __ResourceMetering_init(); } /** * @notice Pause deposits and withdrawals. */ function pause() external { require(msg.sender == GUARDIAN, "KromaPortal: only guardian can pause"); paused = true; emit Paused(msg.sender); } /** * @notice Unpause deposits and withdrawals. */ function unpause() external { require(msg.sender == GUARDIAN, "KromaPortal: only guardian can unpause"); paused = false; emit Unpaused(msg.sender); } /** * @notice Accepts value so that users can send ETH directly to this contract and have the * funds be deposited to their address on L2. This is intended as a convenience * function for EOAs. Contracts should call the depositTransaction() function directly * otherwise any deposited funds will be lost due to address aliasing. */ // solhint-disable-next-line ordering receive() external payable { depositTransaction(msg.sender, msg.value, RECEIVE_DEFAULT_GAS_LIMIT, false, bytes("")); } /** * @notice Getter for the resource config. Used internally by the ResourceMetering * contract. The SystemConfig is the source of truth for the resource config. * * @return ResourceMetering.ResourceConfig */ function _resourceConfig() internal view override returns (ResourceMetering.ResourceConfig memory) { return SYSTEM_CONFIG.resourceConfig(); } /** * @notice Proves a withdrawal transaction. * * @param _tx Withdrawal transaction to finalize. * @param _l2OutputIndex L2 output index to prove against. * @param _outputRootProof Inclusion proof of the L2ToL1MessagePasser contract's storage root. * @param _withdrawalProof Inclusion proof of the withdrawal in L2ToL1MessagePasser contract. */ function proveWithdrawalTransaction( Types.WithdrawalTransaction memory _tx, uint256 _l2OutputIndex, Types.OutputRootProof calldata _outputRootProof, bytes[] calldata _withdrawalProof ) external whenNotPaused { // Prevent users from creating a deposit transaction where this address is the message // sender on L2. Because this is checked here, we do not need to check again in // `finalizeWithdrawalTransaction`. require( _tx.target != address(this), "KromaPortal: you cannot send messages to the portal contract" ); // Get the output root and load onto the stack to prevent multiple mloads. This will // revert if there is no output root for the given block number. bytes32 outputRoot = L2_ORACLE.getL2Output(_l2OutputIndex).outputRoot; // Verify that the output root can be generated with the elements in the proof. require( outputRoot == Hashing.hashOutputRootProof(_outputRootProof), "KromaPortal: invalid output root proof" ); // Load the ProvenWithdrawal into memory, using the withdrawal hash as a unique identifier. bytes32 withdrawalHash = Hashing.hashWithdrawal(_tx); ProvenWithdrawal memory provenWithdrawal = provenWithdrawals[withdrawalHash]; // We generally want to prevent users from proving the same withdrawal multiple times // because each successive proof will update the timestamp. A malicious user can take // advantage of this to prevent other users from finalizing their withdrawal. However, // since withdrawals are proven before an output root is finalized, we need to allow users // to re-prove their withdrawal only in the case that the output root for their specified // output index has been updated. require( provenWithdrawal.timestamp == 0 || L2_ORACLE.getL2Output(provenWithdrawal.l2OutputIndex).outputRoot != provenWithdrawal.outputRoot, "KromaPortal: withdrawal hash has already been proven" ); // Compute the storage slot of the withdrawal hash in the L2ToL1MessagePasser contract. // Refer to the Solidity documentation for more information on how storage layouts are // computed for mappings. bytes32 storageKey = keccak256( abi.encode( withdrawalHash, uint256(0) // The withdrawals mapping is at the first slot in the layout. ) ); // Verify that the hash of this withdrawal was stored in the L2toL1MessagePasser contract // on L2. If this is true, under the assumption that the ZKMerkleTrie contract does not have // bugs, then we know that this withdrawal was actually triggered on L2 and can therefore // be relayed on L1. require( ZK_MERKLE_TRIE.verifyInclusionProof( storageKey, hex"0000000000000000000000000000000000000000000000000000000000000001", _withdrawalProof, _outputRootProof.messagePasserStorageRoot ), "KromaPortal: invalid withdrawal inclusion proof" ); // Designate the withdrawalHash as proven by storing the `outputRoot`, `timestamp`, and // `l2OutputIndex` in the `provenWithdrawals` mapping. A `withdrawalHash` can only be // proven once unless it is submitted again with a different outputRoot. provenWithdrawals[withdrawalHash] = ProvenWithdrawal({ outputRoot: outputRoot, timestamp: uint128(block.timestamp), l2OutputIndex: uint128(_l2OutputIndex) }); // Emit a `WithdrawalProven` event. emit WithdrawalProven(withdrawalHash, _tx.sender, _tx.target); } /** * @notice Finalizes a withdrawal transaction. * * @param _tx Withdrawal transaction to finalize. */ function finalizeWithdrawalTransaction(Types.WithdrawalTransaction memory _tx) external whenNotPaused { // Make sure that the l2Sender has not yet been set. The l2Sender is set to a value other // than the default value when a withdrawal transaction is being finalized. This check is // a defacto reentrancy guard. require( l2Sender == Constants.DEFAULT_L2_SENDER, "KromaPortal: can only trigger one withdrawal per transaction" ); // Grab the proven withdrawal from the `provenWithdrawals` map. bytes32 withdrawalHash = Hashing.hashWithdrawal(_tx); ProvenWithdrawal memory provenWithdrawal = provenWithdrawals[withdrawalHash]; // A withdrawal can only be finalized if it has been proven. We know that a withdrawal has // been proven at least once when its timestamp is non-zero. Unproven withdrawals will have // a timestamp of zero. require(provenWithdrawal.timestamp != 0, "KromaPortal: withdrawal has not been proven yet"); // As a sanity check, we make sure that the proven withdrawal's timestamp is greater than // starting timestamp inside the L2OutputOracle. Not strictly necessary but extra layer of // safety against weird bugs in the proving step. require( provenWithdrawal.timestamp >= L2_ORACLE.startingTimestamp(), "KromaPortal: withdrawal timestamp less than L2 Oracle starting timestamp" ); // A proven withdrawal must wait at least the finalization period before it can be // finalized. This waiting period can elapse in parallel with the waiting period for the // output the withdrawal was proven against. In effect, this means that the minimum // withdrawal time is l2 output submission time + finalization period. require( _isFinalizationPeriodElapsed(provenWithdrawal.timestamp), "KromaPortal: proven withdrawal finalization period has not elapsed" ); // Grab the CheckpointOutput from the L2OutputOracle, will revert if the output that // corresponds to the given index has not been submitted yet. Types.CheckpointOutput memory checkpointOutput = L2_ORACLE.getL2Output( provenWithdrawal.l2OutputIndex ); // Check that the output root that was used to prove the withdrawal is the same as the // current output root for the given output index. An output root may change if it is // deleted by the challenger address and then re-submitted. require( checkpointOutput.outputRoot == provenWithdrawal.outputRoot, "KromaPortal: output root proven is not the same as current output root" ); // Check that the checkpoint output has also been finalized. require( _isFinalizationPeriodElapsed(checkpointOutput.timestamp), "KromaPortal: checkpoint output finalization period has not elapsed" ); // Check that this withdrawal has not already been finalized, this is replay protection. require( finalizedWithdrawals[withdrawalHash] == false, "KromaPortal: withdrawal has already been finalized" ); // Mark the withdrawal as finalized so it can't be replayed. finalizedWithdrawals[withdrawalHash] = true; // Set the l2Sender so contracts know who triggered this withdrawal on L2. l2Sender = _tx.sender; // Trigger the call to the target contract. We use a custom low level method // SafeCall.callWithMinGas to ensure two key properties // 1. Target contracts cannot force this call to run out of gas by returning a very large // amount of data (and this is OK because we don't care about the returndata here). // 2. The amount of gas provided to the execution context of the target is at least the // gas limit specified by the user. If there is not enough gas in the current context // to accomplish this, `callWithMinGas` will revert. bool success = SafeCall.callWithMinGas(_tx.target, _tx.gasLimit, _tx.value, _tx.data); // Reset the l2Sender back to the default value. l2Sender = Constants.DEFAULT_L2_SENDER; // All withdrawals are immediately finalized. Replayability can // be achieved through contracts built on top of this contract emit WithdrawalFinalized(withdrawalHash, success); // Reverting here is useful for determining the exact gas cost to successfully execute the // sub call to the target contract if the minimum gas limit specified by the user would not // be sufficient to execute the sub call. if (success == false && tx.origin == Constants.ESTIMATION_ADDRESS) { revert("KromaPortal: withdrawal failed"); } } /** * @notice Accepts deposits of ETH and data, and emits a TransactionDeposited event for use in * deriving deposit transactions. Note that if a deposit is made by a contract, its * address will be aliased when retrieved using `tx.origin` or `msg.sender`. Consider * using the CrossDomainMessenger contracts for a simpler developer experience. * * @param _to Target address on L2. * @param _value ETH value to send to the recipient. * @param _gasLimit Minimum L2 gas limit (can be greater than or equal to this value). * @param _isCreation Whether or not the transaction is a contract creation. * @param _data Data to trigger the recipient with. */ function depositTransaction( address _to, uint256 _value, uint64 _gasLimit, bool _isCreation, bytes memory _data ) public payable metered(_gasLimit) { // Just to be safe, make sure that people specify address(0) as the target when doing // contract creations. if (_isCreation) { require( _to == address(0), "KromaPortal: must send to address(0) when creating a contract" ); } // Prevent depositing transactions that have too small of a gas limit. require(_gasLimit >= 21_000, "KromaPortal: gas limit must cover instrinsic gas cost"); // Transform the from-address to its alias if the caller is a contract. address from = msg.sender; if (msg.sender != tx.origin) { from = AddressAliasHelper.applyL1ToL2Alias(msg.sender); } // Compute the opaque data that will be emitted as part of the TransactionDeposited event. // We use opaque data so that we can update the TransactionDeposited event in the future // without breaking the current interface. bytes memory opaqueData = abi.encodePacked( msg.value, _value, _gasLimit, _isCreation, _data ); // Emit a TransactionDeposited event so that the rollup node can derive a deposit // transaction for this deposit. emit TransactionDeposited(from, _to, DEPOSIT_VERSION, opaqueData); } /** * @notice Accepts deposits of data from ValidatorPool contract, and emits a TransactionDeposited event for use in * deriving deposit transactions on L2. * * @param _to Target address on L2. * @param _gasLimit Minimum L2 gas limit (can be greater than or equal to this value). * @param _data Data to trigger the recipient with. */ function depositTransactionByValidatorPool( address _to, uint64 _gasLimit, bytes memory _data ) public { require( msg.sender == VALIDATOR_POOL, "KromaPortal: function can only be called from the ValidatorPool" ); // Transform the from-address to its alias. address from = AddressAliasHelper.applyL1ToL2Alias(msg.sender); // Compute the opaque data that will be emitted as part of the TransactionDeposited event. bytes memory opaqueData = abi.encodePacked(uint256(0), uint256(0), _gasLimit, false, _data); // Emit a TransactionDeposited event so that the rollup node can derive a deposit // transaction for this deposit. emit TransactionDeposited(from, _to, DEPOSIT_VERSION, opaqueData); } /** * @notice Determines if the output at the given index is finalized. Reverts if the call to * L2_ORACLE.getL2Output reverts. Returns a boolean otherwise. * * @param _l2OutputIndex Index of the L2 output to check. * * @return Whether or not the output is finalized. */ function isOutputFinalized(uint256 _l2OutputIndex) external view returns (bool) { return _isFinalizationPeriodElapsed(L2_ORACLE.getL2Output(_l2OutputIndex).timestamp); } /** * @notice Determines whether the finalization period has elapsed w/r/t a given timestamp. * * @param _timestamp Timestamp to check. * * @return Whether or not the finalization period has elapsed. */ function _isFinalizationPeriodElapsed(uint256 _timestamp) internal view returns (bool) { return block.timestamp > _timestamp + L2_ORACLE.FINALIZATION_PERIOD_SECONDS(); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol) pragma solidity ^0.8.0; /** * @dev Standard signed math utilities missing in the Solidity language. */ library SignedMath { /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) internal pure returns (int256) { // Formula from the book "Hacker's Delight" int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // must be unchecked in order to support `n = type(int256).min` return uint256(n >= 0 ? n : -n); } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// @notice Arithmetic library with operations for fixed-point numbers. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol) library FixedPointMathLib { /*////////////////////////////////////////////////////////////// SIMPLIFIED FIXED POINT OPERATIONS //////////////////////////////////////////////////////////////*/ uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s. function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down. } function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up. } function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down. } function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up. } function powWad(int256 x, int256 y) internal pure returns (int256) { // Equivalent to x to the power of y because x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y) return expWad((lnWad(x) * y) / int256(WAD)); // Using ln(x) means x must be greater than 0. } function expWad(int256 x) internal pure returns (int256 r) { unchecked { // When the result is < 0.5 we return zero. This happens when // x <= floor(log(0.5e18) * 1e18) ~ -42e18 if (x <= -42139678854452767551) return 0; // When the result is > (2**255 - 1) / 1e18 we can not represent it as an // int. This happens when x >= floor(log((2**255 - 1) / 1e18) * 1e18) ~ 135. if (x >= 135305999368893231589) revert("EXP_OVERFLOW"); // x is now in the range (-42, 136) * 1e18. Convert to (-42, 136) * 2**96 // for more intermediate precision and a binary basis. This base conversion // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78. x = (x << 78) / 5**18; // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers // of two such that exp(x) = exp(x') * 2**k, where k is an integer. // Solving this gives k = round(x / log(2)) and x' = x - k * log(2). int256 k = ((x << 96) / 54916777467707473351141471128 + 2**95) >> 96; x = x - k * 54916777467707473351141471128; // k is in the range [-61, 195]. // Evaluate using a (6, 7)-term rational approximation. // p is made monic, we'll multiply by a scale factor later. int256 y = x + 1346386616545796478920950773328; y = ((y * x) >> 96) + 57155421227552351082224309758442; int256 p = y + x - 94201549194550492254356042504812; p = ((p * y) >> 96) + 28719021644029726153956944680412240; p = p * x + (4385272521454847904659076985693276 << 96); // We leave p in 2**192 basis so we don't need to scale it back up for the division. int256 q = x - 2855989394907223263936484059900; q = ((q * x) >> 96) + 50020603652535783019961831881945; q = ((q * x) >> 96) - 533845033583426703283633433725380; q = ((q * x) >> 96) + 3604857256930695427073651918091429; q = ((q * x) >> 96) - 14423608567350463180887372962807573; q = ((q * x) >> 96) + 26449188498355588339934803723976023; assembly { // Div in assembly because solidity adds a zero check despite the unchecked. // The q polynomial won't have zeros in the domain as all its roots are complex. // No scaling is necessary because p is already 2**96 too large. r := sdiv(p, q) } // r should be in the range (0.09, 0.25) * 2**96. // We now need to multiply r by: // * the scale factor s = ~6.031367120. // * the 2**k factor from the range reduction. // * the 1e18 / 2**96 factor for base conversion. // We do this all at once, with an intermediate result in 2**213 // basis, so the final right shift is always by a positive amount. r = int256((uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)); } } function lnWad(int256 x) internal pure returns (int256 r) { unchecked { require(x > 0, "UNDEFINED"); // We want to convert x from 10**18 fixed point to 2**96 fixed point. // We do this by multiplying by 2**96 / 10**18. But since // ln(x * C) = ln(x) + ln(C), we can simply do nothing here // and add ln(2**96 / 10**18) at the end. // Reduce range of x to (1, 2) * 2**96 // ln(2^k * x) = k * ln(2) + ln(x) int256 k = int256(log2(uint256(x))) - 96; x <<= uint256(159 - k); x = int256(uint256(x) >> 159); // Evaluate using a (8, 8)-term rational approximation. // p is made monic, we will multiply by a scale factor later. int256 p = x + 3273285459638523848632254066296; p = ((p * x) >> 96) + 24828157081833163892658089445524; p = ((p * x) >> 96) + 43456485725739037958740375743393; p = ((p * x) >> 96) - 11111509109440967052023855526967; p = ((p * x) >> 96) - 45023709667254063763336534515857; p = ((p * x) >> 96) - 14706773417378608786704636184526; p = p * x - (795164235651350426258249787498 << 96); // We leave p in 2**192 basis so we don't need to scale it back up for the division. // q is monic by convention. int256 q = x + 5573035233440673466300451813936; q = ((q * x) >> 96) + 71694874799317883764090561454958; q = ((q * x) >> 96) + 283447036172924575727196451306956; q = ((q * x) >> 96) + 401686690394027663651624208769553; q = ((q * x) >> 96) + 204048457590392012362485061816622; q = ((q * x) >> 96) + 31853899698501571402653359427138; q = ((q * x) >> 96) + 909429971244387300277376558375; assembly { // Div in assembly because solidity adds a zero check despite the unchecked. // The q polynomial is known not to have zeros in the domain. // No scaling required because p is already 2**96 too large. r := sdiv(p, q) } // r is in the range (0, 0.125) * 2**96 // Finalization, we need to: // * multiply by the scale factor s = 5.549… // * add ln(2**96 / 10**18) // * add k * ln(2) // * multiply by 10**18 / 2**96 = 5**18 >> 78 // mul s * 5e18 * 2**96, base is now 5**18 * 2**192 r *= 1677202110996718588342820967067443963516166; // add ln(2) * k * 5e18 * 2**192 r += 16597577552685614221487285958193947469193820559219878177908093499208371 * k; // add ln(2**96 / 10**18) * 5e18 * 2**192 r += 600920179829731861736702779321621459595472258049074101567377883020018308; // base conversion: mul 2**18 / 2**192 r >>= 174; } } /*////////////////////////////////////////////////////////////// LOW LEVEL FIXED POINT OPERATIONS //////////////////////////////////////////////////////////////*/ function mulDivDown( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { revert(0, 0) } // Divide z by the denominator. z := div(z, denominator) } } function mulDivUp( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { revert(0, 0) } // First, divide z - 1 by the denominator and add 1. // We allow z - 1 to underflow if z is 0, because we multiply the // end result by 0 if z is zero, ensuring we return 0 if z is zero. z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1)) } } function rpow( uint256 x, uint256 n, uint256 scalar ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { // 0 ** 0 = 1 z := scalar } default { // 0 ** n = 0 z := 0 } } default { switch mod(n, 2) case 0 { // If n is even, store scalar in z for now. z := scalar } default { // If n is odd, store x in z for now. z := x } // Shifting right by 1 is like dividing by 2. let half := shr(1, scalar) for { // Shift n right by 1 before looping to halve it. n := shr(1, n) } n { // Shift n right by 1 each iteration to halve it. n := shr(1, n) } { // Revert immediately if x ** 2 would overflow. // Equivalent to iszero(eq(div(xx, x), x)) here. if shr(128, x) { revert(0, 0) } // Store x squared. let xx := mul(x, x) // Round to the nearest number. let xxRound := add(xx, half) // Revert if xx + half overflowed. if lt(xxRound, xx) { revert(0, 0) } // Set x to scaled xxRound. x := div(xxRound, scalar) // If n is even: if mod(n, 2) { // Compute z * x. let zx := mul(z, x) // If z * x overflowed: if iszero(eq(div(zx, x), z)) { // Revert if x is non-zero. if iszero(iszero(x)) { revert(0, 0) } } // Round to the nearest number. let zxRound := add(zx, half) // Revert if zx + half overflowed. if lt(zxRound, zx) { revert(0, 0) } // Return properly scaled zxRound. z := div(zxRound, scalar) } } } } } /*////////////////////////////////////////////////////////////// GENERAL NUMBER UTILITIES //////////////////////////////////////////////////////////////*/ function sqrt(uint256 x) internal pure returns (uint256 z) { assembly { let y := x // We start y at x, which will help us make our initial estimate. z := 181 // The "correct" value is 1, but this saves a multiplication later. // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically. // We check y >= 2^(k + 8) but shift right by k bits // each branch to ensure that if x >= 256, then y >= 256. if iszero(lt(y, 0x10000000000000000000000000000000000)) { y := shr(128, y) z := shl(64, z) } if iszero(lt(y, 0x1000000000000000000)) { y := shr(64, y) z := shl(32, z) } if iszero(lt(y, 0x10000000000)) { y := shr(32, y) z := shl(16, z) } if iszero(lt(y, 0x1000000)) { y := shr(16, y) z := shl(8, z) } // Goal was to get z*z*y within a small factor of x. More iterations could // get y in a tighter range. Currently, we will have y in [256, 256*2^16). // We ensured y >= 256 so that the relative difference between y and y+1 is small. // That's not possible if x < 256 but we can just verify those cases exhaustively. // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256. // Correctness can be checked exhaustively for x < 256, so we assume y >= 256. // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps. // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256. // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18. // There is no overflow risk here since y < 2^136 after the first branch above. z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181. // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough. z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) // If x+1 is a perfect square, the Babylonian method cycles between // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor. // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case. // If you don't care whether the floor or ceil square root is returned, you can remove this statement. z := sub(z, lt(div(x, z), z)) } } function log2(uint256 x) internal pure returns (uint256 r) { require(x > 0, "UNDEFINED"); assembly { r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffff, shr(r, x)))) r := or(r, shl(3, lt(0xff, shr(r, x)))) r := or(r, shl(2, lt(0xf, shr(r, x)))) r := or(r, shl(1, lt(0x3, shr(r, x)))) r := or(r, lt(0x1, shr(r, x))) } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ```solidity * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a * constructor. * * Emits an {Initialized} event. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: setting the version to 255 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized != type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint8) { return _initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _initializing; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { Predeploys } from "../libraries/Predeploys.sol"; import { ISemver } from "../universal/ISemver.sol"; import { StandardBridge } from "../universal/StandardBridge.sol"; /** * @custom:proxied * @custom:predeploy 0x4200000000000000000000000000000000000009 * @title L2StandardBridge * @notice The L2StandardBridge is responsible for transfering ETH and ERC20 tokens between L1 and * L2. In the case that an ERC20 token is native to L2, it will be escrowed within this * contract. If the ERC20 token is native to L1, it will be burnt. * NOTE: this contract is not intended to support all variations of ERC20 tokens. Examples * of some token types that may not be properly supported by this contract include, but are * not limited to: tokens with transfer fees, rebasing tokens, and tokens with blocklists. */ contract L2StandardBridge is StandardBridge, ISemver { /** * @notice Semantic version. * @custom:semver 1.0.0 */ string public constant version = "1.0.0"; /** * @notice Constructs the L2StandardBridge contract. * * @param _otherBridge Address of the L1StandardBridge. */ constructor( address payable _otherBridge ) StandardBridge(payable(Predeploys.L2_CROSS_DOMAIN_MESSENGER), _otherBridge) {} /** * @notice Allows EOAs to bridge ETH by sending directly to the bridge. */ receive() external payable override onlyEOA { _initiateBridgeETH( msg.sender, msg.sender, msg.value, RECEIVE_DEFAULT_GAS_LIMIT, bytes("") ); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { L2StandardBridge } from "../L2/L2StandardBridge.sol"; import { Predeploys } from "../libraries/Predeploys.sol"; import { SafeCall } from "../libraries/SafeCall.sol"; /** * @title FeeVault * @notice The FeeVault contract contains the basic logic for the various different vault contracts * used to hold fee revenue generated by the L2 system. */ abstract contract FeeVault { /** * @notice Emits each time that a withdrawal occurs. * * @param value Amount that was withdrawn (in wei). * @param to Address that the funds were sent to. * @param from Address that triggered the withdrawal. */ event Withdrawal(uint256 value, address to, address from); /** * @notice Minimum balance before a withdrawal can be triggered. */ uint256 public immutable MIN_WITHDRAWAL_AMOUNT; /** * @notice Wallet that will receive the fees on L1. */ address public immutable RECIPIENT; /** * @notice The minimum gas limit for the FeeVault withdrawal transaction. */ uint32 internal constant WITHDRAWAL_MIN_GAS = 35_000; /** * @notice Total amount of wei processed by the contract. */ uint256 public totalProcessed; modifier onlyRecipient() { require(msg.sender == RECIPIENT, "FeeVault: the only recipient can call"); _; } /** * @param _recipient Wallet that will receive the fees on L1. * @param _minWithdrawalAmount Minimum balance before a withdrawal can be triggered. */ constructor(address _recipient, uint256 _minWithdrawalAmount) { MIN_WITHDRAWAL_AMOUNT = _minWithdrawalAmount; RECIPIENT = _recipient; } /** * @notice Allow the contract to receive ETH. */ receive() external payable {} /** * @notice Checks if the withdrawal is possible, and returns the withdrawal amount. * When a withdrawal is available, it resets the balance and updates the total processed amount. */ function _processWithdrawal() internal virtual returns (uint256) { require( address(this).balance >= MIN_WITHDRAWAL_AMOUNT, "FeeVault: withdrawal amount must be greater than minimum withdrawal amount" ); uint256 amount = address(this).balance; totalProcessed += amount; emit Withdrawal(amount, RECIPIENT, msg.sender); return amount; } /** * @notice Triggers a withdrawal of funds to the recipient on L1. */ function withdraw() external virtual onlyRecipient { uint256 amount = _processWithdrawal(); L2StandardBridge(payable(Predeploys.L2_STANDARD_BRIDGE)).bridgeETHTo{ value: amount }( RECIPIENT, WITHDRAWAL_MIN_GAS, bytes("") ); } /** * @notice Triggers a withdrawal of funds to the recipient on L2. */ function withdrawToL2() external virtual onlyRecipient { uint256 amount = _processWithdrawal(); bool success = SafeCall.call(RECIPIENT, gasleft(), amount, bytes("")); require(success, "FeeVault: ETH transfer failed"); } }
// SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.8.0; library AddressAliasHelper { uint160 constant offset = uint160(0x1111000000000000000000000000000000001111); /// @notice Utility function that converts the address in the L1 that submitted a tx to /// the inbox to the msg.sender viewed in the L2 /// @param l1Address the address in the L1 that triggered the tx to L2 /// @return l2Address L2 address as viewed in msg.sender function applyL1ToL2Alias(address l1Address) internal pure returns (address l2Address) { unchecked { l2Address = address(uint160(l1Address) + offset); } } /// @notice Utility function that converts the msg.sender viewed in the L2 to the /// address in the L1 that submitted a tx to the inbox /// @param l2Address L2 address as viewed in msg.sender /// @return l1Address the address in the L1 that triggered the tx to L2 function undoL1ToL2Alias(address l2Address) internal pure returns (address l1Address) { unchecked { l1Address = address(uint160(l2Address) - offset); } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { Encoding } from "./Encoding.sol"; import { RLPWriter } from "./rlp/RLPWriter.sol"; import { Types } from "./Types.sol"; /** * @title Hashing * @notice Hashing handles Kroma's various different hashing schemes. */ library Hashing { /** * @notice Computes the hash of the RLP encoded L2 transaction that would be generated when a * given deposit is sent to the L2 system. Useful for searching for a deposit in the L2 * system. * * @param _tx User deposit transaction to hash. * * @return Hash of the RLP encoded L2 deposit transaction. */ function hashDepositTransaction( Types.UserDepositTransaction memory _tx ) internal pure returns (bytes32) { return keccak256(Encoding.encodeDepositTransaction(_tx)); } /** * @notice Computes the deposit transaction's "source hash", a value that guarantees the hash * of the L2 transaction that corresponds to a deposit is unique and is * deterministically generated from L1 transaction data. * * @param _l1BlockHash Hash of the L1 block where the deposit was included. * @param _logIndex The index of the log that created the deposit transaction. * * @return Hash of the deposit transaction's "source hash". */ function hashDepositSource( bytes32 _l1BlockHash, uint64 _logIndex ) internal pure returns (bytes32) { bytes32 depositId = keccak256(abi.encode(_l1BlockHash, _logIndex)); return keccak256(abi.encode(bytes32(0), depositId)); } /** * @notice Hashes the cross domain message based on the version that is encoded into the * message nonce. * * @param _nonce Message nonce with version encoded into the first two bytes. * @param _sender Address of the sender of the message. * @param _target Address of the target of the message. * @param _value ETH value to send to the target. * @param _gasLimit Gas limit to use for the message. * @param _data Data to send with the message. * * @return Hashed cross domain message. */ function hashCrossDomainMessage( uint256 _nonce, address _sender, address _target, uint256 _value, uint256 _gasLimit, bytes memory _data ) internal pure returns (bytes32) { (, uint16 version) = Encoding.decodeVersionedNonce(_nonce); if (version == 0) { return hashCrossDomainMessageV0(_nonce, _sender, _target, _value, _gasLimit, _data); } else { revert("Hashing: unknown cross domain message version"); } } /** * @notice Hashes a cross domain message based on the V0 (current) encoding. * * @param _nonce Message nonce. * @param _sender Address of the sender of the message. * @param _target Address of the target of the message. * @param _value ETH value to send to the target. * @param _gasLimit Gas limit to use for the message. * @param _data Data to send with the message. * * @return Hashed cross domain message. */ function hashCrossDomainMessageV0( uint256 _nonce, address _sender, address _target, uint256 _value, uint256 _gasLimit, bytes memory _data ) internal pure returns (bytes32) { return keccak256( Encoding.encodeCrossDomainMessageV0( _nonce, _sender, _target, _value, _gasLimit, _data ) ); } /** * @notice Derives the withdrawal hash according to the encoding in the L2 Withdrawer contract * * @param _tx Withdrawal transaction to hash. * * @return Hashed withdrawal transaction. */ function hashWithdrawal( Types.WithdrawalTransaction memory _tx ) internal pure returns (bytes32) { return keccak256( abi.encode(_tx.nonce, _tx.sender, _tx.target, _tx.value, _tx.gasLimit, _tx.data) ); } /** * @notice Hashes the various elements of an output root proof into an output root hash which * can be used to check if the proof is valid. * * @param _outputRootProof Output root proof which should be hashed to an output root. * * @return Hashed output root proof. */ function hashOutputRootProof( Types.OutputRootProof memory _outputRootProof ) internal pure returns (bytes32) { if (_outputRootProof.version == bytes32(uint256(0))) { return hashOutputRootProofV0(_outputRootProof); } else { revert("Hashing: unknown output root proof version"); } } /** * @notice Hashes the various elements of an output root proof into an output root hash which * can be used to check if the proof is valid. (version 0) * * @param _outputRootProof Output root proof which should be hashed to an output root. * * @return Hashed output root proof. */ function hashOutputRootProofV0( Types.OutputRootProof memory _outputRootProof ) internal pure returns (bytes32) { return keccak256( abi.encode( _outputRootProof.version, _outputRootProof.stateRoot, _outputRootProof.messagePasserStorageRoot, _outputRootProof.blockHash, _outputRootProof.nextBlockHash ) ); } /** * @notice Fills the values of the block hash fields to a given bytes. * * @param _publicInput Public input which should be hashed to a block hash. * @param _rlps Pre-RLP encoded data which should be hashed to a block hash. * @param _raw An array of bytes to be populated. */ function _fillBlockHashFieldsToBytes( Types.PublicInput memory _publicInput, Types.BlockHeaderRLP memory _rlps, bytes[] memory _raw ) private pure { _raw[0] = RLPWriter.writeBytes(abi.encodePacked(_publicInput.parentHash)); _raw[1] = _rlps.uncleHash; _raw[2] = _rlps.coinbase; _raw[3] = RLPWriter.writeBytes(abi.encodePacked(_publicInput.stateRoot)); _raw[4] = RLPWriter.writeBytes(abi.encodePacked(_publicInput.transactionsRoot)); _raw[5] = _rlps.receiptsRoot; _raw[6] = _rlps.logsBloom; _raw[7] = _rlps.difficulty; _raw[8] = RLPWriter.writeUint(_publicInput.number); _raw[9] = RLPWriter.writeUint(_publicInput.gasLimit); _raw[10] = _rlps.gasUsed; _raw[11] = RLPWriter.writeUint(_publicInput.timestamp); _raw[12] = _rlps.extraData; _raw[13] = _rlps.mixHash; _raw[14] = _rlps.nonce; _raw[15] = RLPWriter.writeUint(_publicInput.baseFee); } /** * @notice Hashes the various elements of a block header into a block hash(before shanghai). * * @param _publicInput Public input which should be hashed to a block hash. * @param _rlps Pre-RLP encoded data which should be hashed to a block hash. * * @return Hashed block header. */ function hashBlockHeader( Types.PublicInput memory _publicInput, Types.BlockHeaderRLP memory _rlps ) internal pure returns (bytes32) { bytes[] memory raw = new bytes[](16); _fillBlockHashFieldsToBytes(_publicInput, _rlps, raw); return keccak256(RLPWriter.writeList(raw)); } /** * @notice Hashes the various elements of a block header into a block hash(after shanghai). * * @param _publicInput Public input which should be hashed to a block hash. * @param _rlps Pre-RLP encoded data which should be hashed to a block hash. * * @return Hashed block header. */ function hashBlockHeaderShanghai( Types.PublicInput memory _publicInput, Types.BlockHeaderRLP memory _rlps ) internal pure returns (bytes32) { bytes[] memory raw = new bytes[](17); _fillBlockHashFieldsToBytes(_publicInput, _rlps, raw); raw[16] = RLPWriter.writeBytes(abi.encodePacked(_publicInput.withdrawalsRoot)); return keccak256(RLPWriter.writeList(raw)); } /** * @notice Hashes the various elements of a block header into a block hash(after Cancun). * * @param _publicInput Public input which should be hashed to a block hash. * @param _rlps Pre-RLP encoded data which should be hashed to a block hash. * * @return Hashed block header. */ function hashBlockHeaderCancun( Types.PublicInput memory _publicInput, Types.BlockHeaderRLP memory _rlps ) internal pure returns (bytes32) { bytes[] memory raw = new bytes[](20); _fillBlockHashFieldsToBytes(_publicInput, _rlps, raw); raw[16] = RLPWriter.writeBytes(abi.encodePacked(_publicInput.withdrawalsRoot)); raw[17] = RLPWriter.writeUint(_publicInput.blobGasUsed); raw[18] = RLPWriter.writeUint(_publicInput.excessBlobGas); raw[19] = RLPWriter.writeBytes(abi.encodePacked(_publicInput.parentBeaconRoot)); return keccak256(RLPWriter.writeList(raw)); } /** * @notice Hashes the various elements of a public input into a public input hash. * * @param _prevStateRoot Previous state root. * @param _publicInput Public input which should be hashed to a public input hash. * @param _dummyHashes Dummy hashes returned from generateDummyHashes(). * * @return Hashed block header. */ function hashPublicInput( bytes32 _prevStateRoot, Types.PublicInput memory _publicInput, bytes32[] memory _dummyHashes ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( _prevStateRoot, _publicInput.stateRoot, // NOTE(0xHansLee): the withdrawalsRoot is not used in Scroll's zkEVM circuit, so it is filled by zero bytes32(0), _publicInput.blockHash, _publicInput.parentHash, _publicInput.number, _publicInput.timestamp, _publicInput.baseFee, _publicInput.gasLimit, uint16(_publicInput.txHashes.length), _publicInput.txHashes, _dummyHashes ) ); } /** * @notice Generates a bytes32 array filled with a dummy hash for the given length. * * @param _dummyHashes Dummy hash. * @param _length A length of the array. * * @return Bytes32 array filled with dummy hash. */ function generateDummyHashes( bytes32 _dummyHashes, uint256 _length ) internal pure returns (bytes32[] memory) { bytes32[] memory hashes = new bytes32[](_length); for (uint256 i = 0; i < _length; i++) { hashes[i] = _dummyHashes; } return hashes; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { Constants } from "../libraries/Constants.sol"; import { ISemver } from "../universal/ISemver.sol"; import { ResourceMetering } from "./ResourceMetering.sol"; /** * @title SystemConfig * @notice The SystemConfig contract is used to manage configuration of a Kroma network. All * configuration is stored on L1 and picked up by L2 as part of the derivation of the L2 * chain. */ contract SystemConfig is OwnableUpgradeable, ISemver { /** * @notice Enum representing different types of updates. * * @custom:value BATCHER Represents an update to the batcher hash. * @custom:value GAS_CONFIG Represents an update to txn fee config on L2. * @custom:value GAS_LIMIT Represents an update to gas limit on L2. * @custom:value UNSAFE_BLOCK_SIGNER Represents an update to the signer key for unsafe * block distribution. * @custom:value VALIDATOR_REWARD_SCALAR Represents an update to validator reward scalar. */ enum UpdateType { BATCHER, GAS_CONFIG, GAS_LIMIT, UNSAFE_BLOCK_SIGNER, VALIDATOR_REWARD_SCALAR } /** * @notice Version identifier, used for upgrades. */ uint256 public constant VERSION = 0; /** * @notice Storage slot that the unsafe block signer is stored at. Storing it at this * deterministic storage slot allows for decoupling the storage layout from the way * that `solc` lays out storage. The `kroma-node` uses a storage proof to fetch this value. */ bytes32 public constant UNSAFE_BLOCK_SIGNER_SLOT = keccak256("systemconfig.unsafeblocksigner"); /** * @notice Fixed L2 gas overhead. Used as part of the L2 fee calculation. */ uint256 public overhead; /** * @notice Dynamic L2 gas overhead. Used as part of the L2 fee calculation. */ uint256 public scalar; /** * @notice Identifier for the batcher. For version 1 of this configuration, this is represented * as an address left-padded with zeros to 32 bytes. */ bytes32 public batcherHash; /** * @notice L2 block gas limit. */ uint64 public gasLimit; /** * @notice The configuration for the deposit fee market. Used by the KromaPortal * to meter the cost of buying L2 gas on L1. Set as internal and wrapped with a getter * so that the struct is returned instead of a tuple. */ ResourceMetering.ResourceConfig internal _resourceConfig; /** * @notice The scalar value to distribute transaction fees as validator reward. * The denominator is 10000, so the ratio is expressed in 4 decimal places. */ uint256 public validatorRewardScalar; /** * @notice Emitted when configuration is updated * * @param version SystemConfig version. * @param updateType Type of update. * @param data Encoded update data. */ event ConfigUpdate(uint256 indexed version, UpdateType indexed updateType, bytes data); /** * @notice Semantic version. * @custom:semver 1.0.0 */ string public constant version = "1.0.0"; /** * @notice Constructs the SystemConfig contract. * * @param _owner Initial owner of the contract. * @param _overhead Initial overhead value. * @param _scalar Initial scalar value. * @param _batcherHash Initial batcher hash. * @param _gasLimit Initial gas limit. * @param _unsafeBlockSigner Initial unsafe block signer address. * @param _config Initial resource config. * @param _validatorRewardScalar Initial validator reward scalar. */ constructor( address _owner, uint256 _overhead, uint256 _scalar, bytes32 _batcherHash, uint64 _gasLimit, address _unsafeBlockSigner, ResourceMetering.ResourceConfig memory _config, uint256 _validatorRewardScalar ) { initialize( _owner, _overhead, _scalar, _batcherHash, _gasLimit, _unsafeBlockSigner, _config, _validatorRewardScalar ); } /** * @notice Initializer. The resource config must be set before the * require check. * * @param _owner Initial owner of the contract. * @param _overhead Initial overhead value. * @param _scalar Initial scalar value. * @param _batcherHash Initial batcher hash. * @param _gasLimit Initial gas limit. * @param _unsafeBlockSigner Initial unsafe block signer address. * @param _config Initial ResourceConfig. * @param _validatorRewardScalar Initial validator reward scalar. */ function initialize( address _owner, uint256 _overhead, uint256 _scalar, bytes32 _batcherHash, uint64 _gasLimit, address _unsafeBlockSigner, ResourceMetering.ResourceConfig memory _config, uint256 _validatorRewardScalar ) public initializer { __Ownable_init(); transferOwnership(_owner); overhead = _overhead; scalar = _scalar; batcherHash = _batcherHash; gasLimit = _gasLimit; _setUnsafeBlockSigner(_unsafeBlockSigner); _setResourceConfig(_config); require(_gasLimit >= minimumGasLimit(), "SystemConfig: gas limit too low"); validatorRewardScalar = _validatorRewardScalar; } /** * @notice Returns the minimum L2 gas limit that can be safely set for the system to * operate. The L2 gas limit must be larger than or equal to the amount of * gas that is allocated for deposits per block plus the amount of gas that * is allocated for the system transaction. * This function is used to determine if changes to parameters are safe. * * @return uint64 */ function minimumGasLimit() public view returns (uint64) { return uint64(_resourceConfig.maxResourceLimit) + uint64(_resourceConfig.systemTxMaxGas); } /** * @notice High level getter for the unsafe block signer address. Unsafe blocks can be * propagated across the p2p network if they are signed by the key corresponding to * this address. * * @return Address of the unsafe block signer. */ // solhint-disable-next-line ordering function unsafeBlockSigner() external view returns (address) { address addr; bytes32 slot = UNSAFE_BLOCK_SIGNER_SLOT; assembly { addr := sload(slot) } return addr; } /** * @notice Updates the unsafe block signer address. * * @param _unsafeBlockSigner New unsafe block signer address. */ function setUnsafeBlockSigner(address _unsafeBlockSigner) external onlyOwner { _setUnsafeBlockSigner(_unsafeBlockSigner); bytes memory data = abi.encode(_unsafeBlockSigner); emit ConfigUpdate(VERSION, UpdateType.UNSAFE_BLOCK_SIGNER, data); } /** * @notice Updates the batcher hash. * * @param _batcherHash New batcher hash. */ function setBatcherHash(bytes32 _batcherHash) external onlyOwner { batcherHash = _batcherHash; bytes memory data = abi.encode(_batcherHash); emit ConfigUpdate(VERSION, UpdateType.BATCHER, data); } /** * @notice Updates gas config. * * @param _overhead New overhead value. * @param _scalar New scalar value. */ function setGasConfig(uint256 _overhead, uint256 _scalar) external onlyOwner { overhead = _overhead; scalar = _scalar; bytes memory data = abi.encode(_overhead, _scalar); emit ConfigUpdate(VERSION, UpdateType.GAS_CONFIG, data); } /** * @notice Updates the L2 gas limit. * * @param _gasLimit New gas limit. */ function setGasLimit(uint64 _gasLimit) external onlyOwner { require(_gasLimit >= minimumGasLimit(), "SystemConfig: gas limit too low"); gasLimit = _gasLimit; bytes memory data = abi.encode(_gasLimit); emit ConfigUpdate(VERSION, UpdateType.GAS_LIMIT, data); } /** * @notice Low level setter for the unsafe block signer address. This function exists to * deduplicate code around storing the unsafeBlockSigner address in storage. * * @param _unsafeBlockSigner New unsafeBlockSigner value. */ function _setUnsafeBlockSigner(address _unsafeBlockSigner) internal { bytes32 slot = UNSAFE_BLOCK_SIGNER_SLOT; assembly { sstore(slot, _unsafeBlockSigner) } } /** * @notice A getter for the resource config. Ensures that the struct is * returned instead of a tuple. * * @return ResourceConfig */ function resourceConfig() external view returns (ResourceMetering.ResourceConfig memory) { return _resourceConfig; } /** * @notice An external setter for the resource config. In the future, this * method may emit an event that the `kroma-node` picks up for when the * resource config is changed. * * @param _config The new resource config values. */ function setResourceConfig(ResourceMetering.ResourceConfig memory _config) external onlyOwner { _setResourceConfig(_config); } /** * @notice An internal setter for the resource config. Ensures that the * config is sane before storing it by checking for invariants. * * @param _config The new resource config. */ function _setResourceConfig(ResourceMetering.ResourceConfig memory _config) internal { // Min base fee must be less than or equal to max base fee. require( _config.minimumBaseFee <= _config.maximumBaseFee, "SystemConfig: min base fee must be less than max base" ); // Base fee change denominator must be greater than 1. require( _config.baseFeeMaxChangeDenominator > 1, "SystemConfig: denominator must be larger than 1" ); // Max resource limit plus system tx gas must be less than or equal to the L2 gas limit. // The gas limit must be increased before these values can be increased. require( _config.maxResourceLimit + _config.systemTxMaxGas <= gasLimit, "SystemConfig: gas limit too low" ); // Elasticity multiplier must be greater than 0. require( _config.elasticityMultiplier > 0, "SystemConfig: elasticity multiplier cannot be 0" ); // No precision loss when computing target resource limit. require( ((_config.maxResourceLimit / _config.elasticityMultiplier) * _config.elasticityMultiplier) == _config.maxResourceLimit, "SystemConfig: precision loss with target resource limit" ); _resourceConfig = _config; } /** * @notice Updates the validator reward scalar. * * @param _validatorRewardScalar New validator reward scalar. */ function setValidatorRewardScalar(uint256 _validatorRewardScalar) external onlyOwner { require( _validatorRewardScalar <= Constants.VALIDATOR_REWARD_DENOMINATOR, "SystemConfig: the max value of validator reward scalar has been exceeded" ); validatorRewardScalar = _validatorRewardScalar; bytes memory data = abi.encode(_validatorRewardScalar); emit ConfigUpdate(VERSION, UpdateType.VALIDATOR_REWARD_SCALAR, data); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { Bytes } from "../libraries/Bytes.sol"; import { NodeReader } from "../libraries/NodeReader.sol"; import { IZKMerkleTrie } from "./interfaces/IZKMerkleTrie.sol"; import { ZKTrieHasher } from "./ZKTrieHasher.sol"; /** * @custom:proxied * @title ZKMerkleTrie * @notice The ZKMerkleTrie is contract which can produce a hash according to ZKTrie. * This owns an interface of Poseidon2 that is required to compute hash used by ZKTrie. */ contract ZKMerkleTrie is IZKMerkleTrie, ZKTrieHasher { /** * @notice Struct representing a node in the trie. */ struct TrieNode { bytes encoded; NodeReader.Node decoded; } /** * @notice Magic hash which indicates * See https://github.com/kroma-network/zktrie/blob/main/trie/zk_trie_proof.go. */ bytes32 private constant MAGIC_SMT_BYTES_HASH = keccak256( hex"5448495320495320534f4d45204d4147494320425954455320464f5220534d54206d3172525867503278704449" ); /** * @param _poseidon2 The address of poseidon2 contract. */ constructor(address _poseidon2) ZKTrieHasher(_poseidon2) {} /** * @notice Checks if a given bytes is MAGIC_SMT_BYTES_HASH. * * @param _value Bytes to be compared. */ function isMagicSmtBytesHash(bytes memory _value) private pure returns (bool) { return keccak256(_value) == MAGIC_SMT_BYTES_HASH; } /** * @inheritdoc IZKMerkleTrie */ function verifyInclusionProof( bytes32 _key, bytes memory _value, bytes[] memory _proofs, bytes32 _root ) external view returns (bool) { (bool exists, bytes memory value) = this.get(_key, _proofs, _root); return (exists && Bytes.equal(_value, value)); } /** * @notice Retrieves the value associated with a given key. * * @param _key Key to search for, as hex bytes. * @param _proofs Merkle trie inclusion proof for the key. * @param _root Known root of the Merkle trie. * * @return Whether or not the key exists. * @return Value of the key if it exists. */ function get( bytes32 _key, bytes[] memory _proofs, bytes32 _root ) external view returns (bool, bytes memory) { require(_proofs.length >= 2, "ZKMerkleTrie: provided proof is too short"); require( isMagicSmtBytesHash(_proofs[_proofs.length - 1]), "ZKMerkleTrie: the last item is not magic hash" ); bytes32 key = _hashElem(_key); TrieNode[] memory nodes = _parseProofs(_proofs); NodeReader.Node memory currentNode; bytes32 computedKey = bytes32(0); bool exists = false; bool empty = false; bytes memory value = bytes(""); for (uint256 i = nodes.length - 2; i >= 0; ) { currentNode = nodes[i].decoded; if (currentNode.nodeType == NodeReader.NodeType.MIDDLE) { bool isLeft = _isLeft(key, i); if (isLeft) { require(computedKey == currentNode.childL, "ZKMerkleTrie: invalid key L"); } else { require(computedKey == currentNode.childR, "ZKMerkleTrie: invalid key R"); } computedKey = _hashFixed2Elems(currentNode.childL, currentNode.childR); } else if (currentNode.nodeType == NodeReader.NodeType.LEAF) { require(!exists && !empty, "ZKMerkleTrie: duplicated terminal node"); exists = currentNode.nodeKey == key; if (!exists) { break; } computedKey = _hashFixed3Elems( bytes32(uint256(1)), currentNode.nodeKey, _valueHash(currentNode.compressedFlags, currentNode.valuePreimage) ); bytes32[] memory valuePreimage = currentNode.valuePreimage; uint256 len = valuePreimage.length; assembly { value := valuePreimage mstore(value, mul(len, 32)) } if (currentNode.keyPreimage != bytes32(0)) { // NOTE(chokobole): The comparison order is important, because in this setting, // first condition is mostly evaluted to be true. When we're sure about // database preimage, then we need to enable just one of check below! require( currentNode.keyPreimage == _key || currentNode.keyPreimage == key, "ZKMerkleTrie: invalid key preimage" ); } } else if (currentNode.nodeType == NodeReader.NodeType.EMPTY) { require(!exists && !empty, "ZKMerkleTrie: duplicated terminal node"); empty = true; } if (i == 0) { require(computedKey == _root, "ZKMerkeTrie: invalid root"); break; } unchecked { --i; } } return (exists, value); } /** * @notice Parses an array of proof elements into a new array that contains both the original * encoded element and the decoded element. * * @param _proofs Array of proof elements to parse. * * @return TrieNode parsed into easily accessible structs. */ function _parseProofs(bytes[] memory _proofs) private pure returns (TrieNode[] memory) { uint256 length = _proofs.length; TrieNode[] memory nodes = new TrieNode[](length); // NOTE(chokobole): Last proof is MAGIC_SMT_BYTES_HASH! for (uint256 i = 0; i < length - 1; ) { NodeReader.Node memory node = NodeReader.readNode(_proofs[i]); nodes[i] = TrieNode({ encoded: _proofs[i], decoded: node }); unchecked { ++i; } } return nodes; } /** * @notice Computes merkle path at index n based on a given keyPreimage. * * @param _keyPreimage Keypreimage. * @param _n Bit to mask. * * @return Whether merkle path is left or not. */ function _isLeft(bytes32 _keyPreimage, uint256 _n) private pure returns (bool) { require(_n < 256, "ZKMerkleTrie: too long depth"); return _keyPreimage & bytes32(1 << _n) == 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * * Furthermore, `isContract` will also return true if the target contract within * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, * which only has an effect at the end of a transaction. * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { SafeCall } from "../libraries/SafeCall.sol"; import { CrossDomainMessenger } from "./CrossDomainMessenger.sol"; import { IKromaMintableERC20 } from "./IKromaMintableERC20.sol"; import { KromaMintableERC20 } from "./KromaMintableERC20.sol"; /** * @custom:upgradeable * @title StandardBridge * @notice StandardBridge is a base contract for the L1 and L2 standard ERC20 bridges. It handles * the core bridging logic, including escrowing tokens that are native to the local chain * and minting/burning tokens that are native to the remote chain. */ abstract contract StandardBridge { using SafeERC20 for IERC20; /** * @notice The L2 gas limit set when eth is depoisited using the receive() function. */ uint32 internal constant RECEIVE_DEFAULT_GAS_LIMIT = 200_000; /** * @notice Messenger contract on this domain. */ CrossDomainMessenger public immutable MESSENGER; /** * @notice Corresponding bridge on the other domain. */ StandardBridge public immutable OTHER_BRIDGE; /** * @notice Mapping that stores deposits for a given pair of local and remote tokens. */ mapping(address => mapping(address => uint256)) public deposits; /** * @notice Reserve extra slots (to a total of 50) in the storage layout for future upgrades. * A gap size of 49 was chosen here, so that the first slot used in a child contract * would be a multiple of 50. */ uint256[49] private __gap; /** * @notice Emitted when an ETH bridge is initiated to the other chain. * * @param from Address of the sender. * @param to Address of the receiver. * @param amount Amount of ETH sent. * @param extraData Extra data sent with the transaction. */ event ETHBridgeInitiated( address indexed from, address indexed to, uint256 amount, bytes extraData ); /** * @notice Emitted when an ETH bridge is finalized on this chain. * * @param from Address of the sender. * @param to Address of the receiver. * @param amount Amount of ETH sent. * @param extraData Extra data sent with the transaction. */ event ETHBridgeFinalized( address indexed from, address indexed to, uint256 amount, bytes extraData ); /** * @notice Emitted when an ERC20 bridge is initiated to the other chain. * * @param localToken Address of the ERC20 on this chain. * @param remoteToken Address of the ERC20 on the remote chain. * @param from Address of the sender. * @param to Address of the receiver. * @param amount Amount of the ERC20 sent. * @param extraData Extra data sent with the transaction. */ event ERC20BridgeInitiated( address indexed localToken, address indexed remoteToken, address indexed from, address to, uint256 amount, bytes extraData ); /** * @notice Emitted when an ERC20 bridge is finalized on this chain. * * @param localToken Address of the ERC20 on this chain. * @param remoteToken Address of the ERC20 on the remote chain. * @param from Address of the sender. * @param to Address of the receiver. * @param amount Amount of the ERC20 sent. * @param extraData Extra data sent with the transaction. */ event ERC20BridgeFinalized( address indexed localToken, address indexed remoteToken, address indexed from, address to, uint256 amount, bytes extraData ); /** * @notice Only allow EOAs to call the functions. Note that this is not safe against contracts * calling code within their constructors, but also doesn't really matter since we're * just trying to prevent users accidentally depositing with smart contract wallets. */ modifier onlyEOA() { require( !Address.isContract(msg.sender), "StandardBridge: function can only be called from an EOA" ); _; } /** * @notice Ensures that the caller is a cross-chain message from the other bridge. */ modifier onlyOtherBridge() { require( msg.sender == address(MESSENGER) && MESSENGER.xDomainMessageSender() == address(OTHER_BRIDGE), "StandardBridge: function can only be called from the other bridge" ); _; } /** * @param _messenger Address of CrossDomainMessenger on this network. * @param _otherBridge Address of the other StandardBridge contract. */ constructor(address payable _messenger, address payable _otherBridge) { MESSENGER = CrossDomainMessenger(_messenger); OTHER_BRIDGE = StandardBridge(_otherBridge); } /** * @notice Allows EOAs to bridge ETH by sending directly to the bridge. * Must be implemented by contracts that inherit. */ receive() external payable virtual; /** * @notice Sends ETH to the sender's address on the other chain. * * @param _minGasLimit Minimum amount of gas that the bridge can be relayed with. * @param _extraData Extra data to be sent with the transaction. Note that the recipient will * not be triggered with this data, but it will be emitted and can be used * to identify the transaction. */ function bridgeETH(uint32 _minGasLimit, bytes calldata _extraData) public payable onlyEOA { _initiateBridgeETH(msg.sender, msg.sender, msg.value, _minGasLimit, _extraData); } /** * @notice Sends ETH to a receiver's address on the other chain. Note that if ETH is sent to a * smart contract and the call fails, the ETH will be temporarily locked in the * StandardBridge on the other chain until the call is replayed. If the call cannot be * replayed with any amount of gas (call always reverts), then the ETH will be * permanently locked in the StandardBridge on the other chain. ETH will also * be locked if the receiver is the other bridge, because finalizeBridgeETH will revert * in that case. * * @param _to Address of the receiver. * @param _minGasLimit Minimum amount of gas that the bridge can be relayed with. * @param _extraData Extra data to be sent with the transaction. Note that the recipient will * not be triggered with this data, but it will be emitted and can be used * to identify the transaction. */ function bridgeETHTo( address _to, uint32 _minGasLimit, bytes calldata _extraData ) public payable { _initiateBridgeETH(msg.sender, _to, msg.value, _minGasLimit, _extraData); } /** * @notice Sends ERC20 tokens to the sender's address on the other chain. Note that if the * ERC20 token on the other chain does not recognize the local token as the correct * pair token, the ERC20 bridge will fail and the tokens will be returned to sender on * this chain. * * @param _localToken Address of the ERC20 on this chain. * @param _remoteToken Address of the corresponding token on the remote chain. * @param _amount Amount of local tokens to deposit. * @param _minGasLimit Minimum amount of gas that the bridge can be relayed with. * @param _extraData Extra data to be sent with the transaction. Note that the recipient will * not be triggered with this data, but it will be emitted and can be used * to identify the transaction. */ function bridgeERC20( address _localToken, address _remoteToken, uint256 _amount, uint32 _minGasLimit, bytes calldata _extraData ) public onlyEOA { _initiateBridgeERC20( _localToken, _remoteToken, msg.sender, msg.sender, _amount, _minGasLimit, _extraData ); } /** * @notice Sends ERC20 tokens to a receiver's address on the other chain. Note that if the * ERC20 token on the other chain does not recognize the local token as the correct * pair token, the ERC20 bridge will fail and the tokens will be returned to sender on * this chain. * * @param _localToken Address of the ERC20 on this chain. * @param _remoteToken Address of the corresponding token on the remote chain. * @param _to Address of the receiver. * @param _amount Amount of local tokens to deposit. * @param _minGasLimit Minimum amount of gas that the bridge can be relayed with. * @param _extraData Extra data to be sent with the transaction. Note that the recipient will * not be triggered with this data, but it will be emitted and can be used * to identify the transaction. */ function bridgeERC20To( address _localToken, address _remoteToken, address _to, uint256 _amount, uint32 _minGasLimit, bytes calldata _extraData ) public { _initiateBridgeERC20( _localToken, _remoteToken, msg.sender, _to, _amount, _minGasLimit, _extraData ); } /** * @notice Finalizes an ETH bridge on this chain. Can only be triggered by the other * StandardBridge contract on the remote chain. * * @param _from Address of the sender. * @param _to Address of the receiver. * @param _amount Amount of ETH being bridged. * @param _extraData Extra data to be sent with the transaction. Note that the recipient will * not be triggered with this data, but it will be emitted and can be used * to identify the transaction. */ function finalizeBridgeETH( address _from, address _to, uint256 _amount, bytes calldata _extraData ) public payable onlyOtherBridge { require(msg.value == _amount, "StandardBridge: amount sent does not match amount required"); require(_to != address(this), "StandardBridge: cannot send to self"); require(_to != address(MESSENGER), "StandardBridge: cannot send to messenger"); emit ETHBridgeFinalized(_from, _to, _amount, _extraData); bool success = SafeCall.call(_to, gasleft(), _amount, hex""); require(success, "StandardBridge: ETH transfer failed"); } /** * @notice Finalizes an ERC20 bridge on this chain. Can only be triggered by the other * StandardBridge contract on the remote chain. * * @param _localToken Address of the ERC20 on this chain. * @param _remoteToken Address of the corresponding token on the remote chain. * @param _from Address of the sender. * @param _to Address of the receiver. * @param _amount Amount of the ERC20 being bridged. * @param _extraData Extra data to be sent with the transaction. Note that the recipient will * not be triggered with this data, but it will be emitted and can be used * to identify the transaction. */ function finalizeBridgeERC20( address _localToken, address _remoteToken, address _from, address _to, uint256 _amount, bytes calldata _extraData ) public onlyOtherBridge { if (_isKromaMintableERC20(_localToken)) { require( _isCorrectTokenPair(_localToken, _remoteToken), "StandardBridge: wrong remote token for Kroma Mintable ERC20 local token" ); KromaMintableERC20(_localToken).mint(_to, _amount); } else { deposits[_localToken][_remoteToken] = deposits[_localToken][_remoteToken] - _amount; IERC20(_localToken).safeTransfer(_to, _amount); } emit ERC20BridgeFinalized(_localToken, _remoteToken, _from, _to, _amount, _extraData); } /** * @notice Initiates a bridge of ETH through the CrossDomainMessenger. * * @param _from Address of the sender. * @param _to Address of the receiver. * @param _amount Amount of ETH being bridged. * @param _minGasLimit Minimum amount of gas that the bridge can be relayed with. * @param _extraData Extra data to be sent with the transaction. Note that the recipient will * not be triggered with this data, but it will be emitted and can be used * to identify the transaction. */ function _initiateBridgeETH( address _from, address _to, uint256 _amount, uint32 _minGasLimit, bytes memory _extraData ) internal { require( msg.value == _amount, "StandardBridge: bridging ETH must include sufficient ETH value" ); emit ETHBridgeInitiated(_from, _to, _amount, _extraData); MESSENGER.sendMessage{ value: _amount }( address(OTHER_BRIDGE), abi.encodeWithSelector( this.finalizeBridgeETH.selector, _from, _to, _amount, _extraData ), _minGasLimit ); } /** * @notice Sends ERC20 tokens to a receiver's address on the other chain. * * @param _localToken Address of the ERC20 on this chain. * @param _remoteToken Address of the corresponding token on the remote chain. * @param _to Address of the receiver. * @param _amount Amount of local tokens to deposit. * @param _minGasLimit Minimum amount of gas that the bridge can be relayed with. * @param _extraData Extra data to be sent with the transaction. Note that the recipient will * not be triggered with this data, but it will be emitted and can be used * to identify the transaction. */ function _initiateBridgeERC20( address _localToken, address _remoteToken, address _from, address _to, uint256 _amount, uint32 _minGasLimit, bytes memory _extraData ) internal { if (_isKromaMintableERC20(_localToken)) { require( _isCorrectTokenPair(_localToken, _remoteToken), "StandardBridge: wrong remote token for Kroma Mintable ERC20 local token" ); KromaMintableERC20(_localToken).burn(_from, _amount); } else { IERC20(_localToken).safeTransferFrom(_from, address(this), _amount); deposits[_localToken][_remoteToken] = deposits[_localToken][_remoteToken] + _amount; } emit ERC20BridgeInitiated(_localToken, _remoteToken, _from, _to, _amount, _extraData); MESSENGER.sendMessage( address(OTHER_BRIDGE), abi.encodeWithSelector( this.finalizeBridgeERC20.selector, // Because this call will be executed on the remote chain, we reverse the order of // the remote and local token addresses relative to their order in the // finalizeBridgeERC20 function. _remoteToken, _localToken, _from, _to, _amount, _extraData ), _minGasLimit ); } /** * @notice Checks if a given address is a KromaMintableERC20. Not perfect, but good enough. * Just the way we like it. * * @param _token Address of the token to check. * * @return True if the token is a KromaMintableERC20. */ function _isKromaMintableERC20(address _token) internal view returns (bool) { return ERC165Checker.supportsInterface(_token, type(IKromaMintableERC20).interfaceId); } /** * @notice Checks if the "other token" is the correct pair token for the KromaMintableERC20. * * @param _mintableToken KromaMintableERC20 to check against. * @param _otherToken Pair token to check. * * @return True if the other token is the correct pair token for the KromaMintableERC20. */ function _isCorrectTokenPair(address _mintableToken, address _otherToken) internal view returns (bool) { return _otherToken == KromaMintableERC20(_mintableToken).REMOTE_TOKEN(); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { Hashing } from "./Hashing.sol"; import { Types } from "./Types.sol"; import { RLPWriter } from "./rlp/RLPWriter.sol"; /// @title Encoding /// @notice Encoding handles Kroma's various different encoding schemes. library Encoding { /// @notice RLP encodes the L2 transaction that would be generated when a given deposit is sent /// to the L2 system. Useful for searching for a deposit in the L2 system. The /// transaction is prefixed with 0x7e to identify its EIP-2718 type. /// @param _tx User deposit transaction to encode. /// @return RLP encoded L2 deposit transaction. function encodeDepositTransaction(Types.UserDepositTransaction memory _tx) internal pure returns (bytes memory) { bytes32 source = Hashing.hashDepositSource(_tx.l1BlockHash, _tx.logIndex); bytes[] memory raw = new bytes[](7); raw[0] = RLPWriter.writeBytes(abi.encodePacked(source)); raw[1] = RLPWriter.writeAddress(_tx.from); raw[2] = _tx.isCreation ? RLPWriter.writeBytes("") : RLPWriter.writeAddress(_tx.to); raw[3] = RLPWriter.writeUint(_tx.mint); raw[4] = RLPWriter.writeUint(_tx.value); raw[5] = RLPWriter.writeUint(uint256(_tx.gasLimit)); raw[6] = RLPWriter.writeBytes(_tx.data); return abi.encodePacked(uint8(0x7e), RLPWriter.writeList(raw)); } /// @notice Encodes the cross domain message based on the version that is encoded into the /// message nonce. /// @param _nonce Message nonce with version encoded into the first two bytes. /// @param _sender Address of the sender of the message. /// @param _target Address of the target of the message. /// @param _value ETH value to send to the target. /// @param _gasLimit Gas limit to use for the message. /// @param _data Data to send with the message. /// @return Encoded cross domain message. function encodeCrossDomainMessage( uint256 _nonce, address _sender, address _target, uint256 _value, uint256 _gasLimit, bytes memory _data ) internal pure returns (bytes memory) { (, uint16 version) = decodeVersionedNonce(_nonce); if (version == 0) { return encodeCrossDomainMessageV0(_nonce, _sender, _target, _value, _gasLimit, _data); } else { revert("Encoding: unknown cross domain message version"); } } /// @notice Encodes a cross domain message based on the V0 (current) encoding. /// @param _nonce Message nonce. /// @param _sender Address of the sender of the message. /// @param _target Address of the target of the message. /// @param _value ETH value to send to the target. /// @param _gasLimit Gas limit to use for the message. /// @param _data Data to send with the message. /// @return Encoded cross domain message. function encodeCrossDomainMessageV0( uint256 _nonce, address _sender, address _target, uint256 _value, uint256 _gasLimit, bytes memory _data ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "relayMessage(uint256,address,address,uint256,uint256,bytes)", _nonce, _sender, _target, _value, _gasLimit, _data ); } /// @notice Adds a version number into the first two bytes of a message nonce. /// @param _nonce Message nonce to encode into. /// @param _version Version number to encode into the message nonce. /// @return Message nonce with version encoded into the first two bytes. function encodeVersionedNonce(uint240 _nonce, uint16 _version) internal pure returns (uint256) { uint256 nonce; assembly { nonce := or(shl(240, _version), _nonce) } return nonce; } /// @notice Pulls the version out of a version-encoded nonce. /// @param _nonce Message nonce with version encoded into the first two bytes. /// @return Nonce without encoded version. /// @return Version of the message. function decodeVersionedNonce(uint256 _nonce) internal pure returns (uint240, uint16) { uint240 nonce; uint16 version; assembly { nonce := and(_nonce, 0x0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) version := shr(240, _nonce) } return (nonce, version); } /// @notice Returns an appropriately encoded call to L1Block.setL1BlockValuesEcotone /// @param baseFeeScalar L1 base fee Scalar /// @param blobBaseFeeScalar L1 blob base fee Scalar /// @param sequenceNumber Number of L2 blocks since epoch start. /// @param timestamp L1 timestamp. /// @param number L1 blocknumber. /// @param baseFee L1 base fee. /// @param blobBaseFee L1 blob base fee. /// @param hash L1 blockhash. /// @param batcherHash Versioned hash to authenticate batcher by. /// @param validatorRewardScalar Validator reward scalar. function encodeSetL1BlockValuesEcotone( uint32 baseFeeScalar, uint32 blobBaseFeeScalar, uint64 sequenceNumber, uint64 timestamp, uint64 number, uint256 baseFee, uint256 blobBaseFee, bytes32 hash, bytes32 batcherHash, uint256 validatorRewardScalar ) internal pure returns (bytes memory) { bytes4 functionSignature = bytes4(keccak256("setL1BlockValuesEcotone()")); return abi.encodePacked( functionSignature, baseFeeScalar, blobBaseFeeScalar, sequenceNumber, timestamp, number, baseFee, blobBaseFee, hash, batcherHash, validatorRewardScalar ); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @custom:attribution https://github.com/bakaoh/solidity-rlp-encode * @title RLPWriter * @author RLPWriter is a library for encoding Solidity types to RLP bytes. Adapted from Bakaoh's * RLPEncode library (https://github.com/bakaoh/solidity-rlp-encode) with minor * modifications to improve legibility. */ library RLPWriter { /** * @notice RLP encodes a byte string. * * @param _in The byte string to encode. * * @return The RLP encoded string in bytes. */ function writeBytes(bytes memory _in) internal pure returns (bytes memory) { bytes memory encoded; if (_in.length == 1 && uint8(_in[0]) < 128) { encoded = _in; } else { encoded = abi.encodePacked(_writeLength(_in.length, 128), _in); } return encoded; } /** * @notice RLP encodes a list of RLP encoded byte byte strings. * * @param _in The list of RLP encoded byte strings. * * @return The RLP encoded list of items in bytes. */ function writeList(bytes[] memory _in) internal pure returns (bytes memory) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); } /** * @notice RLP encodes a string. * * @param _in The string to encode. * * @return The RLP encoded string in bytes. */ function writeString(string memory _in) internal pure returns (bytes memory) { return writeBytes(bytes(_in)); } /** * @notice RLP encodes an address. * * @param _in The address to encode. * * @return The RLP encoded address in bytes. */ function writeAddress(address _in) internal pure returns (bytes memory) { return writeBytes(abi.encodePacked(_in)); } /** * @notice RLP encodes a uint. * * @param _in The uint256 to encode. * * @return The RLP encoded uint256 in bytes. */ function writeUint(uint256 _in) internal pure returns (bytes memory) { return writeBytes(_toBinary(_in)); } /** * @notice RLP encodes a bool. * * @param _in The bool to encode. * * @return The RLP encoded bool in bytes. */ function writeBool(bool _in) internal pure returns (bytes memory) { bytes memory encoded = new bytes(1); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); return encoded; } /** * @notice Encode the first byte and then the `len` in binary form if `length` is more than 55. * * @param _len The length of the string or the payload. * @param _offset 128 if item is string, 192 if item is list. * * @return RLP encoded bytes. */ function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory) { bytes memory encoded; if (_len < 56) { encoded = new bytes(1); encoded[0] = bytes1(uint8(_len) + uint8(_offset)); } else { uint256 lenLen; uint256 i = 1; while (_len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55); for (i = 1; i <= lenLen; i++) { encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256)); } } return encoded; } /** * @notice Encode integer in big endian binary form with no leading zeroes. * * @param _x The integer to encode. * * @return RLP encoded bytes. */ function _toBinary(uint256 _x) private pure returns (bytes memory) { bytes memory b = abi.encodePacked(_x); uint256 i = 0; for (; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint256 j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * @custom:attribution https://github.com/Arachnid/solidity-stringutils * @notice Copies a piece of memory to another location. * * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function _memcpy( uint256 _dest, uint256 _src, uint256 _len ) private pure { uint256 dest = _dest; uint256 src = _src; uint256 len = _len; for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint256 mask; unchecked { mask = 256**(32 - len) - 1; } assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /** * @custom:attribution https://github.com/sammayo/solidity-rlp-encoder * @notice Flattens a list of byte strings into one byte string. * * @param _list List of byte strings to flatten. * * @return The flattened byte string. */ function _flatten(bytes[] memory _list) private pure returns (bytes memory) { if (_list.length == 0) { return new bytes(0); } uint256 len; uint256 i = 0; for (; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint256 flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for (i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint256 listPtr; assembly { listPtr := add(item, 0x20) } _memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Bytes * @notice Bytes is a library for manipulating byte arrays. */ 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. */ function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) { return keccak256(_bytes) == keccak256(_other); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title NodeReader * @notice NodeReader is a library for reading ZKTrie Node. */ library NodeReader { /** * @notice Node types. * See https://github.com/kroma-network/zktrie/blob/main/types/README.md. * * @custom:value MIDDLE Represents a middle node. * @custom:value LEAF Represents a leaf node. * @custom:value EMPTY Represents a empty node. * @custom:value ROOT Represents a root node. */ enum NodeType { MIDDLE, LEAF, EMPTY, ROOT } /** * @notice Struct representing a Node. * See https://github.com/kroma-network/zktrie/blob/main/types/README.md. */ struct Node { NodeType nodeType; bytes32 childL; bytes32 childR; bytes32 nodeKey; bytes32[] valuePreimage; uint32 compressedFlags; bytes32 valueHash; bytes32 keyPreimage; } /** * @notice Struct representing an Item. */ struct Item { bytes ptr; uint256 len; } /** * @notice Converts bytes to Item. * * @param _bytes bytes to convert. * * @return Item referencing _bytes. */ function toItem(bytes memory _bytes) internal pure returns (Item memory) { bytes memory ptr; assembly { ptr := add(_bytes, 32) } return Item({ ptr: ptr, len: _bytes.length }); } /** * @notice Reads an Item into an uint8. * Internal ptr and length is updated automatically. * * @param _item Item to read. * * @return An uint8 value. */ function readUint8(Item memory _item) internal pure returns (uint8) { require(_item.len >= 1, "NodeReader: too short for uint8"); bytes memory newPtr; bytes memory ptr = _item.ptr; uint8 ret; assembly { ret := shr(248, mload(ptr)) newPtr := add(ptr, 1) } _item.ptr = newPtr; _item.len -= 1; return ret; } /** * @notice Reads an Item into compressed flags and length of values. * Internal ptr and length is updated automatically. * * @param _item Item to read. * * @return Compressed flags. * @return Length of values. */ function readCompressedFlags(Item memory _item) internal pure returns (uint32, uint8) { require(_item.len >= 4, "NodeReader: too short for uint32"); bytes memory newPtr; bytes memory ptr = _item.ptr; uint32 temp; uint8 flag; uint8 len; assembly { temp := mload(ptr) len := shr(248, temp) flag := shr(240, temp) newPtr := add(ptr, 4) } _item.ptr = newPtr; _item.len -= 4; return (flag, len); } /** * @notice Reads an Item into a bytes32. * Internal ptr and length is updated automatically. * * @param _item Item to read. * * @return A bytes32 value. */ function readBytes32(Item memory _item) internal pure returns (bytes32) { require(_item.len >= 32, "NodeReader: too short for bytes32"); bytes memory newPtr; bytes memory ptr = _item.ptr; bytes32 ret; assembly { ret := mload(ptr) newPtr := add(ptr, 32) } _item.ptr = newPtr; _item.len -= 32; return ret; } /** * @notice Reads an Item by n bytes into a bytes32. * Internal ptr and length is updated automatically. * * @param _item Item to read. * * @return A bytes32 value. */ function readBytesN(Item memory _item, uint256 _length) internal pure returns (bytes32) { require(_item.len >= _length, "NodeReader: too short for n bytes"); bytes memory newPtr; bytes memory ptr = _item.ptr; bytes32 ret; uint256 to = 256 - _length * 8; assembly { newPtr := add(ptr, _length) ret := shr(to, mload(ptr)) } _item.ptr = newPtr; _item.len -= _length; return ret; } /** * @notice Reads bytes into a Node. * * @param _proof Bytes to read. * * @return A decoded Node. */ function readNode(bytes memory _proof) internal pure returns (Node memory) { Node memory node; Item memory item = toItem(_proof); uint256 nodeType = readUint8(item); if (nodeType == uint256(NodeType.MIDDLE)) { // TODO(chokobole): Do the length check as much as possible at once and read the bytes. node.childL = readBytes32(item); node.childR = readBytes32(item); } else if (nodeType == uint256(NodeType.LEAF)) { // TODO(chokobole): Do the length check as much as possible at once and read the bytes. node.nodeKey = readBytes32(item); (uint32 compressedFlags, uint256 valuePreimageLen) = readCompressedFlags(item); require((compressedFlags == 1 && valuePreimageLen == 1) || (compressedFlags == 4 && valuePreimageLen == 4), "NodeReader: invalid compressedFlags"); node.compressedFlags = compressedFlags; node.valuePreimage = new bytes32[](valuePreimageLen); for (uint256 i = 0; i < valuePreimageLen; ) { node.valuePreimage[i] = readBytes32(item); unchecked { ++i; } } uint256 keyPreimageLen = readUint8(item); if (keyPreimageLen > 0) { node.keyPreimage = readBytesN(item, keyPreimageLen); } } else if (nodeType == uint256(NodeType.EMPTY)) { // Do nothing. } else if (nodeType == uint256(NodeType.ROOT)) { revert("NodeReader: unexpected root node type"); } else { revert("NodeReader: invalid node type"); } node.nodeType = NodeType(nodeType); return node; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; /** * @title IZKMerkleTrie */ interface IZKMerkleTrie { /** * @notice Verifies a proof that a given key/value pair is present in the trie. * * @param _key Key of the node to search for, as a hex string. * @param _value Value of the node to search for, as a hex string. * @param _proofs Merkle trie inclusion proof for the desired node. * @param _root Known root of the Merkle trie. Used to verify that the included proof is * correctly constructed. * * @return Whether or not the proof is valid. */ function verifyInclusionProof( bytes32 _key, bytes memory _value, bytes[] memory _proofs, bytes32 _root ) external view returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { Bytes32 } from "../libraries/Bytes32.sol"; /** * @title IPoseidon2 */ interface IPoseidon2 { function poseidon(bytes32[2] memory inputs) external pure returns (bytes32); } /** * @custom:proxied * @title ZKTrieHasher * @notice The ZKTrieHasher is contract which can produce a hash according to ZKTrie. * This owns an interface of Poseidon2 that is required to compute hash used by ZKTrie. */ contract ZKTrieHasher { /** * @notice Poseidon2 contract generated by circomlibjs. */ IPoseidon2 public immutable POSEIDON2; /** * @param _poseidon2 The address of poseidon2 contract. */ constructor(address _poseidon2) { POSEIDON2 = IPoseidon2(_poseidon2); } /** * @notice Computes a hash of values. * * @param _compressedFlags Compressed flags. * @param _values Values. * * @return A hash of values. */ function _valueHash(uint32 _compressedFlags, bytes32[] memory _values) internal view returns (bytes32) { require(_values.length >= 1, "ZKTrieHasher: too few values for _valueHash"); bytes32[] memory ret = new bytes32[](_values.length); for (uint256 i = 0; i < _values.length; ) { if ((_compressedFlags & (1 << i)) != 0) { ret[i] = _hashElem(_values[i]); } else { ret[i] = _values[i]; } unchecked { ++i; } } if (_values.length < 2) { return ret[0]; } return _hashElems(ret); } /** * @notice Computes a hash of an element. * * @param _elem Bytes32 to be hashed. * * @return A hash of an element. */ function _hashElem(bytes32 _elem) internal view returns (bytes32) { (bytes32 high, bytes32 low) = Bytes32.split(_elem); return POSEIDON2.poseidon([high, low]); } /** * @notice Computes a root hash of elements tree. * * @param _elems Bytes32 array to be hashed. * * @return A hash of elements tree. */ function _hashElems(bytes32[] memory _elems) internal view returns (bytes32) { require(_elems.length >= 4, "ZKTrieHasher: too few values for _hashElems"); IPoseidon2 iposeidon = POSEIDON2; uint256 idx; uint256 adjacent_idx; uint256 adjacent_offset = 1; uint256 jump = 2; uint256 length = _elems.length; for (; adjacent_offset < length;) { for (idx = 0; idx < length;) { unchecked { adjacent_idx = idx + adjacent_offset; } if (adjacent_idx < length) { _elems[idx] = iposeidon.poseidon( [_elems[idx], _elems[adjacent_idx]] ); } unchecked { idx += jump; } } adjacent_offset = jump; jump <<= 1; } return _elems[0]; } /** * @notice Computes a root hash of 2 elements. * * @param left_leaf Bytes32 left leaf to be hashed. * @param right_leaf Bytes32 right leaf to be hashed. * * @return A hash of 2 elements. */ function _hashFixed2Elems(bytes32 left_leaf, bytes32 right_leaf) internal view returns (bytes32) { return POSEIDON2.poseidon([left_leaf, right_leaf]); } /** * @notice Computes a root hash of 3 elements. * * @param left_leaf Bytes32 left leaf to be hashed. * @param right_leaf Bytes32 right leaf to be hashed. * @param up_leaf Bytes32 up leaf to be hashed with left||right hash. * * @return A hash of 3 elements. */ function _hashFixed3Elems(bytes32 left_leaf, bytes32 right_leaf, bytes32 up_leaf) internal view returns (bytes32) { IPoseidon2 iposeidon = POSEIDON2; left_leaf = iposeidon.poseidon([left_leaf, right_leaf]); return iposeidon.poseidon([left_leaf, up_leaf]); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/introspection/ERC165Checker.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface. */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return supportsERC165InterfaceUnchecked(account, type(IERC165).interfaceId) && !supportsERC165InterfaceUnchecked(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && supportsERC165InterfaceUnchecked(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces( address account, bytes4[] memory interfaceIds ) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * * Some precompiled contracts will falsely indicate support for a given interface, so caution * should be exercised when using this function. * * Interface identification is specified in ERC-165. */ function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) internal view returns (bool) { // prepare call bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId); // perform static call bool success; uint256 returnSize; uint256 returnValue; assembly { success := staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20) returnSize := returndatasize() returnValue := mload(0x00) } return success && returnSize >= 0x20 && returnValue > 0; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import { Constants } from "../libraries/Constants.sol"; import { Encoding } from "../libraries/Encoding.sol"; import { Hashing } from "../libraries/Hashing.sol"; import { SafeCall } from "../libraries/SafeCall.sol"; /** * @custom:upgradeable * @title CrossDomainMessenger * @notice CrossDomainMessenger is a base contract that provides the core logic for the L1 and L2 * cross-chain messenger contracts. It's designed to be a universal interface that only * needs to be extended slightly to provide low-level message passing functionality on each * chain it's deployed on. Currently only designed for message passing between two paired * chains and does not support one-to-many interactions. * * Any changes to this contract MUST result in a semver bump for contracts that inherit it. */ abstract contract CrossDomainMessenger is PausableUpgradeable { /** * @notice Current message version identifier. */ uint16 public constant MESSAGE_VERSION = 0; /** * @notice Constant overhead added to the base gas for a message. */ uint64 public constant RELAY_CONSTANT_OVERHEAD = 200_000; /** * @notice Numerator for dynamic overhead added to the base gas for a message. */ uint64 public constant MIN_GAS_DYNAMIC_OVERHEAD_NUMERATOR = 64; /** * @notice Denominator for dynamic overhead added to the base gas for a message. */ uint64 public constant MIN_GAS_DYNAMIC_OVERHEAD_DENOMINATOR = 63; /** * @notice Extra gas added to base gas for each byte of calldata in a message. */ uint64 public constant MIN_GAS_CALLDATA_OVERHEAD = 16; /** * @notice Gas reserved for performing the external call in `relayMessage`. */ uint64 public constant RELAY_CALL_OVERHEAD = 40_000; /** * @notice Gas reserved for finalizing the execution of `relayMessage` after the safe call. */ uint64 public constant RELAY_RESERVED_GAS = 40_000; /** * @notice Gas reserved for the execution between the `hasMinGas` check and the external * call in `relayMessage`. */ uint64 public constant RELAY_GAS_CHECK_BUFFER = 5_000; /** * @notice Address of the paired CrossDomainMessenger contract on the other chain. */ address public immutable OTHER_MESSENGER; /** * @notice Mapping of message hashes to boolean receipt values. Note that a message will only * be present in this mapping if it has successfully been relayed on this chain, and * can therefore not be relayed again. */ mapping(bytes32 => bool) public successfulMessages; /** * @notice Address of the sender of the currently executing message on the other chain. If the * value of this variable is the default value (0x00000000...dead) then no message is * currently being executed. Use the xDomainMessageSender getter which will throw an * error if this is the case. */ address internal xDomainMsgSender; /** * @notice Nonce for the next message to be sent, without the message version applied. Use the * messageNonce getter which will insert the message version into the nonce to give you * the actual nonce to be used for the message. */ uint240 internal msgNonce; /** * @notice Mapping of message hashes to a boolean if and only if the message has failed to be * executed at least once. A message will not be present in this mapping if it * successfully executed on the first attempt. */ mapping(bytes32 => bool) public failedMessages; /** * @notice Reserve extra slots in the storage layout for future upgrades. * A gap size of 45 was chosen here, so that the first slot used in a child contract * would be a multiple of 50. */ uint256[45] private __gap; /** * @notice Emitted whenever a message is sent to the other chain. * * @param target Address of the recipient of the message. * @param sender Address of the sender of the message. * @param value ETH value sent along with the message to the recipient. * @param message Message to trigger the recipient address with. * @param messageNonce Unique nonce attached to the message. * @param gasLimit Minimum gas limit that the message can be executed with. */ event SentMessage( address indexed target, address indexed sender, uint256 value, bytes message, uint256 messageNonce, uint256 gasLimit ); /** * @notice Emitted whenever a message is successfully relayed on this chain. * * @param msgHash Hash of the message that was relayed. */ event RelayedMessage(bytes32 indexed msgHash); /** * @notice Emitted whenever a message fails to be relayed on this chain. * * @param msgHash Hash of the message that failed to be relayed. */ event FailedRelayedMessage(bytes32 indexed msgHash); /** * @param _otherMessenger Address of the messenger on the paired chain. */ constructor(address _otherMessenger) { OTHER_MESSENGER = _otherMessenger; } /** * @notice Sends a message to some target address on the other chain. Note that if the call * always reverts, then the message will be unrelayable, and any ETH sent will be * permanently locked. The same will occur if the target on the other chain is * considered unsafe (see the _isUnsafeTarget() function). * * @param _target Target contract or wallet address. * @param _message Message to trigger the target address with. * @param _minGasLimit Minimum gas limit that the message can be executed with. */ function sendMessage( address _target, bytes calldata _message, uint32 _minGasLimit ) external payable { // Triggers a message to the other messenger. Note that the amount of gas provided to the // message is the amount of gas requested by the user PLUS the base gas value. We want to // guarantee the property that the call to the target contract will always have at least // the minimum gas limit specified by the user. _sendMessage( OTHER_MESSENGER, baseGas(_message, _minGasLimit), msg.value, abi.encodeWithSelector( this.relayMessage.selector, messageNonce(), msg.sender, _target, msg.value, _minGasLimit, _message ) ); emit SentMessage(_target, msg.sender, msg.value, _message, messageNonce(), _minGasLimit); unchecked { ++msgNonce; } } /** * @notice Relays a message that was sent by the other CrossDomainMessenger contract. Can only * be executed via cross-chain call from the other messenger OR if the message was * already received once and is currently being replayed. * * @param _nonce Nonce of the message being relayed. * @param _sender Address of the user who sent the message. * @param _target Address that the message is targeted at. * @param _value ETH value to send with the message. * @param _minGasLimit Minimum amount of gas that the message can be executed with. * @param _message Message to send to the target. */ function relayMessage( uint256 _nonce, address _sender, address _target, uint256 _value, uint256 _minGasLimit, bytes calldata _message ) external payable { (, uint16 version) = Encoding.decodeVersionedNonce(_nonce); require( version < 1, "CrossDomainMessenger: only version 0 messages is supported at this time" ); // We use the v0 message hash as the unique identifier for the message because it commits // to the value and minimum gas limit of the message. bytes32 versionedHash = Hashing.hashCrossDomainMessageV0( _nonce, _sender, _target, _value, _minGasLimit, _message ); if (_isOtherMessenger()) { // These properties should always hold when the message is first submitted (as // opposed to being replayed). assert(msg.value == _value); assert(!failedMessages[versionedHash]); } else { require( msg.value == 0, "CrossDomainMessenger: value must be zero unless message is from a system address" ); require( failedMessages[versionedHash], "CrossDomainMessenger: message cannot be replayed" ); } require( _isUnsafeTarget(_target) == false, "CrossDomainMessenger: cannot send message to blocked system address" ); require( successfulMessages[versionedHash] == false, "CrossDomainMessenger: message has already been relayed" ); // If there is not enough gas left to perform the external call and finish the execution, // return early and assign the message to the failedMessages mapping. // We are asserting that we have enough gas to: // 1. Call the target contract (_minGasLimit + RELAY_CALL_OVERHEAD + RELAY_GAS_CHECK_BUFFER) // 1.a. The RELAY_CALL_OVERHEAD is included in `hasMinGas`. // 2. Finish the execution after the external call (RELAY_RESERVED_GAS). // // If `xDomainMsgSender` is not the default L2 sender, this function // is being re-entered. This marks the message as failed to allow it to be replayed. if ( !SafeCall.hasMinGas(_minGasLimit, RELAY_RESERVED_GAS + RELAY_GAS_CHECK_BUFFER) || xDomainMsgSender != Constants.DEFAULT_L2_SENDER ) { failedMessages[versionedHash] = true; emit FailedRelayedMessage(versionedHash); // Revert in this case if the transaction was triggered by the estimation address. This // should only be possible during gas estimation or we have bigger problems. Reverting // here will make the behavior of gas estimation change such that the gas limit // computed will be the amount required to relay the message, even if that amount is // greater than the minimum gas limit specified by the user. if (tx.origin == Constants.ESTIMATION_ADDRESS) { revert("CrossDomainMessenger: failed to relay message"); } return; } xDomainMsgSender = _sender; bool success = SafeCall.call(_target, gasleft() - RELAY_RESERVED_GAS, _value, _message); xDomainMsgSender = Constants.DEFAULT_L2_SENDER; if (success) { successfulMessages[versionedHash] = true; emit RelayedMessage(versionedHash); } else { failedMessages[versionedHash] = true; emit FailedRelayedMessage(versionedHash); // Revert in this case if the transaction was triggered by the estimation address. This // should only be possible during gas estimation or we have bigger problems. Reverting // here will make the behavior of gas estimation change such that the gas limit // computed will be the amount required to relay the message, even if that amount is // greater than the minimum gas limit specified by the user. if (tx.origin == Constants.ESTIMATION_ADDRESS) { revert("CrossDomainMessenger: failed to relay message"); } } } /** * @notice Retrieves the address of the contract or wallet that initiated the currently * executing message on the other chain. Will throw an error if there is no message * currently being executed. Allows the recipient of a call to see who triggered it. * * @return Address of the sender of the currently executing message on the other chain. */ function xDomainMessageSender() external view returns (address) { require( xDomainMsgSender != Constants.DEFAULT_L2_SENDER, "CrossDomainMessenger: xDomainMessageSender is not set" ); return xDomainMsgSender; } /** * @notice Retrieves the next message nonce. Message version will be added to the upper two * bytes of the message nonce. Message version allows us to treat messages as having * different structures. * * @return Nonce of the next message to be sent, with added message version. */ function messageNonce() public view returns (uint256) { return Encoding.encodeVersionedNonce(msgNonce, MESSAGE_VERSION); } /** * @notice Computes the amount of gas required to guarantee that a given message will be * received on the other chain without running out of gas. Guaranteeing that a message * will not run out of gas is important because this ensures that a message can always * be replayed on the other chain if it fails to execute completely. * * @param _message Message to compute the amount of required gas for. * @param _minGasLimit Minimum desired gas limit when message goes to target. * * @return Amount of gas required to guarantee message receipt. */ function baseGas(bytes calldata _message, uint32 _minGasLimit) public pure returns (uint64) { return // Constant overhead RELAY_CONSTANT_OVERHEAD + // Calldata overhead (uint64(_message.length) * MIN_GAS_CALLDATA_OVERHEAD) + // Dynamic overhead (EIP-150) ((_minGasLimit * MIN_GAS_DYNAMIC_OVERHEAD_NUMERATOR) / MIN_GAS_DYNAMIC_OVERHEAD_DENOMINATOR) + // Gas reserved for the worst-case cost of 3/5 of the `CALL` opcode's dynamic gas // factors. (Conservative) RELAY_CALL_OVERHEAD + // Relay reserved gas (to ensure execution of `relayMessage` completes after the // subcontext finishes executing) (Conservative) RELAY_RESERVED_GAS + // Gas reserved for the execution between the `hasMinGas` check and the `CALL` // opcode. (Conservative) RELAY_GAS_CHECK_BUFFER; } /** * @notice Intializer. */ // solhint-disable-next-line func-name-mixedcase function __CrossDomainMessenger_init() internal onlyInitializing { xDomainMsgSender = Constants.DEFAULT_L2_SENDER; } /** * @notice Sends a low-level message to the other messenger. Needs to be implemented by child * contracts because the logic for this depends on the network where the messenger is * being deployed. * * @param _to Recipient of the message on the other chain. * @param _gasLimit Minimum gas limit the message can be executed with. * @param _value Amount of ETH to send with the message. * @param _data Message data. */ function _sendMessage( address _to, uint64 _gasLimit, uint256 _value, bytes memory _data ) internal virtual; /** * @notice Checks whether the message is coming from the other messenger. Implemented by child * contracts because the logic for this depends on the network where the messenger is * being deployed. * * @return Whether the message is coming from the other messenger. */ function _isOtherMessenger() internal view virtual returns (bool); /** * @notice Checks whether a given call target is a system address that could cause the * messenger to peform an unsafe action. This is NOT a mechanism for blocking user * addresses. This is ONLY used to prevent the execution of messages to specific * system addresses that could cause security issues, e.g., having the * CrossDomainMessenger send messages to itself. * * @param _target Address of the contract to check. * * @return Whether or not the address is an unsafe system address. */ function _isUnsafeTarget(address _target) internal view virtual returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @title IKromaMintableERC20 * @notice This interface is available on the KromaMintableERC20 contract. We declare it as a * separate interface so that it can be used in custom implementations of * KromaMintableERC20. */ interface IKromaMintableERC20 { function REMOTE_TOKEN() external view returns (address); function BRIDGE() external view returns (address); function mint(address _to, uint256 _amount) external; function burn(address _from, uint256 _amount) external; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import { ISemver } from "../universal/ISemver.sol"; import { IKromaMintableERC20 } from "./IKromaMintableERC20.sol"; /** * @title KromaMintableERC20 * @notice KromaMintableERC20 is a standard extension of the base ERC20 token contract designed * to allow the StandardBridge contracts to mint and burn tokens. This makes it possible to * use a KromaMintableRC20 as the L2 representation of an L1 token, or vice-versa. * Designed to be backwards compatible with the older StandardL2ERC20 token which was only * meant for use on L2. */ contract KromaMintableERC20 is IKromaMintableERC20, ERC20, ISemver { /** * @notice Address of the corresponding version of this token on the remote chain. */ address public immutable REMOTE_TOKEN; /** * @notice Address of the StandardBridge on this network. */ address public immutable BRIDGE; /** * @notice Emitted whenever tokens are minted for an account. * * @param account Address of the account tokens are being minted for. * @param amount Amount of tokens minted. */ event Mint(address indexed account, uint256 amount); /** * @notice Emitted whenever tokens are burned from an account. * * @param account Address of the account tokens are being burned from. * @param amount Amount of tokens burned. */ event Burn(address indexed account, uint256 amount); /** * @notice A modifier that only allows the bridge to call */ modifier onlyBridge() { require(msg.sender == BRIDGE, "KromaMintableERC20: only bridge can mint and burn"); _; } /** * @notice Semantic version. * @custom:semver 1.0.0 */ string public constant version = "1.0.0"; /** * @notice Constructs the KromaMintableERC20 contract. * * @param _bridge Address of the L2 standard bridge. * @param _remoteToken Address of the corresponding L1 token. * @param _name ERC20 name. * @param _symbol ERC20 symbol. */ constructor( address _bridge, address _remoteToken, string memory _name, string memory _symbol ) ERC20(_name, _symbol) { REMOTE_TOKEN = _remoteToken; BRIDGE = _bridge; } /** * @notice Allows the StandardBridge on this network to mint tokens. * * @param _to Address to mint tokens to. * @param _amount Amount of tokens to mint. */ function mint(address _to, uint256 _amount) external virtual override(IKromaMintableERC20) onlyBridge { _mint(_to, _amount); emit Mint(_to, _amount); } /** * @notice Allows the StandardBridge on this network to burn tokens. * * @param _from Address to burn tokens from. * @param _amount Amount of tokens to burn. */ function burn(address _from, uint256 _amount) external virtual override(IKromaMintableERC20) onlyBridge { _burn(_from, _amount); emit Burn(_from, _amount); } /** * @notice ERC165 interface check function. * * @param _interfaceId Interface ID to check. * * @return Whether or not the interface is supported by this contract. */ function supportsInterface(bytes4 _interfaceId) external pure returns (bool) { bytes4 iface1 = type(IERC165).interfaceId; // Interface corresponding to the updated KromaMintableERC20 (this contract). bytes4 iface2 = type(IKromaMintableERC20).interfaceId; return _interfaceId == iface1 || _interfaceId == iface2; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Bytes32 * @notice Bytes32 is a library for manipulating byte32. */ library Bytes32 { /** * @notice Splits bytes32 to high and low parts. * * @param _bytes Bytes32 to split. * * @return High part of bytes32. * @return Low part of bytes32. */ function split(bytes32 _bytes) internal pure returns (bytes32, bytes32) { bytes16 high = bytes16(_bytes); bytes16 low = bytes16(uint128(uint256(_bytes))); return (fromBytes16(high), fromBytes16(low)); } /** * @notice Converts bytes16 to bytes32. * * @param _bytes Bytes to constrcut to bytes32. * * @return Bytes32 constructed from bytes16. */ function fromBytes16(bytes16 _bytes) internal pure returns (bytes32) { return bytes32(uint256(uint128(_bytes))); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { _requireNotPaused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { _requirePaused(); _; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Throws if the contract is paused. */ function _requireNotPaused() internal view virtual { require(!paused(), "Pausable: paused"); } /** * @dev Throws if the contract is not paused. */ function _requirePaused() internal view virtual { require(paused(), "Pausable: not paused"); } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * The default value of {decimals} is 18. To change this, you should override * this function so it returns a different value. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the default value returned by this function, unless * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by // decrementing then incrementing. _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; // Overflow not possible: amount <= accountBalance <= totalSupply. _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
{ "remappings": [ "@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/", "@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/", "@rari-capital/solmate/=node_modules/@rari-capital/solmate/", "forge-std/=node_modules/forge-std/src/", "ds-test/=node_modules/ds-test/src/", "hardhat-deploy/=node_modules/hardhat-deploy/", "hardhat/=node_modules/hardhat/" ], "optimizer": { "enabled": true, "runs": 10000 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "none" }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "london", "viaIR": false, "libraries": {} }
[{"inputs":[{"components":[{"internalType":"contract L2OutputOracle","name":"_l2Oracle","type":"address"},{"internalType":"contract AssetManager","name":"_assetManager","type":"address"},{"internalType":"address","name":"_trustedValidator","type":"address"},{"internalType":"uint128","name":"_commissionChangeDelaySeconds","type":"uint128"},{"internalType":"uint128","name":"_roundDurationSeconds","type":"uint128"},{"internalType":"uint128","name":"_softJailPeriodSeconds","type":"uint128"},{"internalType":"uint128","name":"_hardJailPeriodSeconds","type":"uint128"},{"internalType":"uint128","name":"_jailThreshold","type":"uint128"},{"internalType":"uint128","name":"_maxOutputFinalizations","type":"uint128"},{"internalType":"uint128","name":"_baseReward","type":"uint128"},{"internalType":"uint128","name":"_minRegisterAmount","type":"uint128"},{"internalType":"uint128","name":"_minActivateAmount","type":"uint128"}],"internalType":"struct IValidatorManager.ConstructorParams","name":"_constructorParams","type":"tuple"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"ImproperValidatorStatus","type":"error"},{"inputs":[],"name":"InsufficientAsset","type":"error"},{"inputs":[],"name":"InvalidConstructorParams","type":"error"},{"inputs":[],"name":"MaxCommissionRateExceeded","type":"error"},{"inputs":[],"name":"NotAllowedCaller","type":"error"},{"inputs":[],"name":"NotElapsedCommissionChangeDelay","type":"error"},{"inputs":[],"name":"NotElapsedJailPeriod","type":"error"},{"inputs":[],"name":"NotInitiatedCommissionChange","type":"error"},{"inputs":[],"name":"NotSelectedPriorityValidator","type":"error"},{"inputs":[],"name":"SameCommissionRate","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"outputIndex","type":"uint256"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint128","name":"amount","type":"uint128"}],"name":"ChallengeRewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"outputIndex","type":"uint256"},{"indexed":true,"internalType":"address","name":"validator","type":"address"},{"indexed":false,"internalType":"uint128","name":"validatorReward","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"baseReward","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"boostedReward","type":"uint128"}],"name":"RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"outputIndex","type":"uint256"},{"indexed":true,"internalType":"address","name":"loser","type":"address"},{"indexed":false,"internalType":"uint128","name":"amount","type":"uint128"}],"name":"SlashReverted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"outputIndex","type":"uint256"},{"indexed":true,"internalType":"address","name":"loser","type":"address"},{"indexed":false,"internalType":"uint128","name":"amount","type":"uint128"}],"name":"Slashed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"validator","type":"address"},{"indexed":false,"internalType":"uint256","name":"activatedAt","type":"uint256"}],"name":"ValidatorActivated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"validator","type":"address"},{"indexed":false,"internalType":"uint8","name":"oldCommissionRate","type":"uint8"},{"indexed":false,"internalType":"uint8","name":"newCommissionRate","type":"uint8"}],"name":"ValidatorCommissionChangeFinalized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"validator","type":"address"},{"indexed":false,"internalType":"uint8","name":"oldCommissionRate","type":"uint8"},{"indexed":false,"internalType":"uint8","name":"newCommissionRate","type":"uint8"}],"name":"ValidatorCommissionChangeInitiated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"validator","type":"address"},{"indexed":false,"internalType":"uint128","name":"expiresAt","type":"uint128"}],"name":"ValidatorJailed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"validator","type":"address"},{"indexed":false,"internalType":"bool","name":"activated","type":"bool"},{"indexed":false,"internalType":"uint8","name":"commissionRate","type":"uint8"},{"indexed":false,"internalType":"uint128","name":"assets","type":"uint128"}],"name":"ValidatorRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"validator","type":"address"},{"indexed":false,"internalType":"uint256","name":"stopsAt","type":"uint256"}],"name":"ValidatorStopped","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"validator","type":"address"}],"name":"ValidatorUnjailed","type":"event"},{"inputs":[],"name":"ASSET_MANAGER","outputs":[{"internalType":"contract AssetManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BASE_REWARD","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BOOSTED_REWARD_DENOM","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BOOSTED_REWARD_NUMERATOR","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"COMMISSION_CHANGE_DELAY_SECONDS","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"COMMISSION_RATE_DENOM","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"HARD_JAIL_PERIOD_SECONDS","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"JAIL_THRESHOLD","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"L2_ORACLE","outputs":[{"internalType":"contract L2OutputOracle","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_OUTPUT_FINALIZATIONS","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_ACTIVATE_AMOUNT","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_REGISTER_AMOUNT","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ROUND_DURATION_SECONDS","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SOFT_JAIL_PERIOD_SECONDS","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TRUSTED_VALIDATOR","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"activateValidator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"activatedValidatorCount","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"activatedValidatorTotalWeight","outputs":[{"internalType":"uint120","name":"","type":"uint120"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"outputIndex","type":"uint256"}],"name":"afterSubmitL2Output","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"bondValidatorKro","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"canFinalizeCommissionChangeAt","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"checkSubmissionEligibility","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[],"name":"finalizeCommissionChange","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"getCommissionRate","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"getPendingCommissionRate","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"getStatus","outputs":[{"internalType":"enum IValidatorManager.ValidatorStatus","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"getWeight","outputs":[{"internalType":"uint120","name":"","type":"uint120"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"inJail","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"newCommissionRate","type":"uint8"}],"name":"initCommissionChange","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"jailExpiresAt","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nextValidator","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"noSubmissionCount","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint128","name":"assets","type":"uint128"},{"internalType":"uint8","name":"commissionRate","type":"uint8"},{"internalType":"address","name":"withdrawAccount","type":"address"}],"name":"registerValidator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"outputIndex","type":"uint256"},{"internalType":"address","name":"loser","type":"address"}],"name":"revertSlash","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"outputIndex","type":"uint256"},{"internalType":"address","name":"winner","type":"address"},{"internalType":"address","name":"loser","type":"address"}],"name":"slash","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"tryActivateValidator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"tryUnjail","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"unbondValidatorKro","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"},{"internalType":"bool","name":"tryRemove","type":"bool"}],"name":"updateValidatorTree","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"}]
Contract Creation Code
6102006040523480156200001257600080fd5b5060405162005e6d38038062005e6d83398101604081905262000035916200017d565b8061016001516001600160801b03168161014001516001600160801b031611156200007357604051631510b77f60e01b815260040160405180910390fd5b80516001600160a01b0390811660809081526020830151821660a0908152604084015190921660c0908152610140808501516001600160801b0390811660e090815261016080880151831661010090815260608901518416610120908152968901518416909452958701518216909552918501518216610180529284015181166101a0529183015182166101c05290910151166101e05262000284565b60405161018081016001600160401b03811182821017156200014257634e487b7160e01b600052604160045260246000fd5b60405290565b80516001600160a01b03811681146200016057600080fd5b919050565b80516001600160801b03811681146200016057600080fd5b600061018082840312156200019157600080fd5b6200019b62000110565b620001a68362000148565b8152620001b66020840162000148565b6020820152620001c96040840162000148565b6040820152620001dc6060840162000165565b6060820152620001ef6080840162000165565b60808201526200020260a0840162000165565b60a08201526200021560c0840162000165565b60c08201526200022860e0840162000165565b60e08201526101006200023d81850162000165565b908201526101206200025184820162000165565b908201526101406200026584820162000165565b908201526101606200027984820162000165565b908201529392505050565b60805160a05160c05160e05161010051610120516101405161016051610180516101a0516101c0516101e0516159eb620004826000396000818161038d01528181614cbf01528181614d2a01528181614d6c01526152120152600081816108580152612ce8015260008181610432015261323b0152600081816103e401528181611c5601526135880152600081816107bb01526135ae0152600081816104590152610f0a0152600081816105c1015281816115460152611de40152600081816106f901528181610ae00152610d74015260008181610366015281816109150152610c5f01526000818161040b0152610f6701526000818161052901528181610a6f01528181610c9301528181610da80152818161108401528181611458015281816119cc01528181611b0201528181611f740152818161210f015281816123090152818161240b0152818161250201528181612eff0152818161303501528181614c1d01528181614df801528181614ea1015261518d0152600081816102dc01528181610e710152818161124c01528181611356015281816118ca015281816119fd01528181611e3401528181611ec60152818161200a015281816121e101528181612add01528181612b6301528181612be701528181612d6d01528181612e14015281816131940152818161333801526133ec01526159eb6000f3fe608060405234801561001057600080fd5b50600436106102d25760003560e01c8063943e400511610186578063b91b2723116100e3578063cdff5e1911610097578063e0cc26a211610071578063e0cc26a21461080e578063e428c2f414610840578063e7816b7f1461085357600080fd5b8063cdff5e1914610799578063daec6770146107b6578063dff221b5146107dd57600080fd5b8063be119347116100c8578063be1193471461072e578063be995dc214610741578063c26148fe1461075457600080fd5b8063b91b272314610359578063bde022bb1461071b57600080fd5b8063a83871721161013a578063ac6c52511161011f578063ac6c52511461062f578063af6ca762146106a4578063b2653fe3146106f457600080fd5b8063a838717214610609578063ab04b8aa1461061c57600080fd5b80639e449b021161016b5780639e449b02146105bc5780639f8a13d7146105e3578063a3433d07146105f657600080fd5b8063943e400514610579578063970531c11461058157600080fd5b80633ee4d4a3116102345780635bab847f116101e85780637d2243b4116101cd5780637d2243b41461054b578063891aab74146105535780638c1516c71461056657600080fd5b80635bab847f146105115780636874e0421461052457600080fd5b80634cca5e6c116102195780634cca5e6c1461045457806354fd4d501461047b57806356b65e97146104c457600080fd5b80633ee4d4a31461040657806342223ae91461042d57600080fd5b806322009af61161028b57806330ccebb51161027057806330ccebb5146103b75780633a549046146103d75780633ca83045146103df57600080fd5b806322009af614610388578063263a3402146103af57600080fd5b80630763fa7e116102bc5780630763fa7e14610330578063110d6069146103595780631796e52e1461036157600080fd5b80621c2ff6146102d7578063065643ea1461031b575b600080fd5b6102fe7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020015b60405180910390f35b61032e61032936600461556f565b61087a565b005b610338602881565b6040516fffffffffffffffffffffffffffffffff9091168152602001610312565b610338606481565b6103387f000000000000000000000000000000000000000000000000000000000000000081565b6103387f000000000000000000000000000000000000000000000000000000000000000081565b61032e610b74565b6103ca6103c53660046155b8565b610bff565b6040516103129190615604565b6102fe610e5b565b6103387f000000000000000000000000000000000000000000000000000000000000000081565b6102fe7f000000000000000000000000000000000000000000000000000000000000000081565b6103387f000000000000000000000000000000000000000000000000000000000000000081565b6103387f000000000000000000000000000000000000000000000000000000000000000081565b6104b76040518060400160405280600581526020017f312e302e3000000000000000000000000000000000000000000000000000000081525081565b6040516103129190615645565b6105016104d23660046155b8565b6001600160a01b03166000908152600560205260409020546fffffffffffffffffffffffffffffffff16151590565b6040519015158152602001610312565b61032e61051f3660046156c6565b610f89565b6102fe7f000000000000000000000000000000000000000000000000000000000000000081565b61032e6110fe565b61032e6105613660046155b8565b611241565b61032e6105743660046155b8565b611354565b61032e6114b8565b61033861058f3660046155b8565b6001600160a01b03166000908152600560205260409020546fffffffffffffffffffffffffffffffff1690565b6103387f000000000000000000000000000000000000000000000000000000000000000081565b6105016105f13660046155b8565b6116c9565b61032e6106043660046156ff565b6116fc565b61032e6106173660046155b8565b6118c8565b61032e61062a36600461571a565b6119fb565b61068461063d3660046155b8565b6001600160a01b031660009081526003602090815260408083205463ffffffff168352600290915290206001015461010090046effffffffffffffffffffffffffffff1690565b6040516effffffffffffffffffffffffffffff9091168152602001610312565b6001805468010000000000000000900463ffffffff166000908152600260205260409020015470010000000000000000000000000000000090046effffffffffffffffffffffffffffff16610684565b6103387f000000000000000000000000000000000000000000000000000000000000000081565b6103386107293660046155b8565b611dc5565b61032e61073c36600461573f565b611e29565b61032e61074f366004615758565b612008565b6107876107623660046155b8565b6001600160a01b03166000908152600460205260409020546301000000900460ff1690565b60405160ff9091168152602001610312565b6107a16123db565b60405163ffffffff9091168152602001610312565b6103387f000000000000000000000000000000000000000000000000000000000000000081565b6107876107eb3660046155b8565b6001600160a01b0316600090815260046020526040902054610100900460ff1690565b61078761081c3660046155b8565b6001600160a01b031660009081526004602052604090205462010000900460ff1690565b61032e61084e3660046155b8565b612400565b6103387f000000000000000000000000000000000000000000000000000000000000000081565b333b1515806108895750333214155b156108c0576040517f9d02a7c200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60006108cb33610bff565b60058111156108dc576108dc6155d5565b14610913576040517f197299a000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006fffffffffffffffffffffffffffffffff16836fffffffffffffffffffffffffffffffff161015610991576040517f24f21b1500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b606460ff831611156109cf576040517f406b265300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b33600081815260046020819052604091829020805460ff871662010000027fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff0090911617600117815591517f19412a20000000000000000000000000000000000000000000000000000000008152908101929092526fffffffffffffffffffffffffffffffff851660248301526001600160a01b03838116604484015290917f0000000000000000000000000000000000000000000000000000000000000000909116906319412a2090606401600060405180830381600087803b158015610ab557600080fd5b505af1158015610ac9573d6000803e3d6000fd5b505050506fffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000811690851610801590610b1557610b15336124c4565b60408051821515815260ff861660208201526fffffffffffffffffffffffffffffffff871681830152905133917f36f43e5c63d19ec0a34168ec0838b5bfae77656b9f5b94b896e9d2172a41f4fe919081900360600190a25050505050565b6003610b7f33610bff565b6005811115610b9057610b906155d5565b141580610bbd5750336000908152600560205260409020546fffffffffffffffffffffffffffffffff1615155b15610bf4576040517f197299a000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b610bfd336124c4565b565b6001600160a01b03811660009081526004602052604081205460ff16610c2757506000919050565b6040517f981cee530000000000000000000000000000000000000000000000000000000081526001600160a01b0383811660048301527f00000000000000000000000000000000000000000000000000000000000000006fffffffffffffffffffffffffffffffff16917f00000000000000000000000000000000000000000000000000000000000000009091169063981cee5390602401602060405180830381865afa158015610cdc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d00919061577f565b6fffffffffffffffffffffffffffffffff161015610d2057506001919050565b6001600160a01b03828116600081815260036020526040908190205490517f8abf0af0000000000000000000000000000000000000000000000000000000008152600481019290925263ffffffff161515917f00000000000000000000000000000000000000000000000000000000000000006fffffffffffffffffffffffffffffffff16917f000000000000000000000000000000000000000000000000000000000000000090911690638abf0af090602401602060405180830381865afa158015610df1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e15919061577f565b6fffffffffffffffffffffffffffffffff161015610e445780610e3b5750600292915050565b50600492915050565b80610e525750600392915050565b50600592915050565b600080546001600160a01b031615610f645760007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166380446bd26040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ecd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ef1919061579c565b9050804210610f53576000610f0682426157e4565b90507f00000000000000000000000000000000000000000000000000000000000000006fffffffffffffffffffffffffffffffff16811115610f51576001600160a01b039250505090565b505b50506000546001600160a01b031690565b507f000000000000000000000000000000000000000000000000000000000000000090565b6000610f9483610bff565b9050818015610fcf57506001816005811115610fb257610fb26155d5565b1480610fcf57506004816005811115610fcd57610fcd6155d5565b145b1561102d57610fdf6001846125bc565b1561102857826001600160a01b03167fdee7e7274fb1911def379ceda542a2723358c99d6d1f89fcbdbe9e9d638d99614260405161101f91815260200190565b60405180910390a25b505050565b6004816005811115611041576110416155d5565b10611028576040517f8abf0af00000000000000000000000000000000000000000000000000000000081526001600160a01b0380851660048301526110f89185917f00000000000000000000000000000000000000000000000000000000000000001690638abf0af090602401602060405180830381865afa1580156110cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110ef919061577f565b6001919061275e565b50505050565b336000908152600560205260409020546fffffffffffffffffffffffffffffffff16611156576040517f197299a000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b33600090815260056020526040902054426fffffffffffffffffffffffffffffffff90911611156111b3576040517f1dfc20f100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6111bc33612a73565b3360008181526005602052604080822080547fffffffffffffffffffffffffffffffff00000000000000000000000000000000169055517f9390b453426557da5ebdc31f19a37753ca04addf656d32f35232211bb2af3f199190a2600361122233610bff565b6005811115611233576112336155d5565b03610bfd57610bfd336124c4565b336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146112a3576040517f9d02a7c200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60006112ad610e5b565b90506001600160a01b03808216148015906112da5750806001600160a01b0316826001600160a01b031614155b15611311576040517fc625317600000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b61131a826116c9565b611350576040517f197299a000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316639e45e8f46040518163ffffffff1660e01b8152600401602060405180830381865afa1580156113b2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113d691906157fb565b6001600160a01b0316336001600160a01b031614611420576040517f9d02a7c200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040517f8c1516c70000000000000000000000000000000000000000000000000000000081526001600160a01b0382811660048301527f00000000000000000000000000000000000000000000000000000000000000001690638c1516c7906024015b600060405180830381600087803b15801561149d57600080fd5b505af11580156114b1573d6000803e3d6000fd5b5050505050565b60026114c333610bff565b60058111156114d4576114d46155d5565b10806115005750336000908152600560205260409020546fffffffffffffffffffffffffffffffff1615155b15611537576040517f197299a000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600061154233611dc5565b90507f00000000000000000000000000000000000000000000000000000000000000006fffffffffffffffffffffffffffffffff16816fffffffffffffffffffffffffffffffff16036115c1576040517fdf80df2100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b806fffffffffffffffffffffffffffffffff1642101561160d576040517f82225faf00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b3360008181526004602090815260409182902080547fffffffffffffffffffffffff0000000000000000000000000000000000ffffff6301000000820460ff90811662010000818102939093167fffffffffffffffffffffffff000000000000000000000000000000000000ffff851617855586519290930416808252938101829052919492939092917fa40865ec905b139b9cdbd0566756b576b074c47d9dde9f62388b1d66d3e72a6491015b60405180910390a250505050565b600060056116d683610bff565b60058111156116e7576116e76155d5565b036116f457506001919050565b506000919050565b600261170733610bff565b6005811115611718576117186155d5565b10806117445750336000908152600560205260409020546fffffffffffffffffffffffffffffffff1615155b1561177b576040517f197299a000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b606460ff821611156117b9576040517f406b265300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b336000908152600460205260409020805460ff620100009091048116908316819003611811576040517f150393f200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b81547fffffffffffffffffffffffff0000000000000000000000000000000000ffffff16630100000060ff8581169182027fffffffffffffffffffffffff00000000000000000000000000000000ffffffff1692909217640100000000426fffffffffffffffffffffffffffffffff1602178455604080519284168352602083019190915233917f9d9fe61047777339f4f4cb36a1f75ee90e3c6aa90c13abd3ffa07f6f86e0a307910160405180910390a2505050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316639e45e8f46040518163ffffffff1660e01b8152600401602060405180830381865afa158015611926573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061194a91906157fb565b6001600160a01b0316336001600160a01b031614611994576040517f9d02a7c200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040517fa83871720000000000000000000000000000000000000000000000000000000081526001600160a01b0382811660048301527f0000000000000000000000000000000000000000000000000000000000000000169063a838717290602401611483565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316639e45e8f46040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a59573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a7d91906157fb565b6001600160a01b0316336001600160a01b031614611ac7576040517f9d02a7c200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040517f536afae40000000000000000000000000000000000000000000000000000000081526001600160a01b0382811660048301526000917f00000000000000000000000000000000000000000000000000000000000000009091169063536afae4906024016020604051808303816000875af1158015611b4d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b71919061577f565b60008481526006602090815260409182902080547fffffffffffffffffffffffffffffffff0000000000000000000000000000000081166fffffffffffffffffffffffffffffffff918216869003821617909155915191831682529192506001600160a01b0384169185917fe2d313b9d9b90c2930241ea64ee5d6f4ff30dfd44a15cd3f1df2c6cb8021ec07910160405180910390a36001600160a01b0382166000908152600560205260409020546fffffffffffffffffffffffffffffffff1615611028576001600160a01b038216600090815260056020526040812054611c8d907f0000000000000000000000000000000000000000000000000000000000000000906fffffffffffffffffffffffffffffffff16615818565b9050806fffffffffffffffffffffffffffffffff16421015611d37576001600160a01b03831660008181526005602090815260409182902080547fffffffffffffffffffffffffffffffff00000000000000000000000000000000166fffffffffffffffffffffffffffffffff861690811790915591519182527f95a398f2b6b2ad94f281708c97fe502386fc16adca43daed577a1e992a4cc814910160405180910390a26110f8565b6001600160a01b03831660008181526005602052604080822080547fffffffffffffffffffffffffffffffff00000000000000000000000000000000169055517f9390b453426557da5ebdc31f19a37753ca04addf656d32f35232211bb2af3f199190a26003611da684610bff565b6005811115611db757611db76155d5565b036110f8576110f8836124c4565b6001600160a01b038116600090815260046020526040812054611e23907f00000000000000000000000000000000000000000000000000000000000000009064010000000090046fffffffffffffffffffffffffffffffff16615849565b92915050565b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614611e8b576040517f9d02a7c200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b611e93612ad8565b506040517fb0ea09a8000000000000000000000000000000000000000000000000000000008152600481018290526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063b0ea09a890602401602060405180830381865afa158015611f15573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f3991906157fb565b6040517f8c1516c70000000000000000000000000000000000000000000000000000000081526001600160a01b0380831660048301529192507f000000000000000000000000000000000000000000000000000000000000000090911690638c1516c790602401600060405180830381600087803b158015611fba57600080fd5b505af1158015611fce573d6000803e3d6000fd5b50506000546001600160a01b03908116908416039150611ff8905057611ff381612a73565b612000565b61200061320e565b6113506132e5565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316639e45e8f46040518163ffffffff1660e01b8152600401602060405180830381865afa158015612066573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061208a91906157fb565b6001600160a01b0316336001600160a01b0316146120d4576040517f9d02a7c200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040517f5636aabd0000000000000000000000000000000000000000000000000000000081526001600160a01b0382811660048301526000917f000000000000000000000000000000000000000000000000000000000000000090911690635636aabd906024016020604051808303816000875af115801561215a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061217e919061577f565b6040516fffffffffffffffffffffffffffffffff821681529091506001600160a01b0383169085907f1237821480ce4d75f917bc39d1641eb17a5e09a2d5bf982cdd8cb2561aa28e689060200160405180910390a36121de82600061357f565b837f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f403838d6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561223d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612261919061579c565b116122b957600084815260066020526040902080546fffffffffffffffffffffffffffffffff8082168401167fffffffffffffffffffffffffffffffff000000000000000000000000000000009091161790556110f8565b6040517fc42996d60000000000000000000000000000000000000000000000000000000081526001600160a01b0384811660048301526fffffffffffffffffffffffffffffffff831660248301527f0000000000000000000000000000000000000000000000000000000000000000169063c42996d6906044016020604051808303816000875af1158015612352573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612376919061577f565b9050612383836000610f89565b6040516fffffffffffffffffffffffffffffffff821681526001600160a01b0384169085907fd537f9e63e8da05cdb52f795e1c79d7b163e2517d5229375474dbe60b48cfa149060200160405180910390a350505050565b6001546000906123fb9063ffffffff64010000000082048116911661587d565b905090565b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614612462576040517f9d02a7c200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600361246d82610bff565b600581111561247e5761247e6155d5565b1480156124b357506001600160a01b0381166000908152600560205260409020546fffffffffffffffffffffffffffffffff16155b156124c1576124c1816124c4565b50565b6040517f8abf0af00000000000000000000000000000000000000000000000000000000081526001600160a01b0380831660048301526125769183917f00000000000000000000000000000000000000000000000000000000000000001690638abf0af090602401602060405180830381865afa158015612549573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061256d919061577f565b600191906136ec565b806001600160a01b03167ff33a24861b76047debce215c7ae4915a9befc5d870e97efbd4152df23c72112a426040516125b191815260200190565b60405180910390a250565b6001600160a01b038116600090815260028301602052604081205463ffffffff168082036125ee576000915050611e23565b6001600160a01b03831660009081526002850160209081526040808320805463ffffffff1916905563ffffffff8481168452600180890190935292208054910154740100000000000000000000000000000000000000009091049091169061010090046effffffffffffffffffffffffffffff165b63ffffffff8216156127055763ffffffff91821660009081526001808801602052604090912090810180546effffffffffffffffffffffffffffff7001000000000000000000000000000000008083048216869003909116027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff9091161790555474010000000000000000000000000000000000000000900490911690612663565b61270f8684613dba565b50508354600163ffffffff64010000000080840482168301909116027fffffffffffffffffffffffffffffffffffffffffffffffff00000000ffffffff90921691909117855591505092915050565b6001600160a01b038216600090815260028401602052604081205463ffffffff16808203612790576000915050612a6c565b63ffffffff80821660009081526001808801602052604090912090810180546effffffffffffffffffffffffffffff8781166101008181027fffffffffffffffffffffffffffffffff000000000000000000000000000000ff85161790945593549290910416927401000000000000000000000000000000000000000090910416908210156129405763ffffffff83166000908152600188810160205260409091200180547fff000000000000000000000000000000ffffffffffffffffffffffffffffffff8116848803700100000000000000000000000000000000928390046effffffffffffffffffffffffffffff908116820116909202179091555b63ffffffff8216156129305763ffffffff91821660009081526001808a01602052604090912090810180546effffffffffffffffffffffffffffff70010000000000000000000000000000000080830482168601909116027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff909116179055547401000000000000000000000000000000000000000090049091169061288f565b5061293b87846145df565b612a64565b63ffffffff83166000908152600188810160205260409091200180547fff000000000000000000000000000000ffffffffffffffffffffffffffffffff8116878503700100000000000000000000000000000000928390046effffffffffffffffffffffffffffff90811682900316909202179091555b63ffffffff821615612a595763ffffffff91821660009081526001808a01602052604090912090810180546effffffffffffffffffffffffffffff7001000000000000000000000000000000008083048216869003909116027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff90911617905554740100000000000000000000000000000000000000009004909116906129b7565b50612a6487846147eb565b600193505050505b9392505050565b6001600160a01b038116600090815260046020526040902054610100900460ff16156124c1576001600160a01b0316600090815260046020526040902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff169055565b6000807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f403838d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612b39573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b5d919061579c565b905060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166369f16eec6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612bbf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612be3919061579c565b90507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663b98debbf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c43573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c6791906157fb565b6001600160a01b031663ad36d6cc836040518263ffffffff1660e01b8152600401612c9491815260200190565b602060405180830381865afa158015612cb1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cd5919061589a565b612ce25760009250505090565b6000805b7f00000000000000000000000000000000000000000000000000000000000000006fffffffffffffffffffffffffffffffff16826fffffffffffffffffffffffffffffffff16108015612d395750828411155b1561314d576040517f33727c4d000000000000000000000000000000000000000000000000000000008152600481018590527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906333727c4d90602401602060405180830381865afa158015612dbc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612de0919061589a565b1561314d576040517fb0ea09a8000000000000000000000000000000000000000000000000000000008152600481018590527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063b0ea09a890602401602060405180830381865afa158015612e63573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e8791906157fb565b90506000806000612e9784614c16565b6040517fad4294510000000000000000000000000000000000000000000000000000000081526001600160a01b0388811660048301526fffffffffffffffffffffffffffffffff858116602484015284811660448401528316606483015293965091945092507f00000000000000000000000000000000000000000000000000000000000000009091169063ad42945190608401600060405180830381600087803b158015612f4557600080fd5b505af1158015612f59573d6000803e3d6000fd5b5050604080516fffffffffffffffffffffffffffffffff8581168252878116602083015286168183015290516001600160a01b03881693508a92507fd74a44a8cd6c73740a70271e07ee96d8a495ff30037ae6381cbcdb8fe7f2a1ea9181900360600190a36000878152600660205260409020546fffffffffffffffffffffffffffffffff16801561312d576040517fc42996d60000000000000000000000000000000000000000000000000000000081526001600160a01b0386811660048301526fffffffffffffffffffffffffffffffff831660248301527f0000000000000000000000000000000000000000000000000000000000000000169063c42996d6906044016020604051808303816000875af115801561307e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130a2919061577f565b60008981526006602090815260409182902080547fffffffffffffffffffffffffffffffff0000000000000000000000000000000016905590516fffffffffffffffffffffffffffffffff831681529192506001600160a01b038716918a917fd537f9e63e8da05cdb52f795e1c79d7b163e2517d5229375474dbe60b48cfa14910160405180910390a35b613138856000610f89565b87600101975085600101955050505050612ce6565b6fffffffffffffffffffffffffffffffff821615613203576040517f9902cdc0000000000000000000000000000000000000000000000000000000008152600481018590527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690639902cdc090602401600060405180830381600087803b1580156131e057600080fd5b505af11580156131f4573d6000803e3d6000fd5b50505050600194505050505090565b600094505050505090565b6000546001600160a01b031661322057565b600080546001600160a01b03168152600460205260409020547f00000000000000000000000000000000000000000000000000000000000000006fffffffffffffffffffffffffffffffff1661010090910460ff161061329157600054610bfd906001600160a01b0316600161357f565b600080546001600160a01b03168152600460205260409020805460ff6101008083048216600101909116027fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff909116179055565b6001805468010000000000000000900463ffffffff1660009081526002602052604081209091015470010000000000000000000000000000000090046effffffffffffffffffffffffffffff16905060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f403838d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613394573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133b8919061579c565b90506000826effffffffffffffffffffffffffffff161180156133db5750600081115b156135535760006001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001663a25ae55761341c6001856157e4565b6040518263ffffffff1660e01b815260040161343a91815260200190565b608060405180830381865afa158015613457573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061347b91906158b7565b9050600083826020015143414460014361349591906157e4565b6040805160208101969096528501939093527fffffffffffffffffffffffffffffffffffffffff000000000000000000000000606092831b1691840191909152607483015240609482015260b4016040516020818303038152906040528051906020012060001c6135069190615989565b9050613513600182614f47565b600080547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b0392909216919091179055506113509050565b600080547fffffffffffffffffffffffff00000000000000000000000000000000000000001690555050565b6000816135ac577f00000000000000000000000000000000000000000000000000000000000000006135ce565b7f00000000000000000000000000000000000000000000000000000000000000005b6001600160a01b038416600090815260056020526040812054919250908290613609906fffffffffffffffffffffffffffffffff1642615116565b6136139190615849565b6001600160a01b03851660008181526005602090815260409182902080547fffffffffffffffffffffffffffffffff00000000000000000000000000000000166fffffffffffffffffffffffffffffffff8616908117909155915191825292935090917f95a398f2b6b2ad94f281708c97fe502386fc16adca43daed577a1e992a4cc814910160405180910390a26136ac6001856125bc565b156110f857836001600160a01b03167fdee7e7274fb1911def379ceda542a2723358c99d6d1f89fcbdbe9e9d638d9961426040516116bb91815260200190565b6001600160a01b038216613787576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602c60248201527f42616c616e636564576569676874547265653a207a65726f206164647265737360448201527f206e6f7420616c6c6f776564000000000000000000000000000000000000000060648201526084015b60405180910390fd5b6001600160a01b038216600090815260028401602052604090205463ffffffff1615613835576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602960248201527f42616c616e636564576569676874547265653a206e6f646520616c726561647960448201527f206578697374696e670000000000000000000000000000000000000000000000606482015260840161377e565b60006040518060e00160405280846001600160a01b03168152602001600063ffffffff168152602001600063ffffffff168152602001600063ffffffff168152602001600115158152602001836effffffffffffffffffffffffffffff168152602001836effffffffffffffffffffffffffffff16815250905083600001600081819054906101000a900463ffffffff168092919060010191906101000a81548163ffffffff021916908363ffffffff1602179055505060008460000160009054906101000a900463ffffffff169050818560010160008363ffffffff1663ffffffff16815260200190815260200160002060008201518160000160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060208201518160000160146101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160186101000a81548163ffffffff021916908363ffffffff160217905550606082015181600001601c6101000a81548163ffffffff021916908363ffffffff16021790555060808201518160010160006101000a81548160ff02191690831515021790555060a08201518160010160016101000a8154816effffffffffffffffffffffffffffff02191690836effffffffffffffffffffffffffffff16021790555060c08201518160010160106101000a8154816effffffffffffffffffffffffffffff02191690836effffffffffffffffffffffffffffff16021790555090505080856002016000866001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a81548163ffffffff021916908363ffffffff1602179055508460000160089054906101000a900463ffffffff1663ffffffff16600003613b1057845463ffffffff90911668010000000000000000027fffffffffffffffffffffffffffffffffffffffff00000000ffffffffffffffff90911617909355505050565b845468010000000000000000900463ffffffff165b63ffffffff808216600090815260018089016020526040822090810180546effffffffffffffffffffffffffffff70010000000000000000000000000000000080830482168b01909116027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff90911617905580549092600160c01b909104169003613c4c5763ffffffff838116600081815260018a016020526040902080547fffffffffffffffff00000000ffffffffffffffffffffffffffffffffffffffff1674010000000000000000000000000000000000000000938616939093029290921790915581547fffffffff00000000ffffffffffffffffffffffffffffffffffffffffffffffff16600160c01b909102178155613c4387846145df565b50505050505050565b8054600160e01b900463ffffffff16600003613d225763ffffffff838116600081815260018a8101602052604090912080547fffffffffffffffff00000000ffffffffffffffffffffffffffffffffffffffff1674010000000000000000000000000000000000000000948716949094029390931783559190910180547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016905581547bffffffffffffffffffffffffffffffffffffffffffffffffffffffff16600160e01b909102178155613c4387846145df565b805463ffffffff600160e01b8204811660009081526001808b016020526040808320820154600160c01b909504909316825291902001546effffffffffffffffffffffffffffff70010000000000000000000000000000000092839004811692909104161115613da2578054600160e01b900463ffffffff169150613db4565b8054600160c01b900463ffffffff1691505b50613b25565b63ffffffff81166000908152600183016020526040902080546001600160a01b0316613e68576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602360248201527f42616c616e636564576569676874547265653a206e6f6465206e6f742065786960448201527f7374730000000000000000000000000000000000000000000000000000000000606482015260840161377e565b8054600160c01b900463ffffffff16600003614136578054600160e01b900463ffffffff16600003613fe557805474010000000000000000000000000000000000000000900463ffffffff16600003613ee65782547fffffffffffffffffffffffffffffffffffffffff00000000ffffffffffffffff168355613fa1565b600181015460ff1615613f4e57805474010000000000000000000000000000000000000000900463ffffffff166000908152600184016020526040902080547fffffffff00000000ffffffffffffffffffffffffffffffffffffffffffffffff169055613fa1565b805474010000000000000000000000000000000000000000900463ffffffff166000908152600184016020526040902080547bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1690555b5063ffffffff1660009081526001918201602052604081209081550180547fff00000000000000000000000000000000000000000000000000000000000000169055565b805463ffffffff600160e01b80830482166000908152600180880160209081526040808420547fffffffffffffffffffffffff00000000000000000000000000000000000000009097166001600160a01b0397881617808955859004861684528084208084018054948a0180546effffffffffffffffffffffffffffff6101009788900481169097027fffffffffffffffffffffffffffffffff000000000000000000000000000000ff8216811783559254700100000000000000000000000000000000908190049097169096027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff9092167fff000000000000000000000000000000000000000000000000000000000000ff9096169590951717909355915490951682526002880190945292909220805494821663ffffffff1990951694909417909355815404909116906145d9565b8054600160e01b900463ffffffff1660000361429d57805463ffffffff600160c01b80830482166000908152600180880160209081526040808420547fffffffffffffffffffffffff00000000000000000000000000000000000000009097166001600160a01b0397881617808955859004861684528084208084018054948a0180546effffffffffffffffffffffffffffff6101009788900481169097027fffffffffffffffffffffffffffffffff000000000000000000000000000000ff8216811783559254700100000000000000000000000000000000908190049097169096027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff9092167fff000000000000000000000000000000000000000000000000000000000000ff9096169590951717909355915490951682526002880190945292909220805494821663ffffffff1990951694909417909355815404909116906145d9565b805463ffffffff600160e01b82048116600090815260018087016020526040808320820154600160c01b909504909316825291902001546effffffffffffffffffffffffffffff6101009283900481169290910416111561446b57805463ffffffff600160c01b80830482166000908152600180880160209081526040808420547fffffffffffffffffffffffff00000000000000000000000000000000000000009097166001600160a01b03978816178089558581048716855281852080850180548b870180546effffffffffffffffffffffffffffff6101009384900481169093027fffffffffffffffffffffffffffffffff000000000000000000000000000000ff821681178355600160e01b9096048c168a52868a20909801549254700100000000000000000000000000000000908190048316938190048316939093019091169091027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff9093167fff000000000000000000000000000000000000000000000000000000000000ff9096169590951791909117909355915490951682526002880190945292909220805494821663ffffffff1990951694909417909355815404909116906145d9565b805463ffffffff600160e01b80830482166000908152600180880160209081526040808420547fffffffffffffffffffffffff00000000000000000000000000000000000000009097166001600160a01b03978816178089558581048716855281852080850180548b870180546effffffffffffffffffffffffffffff6101009384900481169093027fffffffffffffffffffffffffffffffff000000000000000000000000000000ff8216811783559354600160c01b9096048c168a52868a2090980154700100000000000000000000000000000000908190048316958190048316959095019091169093027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff9091167fff000000000000000000000000000000000000000000000000000000000000ff90961695909517949094179055915490951682526002880190945292909220805494821663ffffffff1990951694909417909355815404909116905b50613dba565b63ffffffff80821660009081526001840160205260408082208054740100000000000000000000000000000000000000009004909316825290205b815474010000000000000000000000000000000000000000900463ffffffff161580159061466d5750600180820154908301546effffffffffffffffffffffffffffff6101009283900481169290910416115b156110f857815481547fffffffffffffffffffffffff00000000000000000000000000000000000000008083166001600160a01b03928316178555835416918116919091178255600180840180548483018054610100908190046effffffffffffffffffffffffffffff9081168083027fffffffffffffffffffffffffffffffff000000000000000000000000000000ff80871691909117875584549584900483169384029516949094179092558354929003700100000000000000000000000000000000808404831691909103909116027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff9091161790558354821660009081526002870160209081526040808320805463ffffffff998a1663ffffffff19918216179091558754965490951683528083208054909516740100000000000000000000000000000000000000009687900489161790945594548490048616808252918701909452818420805493909304909416835290912061461a565b5b63ffffffff8082166000908152600180850160205260408083208054600160e01b810486168552828520840154600160c01b90910490951684529220015490916effffffffffffffffffffffffffffff610100918290048116919092049091161115614a3457600180820154825463ffffffff600160c01b90910416600090815285830160205260409020909101546effffffffffffffffffffffffffffff6101009283900481169290910416111561102857805463ffffffff600160c01b80830482166000908152600187810160208181526040808520547fffffffffffffffffffffffff0000000000000000000000000000000000000000808a166001600160a01b0392831617808c558890048916875282872080549091169982169990991790985583890180548a548890048916875282872086018054610100908190046effffffffffffffffffffffffffffff9081168083027fffffffffffffffffffffffffffffffff000000000000000000000000000000ff80871691909117909655835494839004821692830294909516939093179091558b548990048a168852838820909601805496909203700100000000000000000000000000000000808804831691909103909116027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff9095169490941790935587548716845260028a0180825283852080549a881663ffffffff199b8c16179055885486900487168086529282528385205490971684529590955290208054909516909217909355905404166147ec565b600180820154825463ffffffff600160e01b90910416600090815285830160205260409020909101546effffffffffffffffffffffffffffff6101009283900481169290910416111561102857805463ffffffff600160e01b80830482166000908152600187810160208181526040808520547fffffffffffffffffffffffff0000000000000000000000000000000000000000808a166001600160a01b0392831617808c558890048916875282872080549091169982169990991790985583890180548a548890048916875282872086018054610100908190046effffffffffffffffffffffffffffff9081168083027fffffffffffffffffffffffffffffffff000000000000000000000000000000ff80871691909117909655835494839004821692830294909516939093179091558b548990048a168852838820909601805496909203700100000000000000000000000000000000808804831691909103909116027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff9095169490941790935587548716845260028a0180825283852080549a881663ffffffff199b8c16179055885486900487168086529282528385205490971684529590955290208054909516909217909355905404166147ec565b60008060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663360864176040518163ffffffff1660e01b8152600401602060405180830381865afa158015614c79573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614c9d91906157fb565b6001600160a01b0316846001600160a01b031603614ce35750600091508190507f0000000000000000000000000000000000000000000000000000000000000000614f40565b6001600160a01b03841660009081526004602052604081205462010000900460ff1690614d0f86615150565b9050600080614d546fffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000850116856064615286565b9050614d976fffffffffffffffffffffffffffffffff7f000000000000000000000000000000000000000000000000000000000000000016606486810390615286565b9150614dba6fffffffffffffffffffffffffffffffff8416606486810390615286565b6040517f981cee530000000000000000000000000000000000000000000000000000000081526001600160a01b038a811660048301529194506000917f0000000000000000000000000000000000000000000000000000000000000000169063981cee5390602401602060405180830381865afa158015614e3f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614e63919061577f565b6040517f6b9ffeac0000000000000000000000000000000000000000000000000000000081526001600160a01b038b811660048301529192506000917f00000000000000000000000000000000000000000000000000000000000000001690636b9ffeac90602401602060405180830381865afa158015614ee8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614f0c919061577f565b90506000614f2f6fffffffffffffffffffffffffffffffff861684808501615286565b948590039950949750505001925050505b9193909250565b815460009068010000000000000000900463ffffffff165b63ffffffff80821660009081526001808701602052604080832054600160c01b9004909316825291902001546effffffffffffffffffffffffffffff808516700100000000000000000000000000000000909204161115614fe05763ffffffff9081166000908152600185016020526040902054600160c01b900416614f5f565b63ffffffff8181166000818152600187810160205260408083208054600160c01b9004909516835282208101549290915291909101547001000000000000000000000000000000009091046effffffffffffffffffffffffffffff908116909403938481166101009092041611156150795763ffffffff1660009081526001840160205260409020546001600160a01b03169050611e23565b63ffffffff818116600090815260018681016020526040808320808301549054600160e01b9004909416835290912001546101009091046effffffffffffffffffffffffffffff9081169094039384811670010000000000000000000000000000000090920416111561510c5763ffffffff9081166000908152600185016020526040902054600160e01b900416614f5f565b6000915050611e23565b6000816fffffffffffffffffffffffffffffffff16836fffffffffffffffffffffffffffffffff16116151495781612a6c565b5090919050565b6040517f913f1a9f0000000000000000000000000000000000000000000000000000000081526001600160a01b03828116600483015260009182917f0000000000000000000000000000000000000000000000000000000000000000169063913f1a9f90602401602060405180830381865afa1580156151d4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906151f8919061577f565b9050600061523b6fffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000001660286064615286565b905061527e816fffffffffffffffffffffffffffffffff1665010000000000615277856fffffffffffffffffffffffffffffffff166064615335565b91906153fc565b949350505050565b6000838302608081901c6fffffffffffffffffffffffffffffffff84161161530a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601c60248201527f55696e743132384d6174683a206d756c446976206f766572666c6f7700000000604482015260640161377e565b826fffffffffffffffffffffffffffffffff16818161532b5761532b61595a565b0495945050505050565b600080838310801561534e576001811461536157615370565b6501000000000085028490049150615370565b65010000000000840285900491505b506402ef6c3406818002602890811c808402821c808202831c808302841c808402851c938402851c95909502841c641da06a6e33909502841c6455232d2bb2909202841c640d4ca0c283909302841c643177d95571909102841c64fffe4bcada90960290931c9490940191909101039190910303905081831115611e23576501921fb544430392915050565b600080807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff858709858702925082811083820303915050806000036154545783828161544a5761544a61595a565b0492505050612a6c565b8084116154bd576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f4d6174683a206d756c446976206f766572666c6f770000000000000000000000604482015260640161377e565b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b6fffffffffffffffffffffffffffffffff811681146124c157600080fd5b803560ff8116811461555557600080fd5b919050565b6001600160a01b03811681146124c157600080fd5b60008060006060848603121561558457600080fd5b833561558f81615526565b925061559d60208501615544565b915060408401356155ad8161555a565b809150509250925092565b6000602082840312156155ca57600080fd5b8135612a6c8161555a565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b602081016006831061563f577f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b91905290565b600060208083528351808285015260005b8181101561567257858101830151858201604001528201615656565b81811115615684576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b80151581146124c157600080fd5b600080604083850312156156d957600080fd5b82356156e48161555a565b915060208301356156f4816156b8565b809150509250929050565b60006020828403121561571157600080fd5b612a6c82615544565b6000806040838503121561572d57600080fd5b8235915060208301356156f48161555a565b60006020828403121561575157600080fd5b5035919050565b60008060006060848603121561576d57600080fd5b83359250602084013561559d8161555a565b60006020828403121561579157600080fd5b8151612a6c81615526565b6000602082840312156157ae57600080fd5b5051919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b6000828210156157f6576157f66157b5565b500390565b60006020828403121561580d57600080fd5b8151612a6c8161555a565b60006fffffffffffffffffffffffffffffffff83811690831681811015615841576158416157b5565b039392505050565b60006fffffffffffffffffffffffffffffffff808316818516808303821115615874576158746157b5565b01949350505050565b600063ffffffff83811690831681811015615841576158416157b5565b6000602082840312156158ac57600080fd5b8151612a6c816156b8565b6000608082840312156158c957600080fd5b6040516080810181811067ffffffffffffffff82111715615913577f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b60405282516159218161555a565b815260208381015190820152604083015161593b81615526565b6040820152606083015161594e81615526565b60608201529392505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b60006effffffffffffffffffffffffffffff808416806159d2577f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b9216919091069291505056fea164736f6c634300080f000a0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b000000000000000000000000496c79132b773940ca5b38ebcc0c56887a0ea164000000000000000000000000000000000000000000000000000000000000a8c0000000000000000000000000000000000000000000000000000000000000003c0000000000000000000000000000000000000000000000000000000000001c2000000000000000000000000000000000000000000000000000000000000054600000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000003782dace9d9000000000000000000000000000000000000000000000000000056bc75e2d631000000000000000000000000000000000000000000000000000056bc75e2d63100000
Deployed Bytecode
0x608060405234801561001057600080fd5b50600436106102d25760003560e01c8063943e400511610186578063b91b2723116100e3578063cdff5e1911610097578063e0cc26a211610071578063e0cc26a21461080e578063e428c2f414610840578063e7816b7f1461085357600080fd5b8063cdff5e1914610799578063daec6770146107b6578063dff221b5146107dd57600080fd5b8063be119347116100c8578063be1193471461072e578063be995dc214610741578063c26148fe1461075457600080fd5b8063b91b272314610359578063bde022bb1461071b57600080fd5b8063a83871721161013a578063ac6c52511161011f578063ac6c52511461062f578063af6ca762146106a4578063b2653fe3146106f457600080fd5b8063a838717214610609578063ab04b8aa1461061c57600080fd5b80639e449b021161016b5780639e449b02146105bc5780639f8a13d7146105e3578063a3433d07146105f657600080fd5b8063943e400514610579578063970531c11461058157600080fd5b80633ee4d4a3116102345780635bab847f116101e85780637d2243b4116101cd5780637d2243b41461054b578063891aab74146105535780638c1516c71461056657600080fd5b80635bab847f146105115780636874e0421461052457600080fd5b80634cca5e6c116102195780634cca5e6c1461045457806354fd4d501461047b57806356b65e97146104c457600080fd5b80633ee4d4a31461040657806342223ae91461042d57600080fd5b806322009af61161028b57806330ccebb51161027057806330ccebb5146103b75780633a549046146103d75780633ca83045146103df57600080fd5b806322009af614610388578063263a3402146103af57600080fd5b80630763fa7e116102bc5780630763fa7e14610330578063110d6069146103595780631796e52e1461036157600080fd5b80621c2ff6146102d7578063065643ea1461031b575b600080fd5b6102fe7f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db81565b6040516001600160a01b0390911681526020015b60405180910390f35b61032e61032936600461556f565b61087a565b005b610338602881565b6040516fffffffffffffffffffffffffffffffff9091168152602001610312565b610338606481565b6103387f0000000000000000000000000000000000000000000000056bc75e2d6310000081565b6103387f0000000000000000000000000000000000000000000000003782dace9d90000081565b61032e610b74565b6103ca6103c53660046155b8565b610bff565b6040516103129190615604565b6102fe610e5b565b6103387f000000000000000000000000000000000000000000000000000000000000546081565b6102fe7f000000000000000000000000496c79132b773940ca5b38ebcc0c56887a0ea16481565b6103387f000000000000000000000000000000000000000000000000000000000000000281565b6103387f000000000000000000000000000000000000000000000000000000000000003c81565b6104b76040518060400160405280600581526020017f312e302e3000000000000000000000000000000000000000000000000000000081525081565b6040516103129190615645565b6105016104d23660046155b8565b6001600160a01b03166000908152600560205260409020546fffffffffffffffffffffffffffffffff16151590565b6040519015158152602001610312565b61032e61051f3660046156c6565b610f89565b6102fe7f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b81565b61032e6110fe565b61032e6105613660046155b8565b611241565b61032e6105743660046155b8565b611354565b61032e6114b8565b61033861058f3660046155b8565b6001600160a01b03166000908152600560205260409020546fffffffffffffffffffffffffffffffff1690565b6103387f000000000000000000000000000000000000000000000000000000000000a8c081565b6105016105f13660046155b8565b6116c9565b61032e6106043660046156ff565b6116fc565b61032e6106173660046155b8565b6118c8565b61032e61062a36600461571a565b6119fb565b61068461063d3660046155b8565b6001600160a01b031660009081526003602090815260408083205463ffffffff168352600290915290206001015461010090046effffffffffffffffffffffffffffff1690565b6040516effffffffffffffffffffffffffffff9091168152602001610312565b6001805468010000000000000000900463ffffffff166000908152600260205260409020015470010000000000000000000000000000000090046effffffffffffffffffffffffffffff16610684565b6103387f0000000000000000000000000000000000000000000000056bc75e2d6310000081565b6103386107293660046155b8565b611dc5565b61032e61073c36600461573f565b611e29565b61032e61074f366004615758565b612008565b6107876107623660046155b8565b6001600160a01b03166000908152600460205260409020546301000000900460ff1690565b60405160ff9091168152602001610312565b6107a16123db565b60405163ffffffff9091168152602001610312565b6103387f0000000000000000000000000000000000000000000000000000000000001c2081565b6107876107eb3660046155b8565b6001600160a01b0316600090815260046020526040902054610100900460ff1690565b61078761081c3660046155b8565b6001600160a01b031660009081526004602052604090205462010000900460ff1690565b61032e61084e3660046155b8565b612400565b6103387f000000000000000000000000000000000000000000000000000000000000000a81565b333b1515806108895750333214155b156108c0576040517f9d02a7c200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60006108cb33610bff565b60058111156108dc576108dc6155d5565b14610913576040517f197299a000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b7f0000000000000000000000000000000000000000000000056bc75e2d631000006fffffffffffffffffffffffffffffffff16836fffffffffffffffffffffffffffffffff161015610991576040517f24f21b1500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b606460ff831611156109cf576040517f406b265300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b33600081815260046020819052604091829020805460ff871662010000027fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff0090911617600117815591517f19412a20000000000000000000000000000000000000000000000000000000008152908101929092526fffffffffffffffffffffffffffffffff851660248301526001600160a01b03838116604484015290917f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b909116906319412a2090606401600060405180830381600087803b158015610ab557600080fd5b505af1158015610ac9573d6000803e3d6000fd5b505050506fffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000056bc75e2d63100000811690851610801590610b1557610b15336124c4565b60408051821515815260ff861660208201526fffffffffffffffffffffffffffffffff871681830152905133917f36f43e5c63d19ec0a34168ec0838b5bfae77656b9f5b94b896e9d2172a41f4fe919081900360600190a25050505050565b6003610b7f33610bff565b6005811115610b9057610b906155d5565b141580610bbd5750336000908152600560205260409020546fffffffffffffffffffffffffffffffff1615155b15610bf4576040517f197299a000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b610bfd336124c4565b565b6001600160a01b03811660009081526004602052604081205460ff16610c2757506000919050565b6040517f981cee530000000000000000000000000000000000000000000000000000000081526001600160a01b0383811660048301527f0000000000000000000000000000000000000000000000056bc75e2d631000006fffffffffffffffffffffffffffffffff16917f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b9091169063981cee5390602401602060405180830381865afa158015610cdc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d00919061577f565b6fffffffffffffffffffffffffffffffff161015610d2057506001919050565b6001600160a01b03828116600081815260036020526040908190205490517f8abf0af0000000000000000000000000000000000000000000000000000000008152600481019290925263ffffffff161515917f0000000000000000000000000000000000000000000000056bc75e2d631000006fffffffffffffffffffffffffffffffff16917f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b90911690638abf0af090602401602060405180830381865afa158015610df1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e15919061577f565b6fffffffffffffffffffffffffffffffff161015610e445780610e3b5750600292915050565b50600492915050565b80610e525750600392915050565b50600592915050565b600080546001600160a01b031615610f645760007f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db6001600160a01b03166380446bd26040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ecd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ef1919061579c565b9050804210610f53576000610f0682426157e4565b90507f000000000000000000000000000000000000000000000000000000000000003c6fffffffffffffffffffffffffffffffff16811115610f51576001600160a01b039250505090565b505b50506000546001600160a01b031690565b507f000000000000000000000000496c79132b773940ca5b38ebcc0c56887a0ea16490565b6000610f9483610bff565b9050818015610fcf57506001816005811115610fb257610fb26155d5565b1480610fcf57506004816005811115610fcd57610fcd6155d5565b145b1561102d57610fdf6001846125bc565b1561102857826001600160a01b03167fdee7e7274fb1911def379ceda542a2723358c99d6d1f89fcbdbe9e9d638d99614260405161101f91815260200190565b60405180910390a25b505050565b6004816005811115611041576110416155d5565b10611028576040517f8abf0af00000000000000000000000000000000000000000000000000000000081526001600160a01b0380851660048301526110f89185917f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b1690638abf0af090602401602060405180830381865afa1580156110cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110ef919061577f565b6001919061275e565b50505050565b336000908152600560205260409020546fffffffffffffffffffffffffffffffff16611156576040517f197299a000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b33600090815260056020526040902054426fffffffffffffffffffffffffffffffff90911611156111b3576040517f1dfc20f100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6111bc33612a73565b3360008181526005602052604080822080547fffffffffffffffffffffffffffffffff00000000000000000000000000000000169055517f9390b453426557da5ebdc31f19a37753ca04addf656d32f35232211bb2af3f199190a2600361122233610bff565b6005811115611233576112336155d5565b03610bfd57610bfd336124c4565b336001600160a01b037f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db16146112a3576040517f9d02a7c200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60006112ad610e5b565b90506001600160a01b03808216148015906112da5750806001600160a01b0316826001600160a01b031614155b15611311576040517fc625317600000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b61131a826116c9565b611350576040517f197299a000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5050565b7f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db6001600160a01b0316639e45e8f46040518163ffffffff1660e01b8152600401602060405180830381865afa1580156113b2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113d691906157fb565b6001600160a01b0316336001600160a01b031614611420576040517f9d02a7c200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040517f8c1516c70000000000000000000000000000000000000000000000000000000081526001600160a01b0382811660048301527f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b1690638c1516c7906024015b600060405180830381600087803b15801561149d57600080fd5b505af11580156114b1573d6000803e3d6000fd5b5050505050565b60026114c333610bff565b60058111156114d4576114d46155d5565b10806115005750336000908152600560205260409020546fffffffffffffffffffffffffffffffff1615155b15611537576040517f197299a000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600061154233611dc5565b90507f000000000000000000000000000000000000000000000000000000000000a8c06fffffffffffffffffffffffffffffffff16816fffffffffffffffffffffffffffffffff16036115c1576040517fdf80df2100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b806fffffffffffffffffffffffffffffffff1642101561160d576040517f82225faf00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b3360008181526004602090815260409182902080547fffffffffffffffffffffffff0000000000000000000000000000000000ffffff6301000000820460ff90811662010000818102939093167fffffffffffffffffffffffff000000000000000000000000000000000000ffff851617855586519290930416808252938101829052919492939092917fa40865ec905b139b9cdbd0566756b576b074c47d9dde9f62388b1d66d3e72a6491015b60405180910390a250505050565b600060056116d683610bff565b60058111156116e7576116e76155d5565b036116f457506001919050565b506000919050565b600261170733610bff565b6005811115611718576117186155d5565b10806117445750336000908152600560205260409020546fffffffffffffffffffffffffffffffff1615155b1561177b576040517f197299a000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b606460ff821611156117b9576040517f406b265300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b336000908152600460205260409020805460ff620100009091048116908316819003611811576040517f150393f200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b81547fffffffffffffffffffffffff0000000000000000000000000000000000ffffff16630100000060ff8581169182027fffffffffffffffffffffffff00000000000000000000000000000000ffffffff1692909217640100000000426fffffffffffffffffffffffffffffffff1602178455604080519284168352602083019190915233917f9d9fe61047777339f4f4cb36a1f75ee90e3c6aa90c13abd3ffa07f6f86e0a307910160405180910390a2505050565b7f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db6001600160a01b0316639e45e8f46040518163ffffffff1660e01b8152600401602060405180830381865afa158015611926573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061194a91906157fb565b6001600160a01b0316336001600160a01b031614611994576040517f9d02a7c200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040517fa83871720000000000000000000000000000000000000000000000000000000081526001600160a01b0382811660048301527f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b169063a838717290602401611483565b7f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db6001600160a01b0316639e45e8f46040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a59573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a7d91906157fb565b6001600160a01b0316336001600160a01b031614611ac7576040517f9d02a7c200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040517f536afae40000000000000000000000000000000000000000000000000000000081526001600160a01b0382811660048301526000917f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b9091169063536afae4906024016020604051808303816000875af1158015611b4d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b71919061577f565b60008481526006602090815260409182902080547fffffffffffffffffffffffffffffffff0000000000000000000000000000000081166fffffffffffffffffffffffffffffffff918216869003821617909155915191831682529192506001600160a01b0384169185917fe2d313b9d9b90c2930241ea64ee5d6f4ff30dfd44a15cd3f1df2c6cb8021ec07910160405180910390a36001600160a01b0382166000908152600560205260409020546fffffffffffffffffffffffffffffffff1615611028576001600160a01b038216600090815260056020526040812054611c8d907f0000000000000000000000000000000000000000000000000000000000005460906fffffffffffffffffffffffffffffffff16615818565b9050806fffffffffffffffffffffffffffffffff16421015611d37576001600160a01b03831660008181526005602090815260409182902080547fffffffffffffffffffffffffffffffff00000000000000000000000000000000166fffffffffffffffffffffffffffffffff861690811790915591519182527f95a398f2b6b2ad94f281708c97fe502386fc16adca43daed577a1e992a4cc814910160405180910390a26110f8565b6001600160a01b03831660008181526005602052604080822080547fffffffffffffffffffffffffffffffff00000000000000000000000000000000169055517f9390b453426557da5ebdc31f19a37753ca04addf656d32f35232211bb2af3f199190a26003611da684610bff565b6005811115611db757611db76155d5565b036110f8576110f8836124c4565b6001600160a01b038116600090815260046020526040812054611e23907f000000000000000000000000000000000000000000000000000000000000a8c09064010000000090046fffffffffffffffffffffffffffffffff16615849565b92915050565b336001600160a01b037f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db1614611e8b576040517f9d02a7c200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b611e93612ad8565b506040517fb0ea09a8000000000000000000000000000000000000000000000000000000008152600481018290526000907f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db6001600160a01b03169063b0ea09a890602401602060405180830381865afa158015611f15573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f3991906157fb565b6040517f8c1516c70000000000000000000000000000000000000000000000000000000081526001600160a01b0380831660048301529192507f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b90911690638c1516c790602401600060405180830381600087803b158015611fba57600080fd5b505af1158015611fce573d6000803e3d6000fd5b50506000546001600160a01b03908116908416039150611ff8905057611ff381612a73565b612000565b61200061320e565b6113506132e5565b7f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db6001600160a01b0316639e45e8f46040518163ffffffff1660e01b8152600401602060405180830381865afa158015612066573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061208a91906157fb565b6001600160a01b0316336001600160a01b0316146120d4576040517f9d02a7c200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040517f5636aabd0000000000000000000000000000000000000000000000000000000081526001600160a01b0382811660048301526000917f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b90911690635636aabd906024016020604051808303816000875af115801561215a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061217e919061577f565b6040516fffffffffffffffffffffffffffffffff821681529091506001600160a01b0383169085907f1237821480ce4d75f917bc39d1641eb17a5e09a2d5bf982cdd8cb2561aa28e689060200160405180910390a36121de82600061357f565b837f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db6001600160a01b031663f403838d6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561223d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612261919061579c565b116122b957600084815260066020526040902080546fffffffffffffffffffffffffffffffff8082168401167fffffffffffffffffffffffffffffffff000000000000000000000000000000009091161790556110f8565b6040517fc42996d60000000000000000000000000000000000000000000000000000000081526001600160a01b0384811660048301526fffffffffffffffffffffffffffffffff831660248301527f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b169063c42996d6906044016020604051808303816000875af1158015612352573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612376919061577f565b9050612383836000610f89565b6040516fffffffffffffffffffffffffffffffff821681526001600160a01b0384169085907fd537f9e63e8da05cdb52f795e1c79d7b163e2517d5229375474dbe60b48cfa149060200160405180910390a350505050565b6001546000906123fb9063ffffffff64010000000082048116911661587d565b905090565b336001600160a01b037f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b1614612462576040517f9d02a7c200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600361246d82610bff565b600581111561247e5761247e6155d5565b1480156124b357506001600160a01b0381166000908152600560205260409020546fffffffffffffffffffffffffffffffff16155b156124c1576124c1816124c4565b50565b6040517f8abf0af00000000000000000000000000000000000000000000000000000000081526001600160a01b0380831660048301526125769183917f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b1690638abf0af090602401602060405180830381865afa158015612549573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061256d919061577f565b600191906136ec565b806001600160a01b03167ff33a24861b76047debce215c7ae4915a9befc5d870e97efbd4152df23c72112a426040516125b191815260200190565b60405180910390a250565b6001600160a01b038116600090815260028301602052604081205463ffffffff168082036125ee576000915050611e23565b6001600160a01b03831660009081526002850160209081526040808320805463ffffffff1916905563ffffffff8481168452600180890190935292208054910154740100000000000000000000000000000000000000009091049091169061010090046effffffffffffffffffffffffffffff165b63ffffffff8216156127055763ffffffff91821660009081526001808801602052604090912090810180546effffffffffffffffffffffffffffff7001000000000000000000000000000000008083048216869003909116027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff9091161790555474010000000000000000000000000000000000000000900490911690612663565b61270f8684613dba565b50508354600163ffffffff64010000000080840482168301909116027fffffffffffffffffffffffffffffffffffffffffffffffff00000000ffffffff90921691909117855591505092915050565b6001600160a01b038216600090815260028401602052604081205463ffffffff16808203612790576000915050612a6c565b63ffffffff80821660009081526001808801602052604090912090810180546effffffffffffffffffffffffffffff8781166101008181027fffffffffffffffffffffffffffffffff000000000000000000000000000000ff85161790945593549290910416927401000000000000000000000000000000000000000090910416908210156129405763ffffffff83166000908152600188810160205260409091200180547fff000000000000000000000000000000ffffffffffffffffffffffffffffffff8116848803700100000000000000000000000000000000928390046effffffffffffffffffffffffffffff908116820116909202179091555b63ffffffff8216156129305763ffffffff91821660009081526001808a01602052604090912090810180546effffffffffffffffffffffffffffff70010000000000000000000000000000000080830482168601909116027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff909116179055547401000000000000000000000000000000000000000090049091169061288f565b5061293b87846145df565b612a64565b63ffffffff83166000908152600188810160205260409091200180547fff000000000000000000000000000000ffffffffffffffffffffffffffffffff8116878503700100000000000000000000000000000000928390046effffffffffffffffffffffffffffff90811682900316909202179091555b63ffffffff821615612a595763ffffffff91821660009081526001808a01602052604090912090810180546effffffffffffffffffffffffffffff7001000000000000000000000000000000008083048216869003909116027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff90911617905554740100000000000000000000000000000000000000009004909116906129b7565b50612a6487846147eb565b600193505050505b9392505050565b6001600160a01b038116600090815260046020526040902054610100900460ff16156124c1576001600160a01b0316600090815260046020526040902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff169055565b6000807f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db6001600160a01b031663f403838d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612b39573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b5d919061579c565b905060007f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db6001600160a01b03166369f16eec6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612bbf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612be3919061579c565b90507f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db6001600160a01b031663b98debbf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c43573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c6791906157fb565b6001600160a01b031663ad36d6cc836040518263ffffffff1660e01b8152600401612c9491815260200190565b602060405180830381865afa158015612cb1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cd5919061589a565b612ce25760009250505090565b6000805b7f000000000000000000000000000000000000000000000000000000000000000a6fffffffffffffffffffffffffffffffff16826fffffffffffffffffffffffffffffffff16108015612d395750828411155b1561314d576040517f33727c4d000000000000000000000000000000000000000000000000000000008152600481018590527f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db6001600160a01b0316906333727c4d90602401602060405180830381865afa158015612dbc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612de0919061589a565b1561314d576040517fb0ea09a8000000000000000000000000000000000000000000000000000000008152600481018590527f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db6001600160a01b03169063b0ea09a890602401602060405180830381865afa158015612e63573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e8791906157fb565b90506000806000612e9784614c16565b6040517fad4294510000000000000000000000000000000000000000000000000000000081526001600160a01b0388811660048301526fffffffffffffffffffffffffffffffff858116602484015284811660448401528316606483015293965091945092507f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b9091169063ad42945190608401600060405180830381600087803b158015612f4557600080fd5b505af1158015612f59573d6000803e3d6000fd5b5050604080516fffffffffffffffffffffffffffffffff8581168252878116602083015286168183015290516001600160a01b03881693508a92507fd74a44a8cd6c73740a70271e07ee96d8a495ff30037ae6381cbcdb8fe7f2a1ea9181900360600190a36000878152600660205260409020546fffffffffffffffffffffffffffffffff16801561312d576040517fc42996d60000000000000000000000000000000000000000000000000000000081526001600160a01b0386811660048301526fffffffffffffffffffffffffffffffff831660248301527f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b169063c42996d6906044016020604051808303816000875af115801561307e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130a2919061577f565b60008981526006602090815260409182902080547fffffffffffffffffffffffffffffffff0000000000000000000000000000000016905590516fffffffffffffffffffffffffffffffff831681529192506001600160a01b038716918a917fd537f9e63e8da05cdb52f795e1c79d7b163e2517d5229375474dbe60b48cfa14910160405180910390a35b613138856000610f89565b87600101975085600101955050505050612ce6565b6fffffffffffffffffffffffffffffffff821615613203576040517f9902cdc0000000000000000000000000000000000000000000000000000000008152600481018590527f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db6001600160a01b031690639902cdc090602401600060405180830381600087803b1580156131e057600080fd5b505af11580156131f4573d6000803e3d6000fd5b50505050600194505050505090565b600094505050505090565b6000546001600160a01b031661322057565b600080546001600160a01b03168152600460205260409020547f00000000000000000000000000000000000000000000000000000000000000026fffffffffffffffffffffffffffffffff1661010090910460ff161061329157600054610bfd906001600160a01b0316600161357f565b600080546001600160a01b03168152600460205260409020805460ff6101008083048216600101909116027fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff909116179055565b6001805468010000000000000000900463ffffffff1660009081526002602052604081209091015470010000000000000000000000000000000090046effffffffffffffffffffffffffffff16905060007f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db6001600160a01b031663f403838d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613394573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133b8919061579c565b90506000826effffffffffffffffffffffffffffff161180156133db5750600081115b156135535760006001600160a01b037f0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db1663a25ae55761341c6001856157e4565b6040518263ffffffff1660e01b815260040161343a91815260200190565b608060405180830381865afa158015613457573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061347b91906158b7565b9050600083826020015143414460014361349591906157e4565b6040805160208101969096528501939093527fffffffffffffffffffffffffffffffffffffffff000000000000000000000000606092831b1691840191909152607483015240609482015260b4016040516020818303038152906040528051906020012060001c6135069190615989565b9050613513600182614f47565b600080547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b0392909216919091179055506113509050565b600080547fffffffffffffffffffffffff00000000000000000000000000000000000000001690555050565b6000816135ac577f00000000000000000000000000000000000000000000000000000000000054606135ce565b7f0000000000000000000000000000000000000000000000000000000000001c205b6001600160a01b038416600090815260056020526040812054919250908290613609906fffffffffffffffffffffffffffffffff1642615116565b6136139190615849565b6001600160a01b03851660008181526005602090815260409182902080547fffffffffffffffffffffffffffffffff00000000000000000000000000000000166fffffffffffffffffffffffffffffffff8616908117909155915191825292935090917f95a398f2b6b2ad94f281708c97fe502386fc16adca43daed577a1e992a4cc814910160405180910390a26136ac6001856125bc565b156110f857836001600160a01b03167fdee7e7274fb1911def379ceda542a2723358c99d6d1f89fcbdbe9e9d638d9961426040516116bb91815260200190565b6001600160a01b038216613787576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602c60248201527f42616c616e636564576569676874547265653a207a65726f206164647265737360448201527f206e6f7420616c6c6f776564000000000000000000000000000000000000000060648201526084015b60405180910390fd5b6001600160a01b038216600090815260028401602052604090205463ffffffff1615613835576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602960248201527f42616c616e636564576569676874547265653a206e6f646520616c726561647960448201527f206578697374696e670000000000000000000000000000000000000000000000606482015260840161377e565b60006040518060e00160405280846001600160a01b03168152602001600063ffffffff168152602001600063ffffffff168152602001600063ffffffff168152602001600115158152602001836effffffffffffffffffffffffffffff168152602001836effffffffffffffffffffffffffffff16815250905083600001600081819054906101000a900463ffffffff168092919060010191906101000a81548163ffffffff021916908363ffffffff1602179055505060008460000160009054906101000a900463ffffffff169050818560010160008363ffffffff1663ffffffff16815260200190815260200160002060008201518160000160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060208201518160000160146101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160186101000a81548163ffffffff021916908363ffffffff160217905550606082015181600001601c6101000a81548163ffffffff021916908363ffffffff16021790555060808201518160010160006101000a81548160ff02191690831515021790555060a08201518160010160016101000a8154816effffffffffffffffffffffffffffff02191690836effffffffffffffffffffffffffffff16021790555060c08201518160010160106101000a8154816effffffffffffffffffffffffffffff02191690836effffffffffffffffffffffffffffff16021790555090505080856002016000866001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a81548163ffffffff021916908363ffffffff1602179055508460000160089054906101000a900463ffffffff1663ffffffff16600003613b1057845463ffffffff90911668010000000000000000027fffffffffffffffffffffffffffffffffffffffff00000000ffffffffffffffff90911617909355505050565b845468010000000000000000900463ffffffff165b63ffffffff808216600090815260018089016020526040822090810180546effffffffffffffffffffffffffffff70010000000000000000000000000000000080830482168b01909116027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff90911617905580549092600160c01b909104169003613c4c5763ffffffff838116600081815260018a016020526040902080547fffffffffffffffff00000000ffffffffffffffffffffffffffffffffffffffff1674010000000000000000000000000000000000000000938616939093029290921790915581547fffffffff00000000ffffffffffffffffffffffffffffffffffffffffffffffff16600160c01b909102178155613c4387846145df565b50505050505050565b8054600160e01b900463ffffffff16600003613d225763ffffffff838116600081815260018a8101602052604090912080547fffffffffffffffff00000000ffffffffffffffffffffffffffffffffffffffff1674010000000000000000000000000000000000000000948716949094029390931783559190910180547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016905581547bffffffffffffffffffffffffffffffffffffffffffffffffffffffff16600160e01b909102178155613c4387846145df565b805463ffffffff600160e01b8204811660009081526001808b016020526040808320820154600160c01b909504909316825291902001546effffffffffffffffffffffffffffff70010000000000000000000000000000000092839004811692909104161115613da2578054600160e01b900463ffffffff169150613db4565b8054600160c01b900463ffffffff1691505b50613b25565b63ffffffff81166000908152600183016020526040902080546001600160a01b0316613e68576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602360248201527f42616c616e636564576569676874547265653a206e6f6465206e6f742065786960448201527f7374730000000000000000000000000000000000000000000000000000000000606482015260840161377e565b8054600160c01b900463ffffffff16600003614136578054600160e01b900463ffffffff16600003613fe557805474010000000000000000000000000000000000000000900463ffffffff16600003613ee65782547fffffffffffffffffffffffffffffffffffffffff00000000ffffffffffffffff168355613fa1565b600181015460ff1615613f4e57805474010000000000000000000000000000000000000000900463ffffffff166000908152600184016020526040902080547fffffffff00000000ffffffffffffffffffffffffffffffffffffffffffffffff169055613fa1565b805474010000000000000000000000000000000000000000900463ffffffff166000908152600184016020526040902080547bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1690555b5063ffffffff1660009081526001918201602052604081209081550180547fff00000000000000000000000000000000000000000000000000000000000000169055565b805463ffffffff600160e01b80830482166000908152600180880160209081526040808420547fffffffffffffffffffffffff00000000000000000000000000000000000000009097166001600160a01b0397881617808955859004861684528084208084018054948a0180546effffffffffffffffffffffffffffff6101009788900481169097027fffffffffffffffffffffffffffffffff000000000000000000000000000000ff8216811783559254700100000000000000000000000000000000908190049097169096027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff9092167fff000000000000000000000000000000000000000000000000000000000000ff9096169590951717909355915490951682526002880190945292909220805494821663ffffffff1990951694909417909355815404909116906145d9565b8054600160e01b900463ffffffff1660000361429d57805463ffffffff600160c01b80830482166000908152600180880160209081526040808420547fffffffffffffffffffffffff00000000000000000000000000000000000000009097166001600160a01b0397881617808955859004861684528084208084018054948a0180546effffffffffffffffffffffffffffff6101009788900481169097027fffffffffffffffffffffffffffffffff000000000000000000000000000000ff8216811783559254700100000000000000000000000000000000908190049097169096027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff9092167fff000000000000000000000000000000000000000000000000000000000000ff9096169590951717909355915490951682526002880190945292909220805494821663ffffffff1990951694909417909355815404909116906145d9565b805463ffffffff600160e01b82048116600090815260018087016020526040808320820154600160c01b909504909316825291902001546effffffffffffffffffffffffffffff6101009283900481169290910416111561446b57805463ffffffff600160c01b80830482166000908152600180880160209081526040808420547fffffffffffffffffffffffff00000000000000000000000000000000000000009097166001600160a01b03978816178089558581048716855281852080850180548b870180546effffffffffffffffffffffffffffff6101009384900481169093027fffffffffffffffffffffffffffffffff000000000000000000000000000000ff821681178355600160e01b9096048c168a52868a20909801549254700100000000000000000000000000000000908190048316938190048316939093019091169091027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff9093167fff000000000000000000000000000000000000000000000000000000000000ff9096169590951791909117909355915490951682526002880190945292909220805494821663ffffffff1990951694909417909355815404909116906145d9565b805463ffffffff600160e01b80830482166000908152600180880160209081526040808420547fffffffffffffffffffffffff00000000000000000000000000000000000000009097166001600160a01b03978816178089558581048716855281852080850180548b870180546effffffffffffffffffffffffffffff6101009384900481169093027fffffffffffffffffffffffffffffffff000000000000000000000000000000ff8216811783559354600160c01b9096048c168a52868a2090980154700100000000000000000000000000000000908190048316958190048316959095019091169093027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff9091167fff000000000000000000000000000000000000000000000000000000000000ff90961695909517949094179055915490951682526002880190945292909220805494821663ffffffff1990951694909417909355815404909116905b50613dba565b63ffffffff80821660009081526001840160205260408082208054740100000000000000000000000000000000000000009004909316825290205b815474010000000000000000000000000000000000000000900463ffffffff161580159061466d5750600180820154908301546effffffffffffffffffffffffffffff6101009283900481169290910416115b156110f857815481547fffffffffffffffffffffffff00000000000000000000000000000000000000008083166001600160a01b03928316178555835416918116919091178255600180840180548483018054610100908190046effffffffffffffffffffffffffffff9081168083027fffffffffffffffffffffffffffffffff000000000000000000000000000000ff80871691909117875584549584900483169384029516949094179092558354929003700100000000000000000000000000000000808404831691909103909116027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff9091161790558354821660009081526002870160209081526040808320805463ffffffff998a1663ffffffff19918216179091558754965490951683528083208054909516740100000000000000000000000000000000000000009687900489161790945594548490048616808252918701909452818420805493909304909416835290912061461a565b5b63ffffffff8082166000908152600180850160205260408083208054600160e01b810486168552828520840154600160c01b90910490951684529220015490916effffffffffffffffffffffffffffff610100918290048116919092049091161115614a3457600180820154825463ffffffff600160c01b90910416600090815285830160205260409020909101546effffffffffffffffffffffffffffff6101009283900481169290910416111561102857805463ffffffff600160c01b80830482166000908152600187810160208181526040808520547fffffffffffffffffffffffff0000000000000000000000000000000000000000808a166001600160a01b0392831617808c558890048916875282872080549091169982169990991790985583890180548a548890048916875282872086018054610100908190046effffffffffffffffffffffffffffff9081168083027fffffffffffffffffffffffffffffffff000000000000000000000000000000ff80871691909117909655835494839004821692830294909516939093179091558b548990048a168852838820909601805496909203700100000000000000000000000000000000808804831691909103909116027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff9095169490941790935587548716845260028a0180825283852080549a881663ffffffff199b8c16179055885486900487168086529282528385205490971684529590955290208054909516909217909355905404166147ec565b600180820154825463ffffffff600160e01b90910416600090815285830160205260409020909101546effffffffffffffffffffffffffffff6101009283900481169290910416111561102857805463ffffffff600160e01b80830482166000908152600187810160208181526040808520547fffffffffffffffffffffffff0000000000000000000000000000000000000000808a166001600160a01b0392831617808c558890048916875282872080549091169982169990991790985583890180548a548890048916875282872086018054610100908190046effffffffffffffffffffffffffffff9081168083027fffffffffffffffffffffffffffffffff000000000000000000000000000000ff80871691909117909655835494839004821692830294909516939093179091558b548990048a168852838820909601805496909203700100000000000000000000000000000000808804831691909103909116027fff000000000000000000000000000000ffffffffffffffffffffffffffffffff9095169490941790935587548716845260028a0180825283852080549a881663ffffffff199b8c16179055885486900487168086529282528385205490971684529590955290208054909516909217909355905404166147ec565b60008060007f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b6001600160a01b031663360864176040518163ffffffff1660e01b8152600401602060405180830381865afa158015614c79573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614c9d91906157fb565b6001600160a01b0316846001600160a01b031603614ce35750600091508190507f0000000000000000000000000000000000000000000000003782dace9d900000614f40565b6001600160a01b03841660009081526004602052604081205462010000900460ff1690614d0f86615150565b9050600080614d546fffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000003782dace9d900000850116856064615286565b9050614d976fffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000003782dace9d90000016606486810390615286565b9150614dba6fffffffffffffffffffffffffffffffff8416606486810390615286565b6040517f981cee530000000000000000000000000000000000000000000000000000000081526001600160a01b038a811660048301529194506000917f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b169063981cee5390602401602060405180830381865afa158015614e3f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614e63919061577f565b6040517f6b9ffeac0000000000000000000000000000000000000000000000000000000081526001600160a01b038b811660048301529192506000917f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b1690636b9ffeac90602401602060405180830381865afa158015614ee8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614f0c919061577f565b90506000614f2f6fffffffffffffffffffffffffffffffff861684808501615286565b948590039950949750505001925050505b9193909250565b815460009068010000000000000000900463ffffffff165b63ffffffff80821660009081526001808701602052604080832054600160c01b9004909316825291902001546effffffffffffffffffffffffffffff808516700100000000000000000000000000000000909204161115614fe05763ffffffff9081166000908152600185016020526040902054600160c01b900416614f5f565b63ffffffff8181166000818152600187810160205260408083208054600160c01b9004909516835282208101549290915291909101547001000000000000000000000000000000009091046effffffffffffffffffffffffffffff908116909403938481166101009092041611156150795763ffffffff1660009081526001840160205260409020546001600160a01b03169050611e23565b63ffffffff818116600090815260018681016020526040808320808301549054600160e01b9004909416835290912001546101009091046effffffffffffffffffffffffffffff9081169094039384811670010000000000000000000000000000000090920416111561510c5763ffffffff9081166000908152600185016020526040902054600160e01b900416614f5f565b6000915050611e23565b6000816fffffffffffffffffffffffffffffffff16836fffffffffffffffffffffffffffffffff16116151495781612a6c565b5090919050565b6040517f913f1a9f0000000000000000000000000000000000000000000000000000000081526001600160a01b03828116600483015260009182917f000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b169063913f1a9f90602401602060405180830381865afa1580156151d4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906151f8919061577f565b9050600061523b6fffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000003782dace9d9000001660286064615286565b905061527e816fffffffffffffffffffffffffffffffff1665010000000000615277856fffffffffffffffffffffffffffffffff166064615335565b91906153fc565b949350505050565b6000838302608081901c6fffffffffffffffffffffffffffffffff84161161530a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601c60248201527f55696e743132384d6174683a206d756c446976206f766572666c6f7700000000604482015260640161377e565b826fffffffffffffffffffffffffffffffff16818161532b5761532b61595a565b0495945050505050565b600080838310801561534e576001811461536157615370565b6501000000000085028490049150615370565b65010000000000840285900491505b506402ef6c3406818002602890811c808402821c808202831c808302841c808402851c938402851c95909502841c641da06a6e33909502841c6455232d2bb2909202841c640d4ca0c283909302841c643177d95571909102841c64fffe4bcada90960290931c9490940191909101039190910303905081831115611e23576501921fb544430392915050565b600080807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff858709858702925082811083820303915050806000036154545783828161544a5761544a61595a565b0492505050612a6c565b8084116154bd576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f4d6174683a206d756c446976206f766572666c6f770000000000000000000000604482015260640161377e565b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b6fffffffffffffffffffffffffffffffff811681146124c157600080fd5b803560ff8116811461555557600080fd5b919050565b6001600160a01b03811681146124c157600080fd5b60008060006060848603121561558457600080fd5b833561558f81615526565b925061559d60208501615544565b915060408401356155ad8161555a565b809150509250925092565b6000602082840312156155ca57600080fd5b8135612a6c8161555a565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b602081016006831061563f577f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b91905290565b600060208083528351808285015260005b8181101561567257858101830151858201604001528201615656565b81811115615684576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b80151581146124c157600080fd5b600080604083850312156156d957600080fd5b82356156e48161555a565b915060208301356156f4816156b8565b809150509250929050565b60006020828403121561571157600080fd5b612a6c82615544565b6000806040838503121561572d57600080fd5b8235915060208301356156f48161555a565b60006020828403121561575157600080fd5b5035919050565b60008060006060848603121561576d57600080fd5b83359250602084013561559d8161555a565b60006020828403121561579157600080fd5b8151612a6c81615526565b6000602082840312156157ae57600080fd5b5051919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b6000828210156157f6576157f66157b5565b500390565b60006020828403121561580d57600080fd5b8151612a6c8161555a565b60006fffffffffffffffffffffffffffffffff83811690831681811015615841576158416157b5565b039392505050565b60006fffffffffffffffffffffffffffffffff808316818516808303821115615874576158746157b5565b01949350505050565b600063ffffffff83811690831681811015615841576158416157b5565b6000602082840312156158ac57600080fd5b8151612a6c816156b8565b6000608082840312156158c957600080fd5b6040516080810181811067ffffffffffffffff82111715615913577f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b60405282516159218161555a565b815260208381015190820152604083015161593b81615526565b6040820152606083015161594e81615526565b60608201529392505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b60006effffffffffffffffffffffffffffff808416806159d2577f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b9216919091069291505056fea164736f6c634300080f000a
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b000000000000000000000000496c79132b773940ca5b38ebcc0c56887a0ea164000000000000000000000000000000000000000000000000000000000000a8c0000000000000000000000000000000000000000000000000000000000000003c0000000000000000000000000000000000000000000000000000000000001c2000000000000000000000000000000000000000000000000000000000000054600000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000003782dace9d9000000000000000000000000000000000000000000000000000056bc75e2d631000000000000000000000000000000000000000000000000000056bc75e2d63100000
-----Decoded View---------------
Arg [0] : _constructorParams (tuple): System.Collections.Generic.List`1[Nethereum.ABI.FunctionEncoding.ParameterOutput]
-----Encoded View---------------
12 Constructor Arguments found :
Arg [0] : 0000000000000000000000003d92a7b8e7e6f137d27691d1216b026ffe69b8db
Arg [1] : 000000000000000000000000b641745d0c2df53a3975178c86950d948ff0170b
Arg [2] : 000000000000000000000000496c79132b773940ca5b38ebcc0c56887a0ea164
Arg [3] : 000000000000000000000000000000000000000000000000000000000000a8c0
Arg [4] : 000000000000000000000000000000000000000000000000000000000000003c
Arg [5] : 0000000000000000000000000000000000000000000000000000000000001c20
Arg [6] : 0000000000000000000000000000000000000000000000000000000000005460
Arg [7] : 0000000000000000000000000000000000000000000000000000000000000002
Arg [8] : 000000000000000000000000000000000000000000000000000000000000000a
Arg [9] : 0000000000000000000000000000000000000000000000003782dace9d900000
Arg [10] : 0000000000000000000000000000000000000000000000056bc75e2d63100000
Arg [11] : 0000000000000000000000000000000000000000000000056bc75e2d63100000
Loading...
Loading
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.