Source Code
Overview
ETH Balance
0 ETH
More Info
ContractCreator
Multichain Info
N/A
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Latest 1 internal transaction
Advanced mode:
Parent Transaction Hash | Method | Block |
From
|
To
|
|||
---|---|---|---|---|---|---|---|
0x61012060 | 7941048 | 69 days ago | Contract Creation | 0 ETH |
Loading...
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Similar Match Source Code This contract matches the deployed Bytecode of the Source Code for Contract 0x7D1b81Af...30215a9d8 The constructor portion of the code might be different and could alter the actual behaviour of the contract
Contract Name:
L1NativeTokenVault
Compiler Version
v0.8.24+commit.e11b9ed9
Optimization Enabled:
Yes with 200 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {BeaconProxy} from "@openzeppelin/contracts-v4/proxy/beacon/BeaconProxy.sol"; import {IBeacon} from "@openzeppelin/contracts-v4/proxy/beacon/IBeacon.sol"; import {Create2} from "@openzeppelin/contracts-v4/utils/Create2.sol"; import {IERC20} from "@openzeppelin/contracts-v4/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts-v4/token/ERC20/utils/SafeERC20.sol"; import {IL1NativeTokenVault} from "./IL1NativeTokenVault.sol"; import {INativeTokenVault} from "./INativeTokenVault.sol"; import {NativeTokenVault} from "./NativeTokenVault.sol"; import {IL1AssetHandler} from "../interfaces/IL1AssetHandler.sol"; import {IL1Nullifier} from "../interfaces/IL1Nullifier.sol"; import {IBridgedStandardToken} from "../interfaces/IBridgedStandardToken.sol"; import {IL1AssetRouter} from "../asset-router/IL1AssetRouter.sol"; import {ETH_TOKEN_ADDRESS} from "../../common/Config.sol"; import {L2_NATIVE_TOKEN_VAULT_ADDR} from "../../common/L2ContractAddresses.sol"; import {DataEncoding} from "../../common/libraries/DataEncoding.sol"; import {OriginChainIdNotFound, Unauthorized, ZeroAddress, NoFundsTransferred, InsufficientChainBalance, WithdrawFailed} from "../../common/L1ContractErrors.sol"; import {ClaimFailedDepositFailed, ZeroAmountToTransfer, WrongAmountTransferred, WrongCounterpart} from "../L1BridgeContractErrors.sol"; /// @author Matter Labs /// @custom:security-contact [email protected] /// @dev Vault holding L1 native ETH and ERC20 tokens bridged into the ZK chains. /// @dev Designed for use with a proxy for upgradability. contract L1NativeTokenVault is IL1NativeTokenVault, IL1AssetHandler, NativeTokenVault { using SafeERC20 for IERC20; /// @dev L1 nullifier contract that handles legacy functions & finalize withdrawal, confirm l2 tx mappings IL1Nullifier public immutable override L1_NULLIFIER; /// @dev Maps token balances for each chain to prevent unauthorized spending across ZK chains. /// This serves as a security measure until hyperbridging is implemented. /// NOTE: this function may be removed in the future, don't rely on it! mapping(uint256 chainId => mapping(bytes32 assetId => uint256 balance)) public chainBalance; /// @dev Contract is expected to be used as proxy implementation. /// @dev Initialize the implementation to prevent Parity hack. /// @param _l1WethAddress Address of WETH on deployed chain /// @param _l1AssetRouter Address of Asset Router on L1. /// @param _l1Nullifier Address of the nullifier contract, which handles transaction progress between L1 and ZK chains. constructor( address _l1WethAddress, address _l1AssetRouter, IL1Nullifier _l1Nullifier ) NativeTokenVault( _l1WethAddress, _l1AssetRouter, DataEncoding.encodeNTVAssetId(block.chainid, ETH_TOKEN_ADDRESS), block.chainid ) { L1_NULLIFIER = _l1Nullifier; } /// @dev Accepts ether only from the contract that was the shared Bridge. receive() external payable { if (address(L1_NULLIFIER) != msg.sender) { revert Unauthorized(msg.sender); } } /// @dev Initializes a contract for later use. Expected to be used in the proxy /// @param _owner Address which can change pause / unpause the NTV /// implementation. The owner is the Governor and separate from the ProxyAdmin from now on, so that the Governor can call the bridge. function initialize(address _owner, address _bridgedTokenBeacon) external initializer { if (_owner == address(0)) { revert ZeroAddress(); } bridgedTokenBeacon = IBeacon(_bridgedTokenBeacon); _transferOwnership(_owner); } /// @inheritdoc IL1NativeTokenVault function registerEthToken() external { _unsafeRegisterNativeToken(ETH_TOKEN_ADDRESS); } /// @notice Transfers tokens from shared bridge as part of the migration process. /// The shared bridge becomes the L1Nullifier contract. /// @dev Both ETH and ERC20 tokens can be transferred. Exhausts balance of shared bridge after the first call. /// @dev Calling second time for the same token will revert. /// @param _token The address of token to be transferred (address(1) for ether and contract address for ERC20). function transferFundsFromSharedBridge(address _token) external { ensureTokenIsRegistered(_token); if (_token == ETH_TOKEN_ADDRESS) { uint256 balanceBefore = address(this).balance; L1_NULLIFIER.transferTokenToNTV(_token); uint256 balanceAfter = address(this).balance; if (balanceAfter <= balanceBefore) { revert NoFundsTransferred(); } } else { uint256 balanceBefore = IERC20(_token).balanceOf(address(this)); uint256 nullifierChainBalance = IERC20(_token).balanceOf(address(L1_NULLIFIER)); if (nullifierChainBalance == 0) { revert ZeroAmountToTransfer(); } L1_NULLIFIER.transferTokenToNTV(_token); uint256 balanceAfter = IERC20(_token).balanceOf(address(this)); if (balanceAfter - balanceBefore < nullifierChainBalance) { revert WrongAmountTransferred(balanceAfter - balanceBefore, nullifierChainBalance); } } } /// @notice Updates chain token balance within NTV to account for tokens transferred from the shared bridge (part of the migration process). /// @dev Clears chain balance on the shared bridge after the first call. Subsequent calls will not affect the state. /// @param _token The address of token to be transferred (address(1) for ether and contract address for ERC20). /// @param _targetChainId The chain ID of the corresponding ZK chain. function updateChainBalancesFromSharedBridge(address _token, uint256 _targetChainId) external { uint256 nullifierChainBalance = L1_NULLIFIER.chainBalance(_targetChainId, _token); bytes32 assetId = DataEncoding.encodeNTVAssetId(block.chainid, _token); chainBalance[_targetChainId][assetId] = chainBalance[_targetChainId][assetId] + nullifierChainBalance; originChainId[assetId] = block.chainid; L1_NULLIFIER.nullifyChainBalanceByNTV(_targetChainId, _token); } /// @notice Used to register the Asset Handler asset in L2 AssetRouter. /// @param _assetHandlerAddressOnCounterpart the address of the asset handler on the counterpart chain. function bridgeCheckCounterpartAddress( uint256, bytes32, address, address _assetHandlerAddressOnCounterpart ) external view override onlyAssetRouter { if (_assetHandlerAddressOnCounterpart != L2_NATIVE_TOKEN_VAULT_ADDR) { revert WrongCounterpart(); } } function _getOriginChainId(bytes32 _assetId) internal view returns (uint256) { uint256 chainId = originChainId[_assetId]; if (chainId != 0) { return chainId; } else { address token = tokenAddress[_assetId]; if (token == ETH_TOKEN_ADDRESS) { return block.chainid; } else if (IERC20(token).balanceOf(address(this)) > 0) { return block.chainid; } else if (IERC20(token).balanceOf(address(L1_NULLIFIER)) > 0) { return block.chainid; } else { return 0; } } } /*////////////////////////////////////////////////////////////// Start transaction Functions //////////////////////////////////////////////////////////////*/ function _bridgeBurnNativeToken( uint256 _chainId, bytes32 _assetId, address _originalCaller, // solhint-disable-next-line no-unused-vars bool _depositChecked, uint256 _depositAmount, address _receiver, address _nativeToken ) internal override returns (bytes memory _bridgeMintData) { bool depositChecked = IL1AssetRouter(address(ASSET_ROUTER)).transferFundsToNTV( _assetId, _depositAmount, _originalCaller ); _bridgeMintData = super._bridgeBurnNativeToken({ _chainId: _chainId, _assetId: _assetId, _originalCaller: _originalCaller, _depositChecked: depositChecked, _depositAmount: _depositAmount, _receiver: _receiver, _nativeToken: _nativeToken }); } /*////////////////////////////////////////////////////////////// L1 SPECIFIC FUNCTIONS //////////////////////////////////////////////////////////////*/ /// @inheritdoc IL1AssetHandler function bridgeRecoverFailedTransfer( uint256 _chainId, bytes32 _assetId, address _depositSender, bytes calldata _data ) external payable override requireZeroValue(msg.value) onlyAssetRouter whenNotPaused { // slither-disable-next-line unused-return (uint256 _amount, , ) = DataEncoding.decodeBridgeBurnData(_data); address l1Token = tokenAddress[_assetId]; if (_amount == 0) { revert NoFundsTransferred(); } _handleChainBalanceDecrease(_chainId, _assetId, _amount, false); if (l1Token == ETH_TOKEN_ADDRESS) { bool callSuccess; // Low-level assembly call, to avoid any memory copying (save gas) assembly { callSuccess := call(gas(), _depositSender, _amount, 0, 0, 0, 0) } if (!callSuccess) { revert ClaimFailedDepositFailed(); } } else { uint256 originChainId = _getOriginChainId(_assetId); if (originChainId == block.chainid) { IERC20(l1Token).safeTransfer(_depositSender, _amount); } else if (originChainId != 0) { IBridgedStandardToken(l1Token).bridgeMint(_depositSender, _amount); } else { revert OriginChainIdNotFound(); } // Note we don't allow weth deposits anymore, but there might be legacy weth deposits. // until we add Weth bridging capabilities, we don't wrap/unwrap weth to ether. } } /*////////////////////////////////////////////////////////////// INTERNAL & HELPER FUNCTIONS //////////////////////////////////////////////////////////////*/ function _registerTokenIfBridgedLegacy(address) internal override returns (bytes32) { // There are no legacy tokens present on L1. return bytes32(0); } // get the computed address before the contract DeployWithCreate2 deployed using Bytecode of contract DeployWithCreate2 and salt specified by the sender function calculateCreate2TokenAddress( uint256 _originChainId, address _nonNativeToken ) public view override(INativeTokenVault, NativeTokenVault) returns (address) { bytes32 salt = _getCreate2Salt(_originChainId, _nonNativeToken); return Create2.computeAddress( salt, keccak256(abi.encodePacked(type(BeaconProxy).creationCode, abi.encode(bridgedTokenBeacon, ""))) ); } function _withdrawFunds(bytes32 _assetId, address _to, address _token, uint256 _amount) internal override { if (_assetId == BASE_TOKEN_ASSET_ID) { bool callSuccess; // Low-level assembly call, to avoid any memory copying (save gas) assembly { callSuccess := call(gas(), _to, _amount, 0, 0, 0, 0) } if (!callSuccess) { revert WithdrawFailed(); } } else { // Withdraw funds IERC20(_token).safeTransfer(_to, _amount); } } function _deployBeaconProxy(bytes32 _salt, uint256) internal override returns (BeaconProxy proxy) { // Use CREATE2 to deploy the BeaconProxy address proxyAddress = Create2.deploy( 0, _salt, abi.encodePacked(type(BeaconProxy).creationCode, abi.encode(bridgedTokenBeacon, "")) ); return BeaconProxy(payable(proxyAddress)); } function _handleChainBalanceIncrease( uint256 _chainId, bytes32 _assetId, uint256 _amount, bool _isNative ) internal override { // Note, that we do not update balances for chains where the assetId comes from, // since these chains can mint new instances of the token. if (!_hasInfiniteBalance(_isNative, _assetId, _chainId)) { chainBalance[_chainId][_assetId] += _amount; } } function _handleChainBalanceDecrease( uint256 _chainId, bytes32 _assetId, uint256 _amount, bool _isNative ) internal override { // Note, that we do not update balances for chains where the assetId comes from, // since these chains can mint new instances of the token. if (!_hasInfiniteBalance(_isNative, _assetId, _chainId)) { // Check that the chain has sufficient balance if (chainBalance[_chainId][_assetId] < _amount) { revert InsufficientChainBalance(); } chainBalance[_chainId][_assetId] -= _amount; } } /// @dev Returns whether a chain `_chainId` has infinite balance for an asset `_assetId`, i.e. /// it can be minted by it. /// @param _isNative Whether the asset is native to the L1 chain. /// @param _assetId The asset id /// @param _chainId An id of a chain which we test against. /// @return Whether The chain `_chainId` has infinite balance of the token function _hasInfiniteBalance(bool _isNative, bytes32 _assetId, uint256 _chainId) private view returns (bool) { return !_isNative && originChainId[_assetId] == _chainId; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (proxy/beacon/BeaconProxy.sol) pragma solidity ^0.8.0; import "./IBeacon.sol"; import "../Proxy.sol"; import "../ERC1967/ERC1967Upgrade.sol"; /** * @dev This contract implements a proxy that gets the implementation address for each call from an {UpgradeableBeacon}. * * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't * conflict with the storage layout of the implementation behind the proxy. * * _Available since v3.4._ */ contract BeaconProxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the proxy with `beacon`. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This * will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity * constructor. * * Requirements: * * - `beacon` must be a contract with the interface {IBeacon}. */ constructor(address beacon, bytes memory data) payable { _upgradeBeaconToAndCall(beacon, data, false); } /** * @dev Returns the current beacon address. */ function _beacon() internal view virtual returns (address) { return _getBeacon(); } /** * @dev Returns the current implementation address of the associated beacon. */ function _implementation() internal view virtual override returns (address) { return IBeacon(_getBeacon()).implementation(); } /** * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. * * Requirements: * * - `beacon` must be a contract. * - The implementation returned by `beacon` must be a contract. */ function _setBeacon(address beacon, bytes memory data) internal virtual { _upgradeBeaconToAndCall(beacon, data, false); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Create2.sol) pragma solidity ^0.8.0; /** * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer. * `CREATE2` can be used to compute in advance the address where a smart * contract will be deployed, which allows for interesting new mechanisms known * as 'counterfactual interactions'. * * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more * information. */ library Create2 { /** * @dev Deploys a contract using `CREATE2`. The address where the contract * will be deployed can be known in advance via {computeAddress}. * * The bytecode for a contract can be obtained from Solidity with * `type(contractName).creationCode`. * * Requirements: * * - `bytecode` must not be empty. * - `salt` must have not been used for `bytecode` already. * - the factory must have a balance of at least `amount`. * - if `amount` is non-zero, `bytecode` must have a `payable` constructor. */ function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) { require(address(this).balance >= amount, "Create2: insufficient balance"); require(bytecode.length != 0, "Create2: bytecode length is zero"); /// @solidity memory-safe-assembly assembly { addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt) } require(addr != address(0), "Create2: Failed on deploy"); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the * `bytecodeHash` or `salt` will result in a new destination address. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) { return computeAddress(salt, bytecodeHash, address(this)); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) // Get free memory pointer // | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... | // |-------------------|---------------------------------------------------------------------------| // | bytecodeHash | CCCCCCCCCCCCC...CC | // | salt | BBBBBBBBBBBBB...BB | // | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA | // | 0xFF | FF | // |-------------------|---------------------------------------------------------------------------| // | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC | // | keccak(start, 85) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ | mstore(add(ptr, 0x40), bytecodeHash) mstore(add(ptr, 0x20), salt) mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff mstore8(start, 0xff) addr := keccak256(start, 85) } } }
// 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 pragma solidity 0.8.24; import {IL1Nullifier} from "../interfaces/IL1Nullifier.sol"; import {INativeTokenVault} from "./INativeTokenVault.sol"; import {IL1AssetDeploymentTracker} from "../interfaces/IL1AssetDeploymentTracker.sol"; /// @title L1 Native token vault contract interface /// @author Matter Labs /// @custom:security-contact [email protected] /// @notice The NTV is an Asset Handler for the L1AssetRouter to handle native tokens // is IL1AssetHandler, IL1BaseTokenAssetHandler { interface IL1NativeTokenVault is INativeTokenVault, IL1AssetDeploymentTracker { /// @notice The L1Nullifier contract function L1_NULLIFIER() external view returns (IL1Nullifier); /// @notice Returns the total number of specific tokens locked for some chain function chainBalance(uint256 _chainId, bytes32 _assetId) external view returns (uint256); /// @notice Registers ETH token function registerEthToken() external; event TokenBeaconUpdated(address indexed l2TokenBeacon); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IAssetRouterBase} from "../asset-router/IAssetRouterBase.sol"; /// @title Base Native token vault contract interface /// @author Matter Labs /// @custom:security-contact [email protected] /// @notice The NTV is an Asset Handler for the L1AssetRouter to handle native tokens interface INativeTokenVault { event BridgedTokenBeaconUpdated(address bridgedTokenBeacon, bytes32 bridgedTokenProxyBytecodeHash); /// @notice The Weth token address function WETH_TOKEN() external view returns (address); /// @notice The AssetRouter contract function ASSET_ROUTER() external view returns (IAssetRouterBase); /// @notice The chain ID of the L1 chain function L1_CHAIN_ID() external view returns (uint256); /// @notice Returns the chain ID of the origin chain for a given asset ID function originChainId(bytes32 assetId) external view returns (uint256); /// @notice Registers tokens within the NTV. /// @dev The goal is to allow bridging native tokens automatically, by registering them on the fly. /// @notice Allows the bridge to register a token address for the vault. /// @notice No access control is ok, since the bridging of tokens should be permissionless. This requires permissionless registration. function registerToken(address _l1Token) external; /// @notice Ensures that the native token is registered with the NTV. /// @dev This function is used to ensure that the token is registered with the NTV. function ensureTokenIsRegistered(address _nativeToken) external returns (bytes32); /// @notice Used to get the the ERC20 data for a token function getERC20Getters(address _token, uint256 _originChainId) external view returns (bytes memory); /// @notice Used to get the token address of an assetId function tokenAddress(bytes32 assetId) external view returns (address); /// @notice Used to get the assetId of a token function assetId(address token) external view returns (bytes32); /// @notice Used to get the expected bridged token address corresponding to its native counterpart function calculateCreate2TokenAddress(uint256 _originChainId, address _originToken) external view returns (address); /// @notice Tries to register a token from the provided `_burnData` and reverts if it is not possible. function tryRegisterTokenFromBurnData(bytes calldata _burnData, bytes32 _expectedAssetId) external; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable-v4/access/Ownable2StepUpgradeable.sol"; import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable-v4/security/PausableUpgradeable.sol"; import {BeaconProxy} from "@openzeppelin/contracts-v4/proxy/beacon/BeaconProxy.sol"; import {IBeacon} from "@openzeppelin/contracts-v4/proxy/beacon/IBeacon.sol"; import {IERC20} from "@openzeppelin/contracts-v4/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts-v4/token/ERC20/utils/SafeERC20.sol"; import {IBridgedStandardToken} from "../interfaces/IBridgedStandardToken.sol"; import {INativeTokenVault} from "./INativeTokenVault.sol"; import {IAssetHandler} from "../interfaces/IAssetHandler.sol"; import {IAssetRouterBase} from "../asset-router/IAssetRouterBase.sol"; import {DataEncoding} from "../../common/libraries/DataEncoding.sol"; import {BridgedStandardERC20} from "../BridgedStandardERC20.sol"; import {BridgeHelper} from "../BridgeHelper.sol"; import {EmptyToken} from "../L1BridgeContractErrors.sol"; import {BurningNativeWETHNotSupported, AssetIdAlreadyRegistered, EmptyDeposit, Unauthorized, TokensWithFeesNotSupported, TokenNotSupported, NonEmptyMsgValue, ValueMismatch, AddressMismatch, AssetIdMismatch, AmountMustBeGreaterThanZero, ZeroAddress, DeployingBridgedTokenForNativeToken} from "../../common/L1ContractErrors.sol"; import {AssetHandlerModifiers} from "../interfaces/AssetHandlerModifiers.sol"; /// @author Matter Labs /// @custom:security-contact [email protected] /// @dev Vault holding L1 native ETH and ERC20 tokens bridged into the ZK chains. /// @dev Designed for use with a proxy for upgradability. abstract contract NativeTokenVault is INativeTokenVault, IAssetHandler, Ownable2StepUpgradeable, PausableUpgradeable, AssetHandlerModifiers { using SafeERC20 for IERC20; /// @dev The address of the WETH token. address public immutable override WETH_TOKEN; /// @dev L1 Shared Bridge smart contract that handles communication with its counterparts on L2s IAssetRouterBase public immutable override ASSET_ROUTER; /// @dev The assetId of the base token. bytes32 public immutable BASE_TOKEN_ASSET_ID; /// @dev Chain ID of L1 for bridging reasons. uint256 public immutable L1_CHAIN_ID; /// @dev Contract that stores the implementation address for token. /// @dev For more details see https://docs.openzeppelin.com/contracts/3.x/api/proxy#UpgradeableBeacon. IBeacon public bridgedTokenBeacon; /// @dev A mapping assetId => originChainId mapping(bytes32 assetId => uint256 originChainId) public originChainId; /// @dev A mapping assetId => tokenAddress mapping(bytes32 assetId => address tokenAddress) public tokenAddress; /// @dev A mapping tokenAddress => assetId mapping(address tokenAddress => bytes32 assetId) public assetId; /** * @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[46] private __gap; /// @notice Checks that the message sender is the bridgehub. modifier onlyAssetRouter() { if (msg.sender != address(ASSET_ROUTER)) { revert Unauthorized(msg.sender); } _; } /// @dev Contract is expected to be used as proxy implementation. /// @dev Disable the initialization to prevent Parity hack. /// @param _wethToken Address of WETH on deployed chain /// @param _assetRouter Address of assetRouter constructor(address _wethToken, address _assetRouter, bytes32 _baseTokenAssetId, uint256 _l1ChainId) { _disableInitializers(); L1_CHAIN_ID = _l1ChainId; ASSET_ROUTER = IAssetRouterBase(_assetRouter); WETH_TOKEN = _wethToken; BASE_TOKEN_ASSET_ID = _baseTokenAssetId; } /// @inheritdoc INativeTokenVault function registerToken(address _nativeToken) external virtual { _registerToken(_nativeToken); } function _registerToken(address _nativeToken) internal virtual returns (bytes32 newAssetId) { // We allow registering `WETH_TOKEN` inside `NativeTokenVault` only for L1 native token vault. // It is needed to allow withdrawing such assets. We restrict all WETH-related // operations to deposits from L1 only to be able to upgrade their logic more easily in the // future. if (_nativeToken == WETH_TOKEN && block.chainid != L1_CHAIN_ID) { revert TokenNotSupported(WETH_TOKEN); } if (_nativeToken.code.length == 0) { revert EmptyToken(); } if (assetId[_nativeToken] != bytes32(0)) { revert AssetIdAlreadyRegistered(); } newAssetId = _unsafeRegisterNativeToken(_nativeToken); } /// @inheritdoc INativeTokenVault function ensureTokenIsRegistered(address _nativeToken) public returns (bytes32 tokenAssetId) { bytes32 currentAssetId = assetId[_nativeToken]; if (currentAssetId == bytes32(0)) { tokenAssetId = _registerToken(_nativeToken); } else { tokenAssetId = currentAssetId; } } /*////////////////////////////////////////////////////////////// FINISH TRANSACTION FUNCTIONS //////////////////////////////////////////////////////////////*/ /// @inheritdoc IAssetHandler /// @notice Used when the chain receives a transfer from another chain's Asset Router and correspondingly mints the asset. /// @param _chainId The chainId that the message is from. /// @param _assetId The assetId of the asset being bridged. /// @param _data The abi.encoded transfer data. function bridgeMint( uint256 _chainId, bytes32 _assetId, bytes calldata _data ) external payable override requireZeroValue(msg.value) onlyAssetRouter whenNotPaused { address receiver; uint256 amount; // we set all originChainId for all already bridged tokens with the setLegacyTokenAssetId and updateChainBalancesFromSharedBridge functions. // for tokens that are bridged for the first time, the originChainId will be 0. if (originChainId[_assetId] == block.chainid) { (receiver, amount) = _bridgeMintNativeToken(_chainId, _assetId, _data); } else { (receiver, amount) = _bridgeMintBridgedToken(_chainId, _assetId, _data); } // solhint-disable-next-line func-named-parameters emit BridgeMint(_chainId, _assetId, receiver, amount); } function _bridgeMintBridgedToken( uint256 _chainId, bytes32 _assetId, bytes calldata _data ) internal virtual returns (address receiver, uint256 amount) { // Either it was bridged before, therefore address is not zero, or it is first time bridging and standard erc20 will be deployed address token = tokenAddress[_assetId]; bytes memory erc20Data; address originToken; // slither-disable-next-line unused-return (, receiver, originToken, amount, erc20Data) = DataEncoding.decodeBridgeMintData(_data); if (token == address(0)) { token = _ensureAndSaveTokenDeployed(_assetId, originToken, erc20Data); } _handleChainBalanceDecrease(_chainId, _assetId, amount, false); IBridgedStandardToken(token).bridgeMint(receiver, amount); } function _bridgeMintNativeToken( uint256 _chainId, bytes32 _assetId, bytes calldata _data ) internal returns (address receiver, uint256 amount) { address token = tokenAddress[_assetId]; // slither-disable-next-line unused-return (, receiver, , amount, ) = DataEncoding.decodeBridgeMintData(_data); _handleChainBalanceDecrease(_chainId, _assetId, amount, true); _withdrawFunds(_assetId, receiver, token, amount); } function _withdrawFunds(bytes32 _assetId, address _to, address _token, uint256 _amount) internal virtual; /*////////////////////////////////////////////////////////////// Start transaction Functions //////////////////////////////////////////////////////////////*/ /// @inheritdoc IAssetHandler /// @notice Allows bridgehub to acquire mintValue for L1->L2 transactions. /// @dev In case of native token vault _data is the tuple of _depositAmount and _receiver. function bridgeBurn( uint256 _chainId, uint256 _l2MsgValue, bytes32 _assetId, address _originalCaller, bytes calldata _data ) external payable override requireZeroValue(_l2MsgValue) onlyAssetRouter whenNotPaused returns (bytes memory _bridgeMintData) { (uint256 amount, address receiver, address tokenAddress) = _decodeBurnAndCheckAssetId(_data, _assetId); if (originChainId[_assetId] != block.chainid) { _bridgeMintData = _bridgeBurnBridgedToken({ _chainId: _chainId, _assetId: _assetId, _originalCaller: _originalCaller, _amount: amount, _receiver: receiver, _tokenAddress: tokenAddress }); } else { _bridgeMintData = _bridgeBurnNativeToken({ _chainId: _chainId, _assetId: _assetId, _originalCaller: _originalCaller, _depositChecked: false, _depositAmount: amount, _receiver: receiver, _nativeToken: tokenAddress }); } } function tryRegisterTokenFromBurnData(bytes calldata _burnData, bytes32 _expectedAssetId) external { // slither-disable-next-line unused-return (, , address tokenAddress) = DataEncoding.decodeBridgeBurnData(_burnData); if (tokenAddress == address(0)) { revert ZeroAddress(); } bytes32 storedAssetId = assetId[tokenAddress]; if (storedAssetId != bytes32(0)) { revert AssetIdAlreadyRegistered(); } // This token has not been registered within this NTV yet. Usually this means that the // token is native to the chain and the user would prefer to get it registered as such. // However, there are exceptions (e.g. bridged legacy ERC20 tokens on L2) when the // assetId has not been stored yet. We will ask the implementor to double check that the token // is not legacy. // We try to register it as legacy token. If it fails, we know // it is a native one and so register it as a native token. bytes32 newAssetId = _registerTokenIfBridgedLegacy(tokenAddress); if (newAssetId == bytes32(0)) { newAssetId = _registerToken(tokenAddress); } if (newAssetId != _expectedAssetId) { revert AssetIdMismatch(_expectedAssetId, newAssetId); } } function _decodeBurnAndCheckAssetId( bytes calldata _data, bytes32 _suppliedAssetId ) internal returns (uint256 amount, address receiver, address parsedTokenAddress) { (amount, receiver, parsedTokenAddress) = DataEncoding.decodeBridgeBurnData(_data); if (parsedTokenAddress == address(0)) { // This means that the user wants the native token vault to resolve the // address. In this case, it is assumed that the assetId is already registered. parsedTokenAddress = tokenAddress[_suppliedAssetId]; } // If it is still zero, it means that the token has not been registered. if (parsedTokenAddress == address(0)) { revert ZeroAddress(); } bytes32 storedAssetId = assetId[parsedTokenAddress]; if (_suppliedAssetId != storedAssetId) { revert AssetIdMismatch(storedAssetId, _suppliedAssetId); } } function _registerTokenIfBridgedLegacy(address _token) internal virtual returns (bytes32); function _bridgeBurnBridgedToken( uint256 _chainId, bytes32 _assetId, address _originalCaller, uint256 _amount, address _receiver, address _tokenAddress ) internal requireZeroValue(msg.value) returns (bytes memory _bridgeMintData) { if (_amount == 0) { // "Amount cannot be zero"); revert AmountMustBeGreaterThanZero(); } IBridgedStandardToken(_tokenAddress).bridgeBurn(_originalCaller, _amount); _handleChainBalanceIncrease(_chainId, _assetId, _amount, false); emit BridgeBurn({ chainId: _chainId, assetId: _assetId, sender: _originalCaller, receiver: _receiver, amount: _amount }); bytes memory erc20Metadata; { // we set all originChainId for all already bridged tokens with the setLegacyTokenAssetId and updateChainBalancesFromSharedBridge functions. // for native tokens the originChainId is set when they register. uint256 originChainId = originChainId[_assetId]; if (originChainId == 0) { revert ZeroAddress(); } erc20Metadata = getERC20Getters(_tokenAddress, originChainId); } address originToken; { originToken = IBridgedStandardToken(_tokenAddress).originToken(); if (originToken == address(0)) { revert ZeroAddress(); } } _bridgeMintData = DataEncoding.encodeBridgeMintData({ _originalCaller: _originalCaller, _remoteReceiver: _receiver, _originToken: originToken, _amount: _amount, _erc20Metadata: erc20Metadata }); } function _bridgeBurnNativeToken( uint256 _chainId, bytes32 _assetId, address _originalCaller, bool _depositChecked, uint256 _depositAmount, address _receiver, address _nativeToken ) internal virtual returns (bytes memory _bridgeMintData) { if (_nativeToken == WETH_TOKEN) { // This ensures that WETH_TOKEN can never be bridged from chains it is native to. // It can only be withdrawn from the chain where it has already gotten. revert BurningNativeWETHNotSupported(); } if (_assetId == BASE_TOKEN_ASSET_ID) { if (_depositAmount != msg.value) { revert ValueMismatch(_depositAmount, msg.value); } _handleChainBalanceIncrease(_chainId, _assetId, _depositAmount, true); } else { if (msg.value != 0) { revert NonEmptyMsgValue(); } _handleChainBalanceIncrease(_chainId, _assetId, _depositAmount, true); if (!_depositChecked) { uint256 expectedDepositAmount = _depositFunds(_originalCaller, IERC20(_nativeToken), _depositAmount); // note if _originalCaller is this contract, this will return 0. This does not happen. // The token has non-standard transfer logic if (_depositAmount != expectedDepositAmount) { revert TokensWithFeesNotSupported(); } } } if (_depositAmount == 0) { // empty deposit amount revert EmptyDeposit(); } bytes memory erc20Metadata; { erc20Metadata = getERC20Getters(_nativeToken, originChainId[_assetId]); } _bridgeMintData = DataEncoding.encodeBridgeMintData({ _originalCaller: _originalCaller, _remoteReceiver: _receiver, _originToken: _nativeToken, _amount: _depositAmount, _erc20Metadata: erc20Metadata }); emit BridgeBurn({ chainId: _chainId, assetId: _assetId, sender: _originalCaller, receiver: _receiver, amount: _depositAmount }); } /*////////////////////////////////////////////////////////////// INTERNAL & HELPER FUNCTIONS //////////////////////////////////////////////////////////////*/ /// @notice Transfers tokens from the depositor address to the smart contract address. /// @param _from The address of the depositor. /// @param _token The ERC20 token to be transferred. /// @param _amount The amount to be transferred. /// @return The difference between the contract balance before and after the transferring of funds. function _depositFunds(address _from, IERC20 _token, uint256 _amount) internal virtual returns (uint256) { uint256 balanceBefore = _token.balanceOf(address(this)); // slither-disable-next-line arbitrary-send-erc20 _token.safeTransferFrom(_from, address(this), _amount); uint256 balanceAfter = _token.balanceOf(address(this)); return balanceAfter - balanceBefore; } /// @param _token The address of token of interest. /// @dev Receives and parses (name, symbol, decimals) from the token contract function getERC20Getters(address _token, uint256 _originChainId) public view override returns (bytes memory) { return BridgeHelper.getERC20Getters(_token, _originChainId); } /// @notice Registers a native token address for the vault. /// @dev It does not perform any checks for the correctnesss of the token contract. /// @param _nativeToken The address of the token to be registered. function _unsafeRegisterNativeToken(address _nativeToken) internal returns (bytes32 newAssetId) { newAssetId = DataEncoding.encodeNTVAssetId(block.chainid, _nativeToken); tokenAddress[newAssetId] = _nativeToken; assetId[_nativeToken] = newAssetId; originChainId[newAssetId] = block.chainid; ASSET_ROUTER.setAssetHandlerAddressThisChain(bytes32(uint256(uint160(_nativeToken))), address(this)); } function _handleChainBalanceIncrease( uint256 _chainId, bytes32 _assetId, uint256 _amount, bool _isNative ) internal virtual; function _handleChainBalanceDecrease( uint256 _chainId, bytes32 _assetId, uint256 _amount, bool _isNative ) internal virtual; /*////////////////////////////////////////////////////////////// TOKEN DEPLOYER FUNCTIONS //////////////////////////////////////////////////////////////*/ function _ensureAndSaveTokenDeployed( bytes32 _assetId, address _originToken, bytes memory _erc20Data ) internal virtual returns (address expectedToken) { uint256 tokenOriginChainId; (expectedToken, tokenOriginChainId) = _calculateExpectedTokenAddress(_originToken, _erc20Data); _ensureAndSaveTokenDeployedInner({ _tokenOriginChainId: tokenOriginChainId, _assetId: _assetId, _originToken: _originToken, _erc20Data: _erc20Data, _expectedToken: expectedToken }); } /// @notice Calculates the bridged token address corresponding to native token counterpart. function _calculateExpectedTokenAddress( address _originToken, bytes memory _erc20Data ) internal view returns (address expectedToken, uint256 tokenOriginChainId) { /// @dev calling externally to convert from memory to calldata tokenOriginChainId = this.tokenDataOriginChainId(_erc20Data); expectedToken = calculateCreate2TokenAddress(tokenOriginChainId, _originToken); } /// @notice Returns the origin chain id from the token data. function tokenDataOriginChainId(bytes calldata _erc20Data) public view returns (uint256 tokenOriginChainId) { // slither-disable-next-line unused-return (tokenOriginChainId, , , ) = DataEncoding.decodeTokenData(_erc20Data); if (tokenOriginChainId == 0) { tokenOriginChainId = L1_CHAIN_ID; } } /// @notice Checks that the assetId is correct for the origin token and chain. function _assetIdCheck(uint256 _tokenOriginChainId, bytes32 _assetId, address _originToken) internal view { bytes32 expectedAssetId = DataEncoding.encodeNTVAssetId(_tokenOriginChainId, _originToken); if (_assetId != expectedAssetId) { // Make sure that a NativeTokenVault sent the message revert AssetIdMismatch(expectedAssetId, _assetId); } } function _ensureAndSaveTokenDeployedInner( uint256 _tokenOriginChainId, bytes32 _assetId, address _originToken, bytes memory _erc20Data, address _expectedToken ) internal { _assetIdCheck(_tokenOriginChainId, _assetId, _originToken); address deployedToken = _deployBridgedToken(_tokenOriginChainId, _assetId, _originToken, _erc20Data); if (deployedToken != _expectedToken) { revert AddressMismatch(_expectedToken, deployedToken); } tokenAddress[_assetId] = _expectedToken; assetId[_expectedToken] = _assetId; } /// @notice Calculates the bridged token address corresponding to native token counterpart. /// @param _tokenOriginChainId The chain id of the origin token. /// @param _bridgeToken The address of native token. /// @return The address of bridged token. function calculateCreate2TokenAddress( uint256 _tokenOriginChainId, address _bridgeToken ) public view virtual override returns (address); /// @notice Deploys and initializes the bridged token for the native counterpart. /// @param _tokenOriginChainId The chain id of the origin token. /// @param _originToken The address of origin token. /// @param _erc20Data The ERC20 metadata of the token deployed. /// @return The address of the beacon proxy (bridged token). function _deployBridgedToken( uint256 _tokenOriginChainId, bytes32 _assetId, address _originToken, bytes memory _erc20Data ) internal returns (address) { if (_tokenOriginChainId == block.chainid) { revert DeployingBridgedTokenForNativeToken(); } bytes32 salt = _getCreate2Salt(_tokenOriginChainId, _originToken); BeaconProxy l2Token = _deployBeaconProxy(salt, _tokenOriginChainId); BridgedStandardERC20(address(l2Token)).bridgeInitialize(_assetId, _originToken, _erc20Data); originChainId[_assetId] = _tokenOriginChainId; return address(l2Token); } /// @notice Converts the L1 token address to the create2 salt of deployed L2 token. /// @param _l1Token The address of token on L1. /// @return salt The salt used to compute address of bridged token on L2 and for beacon proxy deployment. function _getCreate2Salt(uint256 _originChainId, address _l1Token) internal view virtual returns (bytes32 salt) { salt = keccak256(abi.encode(_originChainId, _l1Token)); } /// @notice Deploys the beacon proxy for the bridged token. /// @dev This function uses raw call to ContractDeployer to make sure that exactly `l2TokenProxyBytecodeHash` is used /// for the code of the proxy. /// @param _salt The salt used for beacon proxy deployment of the bridged token (we pass the native token address). /// @return proxy The beacon proxy, i.e. bridged token. function _deployBeaconProxy( bytes32 _salt, uint256 _tokenOriginChainId ) internal virtual returns (BeaconProxy proxy); /*////////////////////////////////////////////////////////////// PAUSE //////////////////////////////////////////////////////////////*/ /// @notice Pauses all functions marked with the `whenNotPaused` modifier. function pause() external onlyOwner { _pause(); } /// @notice Unpauses the contract, allowing all functions marked with the `whenNotPaused` modifier to be called again. function unpause() external onlyOwner { _unpause(); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; /// @title L1 Asset Handler contract interface /// @author Matter Labs /// @custom:security-contact [email protected] /// @notice Used for any asset handler and called by the L1AssetRouter interface IL1AssetHandler { /// @param _chainId the chainId that the message will be sent to /// @param _assetId the assetId of the asset being bridged /// @param _depositSender the address of the entity that initiated the deposit. /// @param _data the actual data specified for the function function bridgeRecoverFailedTransfer( uint256 _chainId, bytes32 _assetId, address _depositSender, bytes calldata _data ) external payable; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IBridgehub} from "../../bridgehub/IBridgehub.sol"; import {IL1NativeTokenVault} from "../ntv/IL1NativeTokenVault.sol"; import {IL1ERC20Bridge} from "./IL1ERC20Bridge.sol"; /// @param chainId The chain ID of the transaction to check. /// @param l2BatchNumber The L2 batch number where the withdrawal was processed. /// @param l2MessageIndex The position in the L2 logs Merkle tree of the l2Log that was sent with the message. /// @param l2sender The address of the message sender on L2 (base token system contract address or asset handler) /// @param l2TxNumberInBatch The L2 transaction number in the batch, in which the log was sent. /// @param message The L2 withdraw data, stored in an L2 -> L1 message. /// @param merkleProof The Merkle proof of the inclusion L2 -> L1 message about withdrawal initialization. struct FinalizeL1DepositParams { uint256 chainId; uint256 l2BatchNumber; uint256 l2MessageIndex; address l2Sender; uint16 l2TxNumberInBatch; bytes message; bytes32[] merkleProof; } /// @title L1 Bridge contract interface /// @author Matter Labs /// @custom:security-contact [email protected] interface IL1Nullifier { event BridgehubDepositFinalized( uint256 indexed chainId, bytes32 indexed txDataHash, bytes32 indexed l2DepositTxHash ); function isWithdrawalFinalized( uint256 _chainId, uint256 _l2BatchNumber, uint256 _l2MessageIndex ) external view returns (bool); function claimFailedDepositLegacyErc20Bridge( address _depositSender, address _l1Token, uint256 _amount, bytes32 _l2TxHash, uint256 _l2BatchNumber, uint256 _l2MessageIndex, uint16 _l2TxNumberInBatch, bytes32[] calldata _merkleProof ) external; function claimFailedDeposit( uint256 _chainId, address _depositSender, address _l1Token, uint256 _amount, bytes32 _l2TxHash, uint256 _l2BatchNumber, uint256 _l2MessageIndex, uint16 _l2TxNumberInBatch, bytes32[] calldata _merkleProof ) external; function finalizeDeposit(FinalizeL1DepositParams calldata _finalizeWithdrawalParams) external; function BRIDGE_HUB() external view returns (IBridgehub); function legacyBridge() external view returns (IL1ERC20Bridge); function depositHappened(uint256 _chainId, bytes32 _l2TxHash) external view returns (bytes32); function bridgehubConfirmL2TransactionForwarded(uint256 _chainId, bytes32 _txDataHash, bytes32 _txHash) external; function l1NativeTokenVault() external view returns (IL1NativeTokenVault); function setL1NativeTokenVault(IL1NativeTokenVault _nativeTokenVault) external; function setL1AssetRouter(address _l1AssetRouter) external; function chainBalance(uint256 _chainId, address _token) external view returns (uint256); function l2BridgeAddress(uint256 _chainId) external view returns (address); function transferTokenToNTV(address _token) external; function nullifyChainBalanceByNTV(uint256 _chainId, address _token) external; /// @dev Withdraw funds from the initiated deposit, that failed when finalizing on L2. /// @param _chainId The ZK chain id to which deposit was initiated. /// @param _depositSender The address of the entity that initiated the deposit. /// @param _assetId The unique identifier of the deposited L1 token. /// @param _assetData The encoded transfer data, which includes both the deposit amount and the address of the L2 receiver. Might include extra information. /// @param _l2TxHash The L2 transaction hash of the failed deposit finalization. /// @param _l2BatchNumber The L2 batch number where the deposit finalization was processed. /// @param _l2MessageIndex The position in the L2 logs Merkle tree of the l2Log that was sent with the message. /// @param _l2TxNumberInBatch The L2 transaction number in a batch, in which the log was sent. /// @param _merkleProof The Merkle proof of the processing L1 -> L2 transaction with deposit finalization. /// @dev Processes claims of failed deposit, whether they originated from the legacy bridge or the current system. function bridgeRecoverFailedTransfer( uint256 _chainId, address _depositSender, bytes32 _assetId, bytes memory _assetData, bytes32 _l2TxHash, uint256 _l2BatchNumber, uint256 _l2MessageIndex, uint16 _l2TxNumberInBatch, bytes32[] calldata _merkleProof ) external; /// @notice Legacy function to finalize withdrawal via the same /// interface as the old L1SharedBridge. /// @dev Note, that we need to keep this interface, since the `L2AssetRouter` /// will continue returning the previous address as the `l1SharedBridge`. The value /// returned by it is used in the SDK for finalizing withdrawals. /// @param _chainId The chain ID of the transaction to check /// @param _l2BatchNumber The L2 batch number where the withdrawal was processed /// @param _l2MessageIndex The position in the L2 logs Merkle tree of the l2Log that was sent with the message /// @param _l2TxNumberInBatch The L2 transaction number in the batch, in which the log was sent /// @param _message The L2 withdraw data, stored in an L2 -> L1 message /// @param _merkleProof The Merkle proof of the inclusion L2 -> L1 message about withdrawal initialization function finalizeWithdrawal( uint256 _chainId, uint256 _l2BatchNumber, uint256 _l2MessageIndex, uint16 _l2TxNumberInBatch, bytes calldata _message, bytes32[] calldata _merkleProof ) external; }
// SPDX-License-Identifier: MIT // We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version. pragma solidity ^0.8.20; interface IBridgedStandardToken { event BridgeInitialize(address indexed l1Token, string name, string symbol, uint8 decimals); event BridgeMint(address indexed account, uint256 amount); event BridgeBurn(address indexed account, uint256 amount); function bridgeMint(address _account, uint256 _amount) external; function bridgeBurn(address _account, uint256 _amount) external; function l1Address() external view returns (address); function originToken() external view returns (address); function l2Bridge() external view returns (address); function assetId() external view returns (bytes32); function nativeTokenVault() external view returns (address); }
// SPDX-License-Identifier: MIT // We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version. pragma solidity ^0.8.21; import {IL1Nullifier} from "../interfaces/IL1Nullifier.sol"; import {INativeTokenVault} from "../ntv/INativeTokenVault.sol"; import {IAssetRouterBase} from "./IAssetRouterBase.sol"; import {L2TransactionRequestTwoBridgesInner} from "../../bridgehub/IBridgehub.sol"; import {IL1SharedBridgeLegacy} from "../interfaces/IL1SharedBridgeLegacy.sol"; import {IL1ERC20Bridge} from "../interfaces/IL1ERC20Bridge.sol"; /// @title L1 Bridge contract interface /// @author Matter Labs /// @custom:security-contact [email protected] interface IL1AssetRouter is IAssetRouterBase, IL1SharedBridgeLegacy { event BridgehubMintData(bytes bridgeMintData); event BridgehubDepositFinalized( uint256 indexed chainId, bytes32 indexed txDataHash, bytes32 indexed l2DepositTxHash ); event ClaimedFailedDepositAssetRouter(uint256 indexed chainId, bytes32 indexed assetId, bytes assetData); event AssetDeploymentTrackerSet( bytes32 indexed assetId, address indexed assetDeploymentTracker, bytes32 indexed additionalData ); event LegacyDepositInitiated( uint256 indexed chainId, bytes32 indexed l2DepositTxHash, address indexed from, address to, address l1Token, uint256 amount ); /// @notice Initiates a deposit by locking funds on the contract and sending the request /// of processing an L2 transaction where tokens would be minted. /// @dev If the token is bridged for the first time, the L2 token contract will be deployed. Note however, that the /// newly-deployed token does not support any custom logic, i.e. rebase tokens' functionality is not supported. /// @param _originalCaller The `msg.sender` address from the external call that initiated current one. /// @param _l2Receiver The account address that should receive funds on L2. /// @param _l1Token The L1 token address which is deposited. /// @param _amount The total amount of tokens to be bridged. /// @param _l2TxGasLimit The L2 gas limit to be used in the corresponding L2 transaction. /// @param _l2TxGasPerPubdataByte The gasPerPubdataByteLimit to be used in the corresponding L2 transaction. /// @param _refundRecipient The address on L2 that will receive the refund for the transaction. /// @dev If the L2 deposit finalization transaction fails, the `_refundRecipient` will receive the `_l2Value`. /// Please note, the contract may change the refund recipient's address to eliminate sending funds to addresses /// out of control. /// - If `_refundRecipient` is a contract on L1, the refund will be sent to the aliased `_refundRecipient`. /// - If `_refundRecipient` is set to `address(0)` and the sender has NO deployed bytecode on L1, the refund will /// be sent to the `msg.sender` address. /// - If `_refundRecipient` is set to `address(0)` and the sender has deployed bytecode on L1, the refund will be /// sent to the aliased `msg.sender` address. /// @dev The address aliasing of L1 contracts as refund recipient on L2 is necessary to guarantee that the funds /// are controllable through the Mailbox, since the Mailbox applies address aliasing to the from address for the /// L2 tx if the L1 msg.sender is a contract. Without address aliasing for L1 contracts as refund recipients they /// would not be able to make proper L2 tx requests through the Mailbox to use or withdraw the funds from L2, and /// the funds would be lost. /// @return txHash The L2 transaction hash of deposit finalization. function depositLegacyErc20Bridge( address _originalCaller, address _l2Receiver, address _l1Token, uint256 _amount, uint256 _l2TxGasLimit, uint256 _l2TxGasPerPubdataByte, address _refundRecipient ) external payable returns (bytes32 txHash); function L1_NULLIFIER() external view returns (IL1Nullifier); function L1_WETH_TOKEN() external view returns (address); function nativeTokenVault() external view returns (INativeTokenVault); function setAssetDeploymentTracker(bytes32 _assetRegistrationData, address _assetDeploymentTracker) external; function setNativeTokenVault(INativeTokenVault _nativeTokenVault) external; function setL1Erc20Bridge(IL1ERC20Bridge _legacyBridge) external; /// @notice Withdraw funds from the initiated deposit, that failed when finalizing on L2. /// @param _chainId The ZK chain id to which the deposit was initiated. /// @param _depositSender The address of the entity that initiated the deposit. /// @param _assetId The unique identifier of the deposited L1 token. /// @param _assetData The encoded transfer data, which includes both the deposit amount and the address of the L2 receiver. Might include extra information. /// @dev Processes claims of failed deposit, whether they originated from the legacy bridge or the current system. function bridgeRecoverFailedTransfer( uint256 _chainId, address _depositSender, bytes32 _assetId, bytes calldata _assetData ) external; /// @dev Withdraw funds from the initiated deposit, that failed when finalizing on L2. /// @param _chainId The ZK chain id to which deposit was initiated. /// @param _depositSender The address of the entity that initiated the deposit. /// @param _assetId The unique identifier of the deposited L1 token. /// @param _assetData The encoded transfer data, which includes both the deposit amount and the address of the L2 receiver. Might include extra information. /// @param _l2TxHash The L2 transaction hash of the failed deposit finalization. /// @param _l2BatchNumber The L2 batch number where the deposit finalization was processed. /// @param _l2MessageIndex The position in the L2 logs Merkle tree of the l2Log that was sent with the message. /// @param _l2TxNumberInBatch The L2 transaction number in a batch, in which the log was sent. /// @param _merkleProof The Merkle proof of the processing L1 -> L2 transaction with deposit finalization. /// @dev Processes claims of failed deposit, whether they originated from the legacy bridge or the current system. function bridgeRecoverFailedTransfer( uint256 _chainId, address _depositSender, bytes32 _assetId, bytes memory _assetData, bytes32 _l2TxHash, uint256 _l2BatchNumber, uint256 _l2MessageIndex, uint16 _l2TxNumberInBatch, bytes32[] calldata _merkleProof ) external; /// @notice Transfers funds to Native Token Vault, if the asset is registered with it. Does nothing for ETH or non-registered tokens. /// @dev assetId is not the padded address, but the correct encoded id (NTV stores respective format for IDs) /// @param _amount The asset amount to be transferred to native token vault. /// @param _originalCaller The `msg.sender` address from the external call that initiated current one. function transferFundsToNTV(bytes32 _assetId, uint256 _amount, address _originalCaller) external returns (bool); /// @notice Finalize the withdrawal and release funds /// @param _chainId The chain ID of the transaction to check /// @param _l2BatchNumber The L2 batch number where the withdrawal was processed /// @param _l2MessageIndex The position in the L2 logs Merkle tree of the l2Log that was sent with the message /// @param _l2TxNumberInBatch The L2 transaction number in the batch, in which the log was sent /// @param _message The L2 withdraw data, stored in an L2 -> L1 message /// @param _merkleProof The Merkle proof of the inclusion L2 -> L1 message about withdrawal initialization function finalizeWithdrawal( uint256 _chainId, uint256 _l2BatchNumber, uint256 _l2MessageIndex, uint16 _l2TxNumberInBatch, bytes calldata _message, bytes32[] calldata _merkleProof ) external; /// @notice Initiates a transfer transaction within Bridgehub, used by `requestL2TransactionTwoBridges`. /// @param _chainId The chain ID of the ZK chain to which deposit. /// @param _originalCaller The `msg.sender` address from the external call that initiated current one. /// @param _value The `msg.value` on the target chain tx. /// @param _data The calldata for the second bridge deposit. /// @return request The data used by the bridgehub to create L2 transaction request to specific ZK chain. /// @dev Data has the following abi encoding for legacy deposits: /// address _l1Token, /// uint256 _amount, /// address _l2Receiver /// for new deposits: /// bytes32 _assetId, /// bytes _transferData function bridgehubDeposit( uint256 _chainId, address _originalCaller, uint256 _value, bytes calldata _data ) external payable returns (L2TransactionRequestTwoBridgesInner memory request); /// @notice Generates a calldata for calling the deposit finalization on the L2 native token contract. // / @param _chainId The chain ID of the ZK chain to which deposit. /// @param _sender The address of the deposit initiator. /// @param _assetId The deposited asset ID. /// @param _assetData The encoded data, which is used by the asset handler to determine L2 recipient and amount. Might include extra information. /// @return Returns calldata used on ZK chain. function getDepositCalldata( address _sender, bytes32 _assetId, bytes memory _assetData ) external view returns (bytes memory); /// @notice Allows bridgehub to acquire mintValue for L1->L2 transactions. /// @dev If the corresponding L2 transaction fails, refunds are issued to a refund recipient on L2. /// @param _chainId The chain ID of the ZK chain to which deposit. /// @param _assetId The deposited asset ID. /// @param _originalCaller The `msg.sender` address from the external call that initiated current one. /// @param _amount The total amount of tokens to be bridged. function bridgehubDepositBaseToken( uint256 _chainId, bytes32 _assetId, address _originalCaller, uint256 _amount ) external payable; /// @notice Routes the confirmation to nullifier for backward compatibility. /// @notice Confirms the acceptance of a transaction by the Mailbox, as part of the L2 transaction process within Bridgehub. /// This function is utilized by `requestL2TransactionTwoBridges` to validate the execution of a transaction. /// @param _chainId The chain ID of the ZK chain to which confirm the deposit. /// @param _txDataHash The keccak256 hash of 0x01 || abi.encode(bytes32, bytes) to identify deposits. /// @param _txHash The hash of the L1->L2 transaction to confirm the deposit. function bridgehubConfirmL2Transaction(uint256 _chainId, bytes32 _txDataHash, bytes32 _txHash) external; function isWithdrawalFinalized( uint256 _chainId, uint256 _l2BatchNumber, uint256 _l2MessageIndex ) external view returns (bool); }
// SPDX-License-Identifier: MIT // We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version. pragma solidity ^0.8.21; /// @dev `keccak256("")` bytes32 constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; /// @dev Bytes in raw L2 log /// @dev Equal to the bytes size of the tuple - (uint8 ShardId, bool isService, uint16 txNumberInBatch, address sender, /// bytes32 key, bytes32 value) uint256 constant L2_TO_L1_LOG_SERIALIZE_SIZE = 88; /// @dev The maximum length of the bytes array with L2 -> L1 logs uint256 constant MAX_L2_TO_L1_LOGS_COMMITMENT_BYTES = 4 + L2_TO_L1_LOG_SERIALIZE_SIZE * 512; /// @dev The value of default leaf hash for L2 -> L1 logs Merkle tree /// @dev An incomplete fixed-size tree is filled with this value to be a full binary tree /// @dev Actually equal to the `keccak256(new bytes(L2_TO_L1_LOG_SERIALIZE_SIZE))` bytes32 constant L2_L1_LOGS_TREE_DEFAULT_LEAF_HASH = 0x72abee45b59e344af8a6e520241c4744aff26ed411f4c4b00f8af09adada43ba; bytes32 constant DEFAULT_L2_LOGS_TREE_ROOT_HASH = bytes32(0); /// @dev Denotes the type of the ZKsync transaction that came from L1. uint256 constant PRIORITY_OPERATION_L2_TX_TYPE = 255; /// @dev Denotes the type of the ZKsync transaction that is used for system upgrades. uint256 constant SYSTEM_UPGRADE_L2_TX_TYPE = 254; /// @dev The maximal allowed difference between protocol minor versions in an upgrade. The 100 gap is needed /// in case a protocol version has been tested on testnet, but then not launched on mainnet, e.g. /// due to a bug found. /// We are allowed to jump at most 100 minor versions at a time. The major version is always expected to be 0. uint256 constant MAX_ALLOWED_MINOR_VERSION_DELTA = 100; /// @dev The amount of time in seconds the validator has to process the priority transaction /// NOTE: The constant is set to zero for the Alpha release period uint256 constant PRIORITY_EXPIRATION = 0 days; /// @dev Timestamp - seconds since unix epoch. uint256 constant COMMIT_TIMESTAMP_NOT_OLDER = 3 days; /// @dev Maximum available error between real commit batch timestamp and analog used in the verifier (in seconds) /// @dev Must be used cause miner's `block.timestamp` value can differ on some small value (as we know - 12 seconds) uint256 constant COMMIT_TIMESTAMP_APPROXIMATION_DELTA = 1 hours; /// @dev Shift to apply to verify public input before verifying. uint256 constant PUBLIC_INPUT_SHIFT = 32; /// @dev The maximum number of L2 gas that a user can request for an L2 transaction uint256 constant MAX_GAS_PER_TRANSACTION = 80_000_000; /// @dev Even though the price for 1 byte of pubdata is 16 L1 gas, we have a slightly increased /// value. uint256 constant L1_GAS_PER_PUBDATA_BYTE = 17; /// @dev The intrinsic cost of the L1->l2 transaction in computational L2 gas uint256 constant L1_TX_INTRINSIC_L2_GAS = 167_157; /// @dev The intrinsic cost of the L1->l2 transaction in pubdata uint256 constant L1_TX_INTRINSIC_PUBDATA = 88; /// @dev The minimal base price for L1 transaction uint256 constant L1_TX_MIN_L2_GAS_BASE = 173_484; /// @dev The number of L2 gas the transaction starts costing more with each 544 bytes of encoding uint256 constant L1_TX_DELTA_544_ENCODING_BYTES = 1656; /// @dev The number of L2 gas an L1->L2 transaction gains with each new factory dependency uint256 constant L1_TX_DELTA_FACTORY_DEPS_L2_GAS = 2473; /// @dev The number of L2 gas an L1->L2 transaction gains with each new factory dependency uint256 constant L1_TX_DELTA_FACTORY_DEPS_PUBDATA = 64; /// @dev The number of pubdata an L1->L2 transaction requires with each new factory dependency uint256 constant MAX_NEW_FACTORY_DEPS = 64; /// @dev The L2 gasPricePerPubdata required to be used in bridges. uint256 constant REQUIRED_L2_GAS_PRICE_PER_PUBDATA = 800; /// @dev The mask which should be applied to the packed batch and L2 block timestamp in order /// to obtain the L2 block timestamp. Applying this mask is equivalent to calculating modulo 2**128 uint256 constant PACKED_L2_BLOCK_TIMESTAMP_MASK = 0xffffffffffffffffffffffffffffffff; /// @dev Address of the point evaluation precompile used for EIP-4844 blob verification. address constant POINT_EVALUATION_PRECOMPILE_ADDR = address(0x0A); /// @dev The overhead for a transaction slot in L2 gas. /// It is roughly equal to 80kk/MAX_TRANSACTIONS_IN_BATCH, i.e. how many gas would an L1->L2 transaction /// need to pay to compensate for the batch being closed. /// @dev It is expected that the L1 contracts will enforce that the L2 gas price will be high enough to compensate /// the operator in case the batch is closed because of tx slots filling up. uint256 constant TX_SLOT_OVERHEAD_L2_GAS = 10000; /// @dev The overhead for each byte of the bootloader memory that the encoding of the transaction. /// It is roughly equal to 80kk/BOOTLOADER_MEMORY_FOR_TXS, i.e. how many gas would an L1->L2 transaction /// need to pay to compensate for the batch being closed. /// @dev It is expected that the L1 contracts will enforce that the L2 gas price will be high enough to compensate /// the operator in case the batch is closed because of the memory for transactions being filled up. uint256 constant MEMORY_OVERHEAD_GAS = 10; /// @dev The maximum gas limit for a priority transaction in L2. uint256 constant PRIORITY_TX_MAX_GAS_LIMIT = 72_000_000; /// @dev the address used to identify eth as the base token for chains. address constant ETH_TOKEN_ADDRESS = address(1); /// @dev the value returned in bridgehubDeposit in the TwoBridges function. bytes32 constant TWO_BRIDGES_MAGIC_VALUE = bytes32(uint256(keccak256("TWO_BRIDGES_MAGIC_VALUE")) - 1); /// @dev https://eips.ethereum.org/EIPS/eip-1352 address constant BRIDGEHUB_MIN_SECOND_BRIDGE_ADDRESS = address(uint160(type(uint16).max)); /// @dev the maximum number of supported chains, this is an arbitrary limit. /// @dev Note, that in case of a malicious Bridgehub admin, the total number of chains /// can be up to 2 times higher. This may be possible, in case the old ChainTypeManager /// had `100` chains and these were migrated to the Bridgehub only after `MAX_NUMBER_OF_ZK_CHAINS` /// were added to the bridgehub via creation of new chains. uint256 constant MAX_NUMBER_OF_ZK_CHAINS = 100; /// @dev Used as the `msg.sender` for transactions that relayed via a settlement layer. address constant SETTLEMENT_LAYER_RELAY_SENDER = address(uint160(0x1111111111111111111111111111111111111111)); /// @dev The metadata version that is supported by the ZK Chains to prove that an L2->L1 log was included in a batch. uint256 constant SUPPORTED_PROOF_METADATA_VERSION = 1; /// @dev The virtual address of the L1 settlement layer. address constant L1_SETTLEMENT_LAYER_VIRTUAL_ADDRESS = address( uint160(uint256(keccak256("L1_SETTLEMENT_LAYER_VIRTUAL_ADDRESS")) - 1) ); struct PriorityTreeCommitment { uint256 nextLeafIndex; uint256 startIndex; uint256 unprocessedIndex; bytes32[] sides; } // Info that allows to restore a chain. struct ZKChainCommitment { /// @notice Total number of executed batches i.e. batches[totalBatchesExecuted] points at the latest executed batch /// (batch 0 is genesis) uint256 totalBatchesExecuted; /// @notice Total number of proved batches i.e. batches[totalBatchesProved] points at the latest proved batch uint256 totalBatchesVerified; /// @notice Total number of committed batches i.e. batches[totalBatchesCommitted] points at the latest committed /// batch uint256 totalBatchesCommitted; /// @notice The hash of the L2 system contracts ugpgrade transaction. /// @dev It is non zero if the migration happens while the upgrade is not yet finalized. bytes32 l2SystemContractsUpgradeTxHash; /// @notice The batch when the system contracts upgrade transaction was executed. /// @dev It is non-zero if the migration happens while the batch where the upgrade tx was present /// has not been finalized (executed) yet. uint256 l2SystemContractsUpgradeBatchNumber; /// @notice The hashes of the batches that are needed to keep the blockchain working. /// @dev The length of the array is equal to the `totalBatchesCommitted - totalBatchesExecuted + 1`, i.e. we need /// to store all the unexecuted batches' hashes + 1 latest executed one. bytes32[] batchHashes; /// @notice Commitment to the priority merkle tree. PriorityTreeCommitment priorityTree; /// @notice Whether a chain is a permanent rollup. bool isPermanentRollup; } /// @dev Used as the `msg.sender` for system service transactions. address constant SERVICE_TRANSACTION_SENDER = address(uint160(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF));
// SPDX-License-Identifier: MIT // We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version. pragma solidity ^0.8.21; /// @dev the offset for the system contracts uint160 constant SYSTEM_CONTRACTS_OFFSET = 0x8000; // 2^15 /// @dev The offset from which the built-in, but user space contracts are located. uint160 constant USER_CONTRACTS_OFFSET = 0x10000; // 2^16 /// @dev The formal address of the initial program of the system: the bootloader address constant L2_BOOTLOADER_ADDRESS = address(SYSTEM_CONTRACTS_OFFSET + 0x01); /// @dev The address of the known code storage system contract address constant L2_KNOWN_CODE_STORAGE_SYSTEM_CONTRACT_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x04); /// @dev The address of the L2 deployer system contract. address constant L2_DEPLOYER_SYSTEM_CONTRACT_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x06); /// @dev The special reserved L2 address. It is located in the system contracts space but doesn't have deployed /// bytecode. /// @dev The L2 deployer system contract allows changing bytecodes on any address if the `msg.sender` is this address. /// @dev So, whenever the governor wants to redeploy system contracts, it just initiates the L1 upgrade call deployer /// system contract /// via the L1 -> L2 transaction with `sender == L2_FORCE_DEPLOYER_ADDR`. For more details see the /// `diamond-initializers` contracts. address constant L2_FORCE_DEPLOYER_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x07); /// @dev The address of the special smart contract that can send arbitrary length message as an L2 log IL2ToL1Messenger constant L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR = IL2ToL1Messenger( address(SYSTEM_CONTRACTS_OFFSET + 0x08) ); /// @dev The address of the eth token system contract address constant L2_BASE_TOKEN_SYSTEM_CONTRACT_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x0a); /// @dev The address of the context system contract address constant L2_SYSTEM_CONTEXT_SYSTEM_CONTRACT_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x0b); /// @dev The address of the pubdata chunk publisher contract address constant L2_PUBDATA_CHUNK_PUBLISHER_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x11); /// @dev The address used to execute complex upgragedes, also used for the genesis upgrade address constant L2_COMPLEX_UPGRADER_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x0f); /// @dev the address of the msg value system contract address constant MSG_VALUE_SYSTEM_CONTRACT = address(SYSTEM_CONTRACTS_OFFSET + 0x09); /// @dev The address used to execute the genesis upgrade address constant L2_GENESIS_UPGRADE_ADDR = address(USER_CONTRACTS_OFFSET + 0x01); /// @dev The address of the L2 bridge hub system contract, used to start L1->L2 transactions address constant L2_BRIDGEHUB_ADDR = address(USER_CONTRACTS_OFFSET + 0x02); /// @dev the address of the l2 asset router. address constant L2_ASSET_ROUTER_ADDR = address(USER_CONTRACTS_OFFSET + 0x03); /// @dev An l2 system contract address, used in the assetId calculation for native assets. /// This is needed for automatic bridging, i.e. without deploying the AssetHandler contract, /// if the assetId can be calculated with this address then it is in fact an NTV asset address constant L2_NATIVE_TOKEN_VAULT_ADDR = address(USER_CONTRACTS_OFFSET + 0x04); /// @dev the address of the l2 asset router. address constant L2_MESSAGE_ROOT_ADDR = address(USER_CONTRACTS_OFFSET + 0x05); /** * @author Matter Labs * @custom:security-contact [email protected] * @notice Smart contract for sending arbitrary length messages to L1 * @dev by default ZkSync can send fixed-length messages on L1. * A fixed length message has 4 parameters `senderAddress`, `isService`, `key`, `value`, * the first one is taken from the context, the other three are chosen by the sender. * @dev To send a variable-length message we use this trick: * - This system contract accepts an arbitrary length message and sends a fixed length message with * parameters `senderAddress == this`, `isService == true`, `key == msg.sender`, `value == keccak256(message)`. * - The contract on L1 accepts all sent messages and if the message came from this system contract * it requires that the preimage of `value` be provided. */ interface IL2ToL1Messenger { /// @notice Sends an arbitrary length message to L1. /// @param _message The variable length message to be sent to L1. /// @return Returns the keccak256 hashed value of the message. function sendToL1(bytes calldata _message) external returns (bytes32); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {L2_NATIVE_TOKEN_VAULT_ADDR} from "../L2ContractAddresses.sol"; import {LEGACY_ENCODING_VERSION, NEW_ENCODING_VERSION} from "../../bridge/asset-router/IAssetRouterBase.sol"; import {INativeTokenVault} from "../../bridge/ntv/INativeTokenVault.sol"; import {IncorrectTokenAddressFromNTV, UnsupportedEncodingVersion, InvalidNTVBurnData} from "../L1ContractErrors.sol"; /** * @author Matter Labs * @custom:security-contact [email protected] * @notice Helper library for transfer data encoding and decoding to reduce possibility of errors. */ library DataEncoding { /// @notice Abi.encodes the data required for bridgeBurn for NativeTokenVault. /// @param _amount The amount of token to be transferred. /// @param _remoteReceiver The address which to receive tokens on remote chain. /// @param _maybeTokenAddress The helper field that should be either equal to 0 (in this case /// it is assumed that the token has been registered within NativeTokenVault already) or it /// can be equal to the address of the token on the current chain. Providing non-zero address /// allows it to be automatically registered in case it is not yet a part of NativeTokenVault. /// @return The encoded bridgeBurn data function encodeBridgeBurnData( uint256 _amount, address _remoteReceiver, address _maybeTokenAddress ) internal pure returns (bytes memory) { return abi.encode(_amount, _remoteReceiver, _maybeTokenAddress); } /// @notice Function decoding bridgeBurn data previously encoded with this library. /// @param _data The encoded data for bridgeBurn /// @return amount The amount of token to be transferred. /// @return receiver The address which to receive tokens on remote chain. /// @return maybeTokenAddress The helper field that should be either equal to 0 (in this case /// it is assumed that the token has been registered within NativeTokenVault already) or it /// can be equal to the address of the token on the current chain. Providing non-zero address /// allows it to be automatically registered in case it is not yet a part of NativeTokenVault. function decodeBridgeBurnData( bytes memory _data ) internal pure returns (uint256 amount, address receiver, address maybeTokenAddress) { if (_data.length != 96) { // For better error handling revert InvalidNTVBurnData(); } (amount, receiver, maybeTokenAddress) = abi.decode(_data, (uint256, address, address)); } /// @notice Abi.encodes the data required for bridgeMint on remote chain. /// @param _originalCaller The address which initiated the transfer. /// @param _remoteReceiver The address which to receive tokens on remote chain. /// @param _originToken The transferred token address. /// @param _amount The amount of token to be transferred. /// @param _erc20Metadata The transferred token metadata. /// @return The encoded bridgeMint data function encodeBridgeMintData( address _originalCaller, address _remoteReceiver, address _originToken, uint256 _amount, bytes memory _erc20Metadata ) internal pure returns (bytes memory) { // solhint-disable-next-line func-named-parameters return abi.encode(_originalCaller, _remoteReceiver, _originToken, _amount, _erc20Metadata); } /// @notice Function decoding transfer data previously encoded with this library. /// @param _bridgeMintData The encoded bridgeMint data /// @return _originalCaller The address which initiated the transfer. /// @return _remoteReceiver The address which to receive tokens on remote chain. /// @return _parsedOriginToken The transferred token address. /// @return _amount The amount of token to be transferred. /// @return _erc20Metadata The transferred token metadata. function decodeBridgeMintData( bytes memory _bridgeMintData ) internal pure returns ( address _originalCaller, address _remoteReceiver, address _parsedOriginToken, uint256 _amount, bytes memory _erc20Metadata ) { (_originalCaller, _remoteReceiver, _parsedOriginToken, _amount, _erc20Metadata) = abi.decode( _bridgeMintData, (address, address, address, uint256, bytes) ); } /// @notice Encodes the asset data by combining chain id, asset deployment tracker and asset data. /// @param _chainId The id of the chain token is native to. /// @param _assetData The asset data that has to be encoded. /// @param _sender The asset deployment tracker address. /// @return The encoded asset data. function encodeAssetId(uint256 _chainId, bytes32 _assetData, address _sender) internal pure returns (bytes32) { return keccak256(abi.encode(_chainId, _sender, _assetData)); } /// @notice Encodes the asset data by combining chain id, asset deployment tracker and asset data. /// @param _chainId The id of the chain token is native to. /// @param _tokenAddress The address of token that has to be encoded (asset data is the address itself). /// @param _sender The asset deployment tracker address. /// @return The encoded asset data. function encodeAssetId(uint256 _chainId, address _tokenAddress, address _sender) internal pure returns (bytes32) { return keccak256(abi.encode(_chainId, _sender, _tokenAddress)); } /// @notice Encodes the asset data by combining chain id, NTV as asset deployment tracker and asset data. /// @param _chainId The id of the chain token is native to. /// @param _assetData The asset data that has to be encoded. /// @return The encoded asset data. function encodeNTVAssetId(uint256 _chainId, bytes32 _assetData) internal pure returns (bytes32) { return keccak256(abi.encode(_chainId, L2_NATIVE_TOKEN_VAULT_ADDR, _assetData)); } /// @notice Encodes the asset data by combining chain id, NTV as asset deployment tracker and token address. /// @param _chainId The id of the chain token is native to. /// @param _tokenAddress The address of token that has to be encoded (asset data is the address itself). /// @return The encoded asset data. function encodeNTVAssetId(uint256 _chainId, address _tokenAddress) internal pure returns (bytes32) { return keccak256(abi.encode(_chainId, L2_NATIVE_TOKEN_VAULT_ADDR, _tokenAddress)); } /// @dev Encodes the transaction data hash using either the latest encoding standard or the legacy standard. /// @param _encodingVersion EncodingVersion. /// @param _originalCaller The address of the entity that initiated the deposit. /// @param _assetId The unique identifier of the deposited L1 token. /// @param _nativeTokenVault The address of the token, only used if the encoding version is legacy. /// @param _transferData The encoded transfer data, which includes the deposit amount, the address of the L2 receiver, and potentially the token address. /// @return txDataHash The resulting encoded transaction data hash. function encodeTxDataHash( bytes1 _encodingVersion, address _originalCaller, bytes32 _assetId, address _nativeTokenVault, bytes memory _transferData ) internal view returns (bytes32 txDataHash) { if (_encodingVersion == LEGACY_ENCODING_VERSION) { address tokenAddress = INativeTokenVault(_nativeTokenVault).tokenAddress(_assetId); // This is a double check to ensure that the used token for the legacy encoding is correct. // This revert should never be emitted and in real life and should only serve as a guard in // case of inconsistent state of Native Token Vault. bytes32 expectedAssetId = encodeNTVAssetId(block.chainid, tokenAddress); if (_assetId != expectedAssetId) { revert IncorrectTokenAddressFromNTV(_assetId, tokenAddress); } (uint256 depositAmount, , ) = decodeBridgeBurnData(_transferData); txDataHash = keccak256(abi.encode(_originalCaller, tokenAddress, depositAmount)); } else if (_encodingVersion == NEW_ENCODING_VERSION) { // Similarly to calldata, the txDataHash is collision-resistant. // In the legacy data hash, the first encoded variable was the address, which is padded with zeros during `abi.encode`. txDataHash = keccak256( bytes.concat(_encodingVersion, abi.encode(_originalCaller, _assetId, _transferData)) ); } else { revert UnsupportedEncodingVersion(); } } /// @notice Decodes the token data by combining chain id, asset deployment tracker and asset data. function decodeTokenData( bytes calldata _tokenData ) internal pure returns (uint256 chainId, bytes memory name, bytes memory symbol, bytes memory decimals) { bytes1 encodingVersion = _tokenData[0]; if (encodingVersion == LEGACY_ENCODING_VERSION) { (name, symbol, decimals) = abi.decode(_tokenData, (bytes, bytes, bytes)); } else if (encodingVersion == NEW_ENCODING_VERSION) { return abi.decode(_tokenData[1:], (uint256, bytes, bytes, bytes)); } else { revert UnsupportedEncodingVersion(); } } /// @notice Encodes the token data by combining chain id, and its metadata. /// @dev Note that all the metadata of the token is expected to be ABI encoded. /// @param _chainId The id of the chain token is native to. /// @param _name The name of the token. /// @param _symbol The symbol of the token. /// @param _decimals The decimals of the token. /// @return The encoded token data. function encodeTokenData( uint256 _chainId, bytes memory _name, bytes memory _symbol, bytes memory _decimals ) internal pure returns (bytes memory) { return bytes.concat(NEW_ENCODING_VERSION, abi.encode(_chainId, _name, _symbol, _decimals)); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.21; // 0x5ecf2d7a error AccessToFallbackDenied(address target, address invoker); // 0x3995f750 error AccessToFunctionDenied(address target, bytes4 selector, address invoker); // 0x6c167909 error OnlySelfAllowed(); // 0x52e22c98 error RestrictionWasNotPresent(address restriction); // 0xf126e113 error RestrictionWasAlreadyPresent(address restriction); // 0x3331e9c0 error CallNotAllowed(bytes call); // 0xf6fd7071 error RemovingPermanentRestriction(); // 0xfcb9b2e1 error UnallowedImplementation(bytes32 implementationHash); // 0x0dfb42bf error AddressAlreadySet(address addr); // 0x86bb51b8 error AddressHasNoCode(address); // 0x1f73225f error AddressMismatch(address expected, address supplied); // 0x5e85ae73 error AmountMustBeGreaterThanZero(); // 0xfde974f4 error AssetHandlerDoesNotExist(bytes32 assetId); // 0x1294e9e1 error AssetIdMismatch(bytes32 expected, bytes32 supplied); // 0xfe919e28 error AssetIdAlreadyRegistered(); // 0x0bfcef28 error AlreadyWhitelisted(address); // 0x04a0b7e9 error AssetIdNotSupported(bytes32 assetId); // 0x6ef9a972 error BaseTokenGasPriceDenominatorNotSet(); // 0x55ad3fd3 error BatchHashMismatch(bytes32 expected, bytes32 actual); // 0x2078a6a0 error BatchNotExecuted(uint256 batchNumber); // 0xbd4455ff error BatchNumberMismatch(uint256 expectedBatchNumber, uint256 providedBatchNumber); // 0x6cf12312 error BridgeHubAlreadyRegistered(); // 0xdb538614 error BridgeMintNotImplemented(); // 0xe85392f9 error CanOnlyProcessOneBatch(); // 0x00c6ead2 error CantExecuteUnprovenBatches(); // 0xe18cb383 error CantRevertExecutedBatch(); // 0x24591d89 error ChainIdAlreadyExists(); // 0x717a1656 error ChainIdCantBeCurrentChain(); // 0xa179f8c9 error ChainIdMismatch(); // 0x23f3c357 error ChainIdNotRegistered(uint256 chainId); // 0x8f620a06 error ChainIdTooBig(); // 0xf7a01e4d error DelegateCallFailed(bytes returnData); // 0x0a8ed92c error DenominatorIsZero(); // 0xb4f54111 error DeployFailed(); // 0x138ee1a3 error DeployingBridgedTokenForNativeToken(); // 0xc7c9660f error DepositDoesNotExist(); // 0xad2fa98e error DepositExists(); // 0x0e7ee319 error DiamondAlreadyFrozen(); // 0xa7151b9a error DiamondNotFrozen(); // 0x7138356f error EmptyAddress(); // 0x2d4d012f error EmptyAssetId(); // 0x1c25715b error EmptyBytes32(); // 0x95b66fe9 error EmptyDeposit(); // 0x627e0872 error ETHDepositNotSupported(); // 0xac4a3f98 error FacetExists(bytes4 selector, address); // 0xc91cf3b1 error GasPerPubdataMismatch(); // 0x6d4a7df8 error GenesisBatchCommitmentZero(); // 0x7940c83f error GenesisBatchHashZero(); // 0xb4fc6835 error GenesisIndexStorageZero(); // 0x3a1a8589 error GenesisUpgradeZero(); // 0xd356e6ba error HashedLogIsDefault(); // 0x0b08d5be error HashMismatch(bytes32 expected, bytes32 actual); // 0x601b6882 error ZKChainLimitReached(); // 0xdd381a4c error IncorrectBridgeHubAddress(address bridgehub); // 0x826fb11e error InsufficientChainBalance(); // 0xcbd9d2e0 error InvalidCaller(address); // 0x4fbe5dba error InvalidDelay(); // 0xc1780bd6 error InvalidLogSender(address sender, uint256 logKey); // 0xd8e9405c error InvalidNumberOfBlobs(uint256 expected, uint256 numCommitments, uint256 numHashes); // 0x09bde339 error InvalidProof(); // 0x5428eae7 error InvalidProtocolVersion(); // 0x6f1cf752 error InvalidPubdataPricingMode(); // 0x12ba286f error InvalidSelector(bytes4 func); // 0x0214acb6 error InvalidUpgradeTxn(UpgradeTxVerifyParam); // 0xfb5c22e6 error L2TimestampTooBig(); // 0x97e1359e error L2WithdrawalMessageWrongLength(uint256 messageLen); // 0xe37d2c02 error LengthIsNotDivisibleBy32(uint256 length); // 0x1b6825bb error LogAlreadyProcessed(uint8); // 0xcea34703 error MalformedBytecode(BytecodeError); // 0x9bb54c35 error MerkleIndexOutOfBounds(); // 0x8e23ac1a error MerklePathEmpty(); // 0x1c500385 error MerklePathOutOfBounds(); // 0x3312a450 error MigrationPaused(); // 0xfa44b527 error MissingSystemLogs(uint256 expected, uint256 actual); // 0x4a094431 error MsgValueMismatch(uint256 expectedMsgValue, uint256 providedMsgValue); // 0xb385a3da error MsgValueTooLow(uint256 required, uint256 provided); // 0x79cc2d22 error NoCallsProvided(); // 0xa6fef710 error NoFunctionsForDiamondCut(); // 0xcab098d8 error NoFundsTransferred(); // 0xc21b1ab7 error NonEmptyCalldata(); // 0x536ec84b error NonEmptyMsgValue(); // 0xd018e08e error NonIncreasingTimestamp(); // 0x0105f9c0 error NonSequentialBatch(); // 0x0ac76f01 error NonSequentialVersion(); // 0xdd7e3621 error NotInitializedReentrancyGuard(); // 0xdf17e316 error NotWhitelisted(address); // 0xf3ed9dfa error OnlyEraSupported(); // 0x1a21feed error OperationExists(); // 0xeda2fbb1 error OperationMustBePending(); // 0xe1c1ff37 error OperationMustBeReady(); // 0xb926450e error OriginChainIdNotFound(); // 0x9b48e060 error PreviousOperationNotExecuted(); // 0xd5a99014 error PriorityOperationsRollingHashMismatch(); // 0x1a4d284a error PriorityTxPubdataExceedsMaxPubDataPerBatch(); // 0xa461f651 error ProtocolIdMismatch(uint256 expectedProtocolVersion, uint256 providedProtocolId); // 0x64f94ec2 error ProtocolIdNotGreater(); // 0x959f26fb error PubdataGreaterThanLimit(uint256 limit, uint256 length); // 0x63c36549 error QueueIsEmpty(); // 0xab143c06 error Reentrancy(); // 0x667d17de error RemoveFunctionFacetAddressNotZero(address facet); // 0xa2d4b16c error RemoveFunctionFacetAddressZero(); // 0x3580370c error ReplaceFunctionFacetAddressZero(); // 0x9a67c1cb error RevertedBatchNotAfterNewLastBatch(); // 0xd3b6535b error SelectorsMustAllHaveSameFreezability(); // 0xd7a6b5e6 error SharedBridgeValueNotSet(SharedBridgeKey); // 0x856d5b77 error SharedBridgeNotSet(); // 0xdf3a8fdd error SlotOccupied(); // 0xec273439 error CTMAlreadyRegistered(); // 0xc630ef3c error CTMNotRegistered(); // 0xae43b424 error SystemLogsSizeTooBig(); // 0x08753982 error TimeNotReached(uint256 expectedTimestamp, uint256 actualTimestamp); // 0x2d50c33b error TimestampError(); // 0x06439c6b error TokenNotSupported(address token); // 0x23830e28 error TokensWithFeesNotSupported(); // 0x76da24b9 error TooManyFactoryDeps(); // 0xf0b4e88f error TooMuchGas(); // 0x00c5a6a9 error TransactionNotAllowed(); // 0x4c991078 error TxHashMismatch(); // 0x2e311df8 error TxnBodyGasLimitNotEnoughGas(); // 0x8e4a23d6 error Unauthorized(address caller); // 0xe52478c7 error UndefinedDiamondCutAction(); // 0x6aa39880 error UnexpectedSystemLog(uint256 logKey); // 0xf093c2e5 error UpgradeBatchNumberIsNotZero(); // 0x084a1449 error UnsupportedEncodingVersion(); // 0x47b3b145 error ValidateTxnNotEnoughGas(); // 0x626ade30 error ValueMismatch(uint256 expected, uint256 actual); // 0xe1022469 error VerifiedBatchesExceedsCommittedBatches(); // 0xae899454 error WithdrawalAlreadyFinalized(); // 0x750b219c error WithdrawFailed(); // 0x15e8e429 error WrongMagicValue(uint256 expectedMagicValue, uint256 providedMagicValue); // 0xd92e233d error ZeroAddress(); // 0xc84885d4 error ZeroChainId(); // 0x99d8fec9 error EmptyData(); // 0xf3dd1b9c error UnsupportedCommitBatchEncoding(uint8 version); // 0xf338f830 error UnsupportedProofBatchEncoding(uint8 version); // 0x14d2ed8a error UnsupportedExecuteBatchEncoding(uint8 version); // 0xd7d93e1f error IncorrectBatchBounds( uint256 processFromExpected, uint256 processToExpected, uint256 processFromProvided, uint256 processToProvided ); // 0x64107968 error AssetHandlerNotRegistered(bytes32 assetId); // 0x64846fe4 error NotARestriction(address addr); // 0xfa5cd00f error NotAllowed(address addr); // 0xccdd18d2 error BytecodeAlreadyPublished(bytes32 bytecodeHash); // 0x25d8333c error CallerNotTimerAdmin(); // 0x907f8e51 error DeadlineNotYetPassed(); // 0x6eef58d1 error NewDeadlineNotGreaterThanCurrent(); // 0x8b7e144a error NewDeadlineExceedsMaxDeadline(); // 0x2a5989a0 error AlreadyPermanentRollup(); // 0x92daded2 error InvalidDAForPermanentRollup(); // 0x7a4902ad error TimerAlreadyStarted(); // 0x09aa9830 error MerklePathLengthMismatch(uint256 pathLength, uint256 expectedLength); // 0xc33e6128 error MerkleNothingToProve(); // 0xafbb7a4e error MerkleIndexOrHeightMismatch(); // 0x1b582fcf error MerkleWrongIndex(uint256 index, uint256 maxNodeNumber); // 0x485cfcaa error MerkleWrongLength(uint256 newLeavesLength, uint256 leafNumber); // 0xce63ce17 error NoCTMForAssetId(bytes32 assetId); // 0x02181a13 error SettlementLayersMustSettleOnL1(); // 0x1850b46b error TokenNotLegacy(); // 0x1929b7de error IncorrectTokenAddressFromNTV(bytes32 assetId, address tokenAddress); // 0x48c5fa28 error InvalidProofLengthForFinalNode(); // 0xfade089a error LegacyEncodingUsedForNonL1Token(); // 0xa51fa558 error TokenIsLegacy(); // 0x29963361 error LegacyBridgeUsesNonNativeToken(); // 0x11832de8 error AssetRouterAllowanceNotZero(); // 0xaa5f6180 error BurningNativeWETHNotSupported(); // 0xb20b58ce error NoLegacySharedBridge(); // 0x8e3ce3cb error TooHighDeploymentNonce(); // 0x78d2ed02 error ChainAlreadyLive(); // 0x4e98b356 error MigrationsNotPaused(); // 0xf20c5c2a error WrappedBaseTokenAlreadyRegistered(); // 0xde4c0b96 error InvalidNTVBurnData(); // 0xbe7193d4 error InvalidSystemLogsLength(); // 0x8efef97a error LegacyBridgeNotSet(); // 0x767eed08 error LegacyMethodForNonL1Token(); // 0xc352bb73 error UnknownVerifierType(); // 0x456f8f7a error EmptyProofLength(); enum SharedBridgeKey { PostUpgradeFirstBatch, LegacyBridgeFirstBatch, LegacyBridgeLastDepositBatch, LegacyBridgeLastDepositTxn } enum BytecodeError { Version, NumberOfWords, Length, WordsMustBeOdd } enum UpgradeTxVerifyParam { From, To, Paymaster, Value, MaxFeePerGas, MaxPriorityFeePerGas, Reserved0, Reserved1, Reserved2, Reserved3, Signature, PaymasterInput, ReservedDynamic }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.21; // 0x6d963f88 error EthTransferFailed(); // 0x1c55230b error NativeTokenVaultAlreadySet(); // 0x61cdb17e error WrongMsgLength(uint256 expected, uint256 length); // 0xe4742c42 error ZeroAmountToTransfer(); // 0xfeda3bf8 error WrongAmountTransferred(uint256 balance, uint256 nullifierChainBalance); // 0x066f53b1 error EmptyToken(); // 0x0fef9068 error ClaimFailedDepositFailed(); // 0x636c90db error WrongL2Sender(address providedL2Sender); // 0xb4aeddbc error WrongCounterpart();
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol) pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overridden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../interfaces/IERC1967.sol"; import "../../interfaces/draft-IERC1822.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ */ abstract contract ERC1967Upgrade is IERC1967 { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.4) (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. * * ==== Security Considerations * * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be * considered as an intention to spend the allowance in any specific way. The second is that because permits have * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be * generally recommended is: * * ```solidity * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public { * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {} * doThing(..., value); * } * * function doThing(..., uint256 value) public { * token.safeTransferFrom(msg.sender, address(this), value); * ... * } * ``` * * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also * {SafeERC20-safeTransferFrom}). * * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so * contracts should have entry points that don't rely on permit. */ 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]. * * CAUTION: See Security Considerations above. */ 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 pragma solidity 0.8.24; /// @author Matter Labs /// @custom:security-contact [email protected] interface IL1AssetDeploymentTracker { function bridgeCheckCounterpartAddress( uint256 _chainId, bytes32 _assetId, address _originalCaller, address _assetHandlerAddressOnCounterpart ) external view; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IBridgehub} from "../../bridgehub/IBridgehub.sol"; /// @dev The encoding version used for legacy txs. bytes1 constant LEGACY_ENCODING_VERSION = 0x00; /// @dev The encoding version used for new txs. bytes1 constant NEW_ENCODING_VERSION = 0x01; /// @dev The encoding version used for txs that set the asset handler on the counterpart contract. bytes1 constant SET_ASSET_HANDLER_COUNTERPART_ENCODING_VERSION = 0x02; /// @title L1 Bridge contract interface /// @author Matter Labs /// @custom:security-contact [email protected] interface IAssetRouterBase { event BridgehubDepositBaseTokenInitiated( uint256 indexed chainId, address indexed from, bytes32 assetId, uint256 amount ); event BridgehubDepositInitiated( uint256 indexed chainId, bytes32 indexed txDataHash, address indexed from, bytes32 assetId, bytes bridgeMintCalldata ); event BridgehubWithdrawalInitiated( uint256 chainId, address indexed sender, bytes32 indexed assetId, bytes32 assetDataHash // Todo: What's the point of emitting hash? ); event AssetDeploymentTrackerRegistered( bytes32 indexed assetId, bytes32 indexed additionalData, address assetDeploymentTracker ); event AssetHandlerRegistered(bytes32 indexed assetId, address indexed _assetHandlerAddress); event DepositFinalizedAssetRouter(uint256 indexed chainId, bytes32 indexed assetId, bytes assetData); function BRIDGE_HUB() external view returns (IBridgehub); /// @notice Sets the asset handler address for a specified asset ID on the chain of the asset deployment tracker. /// @dev The caller of this function is encoded within the `assetId`, therefore, it should be invoked by the asset deployment tracker contract. /// @dev No access control on the caller, as msg.sender is encoded in the assetId. /// @dev Typically, for most tokens, ADT is the native token vault. However, custom tokens may have their own specific asset deployment trackers. /// @dev `setAssetHandlerAddressOnCounterpart` should be called on L1 to set asset handlers on L2 chains for a specific asset ID. /// @param _assetRegistrationData The asset data which may include the asset address and any additional required data or encodings. /// @param _assetHandlerAddress The address of the asset handler to be set for the provided asset. function setAssetHandlerAddressThisChain(bytes32 _assetRegistrationData, address _assetHandlerAddress) external; function assetHandlerAddress(bytes32 _assetId) external view returns (address); /// @notice Finalize the withdrawal and release funds. /// @param _chainId The chain ID of the transaction to check. /// @param _assetId The bridged asset ID. /// @param _transferData The position in the L2 logs Merkle tree of the l2Log that was sent with the message. /// @dev We have both the legacy finalizeWithdrawal and the new finalizeDeposit functions, /// finalizeDeposit uses the new format. On the L2 we have finalizeDeposit with new and old formats both. function finalizeDeposit(uint256 _chainId, bytes32 _assetId, bytes memory _transferData) external payable; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol) pragma solidity ^0.8.0; import "./OwnableUpgradeable.sol"; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides 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} and {acceptOwnership}. * * This module is used through inheritance. It will make available all functions * from parent (Ownable). */ abstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable { address private _pendingOwner; event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner); function __Ownable2Step_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable2Step_init_unchained() internal onlyInitializing { } /** * @dev Returns the address of the pending owner. */ function pendingOwner() public view virtual returns (address) { return _pendingOwner; } /** * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one. * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual override onlyOwner { _pendingOwner = newOwner; emit OwnershipTransferStarted(owner(), newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner. * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual override { delete _pendingOwner; super._transferOwnership(newOwner); } /** * @dev The new owner accepts the ownership transfer. */ function acceptOwnership() public virtual { address sender = _msgSender(); require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner"); _transferOwnership(sender); } /** * @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.7.0) (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import {Initializable} from "../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 pragma solidity 0.8.24; /// @title Asset Handler contract interface /// @author Matter Labs /// @custom:security-contact [email protected] /// @notice Used for any asset handler and called by the AssetRouter interface IAssetHandler { /// @dev Emitted when a token is minted event BridgeMint(uint256 indexed chainId, bytes32 indexed assetId, address receiver, uint256 amount); /// @dev Emitted when a token is burned event BridgeBurn( uint256 indexed chainId, bytes32 indexed assetId, address indexed sender, address receiver, uint256 amount ); /// @param _chainId the chainId that the message is from /// @param _assetId the assetId of the asset being bridged /// @param _data the actual data specified for the function /// @dev Note, that while payable, this function will only receive base token on L2 chains, /// while L1 the provided msg.value is always 0. However, this may change in the future, /// so if your AssetHandler implementation relies on it, it is better to explicitly check it. function bridgeMint(uint256 _chainId, bytes32 _assetId, bytes calldata _data) external payable; /// @notice Burns bridged tokens and returns the calldata for L2 <-> L1 message. /// @dev In case of native token vault _data is the tuple of _depositAmount and _l2Receiver. /// @param _chainId the chainId that the message will be sent to /// @param _msgValue the msg.value of the L2 transaction. For now it is always 0. /// @param _assetId the assetId of the asset being bridged /// @param _originalCaller the original caller of the /// @param _data the actual data specified for the function /// @return _bridgeMintData The calldata used by counterpart asset handler to unlock tokens for recipient. function bridgeBurn( uint256 _chainId, uint256 _msgValue, bytes32 _assetId, address _originalCaller, bytes calldata _data ) external payable returns (bytes memory _bridgeMintData); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {ERC20PermitUpgradeable} from "@openzeppelin/contracts-upgradeable-v4/token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol"; import {UpgradeableBeacon} from "@openzeppelin/contracts-v4/proxy/beacon/UpgradeableBeacon.sol"; import {ERC1967Upgrade} from "@openzeppelin/contracts-v4/proxy/ERC1967/ERC1967Upgrade.sol"; import {IBridgedStandardToken} from "./interfaces/IBridgedStandardToken.sol"; import {Unauthorized, NonSequentialVersion, ZeroAddress} from "../common/L1ContractErrors.sol"; import {L2_NATIVE_TOKEN_VAULT_ADDR} from "../common/L2ContractAddresses.sol"; import {DataEncoding} from "../common/libraries/DataEncoding.sol"; import {INativeTokenVault} from "../bridge/ntv/INativeTokenVault.sol"; /// @author Matter Labs /// @custom:security-contact [email protected] /// @notice The ERC20 token implementation, that is used in the "default" ERC20 bridge. Note, that it does not /// support any custom token logic, i.e. rebase tokens' functionality is not supported. contract BridgedStandardERC20 is ERC20PermitUpgradeable, IBridgedStandardToken, ERC1967Upgrade { /// @dev Describes whether there is a specific getter in the token. /// @notice Used to explicitly separate which getters the token has and which it does not. /// @notice Different tokens in L1 can implement or not implement getter function as `name`/`symbol`/`decimals`, /// @notice Our goal is to store all the getters that L1 token implements, and for others, we keep it as an unimplemented method. struct ERC20Getters { bool ignoreName; bool ignoreSymbol; bool ignoreDecimals; } ERC20Getters private availableGetters; /// @dev The decimals of the token, that are used as a value for `decimals` getter function. /// @notice A private variable is used only for decimals, but not for `name` and `symbol`, because standard /// @notice OpenZeppelin token represents `name` and `symbol` as storage variables and `decimals` as constant. uint8 private decimals_; /// @notice The l2Bridge now is deprecated, use the L2AssetRouter and L2NativeTokenVault instead. /// @dev Address of the L2 bridge that is used as trustee who can mint/burn tokens address public override l2Bridge; /// @dev Address of the token on its origin chain that can be deposited to mint this bridged token address public override originToken; /// @dev Address of the native token vault that is used as trustee who can mint/burn tokens address public nativeTokenVault; /// @dev The assetId of the token. bytes32 public assetId; /// @dev This also sets the native token vault to the default value if it is not set. /// It is not set only on the L2s for legacy tokens. modifier onlyNTV() { address ntv = nativeTokenVault; if (ntv == address(0)) { ntv = L2_NATIVE_TOKEN_VAULT_ADDR; nativeTokenVault = L2_NATIVE_TOKEN_VAULT_ADDR; assetId = DataEncoding.encodeNTVAssetId( INativeTokenVault(L2_NATIVE_TOKEN_VAULT_ADDR).L1_CHAIN_ID(), originToken ); } if (msg.sender != ntv) { revert Unauthorized(msg.sender); } _; } modifier onlyNextVersion(uint8 _version) { // The version should be incremented by 1. Otherwise, the governor risks disabling // future reinitialization of the token by providing too large a version. if (_version != _getInitializedVersion() + 1) { revert NonSequentialVersion(); } _; } /// @dev Contract is expected to be used as proxy implementation. constructor() { // Disable initialization to prevent Parity hack. _disableInitializers(); } /// @notice Initializes a contract token for later use. Expected to be used in the proxy. /// @dev Stores the L1 address of the bridge and set `name`/`symbol`/`decimals` getters that L1 token has. /// @param _assetId The assetId of the token. /// @param _originToken Address of the origin token that can be deposited to mint this bridged token /// @param _data The additional data that the L1 bridge provide for initialization. /// In this case, it is packed `name`/`symbol`/`decimals` of the L1 token. function bridgeInitialize(bytes32 _assetId, address _originToken, bytes calldata _data) external initializer { if (_originToken == address(0)) { revert ZeroAddress(); } originToken = _originToken; assetId = _assetId; nativeTokenVault = msg.sender; bytes memory nameBytes; bytes memory symbolBytes; bytes memory decimalsBytes; // We parse the data exactly as they were created on the L1 bridge // slither-disable-next-line unused-return (, nameBytes, symbolBytes, decimalsBytes) = DataEncoding.decodeTokenData(_data); ERC20Getters memory getters; string memory decodedName; string memory decodedSymbol; // L1 bridge didn't check if the L1 token return values with proper types for `name`/`symbol`/`decimals` // That's why we need to try to decode them, and if it works out, set the values as getters. // NOTE: Solidity doesn't have a convenient way to try to decode a value: // - Decode them manually, i.e. write a function that will validate that data in the correct format // and return decoded value and a boolean value - whether it was possible to decode. // - Use the standard abi.decode method, but wrap it into an external call in which error can be handled. // We use the second option here. try this.decodeString(nameBytes) returns (string memory nameString) { decodedName = nameString; } catch { getters.ignoreName = true; } try this.decodeString(symbolBytes) returns (string memory symbolString) { decodedSymbol = symbolString; } catch { getters.ignoreSymbol = true; } // Set decoded values for name and symbol. __ERC20_init_unchained(decodedName, decodedSymbol); // Set the name for EIP-712 signature. __ERC20Permit_init(decodedName); try this.decodeUint8(decimalsBytes) returns (uint8 decimalsUint8) { // Set decoded value for decimals. decimals_ = decimalsUint8; } catch { getters.ignoreDecimals = true; } availableGetters = getters; emit BridgeInitialize(_originToken, decodedName, decodedSymbol, decimals_); } /// @notice A method to be called by the governor to update the token's metadata. /// @param _availableGetters The getters that the token has. /// @param _newName The new name of the token. /// @param _newSymbol The new symbol of the token. /// @param _version The version of the token that will be initialized. /// @dev The _version must be exactly the version higher by 1 than the current version. This is needed /// to ensure that the governor can not accidentally disable future reinitialization of the token. function reinitializeToken( ERC20Getters calldata _availableGetters, string calldata _newName, string calldata _newSymbol, uint8 _version ) external onlyNextVersion(_version) reinitializer(_version) { // It is expected that this token is deployed as a beacon proxy, so we'll // allow the governor of the beacon to reinitialize the token. address beaconAddress = _getBeacon(); if (msg.sender != UpgradeableBeacon(beaconAddress).owner()) { revert Unauthorized(msg.sender); } __ERC20_init_unchained(_newName, _newSymbol); __ERC20Permit_init(_newName); availableGetters = _availableGetters; emit BridgeInitialize(originToken, _newName, _newSymbol, decimals_); } /// @dev Mint tokens to a given account. /// @param _to The account that will receive the created tokens. /// @param _amount The amount that will be created. /// @notice Should be called by bridge after depositing tokens from L1. function bridgeMint(address _to, uint256 _amount) external override onlyNTV { _mint(_to, _amount); emit BridgeMint(_to, _amount); } /// @dev Burn tokens from a given account. /// @param _from The account from which tokens will be burned. /// @param _amount The amount that will be burned. /// @notice Should be called by bridge before withdrawing tokens to L1. function bridgeBurn(address _from, uint256 _amount) external override onlyNTV { _burn(_from, _amount); emit BridgeBurn(_from, _amount); } /// @dev External function to decode a string from bytes. function decodeString(bytes calldata _input) external pure returns (string memory result) { (result) = abi.decode(_input, (string)); } /// @dev External function to decode a uint8 from bytes. function decodeUint8(bytes calldata _input) external pure returns (uint8 result) { (result) = abi.decode(_input, (uint8)); } function name() public view override returns (string memory) { // If method is not available, behave like a token that does not implement this method - revert on call. // solhint-disable-next-line reason-string, gas-custom-errors if (availableGetters.ignoreName) revert(); return super.name(); } function symbol() public view override returns (string memory) { // If method is not available, behave like a token that does not implement this method - revert on call. // solhint-disable-next-line reason-string, gas-custom-errors if (availableGetters.ignoreSymbol) revert(); return super.symbol(); } function decimals() public view override returns (uint8) { // If method is not available, behave like a token that does not implement this method - revert on call. // solhint-disable-next-line reason-string, gas-custom-errors if (availableGetters.ignoreDecimals) revert(); return decimals_; } /*////////////////////////////////////////////////////////////// LEGACY FUNCTIONS //////////////////////////////////////////////////////////////*/ /// @notice Returns the address of the token on its native chain. /// Legacy for the l2 bridge. function l1Address() public view override returns (address) { return originToken; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IERC20Metadata} from "@openzeppelin/contracts-v4/token/ERC20/extensions/IERC20Metadata.sol"; import {ETH_TOKEN_ADDRESS} from "../common/Config.sol"; import {DataEncoding} from "../common/libraries/DataEncoding.sol"; /** * @author Matter Labs * @custom:security-contact [email protected] * @notice Helper library for working with native tokens on both L1 and L2. */ library BridgeHelper { /// @dev Receives and parses (name, symbol, decimals) from the token contract function getERC20Getters(address _token, uint256 _originChainId) internal view returns (bytes memory) { bytes memory name; bytes memory symbol; bytes memory decimals; if (_token == ETH_TOKEN_ADDRESS) { // when depositing eth to a non-eth based chain it is an ERC20 name = abi.encode("Ether"); symbol = abi.encode("ETH"); decimals = abi.encode(uint8(18)); } else { bool success; /// note this also works on the L2 for the base token. (success, name) = _token.staticcall(abi.encodeCall(IERC20Metadata.name, ())); if (!success) { // We ignore the revert data name = hex""; } (success, symbol) = _token.staticcall(abi.encodeCall(IERC20Metadata.symbol, ())); if (!success) { // We ignore the revert data symbol = hex""; } (success, decimals) = _token.staticcall(abi.encodeCall(IERC20Metadata.decimals, ())); if (!success) { // We ignore the revert data decimals = hex""; } } return DataEncoding.encodeTokenData({_chainId: _originChainId, _name: name, _symbol: symbol, _decimals: decimals}); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {NonEmptyMsgValue} from "../../common/L1ContractErrors.sol"; abstract contract AssetHandlerModifiers { /// @notice Modifier that ensures that a certain value is zero. /// @dev This should be used in bridgeBurn-like functions to ensure that users /// do not accidentally provide value there. modifier requireZeroValue(uint256 _value) { if (_value != 0) { revert NonEmptyMsgValue(); } _; } }
// SPDX-License-Identifier: MIT // We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version. pragma solidity ^0.8.21; import {L2Message, L2Log, TxStatus} from "../common/Messaging.sol"; import {IL1AssetHandler} from "../bridge/interfaces/IL1AssetHandler.sol"; import {ICTMDeploymentTracker} from "./ICTMDeploymentTracker.sol"; import {IMessageRoot} from "./IMessageRoot.sol"; import {IAssetHandler} from "../bridge/interfaces/IAssetHandler.sol"; struct L2TransactionRequestDirect { uint256 chainId; uint256 mintValue; address l2Contract; uint256 l2Value; bytes l2Calldata; uint256 l2GasLimit; uint256 l2GasPerPubdataByteLimit; bytes[] factoryDeps; address refundRecipient; } struct L2TransactionRequestTwoBridgesOuter { uint256 chainId; uint256 mintValue; uint256 l2Value; uint256 l2GasLimit; uint256 l2GasPerPubdataByteLimit; address refundRecipient; address secondBridgeAddress; uint256 secondBridgeValue; bytes secondBridgeCalldata; } struct L2TransactionRequestTwoBridgesInner { bytes32 magicValue; address l2Contract; bytes l2Calldata; bytes[] factoryDeps; bytes32 txDataHash; } struct BridgehubMintCTMAssetData { uint256 chainId; bytes32 baseTokenAssetId; bytes ctmData; bytes chainData; } struct BridgehubBurnCTMAssetData { uint256 chainId; bytes ctmData; bytes chainData; } /// @author Matter Labs /// @custom:security-contact [email protected] interface IBridgehub is IAssetHandler, IL1AssetHandler { /// @notice pendingAdmin is changed /// @dev Also emitted when new admin is accepted and in this case, `newPendingAdmin` would be zero address event NewPendingAdmin(address indexed oldPendingAdmin, address indexed newPendingAdmin); /// @notice Admin changed event NewAdmin(address indexed oldAdmin, address indexed newAdmin); /// @notice CTM asset registered event AssetRegistered( bytes32 indexed assetInfo, address indexed _assetAddress, bytes32 indexed additionalData, address sender ); event SettlementLayerRegistered(uint256 indexed chainId, bool indexed isWhitelisted); /// @notice Emitted when the bridging to the chain is started. /// @param chainId Chain ID of the ZK chain /// @param assetId Asset ID of the token for the zkChain's CTM /// @param settlementLayerChainId The chain id of the settlement layer the chain migrates to. event MigrationStarted(uint256 indexed chainId, bytes32 indexed assetId, uint256 indexed settlementLayerChainId); /// @notice Emitted when the bridging to the chain is complete. /// @param chainId Chain ID of the ZK chain /// @param assetId Asset ID of the token for the zkChain's CTM /// @param zkChain The address of the ZK chain on the chain where it is migrated to. event MigrationFinalized(uint256 indexed chainId, bytes32 indexed assetId, address indexed zkChain); /// @notice Starts the transfer of admin rights. Only the current admin or owner can propose a new pending one. /// @notice New admin can accept admin rights by calling `acceptAdmin` function. /// @param _newPendingAdmin Address of the new admin function setPendingAdmin(address _newPendingAdmin) external; /// @notice Accepts transfer of admin rights. Only pending admin can accept the role. function acceptAdmin() external; /// Getters function chainTypeManagerIsRegistered(address _chainTypeManager) external view returns (bool); function chainTypeManager(uint256 _chainId) external view returns (address); function assetIdIsRegistered(bytes32 _baseTokenAssetId) external view returns (bool); function baseToken(uint256 _chainId) external view returns (address); function baseTokenAssetId(uint256 _chainId) external view returns (bytes32); function sharedBridge() external view returns (address); function messageRoot() external view returns (IMessageRoot); function getZKChain(uint256 _chainId) external view returns (address); function getAllZKChains() external view returns (address[] memory); function getAllZKChainChainIDs() external view returns (uint256[] memory); function migrationPaused() external view returns (bool); function admin() external view returns (address); function assetRouter() external view returns (address); /// Mailbox forwarder function proveL2MessageInclusion( uint256 _chainId, uint256 _batchNumber, uint256 _index, L2Message calldata _message, bytes32[] calldata _proof ) external view returns (bool); function proveL2LogInclusion( uint256 _chainId, uint256 _batchNumber, uint256 _index, L2Log memory _log, bytes32[] calldata _proof ) external view returns (bool); function proveL1ToL2TransactionStatus( uint256 _chainId, bytes32 _l2TxHash, uint256 _l2BatchNumber, uint256 _l2MessageIndex, uint16 _l2TxNumberInBatch, bytes32[] calldata _merkleProof, TxStatus _status ) external view returns (bool); function requestL2TransactionDirect( L2TransactionRequestDirect calldata _request ) external payable returns (bytes32 canonicalTxHash); function requestL2TransactionTwoBridges( L2TransactionRequestTwoBridgesOuter calldata _request ) external payable returns (bytes32 canonicalTxHash); function l2TransactionBaseCost( uint256 _chainId, uint256 _gasPrice, uint256 _l2GasLimit, uint256 _l2GasPerPubdataByteLimit ) external view returns (uint256); //// Registry function createNewChain( uint256 _chainId, address _chainTypeManager, bytes32 _baseTokenAssetId, uint256 _salt, address _admin, bytes calldata _initData, bytes[] calldata _factoryDeps ) external returns (uint256 chainId); function addChainTypeManager(address _chainTypeManager) external; function removeChainTypeManager(address _chainTypeManager) external; function addTokenAssetId(bytes32 _baseTokenAssetId) external; function setAddresses( address _sharedBridge, ICTMDeploymentTracker _l1CtmDeployer, IMessageRoot _messageRoot ) external; event NewChain(uint256 indexed chainId, address chainTypeManager, address indexed chainGovernance); event ChainTypeManagerAdded(address indexed chainTypeManager); event ChainTypeManagerRemoved(address indexed chainTypeManager); event BaseTokenAssetIdRegistered(bytes32 indexed assetId); function whitelistedSettlementLayers(uint256 _chainId) external view returns (bool); function registerSettlementLayer(uint256 _newSettlementLayerChainId, bool _isWhitelisted) external; function settlementLayer(uint256 _chainId) external view returns (uint256); // function finalizeMigrationToGateway( // uint256 _chainId, // address _baseToken, // address _sharedBridge, // address _admin, // uint256 _expectedProtocolVersion, // ZKChainCommitment calldata _commitment, // bytes calldata _diamondCut // ) external; function forwardTransactionOnGateway( uint256 _chainId, bytes32 _canonicalTxHash, uint64 _expirationTimestamp ) external; function ctmAssetIdFromChainId(uint256 _chainId) external view returns (bytes32); function ctmAssetIdFromAddress(address _ctmAddress) external view returns (bytes32); function l1CtmDeployer() external view returns (ICTMDeploymentTracker); function ctmAssetIdToAddress(bytes32 _assetInfo) external view returns (address); function setCTMAssetAddress(bytes32 _additionalData, address _assetAddress) external; function L1_CHAIN_ID() external view returns (uint256); function registerAlreadyDeployedZKChain(uint256 _chainId, address _hyperchain) external; /// @notice return the ZK chain contract for a chainId /// @dev It is a legacy method. Do not use! function getHyperchain(uint256 _chainId) external view returns (address); function registerLegacyChain(uint256 _chainId) external; function pauseMigration() external; function unpauseMigration() external; }
// SPDX-License-Identifier: MIT // We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version. pragma solidity ^0.8.21; import {IL1Nullifier} from "./IL1Nullifier.sol"; import {IL1NativeTokenVault} from "../ntv/IL1NativeTokenVault.sol"; import {IL1AssetRouter} from "../asset-router/IL1AssetRouter.sol"; /// @title L1 Bridge contract legacy interface /// @author Matter Labs /// @custom:security-contact [email protected] /// @notice Legacy Bridge interface before ZK chain migration, used for backward compatibility with ZKsync Era interface IL1ERC20Bridge { event DepositInitiated( bytes32 indexed l2DepositTxHash, address indexed from, address indexed to, address l1Token, uint256 amount ); event WithdrawalFinalized(address indexed to, address indexed l1Token, uint256 amount); event ClaimedFailedDeposit(address indexed to, address indexed l1Token, uint256 amount); function isWithdrawalFinalized(uint256 _l2BatchNumber, uint256 _l2MessageIndex) external view returns (bool); function deposit( address _l2Receiver, address _l1Token, uint256 _amount, uint256 _l2TxGasLimit, uint256 _l2TxGasPerPubdataByte, address _refundRecipient ) external payable returns (bytes32 txHash); function deposit( address _l2Receiver, address _l1Token, uint256 _amount, uint256 _l2TxGasLimit, uint256 _l2TxGasPerPubdataByte ) external payable returns (bytes32 txHash); function claimFailedDeposit( address _depositSender, address _l1Token, bytes32 _l2TxHash, uint256 _l2BatchNumber, uint256 _l2MessageIndex, uint16 _l2TxNumberInBatch, bytes32[] calldata _merkleProof ) external; function finalizeWithdrawal( uint256 _l2BatchNumber, uint256 _l2MessageIndex, uint16 _l2TxNumberInBatch, bytes calldata _message, bytes32[] calldata _merkleProof ) external; function l2TokenAddress(address _l1Token) external view returns (address); function L1_NULLIFIER() external view returns (IL1Nullifier); function L1_ASSET_ROUTER() external view returns (IL1AssetRouter); function L1_NATIVE_TOKEN_VAULT() external view returns (IL1NativeTokenVault); function l2TokenBeacon() external view returns (address); function l2Bridge() external view returns (address); function depositAmount( address _account, address _l1Token, bytes32 _depositL2TxHash ) external view returns (uint256 amount); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; /// @title L1 Bridge contract interface /// @author Matter Labs /// @custom:security-contact [email protected] interface IL1SharedBridgeLegacy { function l2BridgeAddress(uint256 _chainId) external view returns (address); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol) pragma solidity ^0.8.0; /** * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC. * * _Available since v4.8.3._ */ interface IERC1967 { /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Emitted when the beacon is changed. */ event BeaconUpgraded(address indexed beacon); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822Proxiable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol) // This file was procedurally generated from scripts/generate/templates/StorageSlot.js. pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ```solidity * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._ * _Available since v4.9 for `string`, `bytes`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } struct StringSlot { string value; } struct BytesSlot { bytes value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `StringSlot` with member `value` located at `slot`. */ function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `StringSlot` representation of the string storage pointer `store`. */ function getStringSlot(string storage store) internal pure returns (StringSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := store.slot } } /** * @dev Returns an `BytesSlot` with member `value` located at `slot`. */ function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`. */ function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := store.slot } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import {Initializable} from "../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 // 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 // OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol) pragma solidity ^0.8.0; import {Initializable} from "../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; } function _contextSuffixLength() internal view virtual returns (uint256) { return 0; } /** * @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) (token/ERC20/extensions/draft-ERC20Permit.sol) pragma solidity ^0.8.0; // EIP-2612 is Final as of 2022-11-01. This file is deprecated. import "./ERC20PermitUpgradeable.sol";
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol) pragma solidity ^0.8.0; import "./IBeacon.sol"; import "../../access/Ownable.sol"; import "../../utils/Address.sol"; /** * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their * implementation contract, which is where they will delegate all function calls. * * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon. */ contract UpgradeableBeacon is IBeacon, Ownable { address private _implementation; /** * @dev Emitted when the implementation returned by the beacon is changed. */ event Upgraded(address indexed implementation); /** * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the * beacon. */ constructor(address implementation_) { _setImplementation(implementation_); } /** * @dev Returns the current implementation address. */ function implementation() public view virtual override returns (address) { return _implementation; } /** * @dev Upgrades the beacon to a new implementation. * * Emits an {Upgraded} event. * * Requirements: * * - msg.sender must be the owner of the contract. * - `newImplementation` must be a contract. */ function upgradeTo(address newImplementation) public virtual onlyOwner { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation contract address for this beacon * * Requirements: * * - `newImplementation` must be a contract. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract"); _implementation = newImplementation; } }
// 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); }
// SPDX-License-Identifier: MIT // We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version. pragma solidity ^0.8.21; /// @dev The enum that represents the transaction execution status /// @param Failure The transaction execution failed /// @param Success The transaction execution succeeded enum TxStatus { Failure, Success } /// @dev The log passed from L2 /// @param l2ShardId The shard identifier, 0 - rollup, 1 - porter /// All other values are not used but are reserved for the future /// @param isService A boolean flag that is part of the log along with `key`, `value`, and `sender` address. /// This field is required formally but does not have any special meaning /// @param txNumberInBatch The L2 transaction number in a Batch, in which the log was sent /// @param sender The L2 address which sent the log /// @param key The 32 bytes of information that was sent in the log /// @param value The 32 bytes of information that was sent in the log // Both `key` and `value` are arbitrary 32-bytes selected by the log sender struct L2Log { uint8 l2ShardId; bool isService; uint16 txNumberInBatch; address sender; bytes32 key; bytes32 value; } /// @dev An arbitrary length message passed from L2 /// @notice Under the hood it is `L2Log` sent from the special system L2 contract /// @param txNumberInBatch The L2 transaction number in a Batch, in which the message was sent /// @param sender The address of the L2 account from which the message was passed /// @param data An arbitrary length message struct L2Message { uint16 txNumberInBatch; address sender; bytes data; } /// @dev Internal structure that contains the parameters for the writePriorityOp /// internal function. /// @param txId The id of the priority transaction. /// @param l2GasPrice The gas price for the l2 priority operation. /// @param expirationTimestamp The timestamp by which the priority operation must be processed by the operator. /// @param request The external calldata request for the priority operation. struct WritePriorityOpParams { uint256 txId; uint256 l2GasPrice; uint64 expirationTimestamp; BridgehubL2TransactionRequest request; } /// @dev Structure that includes all fields of the L2 transaction /// @dev The hash of this structure is the "canonical L2 transaction hash" and can /// be used as a unique identifier of a tx /// @param txType The tx type number, depending on which the L2 transaction can be /// interpreted differently /// @param from The sender's address. `uint256` type for possible address format changes /// and maintaining backward compatibility /// @param to The recipient's address. `uint256` type for possible address format changes /// and maintaining backward compatibility /// @param gasLimit The L2 gas limit for L2 transaction. Analog to the `gasLimit` on an /// L1 transactions /// @param gasPerPubdataByteLimit Maximum number of L2 gas that will cost one byte of pubdata /// (every piece of data that will be stored on L1 as calldata) /// @param maxFeePerGas The absolute maximum sender willing to pay per unit of L2 gas to get /// the transaction included in a Batch. Analog to the EIP-1559 `maxFeePerGas` on an L1 transactions /// @param maxPriorityFeePerGas The additional fee that is paid directly to the validator /// to incentivize them to include the transaction in a Batch. Analog to the EIP-1559 /// `maxPriorityFeePerGas` on an L1 transactions /// @param paymaster The address of the EIP-4337 paymaster, that will pay fees for the /// transaction. `uint256` type for possible address format changes and maintaining backward compatibility /// @param nonce The nonce of the transaction. For L1->L2 transactions it is the priority /// operation Id /// @param value The value to pass with the transaction /// @param reserved The fixed-length fields for usage in a future extension of transaction /// formats /// @param data The calldata that is transmitted for the transaction call /// @param signature An abstract set of bytes that are used for transaction authorization /// @param factoryDeps The set of L2 bytecode hashes whose preimages were shown on L1 /// @param paymasterInput The arbitrary-length data that is used as a calldata to the paymaster pre-call /// @param reservedDynamic The arbitrary-length field for usage in a future extension of transaction formats struct L2CanonicalTransaction { uint256 txType; uint256 from; uint256 to; uint256 gasLimit; uint256 gasPerPubdataByteLimit; uint256 maxFeePerGas; uint256 maxPriorityFeePerGas; uint256 paymaster; uint256 nonce; uint256 value; // In the future, we might want to add some // new fields to the struct. The `txData` struct // is to be passed to account and any changes to its structure // would mean a breaking change to these accounts. To prevent this, // we should keep some fields as "reserved" // It is also recommended that their length is fixed, since // it would allow easier proof integration (in case we will need // some special circuit for preprocessing transactions) uint256[4] reserved; bytes data; bytes signature; uint256[] factoryDeps; bytes paymasterInput; // Reserved dynamic type for the future use-case. Using it should be avoided, // But it is still here, just in case we want to enable some additional functionality bytes reservedDynamic; } /// @param sender The sender's address. /// @param contractAddressL2 The address of the contract on L2 to call. /// @param valueToMint The amount of base token that should be minted on L2 as the result of this transaction. /// @param l2Value The msg.value of the L2 transaction. /// @param l2Calldata The calldata for the L2 transaction. /// @param l2GasLimit The limit of the L2 gas for the L2 transaction /// @param l2GasPerPubdataByteLimit The price for a single pubdata byte in L2 gas. /// @param factoryDeps The array of L2 bytecodes that the tx depends on. /// @param refundRecipient The recipient of the refund for the transaction on L2. If the transaction fails, then /// this address will receive the `l2Value`. // solhint-disable-next-line gas-struct-packing struct BridgehubL2TransactionRequest { address sender; address contractL2; uint256 mintValue; uint256 l2Value; bytes l2Calldata; uint256 l2GasLimit; uint256 l2GasPerPubdataByteLimit; bytes[] factoryDeps; address refundRecipient; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {L2TransactionRequestTwoBridgesInner, IBridgehub} from "./IBridgehub.sol"; import {IAssetRouterBase} from "../bridge/asset-router/IAssetRouterBase.sol"; import {IL1AssetDeploymentTracker} from "../bridge/interfaces/IL1AssetDeploymentTracker.sol"; /// @author Matter Labs /// @custom:security-contact [email protected] interface ICTMDeploymentTracker is IL1AssetDeploymentTracker { function bridgehubDeposit( uint256 _chainId, address _originalCaller, uint256 _l2Value, bytes calldata _data ) external payable returns (L2TransactionRequestTwoBridgesInner memory request); function BRIDGE_HUB() external view returns (IBridgehub); function L1_ASSET_ROUTER() external view returns (IAssetRouterBase); function registerCTMAssetOnL1(address _ctmAddress) external; function calculateAssetId(address _l1CTM) external view returns (bytes32); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IBridgehub} from "./IBridgehub.sol"; /** * @author Matter Labs * @notice MessageRoot contract is responsible for storing and aggregating the roots of the batches from different chains into the MessageRoot. * @custom:security-contact [email protected] */ interface IMessageRoot { function BRIDGE_HUB() external view returns (IBridgehub); function addNewChain(uint256 _chainId) external; function addChainBatchRoot(uint256 _chainId, uint256 _batchNumber, bytes32 _chainBatchRoot) external; }
// 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 // OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/ERC20Permit.sol) pragma solidity ^0.8.0; import "./IERC20PermitUpgradeable.sol"; import "../ERC20Upgradeable.sol"; import "../../../utils/cryptography/ECDSAUpgradeable.sol"; import "../../../utils/cryptography/EIP712Upgradeable.sol"; import "../../../utils/CountersUpgradeable.sol"; import {Initializable} from "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation 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. * * _Available since v3.4._ * * @custom:storage-size 51 */ abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; mapping(address => CountersUpgradeable.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private constant _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`. * However, to ensure consistency with the upgradeable transpiler, we will continue * to reserve a slot. * @custom:oz-renamed-from _PERMIT_TYPEHASH */ // solhint-disable-next-line var-name-mixedcase bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ function __ERC20Permit_init(string memory name) internal onlyInitializing { __EIP712_init_unchained(name, "1"); } function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {} /** * @inheritdoc IERC20PermitUpgradeable */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSAUpgradeable.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @inheritdoc IERC20PermitUpgradeable */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @inheritdoc IERC20PermitUpgradeable */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { CountersUpgradeable.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } /** * @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) (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 // OpenZeppelin Contracts (last updated v4.9.4) (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. * * ==== Security Considerations * * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be * considered as an intention to spend the allowance in any specific way. The second is that because permits have * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be * generally recommended is: * * ```solidity * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public { * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {} * doThing(..., value); * } * * function doThing(..., uint256 value) public { * token.safeTransferFrom(msg.sender, address(this), value); * ... * } * ``` * * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also * {SafeERC20-safeTransferFrom}). * * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so * contracts should have entry points that don't rely on permit. */ interface IERC20PermitUpgradeable { /** * @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]. * * CAUTION: See Security Considerations above. */ 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) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import {Initializable} from "../../proxy/utils/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _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 {} /** * @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[45] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../StringsUpgradeable.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV // Deprecated in v4.8 } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. /// @solidity memory-safe-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) { // 32 is the length in bytes of hash, // enforced by the type signature above /// @solidity memory-safe-assembly assembly { mstore(0x00, "\x19Ethereum Signed Message:\n32") mstore(0x1c, hash) message := keccak256(0x00, 0x3c) } } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) mstore(ptr, "\x19\x01") mstore(add(ptr, 0x02), domainSeparator) mstore(add(ptr, 0x22), structHash) data := keccak256(ptr, 0x42) } } /** * @dev Returns an Ethereum Signed Data with intended validator, created from a * `validator` and `data` according to the version 0 of EIP-191. * * See {recover}. */ function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x00", validator, data)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol) pragma solidity ^0.8.8; import "./ECDSAUpgradeable.sol"; import "../../interfaces/IERC5267Upgradeable.sol"; import {Initializable} from "../../proxy/utils/Initializable.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the * separator from the immutable values, which is cheaper than accessing a cached version in cold storage. * * _Available since v3.4._ * * @custom:storage-size 52 */ abstract contract EIP712Upgradeable is Initializable, IERC5267Upgradeable { bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /// @custom:oz-renamed-from _HASHED_NAME bytes32 private _hashedName; /// @custom:oz-renamed-from _HASHED_VERSION bytes32 private _hashedVersion; string private _name; string private _version; /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712_init(string memory name, string memory version) internal onlyInitializing { __EIP712_init_unchained(name, version); } function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing { _name = name; _version = version; // Reset prior values in storage if upgrading _hashedName = 0; _hashedVersion = 0; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(); } function _buildDomainSeparator() private view returns (bytes32) { return keccak256(abi.encode(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash); } /** * @dev See {EIP-5267}. * * _Available since v4.9._ */ function eip712Domain() public view virtual override returns ( bytes1 fields, string memory name, string memory version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions ) { // If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized // and the EIP712 domain is not reliable, as it will be missing name and version. require(_hashedName == 0 && _hashedVersion == 0, "EIP712: Uninitialized"); return ( hex"0f", // 01111 _EIP712Name(), _EIP712Version(), block.chainid, address(this), bytes32(0), new uint256[](0) ); } /** * @dev The name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712Name() internal virtual view returns (string memory) { return _name; } /** * @dev The version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712Version() internal virtual view returns (string memory) { return _version; } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead. */ function _EIP712NameHash() internal view returns (bytes32) { string memory name = _EIP712Name(); if (bytes(name).length > 0) { return keccak256(bytes(name)); } else { // If the name is empty, the contract may have been upgraded without initializing the new storage. // We return the name hash in storage if non-zero, otherwise we assume the name is empty by design. bytes32 hashedName = _hashedName; if (hashedName != 0) { return hashedName; } else { return keccak256(""); } } } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead. */ function _EIP712VersionHash() internal view returns (bytes32) { string memory version = _EIP712Version(); if (bytes(version).length > 0) { return keccak256(bytes(version)); } else { // If the version is empty, the contract may have been upgraded without initializing the new storage. // We return the version hash in storage if non-zero, otherwise we assume the version is empty by design. bytes32 hashedVersion = _hashedVersion; if (hashedVersion != 0) { return hashedVersion; } else { return keccak256(""); } } } /** * @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[48] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.4) (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; } function _contextSuffixLength() internal view virtual returns (uint256) { return 0; } }
// 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 IERC20Upgradeable { /** * @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 v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @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); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol) pragma solidity ^0.8.0; import "./math/MathUpgradeable.sol"; import "./math/SignedMathUpgradeable.sol"; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _SYMBOLS = "0123456789abcdef"; uint8 private constant _ADDRESS_LENGTH = 20; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = MathUpgradeable.log10(value) + 1; string memory buffer = new string(length); uint256 ptr; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { mstore8(ptr, byte(mod(value, 10), _SYMBOLS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @dev Converts a `int256` to its ASCII `string` decimal representation. */ function toString(int256 value) internal pure returns (string memory) { return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMathUpgradeable.abs(value)))); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { unchecked { return toHexString(value, MathUpgradeable.log256(value) + 1); } } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); } /** * @dev Returns true if the two strings are equal. */ function equal(string memory a, string memory b) internal pure returns (bool) { return keccak256(bytes(a)) == keccak256(bytes(b)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol) pragma solidity ^0.8.0; interface IERC5267Upgradeable { /** * @dev MAY be emitted to signal that the domain could have changed. */ event EIP712DomainChanged(); /** * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712 * signature. */ function eip712Domain() external view returns ( bytes1 fields, string memory name, string memory version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions ); }
// 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 MathUpgradeable { 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 // 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 SignedMathUpgradeable { /** * @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); } } }
{ "remappings": [ "@ensdomains/=node_modules/@ensdomains/", "ds-test/=lib/forge-std/lib/ds-test/src/", "eth-gas-reporter/=node_modules/eth-gas-reporter/", "forge-std/=lib/forge-std/src/", "hardhat/=node_modules/hardhat/", "murky/=lib/murky/src/", "foundry-test/=test/foundry/", "l2-contracts/=../l2-contracts/contracts/", "@openzeppelin/contracts-v4/=lib/openzeppelin-contracts-v4/contracts/", "@openzeppelin/contracts-upgradeable-v4/=lib/openzeppelin-contracts-upgradeable-v4/contracts/", "erc4626-tests/=lib/openzeppelin-contracts-upgradeable-v4/lib/erc4626-tests/", "openzeppelin-contracts-upgradeable-v4/=lib/openzeppelin-contracts-upgradeable-v4/", "openzeppelin-contracts-v4/=lib/openzeppelin-contracts-v4/", "openzeppelin-contracts/=lib/murky/lib/openzeppelin-contracts/" ], "optimizer": { "enabled": true, "runs": 200 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "ipfs", "appendCBOR": true }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "cancun", "viaIR": false, "libraries": {} }
Contract ABI
API[{"inputs":[{"internalType":"address","name":"_l1WethAddress","type":"address"},{"internalType":"address","name":"_l1AssetRouter","type":"address"},{"internalType":"contract IL1Nullifier","name":"_l1Nullifier","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"expected","type":"address"},{"internalType":"address","name":"supplied","type":"address"}],"name":"AddressMismatch","type":"error"},{"inputs":[],"name":"AmountMustBeGreaterThanZero","type":"error"},{"inputs":[],"name":"AssetIdAlreadyRegistered","type":"error"},{"inputs":[{"internalType":"bytes32","name":"expected","type":"bytes32"},{"internalType":"bytes32","name":"supplied","type":"bytes32"}],"name":"AssetIdMismatch","type":"error"},{"inputs":[],"name":"BurningNativeWETHNotSupported","type":"error"},{"inputs":[],"name":"ClaimFailedDepositFailed","type":"error"},{"inputs":[],"name":"DeployingBridgedTokenForNativeToken","type":"error"},{"inputs":[],"name":"EmptyDeposit","type":"error"},{"inputs":[],"name":"EmptyToken","type":"error"},{"inputs":[],"name":"InsufficientChainBalance","type":"error"},{"inputs":[],"name":"InvalidNTVBurnData","type":"error"},{"inputs":[],"name":"NoFundsTransferred","type":"error"},{"inputs":[],"name":"NonEmptyMsgValue","type":"error"},{"inputs":[],"name":"OriginChainIdNotFound","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"TokenNotSupported","type":"error"},{"inputs":[],"name":"TokensWithFeesNotSupported","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"Unauthorized","type":"error"},{"inputs":[],"name":"UnsupportedEncodingVersion","type":"error"},{"inputs":[{"internalType":"uint256","name":"expected","type":"uint256"},{"internalType":"uint256","name":"actual","type":"uint256"}],"name":"ValueMismatch","type":"error"},{"inputs":[],"name":"WithdrawFailed","type":"error"},{"inputs":[{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"nullifierChainBalance","type":"uint256"}],"name":"WrongAmountTransferred","type":"error"},{"inputs":[],"name":"WrongCounterpart","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"inputs":[],"name":"ZeroAmountToTransfer","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"chainId","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"assetId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"BridgeBurn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"chainId","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"assetId","type":"bytes32"},{"indexed":false,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"BridgeMint","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"bridgedTokenBeacon","type":"address"},{"indexed":false,"internalType":"bytes32","name":"bridgedTokenProxyBytecodeHash","type":"bytes32"}],"name":"BridgedTokenBeaconUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"l2TokenBeacon","type":"address"}],"name":"TokenBeaconUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"ASSET_ROUTER","outputs":[{"internalType":"contract IAssetRouterBase","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BASE_TOKEN_ASSET_ID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"L1_CHAIN_ID","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"L1_NULLIFIER","outputs":[{"internalType":"contract IL1Nullifier","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WETH_TOKEN","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenAddress","type":"address"}],"name":"assetId","outputs":[{"internalType":"bytes32","name":"assetId","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_chainId","type":"uint256"},{"internalType":"uint256","name":"_l2MsgValue","type":"uint256"},{"internalType":"bytes32","name":"_assetId","type":"bytes32"},{"internalType":"address","name":"_originalCaller","type":"address"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"bridgeBurn","outputs":[{"internalType":"bytes","name":"_bridgeMintData","type":"bytes"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes32","name":"","type":"bytes32"},{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"_assetHandlerAddressOnCounterpart","type":"address"}],"name":"bridgeCheckCounterpartAddress","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_chainId","type":"uint256"},{"internalType":"bytes32","name":"_assetId","type":"bytes32"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"bridgeMint","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_chainId","type":"uint256"},{"internalType":"bytes32","name":"_assetId","type":"bytes32"},{"internalType":"address","name":"_depositSender","type":"address"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"bridgeRecoverFailedTransfer","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"bridgedTokenBeacon","outputs":[{"internalType":"contract IBeacon","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_originChainId","type":"uint256"},{"internalType":"address","name":"_nonNativeToken","type":"address"}],"name":"calculateCreate2TokenAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"bytes32","name":"assetId","type":"bytes32"}],"name":"chainBalance","outputs":[{"internalType":"uint256","name":"balance","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_nativeToken","type":"address"}],"name":"ensureTokenIsRegistered","outputs":[{"internalType":"bytes32","name":"tokenAssetId","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_originChainId","type":"uint256"}],"name":"getERC20Getters","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_bridgedTokenBeacon","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"assetId","type":"bytes32"}],"name":"originChainId","outputs":[{"internalType":"uint256","name":"originChainId","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"registerEthToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_nativeToken","type":"address"}],"name":"registerToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"assetId","type":"bytes32"}],"name":"tokenAddress","outputs":[{"internalType":"address","name":"tokenAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"_erc20Data","type":"bytes"}],"name":"tokenDataOriginChainId","outputs":[{"internalType":"uint256","name":"tokenOriginChainId","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"transferFundsFromSharedBridge","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"_burnData","type":"bytes"},{"internalType":"bytes32","name":"_expectedAssetId","type":"bytes32"}],"name":"tryRegisterTokenFromBurnData","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_targetChainId","type":"uint256"}],"name":"updateChainBalancesFromSharedBridge","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]
Deployed Bytecode
0x60806040526004361062000206575f3560e01c80638310f2c61162000112578063c6a70bbb116200009e578063e60ccaba116200006a578063e60ccaba1462000695578063f2d4424614620006ca578063f2fde38b14620006eb578063fd3f60df146200070f575f80fd5b8063c6a70bbb14620005f5578063cb6da609146200062a578063cb944dec1462000641578063e30c39781462000676575f80fd5b80639cc395d011620000de5780639cc395d01462000572578063a7236d161462000596578063c2e9029314620005ba578063c487412c14620005d1575f80fd5b80638310f2c614620004e05780638456cb5914620005045780638da5cb5b146200051b57806397bb3ce9146200053a575f80fd5b80633f4ba83a11620001925780635f3455b5116200015e5780635f3455b5146200045d578063699b0fb9146200048c578063715018a614620004b257806379ba509714620004c9575f80fd5b80633f4ba83a14620003da578063485cc95514620003f157806349b4085314620004155780635c975abb1462000439575f80fd5b80632f90b18411620001d25780632f90b18414620003065780633345359b146200033b57806336ba0355146200037557806337d277d4146200038c575f80fd5b806307a6d4bc146200026357806309824a80146200029a57806319a2a28514620002be5780631c9f014914620002e2575f80fd5b366200025f577f0000000000000000000000003e8b2fe58675126ed30d0d12dea2a9bda72d18ae6001600160a01b031633146200025d5760405163472511eb60e11b81523360048201526024015b60405180910390fd5b005b5f80fd5b3480156200026f575f80fd5b50620002876200028136600462002fca565b6200073e565b6040519081526020015b60405180910390f35b348015620002a6575f80fd5b506200025d620002b836600462003022565b62000783565b348015620002ca575f80fd5b5062000287620002dc36600462003022565b62000792565b348015620002ee575f80fd5b506200025d6200030036600462003040565b620007cd565b34801562000312575f80fd5b50620002877f0000000000000000000000000000000000000000000000000000000000aa36a781565b34801562000347575f80fd5b5062000287620003593660046200306d565b60fb60209081525f928352604080842090915290825290205481565b6200025d620003863660046200308e565b62000944565b34801562000398575f80fd5b50620003c17f0000000000000000000000007b79995e5f793a07bc00c21412e50ecae098e7f981565b6040516001600160a01b03909116815260200162000291565b348015620003e6575f80fd5b506200025d62000a50565b348015620003fd575f80fd5b506200025d6200040f366004620030e1565b62000a66565b34801562000421575f80fd5b506200025d620004333660046200311d565b62000bc0565b34801562000445575f80fd5b5060975460ff16604051901515815260200162000291565b34801562000469575f80fd5b50620002876200047b36600462003169565b60ca6020525f908152604090205481565b620004a36200049d36600462003181565b62000ca8565b60405162000291919062003246565b348015620004be575f80fd5b506200025d62000d89565b348015620004d5575f80fd5b506200025d62000d9e565b348015620004ec575f80fd5b506200025d620004fe36600462003022565b62000e1c565b34801562000510575f80fd5b506200025d62001127565b34801562000527575f80fd5b506033546001600160a01b0316620003c1565b34801562000546575f80fd5b50620003c16200055836600462003169565b60cb6020525f90815260409020546001600160a01b031681565b3480156200057e575f80fd5b506200025d620005903660046200325a565b6200113b565b348015620005a2575f80fd5b50620004a3620005b436600462003040565b620011ca565b6200025d620005cb366004620032a6565b620011df565b348015620005dd575f80fd5b50620003c1620005ef36600462003311565b620013eb565b34801562000601575f80fd5b50620003c17f000000000000000000000000f2a49545c5b1a85d2fb018cc39103661639a9b0681565b34801562000636575f80fd5b506200025d62001489565b3480156200064d575f80fd5b50620002877f6337a96bd2cd359fa0bae3bbedfca736753213c95037ae158c5fa7c048ae211281565b34801562000682575f80fd5b506065546001600160a01b0316620003c1565b348015620006a1575f80fd5b50620003c17f0000000000000000000000003e8b2fe58675126ed30d0d12dea2a9bda72d18ae81565b348015620006d6575f80fd5b5060c954620003c1906001600160a01b031681565b348015620006f7575f80fd5b506200025d6200070936600462003022565b62001495565b3480156200071b575f80fd5b50620002876200072d36600462003022565b60cc6020525f908152604090205481565b5f6200074b838362001509565b5091925050505f8190036200077d57507f0000000000000000000000000000000000000000000000000000000000aa36a75b92915050565b6200078e81620015bb565b5050565b6001600160a01b0381165f90815260cc602052604081205480620007c357620007bb83620015bb565b9150620007c7565b8091505b50919050565b604051632735146160e21b8152600481018290526001600160a01b0383811660248301525f917f0000000000000000000000003e8b2fe58675126ed30d0d12dea2a9bda72d18ae90911690639cd4518490604401602060405180830381865afa1580156200083d573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000863919062003337565b90505f620008724685620016d6565b5f84815260fb602090815260408083208484529091529020549091506200089b90839062003363565b5f84815260fb6020908152604080832085845282528083209390935560ca905281902046905551635de097b160e01b8152600481018490526001600160a01b0385811660248301527f0000000000000000000000003e8b2fe58675126ed30d0d12dea2a9bda72d18ae1690635de097b1906044015f604051808303815f87803b15801562000927575f80fd5b505af11580156200093a573d5f803e3d5ffd5b5050505050505050565b348015620009655760405163536ec84b60e01b815260040160405180910390fd5b336001600160a01b037f000000000000000000000000f2a49545c5b1a85d2fb018cc39103661639a9b061614620009b25760405163472511eb60e11b815233600482015260240162000254565b620009bc6200172c565b5f84815260ca60205260408120548190469003620009ed57620009e28787878762001774565b909250905062000a01565b620009fb87878787620017ff565b90925090505b604080516001600160a01b038416815260208101839052879189917fbc0f4055a7869d8ecad34b33382a0bc181c5811565fec42f335505be5fd661d2910160405180910390a350505050505050565b62000a5a62001900565b62000a646200195c565b565b5f54610100900460ff161580801562000a8557505f54600160ff909116105b8062000aa05750303b15801562000aa057505f5460ff166001145b62000b055760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b606482015260840162000254565b5f805460ff19166001179055801562000b27575f805461ff0019166101001790555b6001600160a01b03831662000b4f5760405163d92e233d60e01b815260040160405180910390fd5b60c980546001600160a01b0319166001600160a01b03841617905562000b7583620019b0565b801562000bbb575f805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050565b5f62000c0184848080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250620019cb92505050565b9250506001600160a01b038216905062000c2e5760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381165f90815260cc6020526040902054801562000c6657604051631fd233c560e31b815260040160405180910390fd5b5f62000c7283620015bb565b905083811462000ca057604051631294e9e160e01b8152600481018590526024810182905260440162000254565b505050505050565b606085801562000ccb5760405163536ec84b60e01b815260040160405180910390fd5b336001600160a01b037f000000000000000000000000f2a49545c5b1a85d2fb018cc39103661639a9b06161462000d185760405163472511eb60e11b815233600482015260240162000254565b62000d226200172c565b5f805f62000d3287878b62001a14565b5f8c815260ca60205260409020549295509093509150461462000d675762000d5f8b8a8a86868662001afc565b945062000d7b565b62000d788b8a8a5f87878762001ce3565b94505b505050509695505050505050565b62000d9362001900565b62000a645f620019b0565b60655433906001600160a01b0316811462000e0e5760405162461bcd60e51b815260206004820152602960248201527f4f776e61626c6532537465703a2063616c6c6572206973206e6f7420746865206044820152683732bb9037bbb732b960b91b606482015260840162000254565b62000e1981620019b0565b50565b62000e278162000792565b505f196001600160a01b0382160162000ed9576040516340a434d560e01b81526001600160a01b03828116600483015247917f0000000000000000000000003e8b2fe58675126ed30d0d12dea2a9bda72d18ae909116906340a434d5906024015f604051808303815f87803b15801562000e9f575f80fd5b505af115801562000eb2573d5f803e3d5ffd5b50479250505081811162000bbb57604051631956131b60e31b815260040160405180910390fd5b6040516370a0823160e01b81523060048201525f906001600160a01b038316906370a0823190602401602060405180830381865afa15801562000f1e573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000f44919062003337565b6040516370a0823160e01b81526001600160a01b037f0000000000000000000000003e8b2fe58675126ed30d0d12dea2a9bda72d18ae811660048301529192505f918416906370a0823190602401602060405180830381865afa15801562000fae573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000fd4919062003337565b9050805f0362000ff75760405163723a162160e11b815260040160405180910390fd5b6040516340a434d560e01b81526001600160a01b0384811660048301527f0000000000000000000000003e8b2fe58675126ed30d0d12dea2a9bda72d18ae16906340a434d5906024015f604051808303815f87803b15801562001058575f80fd5b505af11580156200106b573d5f803e3d5ffd5b50506040516370a0823160e01b81523060048201525f92506001600160a01b03861691506370a0823190602401602060405180830381865afa158015620010b4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620010da919062003337565b905081620010e9848362003379565b10156200112157620010fc838262003379565b604051631fdb477f60e31b815260048101919091526024810183905260440162000254565b50505050565b6200113162001900565b62000a6462001da2565b336001600160a01b037f000000000000000000000000f2a49545c5b1a85d2fb018cc39103661639a9b061614620011885760405163472511eb60e11b815233600482015260240162000254565b620011986201000060046200338f565b6001600160a01b0316816001600160a01b0316146200112157604051632d2bb76f60e21b815260040160405180910390fd5b6060620011d8838362001de2565b9392505050565b348015620012005760405163536ec84b60e01b815260040160405180910390fd5b336001600160a01b037f000000000000000000000000f2a49545c5b1a85d2fb018cc39103661639a9b0616146200124d5760405163472511eb60e11b815233600482015260240162000254565b620012576200172c565b5f6200129884848080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250620019cb92505050565b50505f87815260cb60205260408120549192506001600160a01b0390911690829003620012d857604051631956131b60e31b815260040160405180910390fd5b620012e68888845f62002075565b5f196001600160a01b0382160162001329575f805f805f868b5af190508062001322576040516301fdf20d60e31b815260040160405180910390fd5b506200093a565b5f6200133588620020f6565b90504681036200135b57620013556001600160a01b03831688856200225c565b620013e0565b8015620013c7576040516346154c9f60e11b81526001600160a01b03888116600483015260248201859052831690638c2a993e906044015f604051808303815f87803b158015620013aa575f80fd5b505af1158015620013bd573d5f803e3d5ffd5b50505050620013e0565b604051635c93228760e11b815260040160405180910390fd5b505050505050505050565b5f80620013f98484620022c1565b9050620014818160405180602001620014129062002f74565b601f1982820381018352601f90910116604081815260c9546001600160a01b03166020830152808201525f606082015260800160408051601f1981840301815290829052620014659291602001620033b9565b60405160208183030381529060405280519060200120620022e8565b949350505050565b62000e196001620022f6565b6200149f62001900565b606580546001600160a01b0383166001600160a01b03199091168117909155620014d16033546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b5f60608060605f86865f818110620015255762001525620033eb565b909101356001600160f81b031916915081905062001558576200154b86880188620034c9565b91955093509150620015b0565b6001600160f81b031981811601620015975762001579866001818a62003555565b8101906200158891906200357e565b945094509450945050620015b2565b60405163084a144960e01b815260040160405180910390fd5b505b92959194509250565b5f7f0000000000000000000000007b79995e5f793a07bc00c21412e50ecae098e7f96001600160a01b0316826001600160a01b03161480156200161e57507f0000000000000000000000000000000000000000000000000000000000aa36a74614155b1562001669576040516306439c6b60e01b81526001600160a01b037f0000000000000000000000007b79995e5f793a07bc00c21412e50ecae098e7f916600482015260240162000254565b816001600160a01b03163b5f03620016945760405163066f53b160e01b815260040160405180910390fd5b6001600160a01b0382165f90815260cc602052604090205415620016cb57604051631fd233c560e31b815260040160405180910390fd5b6200077d82620022f6565b5f82620016e86201000060046200338f565b6040805160208101939093526001600160a01b0391821690830152831660608201526080015b60405160208183030381529060405280519060200120905092915050565b60975460ff161562000a645760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b604482015260640162000254565b5f83815260cb60209081526040808320548151601f860184900484028101840190925284825283926001600160a01b0390911691620017cd9187908790819084018382808284375f92019190915250620023c892505050565b50919550909350620017e791508890508784600162002075565b620017f586848385620023f6565b5094509492505050565b5f83815260cb60209081526040808320548151601f860184900484028101840190925284825283926001600160a01b039091169160609184916200185d9189908990819084018382808284375f92019190915250620023c892505050565b92985096509093509150506001600160a01b03831662001887576200188488828462002465565b92505b620018958989865f62002075565b6040516346154c9f60e11b81526001600160a01b03868116600483015260248201869052841690638c2a993e906044015f604051808303815f87803b158015620018dd575f80fd5b505af1158015620018f0573d5f803e3d5ffd5b5050505050505094509492505050565b6033546001600160a01b0316331462000a645760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640162000254565b620019666200248f565b6097805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b606580546001600160a01b031916905562000e1981620024da565b5f805f8351606014620019f157604051636f2605cb60e11b815260040160405180910390fd5b8380602001905181019062001a07919062003614565b9196909550909350915050565b5f805f62001a5786868080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250620019cb92505050565b919450925090506001600160a01b03811662001a8657505f83815260cb60205260409020546001600160a01b03165b6001600160a01b03811662001aae5760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381165f90815260cc602052604090205484811462001af257604051631294e9e160e01b8152600481018290526024810186905260440162000254565b5093509350939050565b606034801562001b1f5760405163536ec84b60e01b815260040160405180910390fd5b845f0362001b4057604051635e85ae7360e01b815260040160405180910390fd5b6040516374f4f54760e01b81526001600160a01b038781166004830152602482018790528416906374f4f547906044015f604051808303815f87803b15801562001b88575f80fd5b505af115801562001b9b573d5f803e3d5ffd5b5050505062001bad8888875f6200252b565b604080516001600160a01b0386811682526020820188905288169189918b917f1cd02155ad1064c60598a8bd0e4e795d7e7d0a0f3c38aad04d261f1297fb2545910160405180910390a45f87815260ca602052604081205460609181900362001c295760405163d92e233d60e01b815260040160405180910390fd5b62001c358582620011ca565b9150505f846001600160a01b03166313096a416040518163ffffffff1660e01b8152600401602060405180830381865afa15801562001c76573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062001c9c919062003659565b90506001600160a01b03811662001cc65760405163d92e233d60e01b815260040160405180910390fd5b62001cd58887838a8662002567565b9a9950505050505050505050565b6040516315f5329760e21b815260048101879052602481018490526001600160a01b0386811660448301526060915f917f000000000000000000000000f2a49545c5b1a85d2fb018cc39103661639a9b0616906357d4ca5c906064016020604051808303815f875af115801562001d5c573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062001d82919062003677565b905062001d95898989848989896200259e565b9998505050505050505050565b62001dac6200172c565b6097805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258620019933390565b60608080805f196001600160a01b0387160162001e845760405160200162001e239060208082526005908201526422ba3432b960d91b604082015260600190565b60408051601f198184030181528282526020838101526003918301919091526208aa8960eb1b6060830152935060800160408051601f198184030181528282526012602084015293500160405160208183030381529060405290506200205d565b60408051600481526024810182526020810180516001600160e01b03166306fdde0360e01b17905290515f916001600160a01b0389169162001ec7919062003698565b5f60405180830381855afa9150503d805f811462001f01576040519150601f19603f3d011682016040523d82523d5f602084013e62001f06565b606091505b50945090508062001f235760405180602001604052805f81525093505b60408051600481526024810182526020810180516001600160e01b03166395d89b4160e01b17905290516001600160a01b0389169162001f639162003698565b5f60405180830381855afa9150503d805f811462001f9d576040519150601f19603f3d011682016040523d82523d5f602084013e62001fa2565b606091505b50935090508062001fbf5760405180602001604052805f81525092505b60408051600481526024810182526020810180516001600160e01b031663313ce56760e01b17905290516001600160a01b0389169162001fff9162003698565b5f60405180830381855afa9150503d805f811462002039576040519150601f19603f3d011682016040523d82523d5f602084013e6200203e565b606091505b5092509050806200205b5760405180602001604052805f81525091505b505b6200206b858484846200277b565b9695505050505050565b62002082818486620027d4565b62001121575f84815260fb60209081526040808320868452909152902054821115620020c157604051634137d88f60e11b815260040160405180910390fd5b5f84815260fb6020908152604080832086845290915281208054849290620020eb90849062003379565b909155505050505050565b5f81815260ca60205260408120548015620021115792915050565b5f83815260cb60205260409020546001600160a01b03165f1981016200213a5750469392505050565b6040516370a0823160e01b81523060048201525f906001600160a01b038316906370a0823190602401602060405180830381865afa1580156200217f573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620021a5919062003337565b1115620021b55750469392505050565b6040516370a0823160e01b81526001600160a01b037f0000000000000000000000003e8b2fe58675126ed30d0d12dea2a9bda72d18ae811660048301525f91908316906370a0823190602401602060405180830381865afa1580156200221d573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062002243919062003337565b1115620022535750469392505050565b505f9392505050565b6040516001600160a01b03831660248201526044810182905262000bbb90849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152620027f5565b5f82826040516020016200170e9291909182526001600160a01b0316602082015260400190565b5f620011d8838330620028cf565b5f620023034683620016d6565b5f81815260cb6020908152604080832080546001600160a01b0319166001600160a01b0388811691821790925580855260cc845282852086905585855260ca909352928190204690555163548a5a3360e01b815260048101919091523060248201529192507f000000000000000000000000f2a49545c5b1a85d2fb018cc39103661639a9b06169063548a5a33906044015f604051808303815f87803b158015620023ac575f80fd5b505af1158015620023bf573d5f803e3d5ffd5b50505050919050565b5f805f80606085806020019051810190620023e49190620036b5565b939a9299509097509550909350915050565b7f6337a96bd2cd359fa0bae3bbedfca736753213c95037ae158c5fa7c048ae211284036200244f575f805f805f85885af19050806200244857604051631d42c86760e21b815260040160405180910390fd5b5062001121565b620011216001600160a01b03831684836200225c565b5f80620024738484620028f8565b90925090506200248781868686866200297a565b509392505050565b60975460ff1662000a645760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b604482015260640162000254565b603380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b62002538818486620027d4565b62001121575f84815260fb6020908152604080832086845290915281208054849290620020eb90849062003363565b60608585858585604051602001620025849594939291906200377b565b604051602081830303815290604052905095945050505050565b60607f0000000000000000000000007b79995e5f793a07bc00c21412e50ecae098e7f96001600160a01b0316826001600160a01b031603620025f357604051630154bec360e71b815260040160405180910390fd5b7f6337a96bd2cd359fa0bae3bbedfca736753213c95037ae158c5fa7c048ae211287036200265b573484146200264657604051630626ade360e41b81526004810185905234602482015260440162000254565b6200265588888660016200252b565b620026c3565b34156200267b5760405163536ec84b60e01b815260040160405180910390fd5b6200268a88888660016200252b565b84620026c3575f6200269e87848762002a1e565b9050808514620026c15760405163047061c560e31b815260040160405180910390fd5b505b835f03620026e4576040516395b66fe960e01b815260040160405180910390fd5b5f87815260ca602052604090205460609062002702908490620011ca565b905062002713878585888562002567565b9150866001600160a01b0316888a7f1cd02155ad1064c60598a8bd0e4e795d7e7d0a0f3c38aad04d261f1297fb25458789604051620027679291906001600160a01b03929092168252602082015260400190565b60405180910390a450979650505050505050565b6060600160f81b858585856040516020016200279b9493929190620037b7565b60408051601f1981840301815290829052620027bb9291602001620037fb565b6040516020818303038152906040529050949350505050565b5f83158015620014815750505f91825260ca60205260409091205414919050565b5f6200284b826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031662002b1d9092919063ffffffff16565b905080515f14806200286e5750808060200190518101906200286e919062003677565b62000bbb5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840162000254565b5f604051836040820152846020820152828152600b8101905060ff815360559020949350505050565b6040516301e9b52f60e21b81525f90819030906307a6d4bc906200292190869060040162003246565b602060405180830381865afa1580156200293d573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062002963919062003337565b9050620029718185620013eb565b91509250929050565b6200298785858562002b2d565b5f620029968686868662002b68565b9050816001600160a01b0316816001600160a01b031614620029df57604051631f73225f60e01b81526001600160a01b0380841660048301528216602482015260440162000254565b505f84815260cb6020908152604080832080546001600160a01b039095166001600160a01b03199095168517905592825260cc90522092909255505050565b6040516370a0823160e01b81523060048201525f9081906001600160a01b038516906370a0823190602401602060405180830381865afa15801562002a65573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062002a8b919062003337565b905062002aa46001600160a01b03851686308662002c25565b6040516370a0823160e01b81523060048201525f906001600160a01b038616906370a0823190602401602060405180830381865afa15801562002ae9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062002b0f919062003337565b90506200206b828262003379565b60606200148184845f8562002c5f565b5f62002b3a8483620016d6565b90508083146200112157604051631294e9e160e01b8152600481018290526024810184905260440162000254565b5f46850362002b8a5760405163138ee1a360e01b815260040160405180910390fd5b5f62002b978685620022c1565b90505f62002ba6828862002d3e565b6040516309a6ab8760e41b81529091506001600160a01b03821690639a6ab8709062002bdb908990899089906004016200382d565b5f604051808303815f87803b15801562002bf3575f80fd5b505af115801562002c06573d5f803e3d5ffd5b5050505f87815260ca6020526040902088905550915050949350505050565b6040516001600160a01b0380851660248301528316604482015260648101829052620011219085906323b872dd60e01b9060840162002289565b60608247101562002cc25760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b606482015260840162000254565b5f80866001600160a01b0316858760405162002cdf919062003698565b5f6040518083038185875af1925050503d805f811462002d1b576040519150601f19603f3d011682016040523d82523d5f602084013e62002d20565b606091505b509150915062002d338783838762002dc0565b979650505050505050565b5f80620014815f856040518060200162002d589062002f74565b601f1982820381018352601f90910116604081815260c9546001600160a01b03166020830152808201525f606082015260800160408051601f198184030181529082905262002dab9291602001620033b9565b60405160208183030381529060405262002e3f565b6060831562002e335782515f0362002e2b576001600160a01b0385163b62002e2b5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640162000254565b508162001481565b62001481838362002f47565b5f8347101562002e925760405162461bcd60e51b815260206004820152601d60248201527f437265617465323a20696e73756666696369656e742062616c616e6365000000604482015260640162000254565b81515f0362002ee45760405162461bcd60e51b815260206004820181905260248201527f437265617465323a2062797465636f6465206c656e677468206973207a65726f604482015260640162000254565b8282516020840186f590506001600160a01b038116620011d85760405162461bcd60e51b815260206004820152601960248201527f437265617465323a204661696c6564206f6e206465706c6f7900000000000000604482015260640162000254565b81511562002f585781518083602001fd5b8060405162461bcd60e51b815260040162000254919062003246565b6106a4806200386283390190565b5f8083601f84011262002f93575f80fd5b50813567ffffffffffffffff81111562002fab575f80fd5b60208301915083602082850101111562002fc3575f80fd5b9250929050565b5f806020838503121562002fdc575f80fd5b823567ffffffffffffffff81111562002ff3575f80fd5b620030018582860162002f82565b90969095509350505050565b6001600160a01b038116811462000e19575f80fd5b5f6020828403121562003033575f80fd5b8135620011d8816200300d565b5f806040838503121562003052575f80fd5b82356200305f816200300d565b946020939093013593505050565b5f80604083850312156200307f575f80fd5b50508035926020909101359150565b5f805f8060608587031215620030a2575f80fd5b8435935060208501359250604085013567ffffffffffffffff811115620030c7575f80fd5b620030d58782880162002f82565b95989497509550505050565b5f8060408385031215620030f3575f80fd5b823562003100816200300d565b9150602083013562003112816200300d565b809150509250929050565b5f805f6040848603121562003130575f80fd5b833567ffffffffffffffff81111562003147575f80fd5b620031558682870162002f82565b909790965060209590950135949350505050565b5f602082840312156200317a575f80fd5b5035919050565b5f805f805f8060a0878903121562003197575f80fd5b8635955060208701359450604087013593506060870135620031b9816200300d565b9250608087013567ffffffffffffffff811115620031d5575f80fd5b620031e389828a0162002f82565b979a9699509497509295939492505050565b5f5b8381101562003211578181015183820152602001620031f7565b50505f910152565b5f815180845262003232816020860160208601620031f5565b601f01601f19169290920160200192915050565b602081525f620011d8602083018462003219565b5f805f80608085870312156200326e575f80fd5b8435935060208501359250604085013562003289816200300d565b915060608501356200329b816200300d565b939692955090935050565b5f805f805f60808688031215620032bb575f80fd5b85359450602086013593506040860135620032d6816200300d565b9250606086013567ffffffffffffffff811115620032f2575f80fd5b620033008882890162002f82565b969995985093965092949392505050565b5f806040838503121562003323575f80fd5b82359150602083013562003112816200300d565b5f6020828403121562003348575f80fd5b5051919050565b634e487b7160e01b5f52601160045260245ffd5b808201808211156200077d576200077d6200334f565b818103818111156200077d576200077d6200334f565b6001600160a01b03818116838216019080821115620033b257620033b26200334f565b5092915050565b5f8351620033cc818460208801620031f5565b835190830190620033e2818360208801620031f5565b01949350505050565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff811182821017156200343f576200343f620033ff565b604052919050565b5f67ffffffffffffffff821115620034635762003463620033ff565b50601f01601f191660200190565b5f82601f83011262003481575f80fd5b813562003498620034928262003447565b62003413565b818152846020838601011115620034ad575f80fd5b816020850160208301375f918101602001919091529392505050565b5f805f60608486031215620034dc575f80fd5b833567ffffffffffffffff80821115620034f4575f80fd5b620035028783880162003471565b9450602086013591508082111562003518575f80fd5b620035268783880162003471565b935060408601359150808211156200353c575f80fd5b506200354b8682870162003471565b9150509250925092565b5f808585111562003564575f80fd5b8386111562003571575f80fd5b5050820193919092039150565b5f805f806080858703121562003592575f80fd5b84359350602085013567ffffffffffffffff80821115620035b1575f80fd5b620035bf8883890162003471565b94506040870135915080821115620035d5575f80fd5b620035e38883890162003471565b93506060870135915080821115620035f9575f80fd5b50620036088782880162003471565b91505092959194509250565b5f805f6060848603121562003627575f80fd5b8351925060208401516200363b816200300d565b60408501519092506200364e816200300d565b809150509250925092565b5f602082840312156200366a575f80fd5b8151620011d8816200300d565b5f6020828403121562003688575f80fd5b81518015158114620011d8575f80fd5b5f8251620036ab818460208701620031f5565b9190910192915050565b5f805f805f60a08688031215620036ca575f80fd5b8551620036d7816200300d565b6020870151909550620036ea816200300d565b6040870151909450620036fd816200300d565b60608701516080880151919450925067ffffffffffffffff81111562003721575f80fd5b8601601f8101881362003732575f80fd5b805162003743620034928262003447565b81815289602083850101111562003758575f80fd5b6200376b826020830160208601620031f5565b8093505050509295509295909350565b6001600160a01b0386811682528581166020830152841660408201526060810183905260a0608082018190525f9062002d339083018462003219565b848152608060208201525f620037d1608083018662003219565b8281036040840152620037e5818662003219565b9050828103606084015262002d33818562003219565b6001600160f81b03198316815281515f906200381f816001850160208701620031f5565b919091016001019392505050565b8381526001600160a01b03831660208201526060604082018190525f90620038589083018462003219565b9594505050505056fe60806040526040516106a43803806106a48339810160408190526100229161040f565b61002d82825f610034565b5050610530565b61003d836100f1565b6040516001600160a01b038416907f1cf3b03a6cf19fa2baba4df148e9dcabedea7f8a5c07840e207e5c089be95d3e905f90a25f8251118061007c5750805b156100ec576100ea836001600160a01b0316635c60da1b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156100c0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906100e491906104ca565b83610273565b505b505050565b6001600160a01b0381163b61015b5760405162461bcd60e51b815260206004820152602560248201527f455243313936373a206e657720626561636f6e206973206e6f74206120636f6e6044820152641d1c9858dd60da1b60648201526084015b60405180910390fd5b6101cd816001600160a01b0316635c60da1b6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561019a573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101be91906104ca565b6001600160a01b03163b151590565b6102325760405162461bcd60e51b815260206004820152603060248201527f455243313936373a20626561636f6e20696d706c656d656e746174696f6e206960448201526f1cc81b9bdd08184818dbdb9d1c9858dd60821b6064820152608401610152565b7fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d5080546001600160a01b0319166001600160a01b0392909216919091179055565b6060610298838360405180606001604052806027815260200161067d6027913961029f565b9392505050565b60605f80856001600160a01b0316856040516102bb91906104e3565b5f60405180830381855af49150503d805f81146102f3576040519150601f19603f3d011682016040523d82523d5f602084013e6102f8565b606091505b50909250905061030a86838387610314565b9695505050505050565b606083156103825782515f0361037b576001600160a01b0385163b61037b5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610152565b508161038c565b61038c8383610394565b949350505050565b8151156103a45781518083602001fd5b8060405162461bcd60e51b815260040161015291906104fe565b80516001600160a01b03811681146103d4575f80fd5b919050565b634e487b7160e01b5f52604160045260245ffd5b5f5b838110156104075781810151838201526020016103ef565b50505f910152565b5f8060408385031215610420575f80fd5b610429836103be565b60208401519092506001600160401b0380821115610445575f80fd5b818501915085601f830112610458575f80fd5b81518181111561046a5761046a6103d9565b604051601f8201601f19908116603f01168101908382118183101715610492576104926103d9565b816040528281528860208487010111156104aa575f80fd5b6104bb8360208301602088016103ed565b80955050505050509250929050565b5f602082840312156104da575f80fd5b610298826103be565b5f82516104f48184602087016103ed565b9190910192915050565b602081525f825180602084015261051c8160408501602087016103ed565b601f01601f19169190910160400192915050565b6101408061053d5f395ff3fe60806040523661001357610011610017565b005b6100115b610027610022610029565b6100bf565b565b5f61005b7fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50546001600160a01b031690565b6001600160a01b0316635c60da1b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610096573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906100ba91906100dd565b905090565b365f80375f80365f845af43d5f803e8080156100d9573d5ff35b3d5ffd5b5f602082840312156100ed575f80fd5b81516001600160a01b0381168114610103575f80fd5b939250505056fea2646970667358221220f34315cff80d474f91e1ca66689812949f1c11332a32885e4431682e6471076364736f6c63430008180033416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a264697066735822122029475d5c9d524e530a5d9cf5fc3220660113f9710d56a57ede1140eaead6dafc64736f6c63430008180033
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
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.