ETH Price: $2,548.92 (-4.49%)

Transaction Decoder

Block:
17951481 at Aug-19-2023 09:24:59 PM +UTC
Transaction Fee:
0.002417435247035403 ETH $6.16
Gas Used:
193,977 Gas / 12.462483939 Gwei

Account State Difference:

  Address   Before After State Difference Code
0x64627c96...39Bc6A55a
0.013211047832259047 Eth
Nonce: 54
0.010793612585223644 Eth
Nonce: 55
0.002417435247035403
(beaverbuild)
18.232637202675241751 Eth18.232646901525241751 Eth0.00000969885

Execution Trace

ETH 0.008 MetaBridge.bridge( adapterId=lifiAdapter, srcToken=0x0000000000000000000000000000000000000000, amount=8000000000000000, data=0x0000000000000000000000006EF81A18E1E432C289DC0D1A670B78E8BBF9AA350000000000000000000000006EF81A18E1E432C289DC0D1A670B78E8BBF9AA35000000000000000000000000000000000000000000000000000000000000000A00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001C2C4B0111A000000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000003FAA25226000000000000000000000000000E6B738DA243E8FA2A0ED5915645789ADD5DE5152000000000000000000000000000000000000000000000000000000000000006C1223354CA012C85624458CF964627C96AB9D0A24B8BAA3F53336CBB39BC6A55A0000000A0000000000000000001C081639A90653710BDA329B2A6224E4B44833DE30F38E7F81D56400000000000000000000000000000000B8901ACB165ED027E32754E0FFE830802919727F0000000000000000000000000000000000000000 )
  • ETH 0.008 0xe6e3f947ccd0add1effde3bf3d210e5d711beace.4cfee326( )
    • ETH 0.008 0x04c76710f64ab714bbf803f011a132481084a131.ab138240( )
      • ETH 0.00007 GnosisSafeProxy.CALL( )
        • ETH 0.00007 GnosisSafe.DELEGATECALL( )
        • ETH 0.00793 HopFacetPacked.startBridgeTokensViaHopL1NativePacked( )
          • ETH 0.00793 L1_ETH_Bridge.sendToL2( chainId=10, recipient=0x64627c96aB9d0a24B8bAA3F53336cbb39Bc6A55a, amount=7930000000000000, amountOutMin=7890190897579603, deadline=1693085099, relayer=0x710bDa329b2a6224E4B44833DE30F38E7f81d564, relayerFee=0 )
            • OptimismMessengerWrapper.sendCrossDomainMessage( _calldata=0xCC29A30600000000000000000000000064627C96AB9D0A24B8BAA3F53336CBB39BC6A55A000000000000000000000000000000000000000000000000001C2C4B0111A000000000000000000000000000000000000000000000000000001C081639A906530000000000000000000000000000000000000000000000000000000064EA6DAB000000000000000000000000710BDA329B2A6224E4B44833DE30F38E7F81D5640000000000000000000000000000000000000000000000000000000000000000 )
              • Lib_ResolvedDelegateProxy.3dbb202b( )
                File 1 of 7: MetaBridge
                pragma solidity ^0.8.0;
                import "@openzeppelin/contracts/access/Ownable.sol";
                import "@openzeppelin/contracts/security/Pausable.sol";
                import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
                import "@openzeppelin/contracts/utils/Address.sol";
                import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
                import {IAdapter, IBridge, ISpender} from "contracts/interfaces/Exports.sol";
                import {Constants} from "contracts/utils/Exports.sol";
                import "./Spender.sol";
                contract MetaBridge is IBridge, Ownable, Pausable, ReentrancyGuard {
                    using SafeERC20 for IERC20;
                    using Address for address;
                    ISpender public immutable spender;
                    // Mapping of adapterId to adapter
                    mapping(string => address) public adapters;
                    mapping(string => bool) public adapterRemoved;
                    constructor() {
                        spender = new Spender();
                    }
                    /**
                     * @notice Sets the adapter for an aggregator. It can't be changed later.
                     * @param adapterId Aggregator's identifier
                     * @param adapterAddress Address of the contract that contains the logic for this aggregator
                     */
                    function setAdapter(string calldata adapterId, address adapterAddress)
                        external
                        override
                        onlyOwner
                    {
                        require(adapterAddress.isContract(), "ADAPTER_IS_NOT_A_CONTRACT");
                        require(!adapterRemoved[adapterId], "ADAPTER_REMOVED");
                        require(adapters[adapterId] == address(0), "ADAPTER_EXISTS");
                        require(bytes(adapterId).length > 0, "INVALID_ADAPTED_ID");
                        adapters[adapterId] = adapterAddress;
                        emit AdapterSet(adapterId, adapterAddress);
                    }
                    /**
                     * @notice Removes the adapter for an existing aggregator. This can't be undone.
                     * @param adapterId Adapter's identifier
                     */
                    function removeAdapter(string calldata adapterId)
                        external
                        override
                        onlyOwner
                    {
                        require(adapters[adapterId] != address(0), "ADAPTER_DOES_NOT_EXIST");
                        delete adapters[adapterId];
                        adapterRemoved[adapterId] = true;
                        emit AdapterRemoved(adapterId);
                    }
                    /**
                     * @notice Performs a bridge
                     * @param adapterId Identifier of the aggregator to be used for the bridge
                     * @param srcToken Identifier of the source chain
                     * @param amount Amount of tokens to be transferred from the destination chain
                     * @param data Dynamic data which is passed in to the delegatecall made to the adapter
                     */
                    function bridge(
                        string calldata adapterId,
                        address srcToken,
                        uint256 amount,
                        bytes calldata data
                    ) external payable override whenNotPaused nonReentrant {
                        address adapter = adapters[adapterId];
                        require(adapter != address(0), "ADAPTER_NOT_FOUND");
                        // Move ERC20 funds to the spender
                        if (srcToken != Constants.NATIVE_TOKEN) {
                            require(msg.value == 0, "NATIVE_ASSET_SENT");
                            IERC20(srcToken).safeTransferFrom(
                                msg.sender,
                                address(spender),
                                amount
                            );
                        } else {
                            require(msg.value == amount, "MSGVALUE_AMOUNT_MISMATCH");
                        }
                        spender.bridge{value: msg.value}(
                            adapter,
                            abi.encodePacked(
                                // bridge signature
                                IAdapter.bridge.selector,
                                abi.encode(msg.sender),
                                data
                            )
                        );
                    }
                    /**
                     * @notice Prevents the bridge function from being executed until the contract is unpaused.
                     */
                    function pauseBridge() external onlyOwner {
                        _pause();
                    }
                    /**
                     * @notice Unpauses the contract to make the bridge function callable by owner.
                     */
                    function unpauseBridge() external onlyOwner {
                        _unpause();
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts v4.4.1 (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 Returns the address of the current owner.
                     */
                    function owner() public view virtual returns (address) {
                        return _owner;
                    }
                    /**
                     * @dev Throws if called by any account other than the owner.
                     */
                    modifier onlyOwner() {
                        require(owner() == _msgSender(), "Ownable: caller is not the owner");
                        _;
                    }
                    /**
                     * @dev Leaves the contract without owner. It will not be possible to call
                     * `onlyOwner` functions anymore. Can only be called by the current owner.
                     *
                     * NOTE: Renouncing ownership will leave the contract without an owner,
                     * thereby removing 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 v4.4.1 (security/Pausable.sol)
                pragma solidity ^0.8.0;
                import "../utils/Context.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 Pausable is Context {
                    /**
                     * @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.
                     */
                    constructor() {
                        _paused = false;
                    }
                    /**
                     * @dev Returns true if the contract is paused, and false otherwise.
                     */
                    function paused() public view virtual returns (bool) {
                        return _paused;
                    }
                    /**
                     * @dev Modifier to make a function callable only when the contract is not paused.
                     *
                     * Requirements:
                     *
                     * - The contract must not be paused.
                     */
                    modifier whenNotPaused() {
                        require(!paused(), "Pausable: paused");
                        _;
                    }
                    /**
                     * @dev Modifier to make a function callable only when the contract is paused.
                     *
                     * Requirements:
                     *
                     * - The contract must be paused.
                     */
                    modifier whenPaused() {
                        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());
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
                pragma solidity ^0.8.0;
                /**
                 * @dev Contract module that helps prevent reentrant calls to a function.
                 *
                 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
                 * available, which can be applied to functions to make sure there are no nested
                 * (reentrant) calls to them.
                 *
                 * Note that because there is a single `nonReentrant` guard, functions marked as
                 * `nonReentrant` may not call one another. This can be worked around by making
                 * those functions `private`, and then adding `external` `nonReentrant` entry
                 * points to them.
                 *
                 * TIP: If you would like to learn more about reentrancy and alternative ways
                 * to protect against it, check out our blog post
                 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
                 */
                abstract contract ReentrancyGuard {
                    // Booleans are more expensive than uint256 or any type that takes up a full
                    // word because each write operation emits an extra SLOAD to first read the
                    // slot's contents, replace the bits taken up by the boolean, and then write
                    // back. This is the compiler's defense against contract upgrades and
                    // pointer aliasing, and it cannot be disabled.
                    // The values being non-zero value makes deployment a bit more expensive,
                    // but in exchange the refund on every call to nonReentrant will be lower in
                    // amount. Since refunds are capped to a percentage of the total
                    // transaction's gas, it is best to keep them low in cases like this one, to
                    // increase the likelihood of the full refund coming into effect.
                    uint256 private constant _NOT_ENTERED = 1;
                    uint256 private constant _ENTERED = 2;
                    uint256 private _status;
                    constructor() {
                        _status = _NOT_ENTERED;
                    }
                    /**
                     * @dev Prevents a contract from calling itself, directly or indirectly.
                     * Calling a `nonReentrant` function from another `nonReentrant`
                     * function is not supported. It is possible to prevent this from happening
                     * by making the `nonReentrant` function external, and making it call a
                     * `private` function that does the actual work.
                     */
                    modifier nonReentrant() {
                        // On the first call to nonReentrant, _notEntered will be true
                        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                        // Any calls to nonReentrant after this point will fail
                        _status = _ENTERED;
                        _;
                        // By storing the original value once again, a refund is triggered (see
                        // https://eips.ethereum.org/EIPS/eip-2200)
                        _status = _NOT_ENTERED;
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.5.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
                     * ====
                     *
                     * [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://diligence.consensys.net/posts/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.5.11/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 functionCall(target, data, "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");
                        require(isContract(target), "Address: call to non-contract");
                        (bool success, bytes memory returndata) = target.call{value: value}(data);
                        return verifyCallResult(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) {
                        require(isContract(target), "Address: static call to non-contract");
                        (bool success, bytes memory returndata) = target.staticcall(data);
                        return verifyCallResult(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) {
                        require(isContract(target), "Address: delegate call to non-contract");
                        (bool success, bytes memory returndata) = target.delegatecall(data);
                        return verifyCallResult(success, returndata, errorMessage);
                    }
                    /**
                     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
                     * revert reason 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 {
                            // 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
                                assembly {
                                    let returndata_size := mload(returndata)
                                    revert(add(32, returndata), returndata_size)
                                }
                            } else {
                                revert(errorMessage);
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
                pragma solidity ^0.8.0;
                /**
                 * @dev Interface of the ERC20 standard as defined in the EIP.
                 */
                interface IERC20 {
                    /**
                     * @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);
                    /**
                     * @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);
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
                pragma solidity ^0.8.0;
                import "../IERC20.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;
                    function safeTransfer(
                        IERC20 token,
                        address to,
                        uint256 value
                    ) internal {
                        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                    }
                    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));
                    }
                    function safeIncreaseAllowance(
                        IERC20 token,
                        address spender,
                        uint256 value
                    ) internal {
                        uint256 newAllowance = token.allowance(address(this), spender) + value;
                        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                    }
                    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");
                            uint256 newAllowance = oldAllowance - value;
                            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                        }
                    }
                    /**
                     * @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");
                        if (returndata.length > 0) {
                            // Return data is optional
                            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                        }
                    }
                }
                pragma solidity ^0.8.0;
                import { IAdapter } from "./IAdapter.sol";
                import { IBridge } from "./IBridge.sol";
                import { ISpender } from "./ISpender.sol";pragma solidity ^0.8.0;
                import { Constants } from "./Constants.sol";pragma solidity ^0.8.0;
                import "@openzeppelin/contracts/utils/Address.sol";
                import {IBridge, ISpender} from "contracts/interfaces/Exports.sol";
                contract Spender is ISpender {
                    using Address for address;
                    IBridge public immutable metabridge;
                    constructor() public {
                        metabridge = IBridge(msg.sender);
                    }
                    /**
                     * @notice Performs a bridge
                     * @param adapter Address of the aggregator to be used for the bridge
                     * @param data Dynamic data which is passed in to the delegatecall made to the adapter
                     */
                    function bridge(address adapter, bytes calldata data)
                        external
                        payable
                        override
                    {
                        require(msg.sender == address(metabridge), "FORBIDDEN");
                        adapter.functionDelegateCall(data, "ADAPTER_DELEGATECALL_FAILED");
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
                pragma solidity ^0.8.0;
                /**
                 * @dev Provides information about the current execution context, including the
                 * sender of the transaction and its data. While these are generally available
                 * via msg.sender and msg.data, they should not be accessed in such a direct
                 * manner, since when dealing with meta-transactions the account sending and
                 * paying for execution may not be the actual sender (as far as an application
                 * is concerned).
                 *
                 * This contract is only required for intermediate, library-like contracts.
                 */
                abstract contract Context {
                    function _msgSender() internal view virtual returns (address) {
                        return msg.sender;
                    }
                    function _msgData() internal view virtual returns (bytes calldata) {
                        return msg.data;
                    }
                }
                pragma solidity ^0.8.0;
                interface IAdapter {
                    event Bridge(
                        address recipient,
                        address aggregator,
                        uint256 destChain,
                        address srcToken,
                        address destToken,
                        uint256 srcAmount
                    );
                    event Fee(address srcToken, address feeWallet, uint256 fee);
                    function bridge(
                        address recipient,
                        address aggregator,
                        address spender,
                        uint256 destChain,
                        address srcToken,
                        address destToken,
                        uint256 srcAmount,
                        bytes calldata data,
                        uint256 fee,
                        address payable feeWallet
                    ) external payable;
                }
                pragma solidity ^0.8.0;
                interface IBridge {
                    event AdapterSet(
                        string adapterId,
                        address addr
                    );
                    event AdapterRemoved(string adapterId);
                    function setAdapter(string calldata adapterId, address adapterAddress) external;
                    function removeAdapter(string calldata adapterId) external;
                    function bridge(
                        string calldata adapterId,
                        address tokenFrom,
                        uint256 amount,
                        bytes calldata data
                    ) external payable;
                }pragma solidity ^0.8.0;
                interface ISpender {
                    function bridge(address adapterAddress, bytes calldata data) external payable;
                }pragma solidity ^0.8.0;
                library Constants {
                    address internal constant NATIVE_TOKEN = 0x0000000000000000000000000000000000000000;
                }
                

                File 2 of 7: GnosisSafeProxy
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity >=0.7.0 <0.9.0;
                
                /// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
                /// @author Richard Meissner - <[email protected]>
                interface IProxy {
                    function masterCopy() external view returns (address);
                }
                
                /// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
                /// @author Stefan George - <[email protected]>
                /// @author Richard Meissner - <[email protected]>
                contract GnosisSafeProxy {
                    // singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
                    // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
                    address internal singleton;
                
                    /// @dev Constructor function sets address of singleton contract.
                    /// @param _singleton Singleton address.
                    constructor(address _singleton) {
                        require(_singleton != address(0), "Invalid singleton address provided");
                        singleton = _singleton;
                    }
                
                    /// @dev Fallback function forwards all transactions and returns all received return data.
                    fallback() external payable {
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
                            // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
                            if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
                                mstore(0, _singleton)
                                return(0, 0x20)
                            }
                            calldatacopy(0, 0, calldatasize())
                            let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
                            returndatacopy(0, 0, returndatasize())
                            if eq(success, 0) {
                                revert(0, returndatasize())
                            }
                            return(0, returndatasize())
                        }
                    }
                }
                
                /// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
                /// @author Stefan George - <[email protected]>
                contract GnosisSafeProxyFactory {
                    event ProxyCreation(GnosisSafeProxy proxy, address singleton);
                
                    /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
                    /// @param singleton Address of singleton contract.
                    /// @param data Payload for message call sent to new proxy contract.
                    function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
                        proxy = new GnosisSafeProxy(singleton);
                        if (data.length > 0)
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
                                    revert(0, 0)
                                }
                            }
                        emit ProxyCreation(proxy, singleton);
                    }
                
                    /// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
                    function proxyRuntimeCode() public pure returns (bytes memory) {
                        return type(GnosisSafeProxy).runtimeCode;
                    }
                
                    /// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
                    function proxyCreationCode() public pure returns (bytes memory) {
                        return type(GnosisSafeProxy).creationCode;
                    }
                
                    /// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
                    ///      This method is only meant as an utility to be called from other methods
                    /// @param _singleton Address of singleton contract.
                    /// @param initializer Payload for message call sent to new proxy contract.
                    /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                    function deployProxyWithNonce(
                        address _singleton,
                        bytes memory initializer,
                        uint256 saltNonce
                    ) internal returns (GnosisSafeProxy proxy) {
                        // If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
                        bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
                        bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
                        }
                        require(address(proxy) != address(0), "Create2 call failed");
                    }
                
                    /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
                    /// @param _singleton Address of singleton contract.
                    /// @param initializer Payload for message call sent to new proxy contract.
                    /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                    function createProxyWithNonce(
                        address _singleton,
                        bytes memory initializer,
                        uint256 saltNonce
                    ) public returns (GnosisSafeProxy proxy) {
                        proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
                        if (initializer.length > 0)
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
                                    revert(0, 0)
                                }
                            }
                        emit ProxyCreation(proxy, _singleton);
                    }
                
                    /// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
                    /// @param _singleton Address of singleton contract.
                    /// @param initializer Payload for message call sent to new proxy contract.
                    /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                    /// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
                    function createProxyWithCallback(
                        address _singleton,
                        bytes memory initializer,
                        uint256 saltNonce,
                        IProxyCreationCallback callback
                    ) public returns (GnosisSafeProxy proxy) {
                        uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
                        proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
                        if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
                    }
                
                    /// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
                    ///      This method is only meant for address calculation purpose when you use an initializer that would revert,
                    ///      therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
                    /// @param _singleton Address of singleton contract.
                    /// @param initializer Payload for message call sent to new proxy contract.
                    /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                    function calculateCreateProxyWithNonceAddress(
                        address _singleton,
                        bytes calldata initializer,
                        uint256 saltNonce
                    ) external returns (GnosisSafeProxy proxy) {
                        proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
                        revert(string(abi.encodePacked(proxy)));
                    }
                }
                
                interface IProxyCreationCallback {
                    function proxyCreated(
                        GnosisSafeProxy proxy,
                        address _singleton,
                        bytes calldata initializer,
                        uint256 saltNonce
                    ) external;
                }

                File 3 of 7: GnosisSafe
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity >=0.7.0 <0.9.0;
                import "./base/ModuleManager.sol";
                import "./base/OwnerManager.sol";
                import "./base/FallbackManager.sol";
                import "./base/GuardManager.sol";
                import "./common/EtherPaymentFallback.sol";
                import "./common/Singleton.sol";
                import "./common/SignatureDecoder.sol";
                import "./common/SecuredTokenTransfer.sol";
                import "./common/StorageAccessible.sol";
                import "./interfaces/ISignatureValidator.sol";
                import "./external/GnosisSafeMath.sol";
                /// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191.
                /// @author Stefan George - <[email protected]>
                /// @author Richard Meissner - <[email protected]>
                contract GnosisSafe is
                    EtherPaymentFallback,
                    Singleton,
                    ModuleManager,
                    OwnerManager,
                    SignatureDecoder,
                    SecuredTokenTransfer,
                    ISignatureValidatorConstants,
                    FallbackManager,
                    StorageAccessible,
                    GuardManager
                {
                    using GnosisSafeMath for uint256;
                    string public constant VERSION = "1.3.0";
                    // keccak256(
                    //     "EIP712Domain(uint256 chainId,address verifyingContract)"
                    // );
                    bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;
                    // keccak256(
                    //     "SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)"
                    // );
                    bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8;
                    event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler);
                    event ApproveHash(bytes32 indexed approvedHash, address indexed owner);
                    event SignMsg(bytes32 indexed msgHash);
                    event ExecutionFailure(bytes32 txHash, uint256 payment);
                    event ExecutionSuccess(bytes32 txHash, uint256 payment);
                    uint256 public nonce;
                    bytes32 private _deprecatedDomainSeparator;
                    // Mapping to keep track of all message hashes that have been approve by ALL REQUIRED owners
                    mapping(bytes32 => uint256) public signedMessages;
                    // Mapping to keep track of all hashes (message or transaction) that have been approve by ANY owners
                    mapping(address => mapping(bytes32 => uint256)) public approvedHashes;
                    // This constructor ensures that this contract can only be used as a master copy for Proxy contracts
                    constructor() {
                        // By setting the threshold it is not possible to call setup anymore,
                        // so we create a Safe with 0 owners and threshold 1.
                        // This is an unusable Safe, perfect for the singleton
                        threshold = 1;
                    }
                    /// @dev Setup function sets initial storage of contract.
                    /// @param _owners List of Safe owners.
                    /// @param _threshold Number of required confirmations for a Safe transaction.
                    /// @param to Contract address for optional delegate call.
                    /// @param data Data payload for optional delegate call.
                    /// @param fallbackHandler Handler for fallback calls to this contract
                    /// @param paymentToken Token that should be used for the payment (0 is ETH)
                    /// @param payment Value that should be paid
                    /// @param paymentReceiver Adddress that should receive the payment (or 0 if tx.origin)
                    function setup(
                        address[] calldata _owners,
                        uint256 _threshold,
                        address to,
                        bytes calldata data,
                        address fallbackHandler,
                        address paymentToken,
                        uint256 payment,
                        address payable paymentReceiver
                    ) external {
                        // setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice
                        setupOwners(_owners, _threshold);
                        if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler);
                        // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules
                        setupModules(to, data);
                        if (payment > 0) {
                            // To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself)
                            // baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment
                            handlePayment(payment, 0, 1, paymentToken, paymentReceiver);
                        }
                        emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler);
                    }
                    /// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction.
                    ///      Note: The fees are always transferred, even if the user transaction fails.
                    /// @param to Destination address of Safe transaction.
                    /// @param value Ether value of Safe transaction.
                    /// @param data Data payload of Safe transaction.
                    /// @param operation Operation type of Safe transaction.
                    /// @param safeTxGas Gas that should be used for the Safe transaction.
                    /// @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
                    /// @param gasPrice Gas price that should be used for the payment calculation.
                    /// @param gasToken Token address (or 0 if ETH) that is used for the payment.
                    /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
                    /// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v})
                    function execTransaction(
                        address to,
                        uint256 value,
                        bytes calldata data,
                        Enum.Operation operation,
                        uint256 safeTxGas,
                        uint256 baseGas,
                        uint256 gasPrice,
                        address gasToken,
                        address payable refundReceiver,
                        bytes memory signatures
                    ) public payable virtual returns (bool success) {
                        bytes32 txHash;
                        // Use scope here to limit variable lifetime and prevent `stack too deep` errors
                        {
                            bytes memory txHashData =
                                encodeTransactionData(
                                    // Transaction info
                                    to,
                                    value,
                                    data,
                                    operation,
                                    safeTxGas,
                                    // Payment info
                                    baseGas,
                                    gasPrice,
                                    gasToken,
                                    refundReceiver,
                                    // Signature info
                                    nonce
                                );
                            // Increase nonce and execute transaction.
                            nonce++;
                            txHash = keccak256(txHashData);
                            checkSignatures(txHash, txHashData, signatures);
                        }
                        address guard = getGuard();
                        {
                            if (guard != address(0)) {
                                Guard(guard).checkTransaction(
                                    // Transaction info
                                    to,
                                    value,
                                    data,
                                    operation,
                                    safeTxGas,
                                    // Payment info
                                    baseGas,
                                    gasPrice,
                                    gasToken,
                                    refundReceiver,
                                    // Signature info
                                    signatures,
                                    msg.sender
                                );
                            }
                        }
                        // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500)
                        // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150
                        require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, "GS010");
                        // Use scope here to limit variable lifetime and prevent `stack too deep` errors
                        {
                            uint256 gasUsed = gasleft();
                            // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas)
                            // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas
                            success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas);
                            gasUsed = gasUsed.sub(gasleft());
                            // If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful
                            // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert
                            require(success || safeTxGas != 0 || gasPrice != 0, "GS013");
                            // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls
                            uint256 payment = 0;
                            if (gasPrice > 0) {
                                payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver);
                            }
                            if (success) emit ExecutionSuccess(txHash, payment);
                            else emit ExecutionFailure(txHash, payment);
                        }
                        {
                            if (guard != address(0)) {
                                Guard(guard).checkAfterExecution(txHash, success);
                            }
                        }
                    }
                    function handlePayment(
                        uint256 gasUsed,
                        uint256 baseGas,
                        uint256 gasPrice,
                        address gasToken,
                        address payable refundReceiver
                    ) private returns (uint256 payment) {
                        // solhint-disable-next-line avoid-tx-origin
                        address payable receiver = refundReceiver == address(0) ? payable(tx.origin) : refundReceiver;
                        if (gasToken == address(0)) {
                            // For ETH we will only adjust the gas price to not be higher than the actual used gas price
                            payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice);
                            require(receiver.send(payment), "GS011");
                        } else {
                            payment = gasUsed.add(baseGas).mul(gasPrice);
                            require(transferToken(gasToken, receiver, payment), "GS012");
                        }
                    }
                    /**
                     * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
                     * @param dataHash Hash of the data (could be either a message hash or transaction hash)
                     * @param data That should be signed (this is passed to an external validator contract)
                     * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
                     */
                    function checkSignatures(
                        bytes32 dataHash,
                        bytes memory data,
                        bytes memory signatures
                    ) public view {
                        // Load threshold to avoid multiple storage loads
                        uint256 _threshold = threshold;
                        // Check that a threshold is set
                        require(_threshold > 0, "GS001");
                        checkNSignatures(dataHash, data, signatures, _threshold);
                    }
                    /**
                     * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
                     * @param dataHash Hash of the data (could be either a message hash or transaction hash)
                     * @param data That should be signed (this is passed to an external validator contract)
                     * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
                     * @param requiredSignatures Amount of required valid signatures.
                     */
                    function checkNSignatures(
                        bytes32 dataHash,
                        bytes memory data,
                        bytes memory signatures,
                        uint256 requiredSignatures
                    ) public view {
                        // Check that the provided signature data is not too short
                        require(signatures.length >= requiredSignatures.mul(65), "GS020");
                        // There cannot be an owner with address 0.
                        address lastOwner = address(0);
                        address currentOwner;
                        uint8 v;
                        bytes32 r;
                        bytes32 s;
                        uint256 i;
                        for (i = 0; i < requiredSignatures; i++) {
                            (v, r, s) = signatureSplit(signatures, i);
                            if (v == 0) {
                                // If v is 0 then it is a contract signature
                                // When handling contract signatures the address of the contract is encoded into r
                                currentOwner = address(uint160(uint256(r)));
                                // Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes
                                // This check is not completely accurate, since it is possible that more signatures than the threshold are send.
                                // Here we only check that the pointer is not pointing inside the part that is being processed
                                require(uint256(s) >= requiredSignatures.mul(65), "GS021");
                                // Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes)
                                require(uint256(s).add(32) <= signatures.length, "GS022");
                                // Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length
                                uint256 contractSignatureLen;
                                // solhint-disable-next-line no-inline-assembly
                                assembly {
                                    contractSignatureLen := mload(add(add(signatures, s), 0x20))
                                }
                                require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, "GS023");
                                // Check signature
                                bytes memory contractSignature;
                                // solhint-disable-next-line no-inline-assembly
                                assembly {
                                    // The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s
                                    contractSignature := add(add(signatures, s), 0x20)
                                }
                                require(ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, "GS024");
                            } else if (v == 1) {
                                // If v is 1 then it is an approved hash
                                // When handling approved hashes the address of the approver is encoded into r
                                currentOwner = address(uint160(uint256(r)));
                                // Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction
                                require(msg.sender == currentOwner || approvedHashes[currentOwner][dataHash] != 0, "GS025");
                            } else if (v > 30) {
                                // If v > 30 then default va (27,28) has been adjusted for eth_sign flow
                                // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover
                                currentOwner = ecrecover(keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
                32", dataHash)), v - 4, r, s);
                            } else {
                                // Default is the ecrecover flow with the provided data hash
                                // Use ecrecover with the messageHash for EOA signatures
                                currentOwner = ecrecover(dataHash, v, r, s);
                            }
                            require(currentOwner > lastOwner && owners[currentOwner] != address(0) && currentOwner != SENTINEL_OWNERS, "GS026");
                            lastOwner = currentOwner;
                        }
                    }
                    /// @dev Allows to estimate a Safe transaction.
                    ///      This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data.
                    ///      Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction`
                    /// @param to Destination address of Safe transaction.
                    /// @param value Ether value of Safe transaction.
                    /// @param data Data payload of Safe transaction.
                    /// @param operation Operation type of Safe transaction.
                    /// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs).
                    /// @notice Deprecated in favor of common/StorageAccessible.sol and will be removed in next version.
                    function requiredTxGas(
                        address to,
                        uint256 value,
                        bytes calldata data,
                        Enum.Operation operation
                    ) external returns (uint256) {
                        uint256 startGas = gasleft();
                        // We don't provide an error message here, as we use it to return the estimate
                        require(execute(to, value, data, operation, gasleft()));
                        uint256 requiredGas = startGas - gasleft();
                        // Convert response to string and return via error message
                        revert(string(abi.encodePacked(requiredGas)));
                    }
                    /**
                     * @dev Marks a hash as approved. This can be used to validate a hash that is used by a signature.
                     * @param hashToApprove The hash that should be marked as approved for signatures that are verified by this contract.
                     */
                    function approveHash(bytes32 hashToApprove) external {
                        require(owners[msg.sender] != address(0), "GS030");
                        approvedHashes[msg.sender][hashToApprove] = 1;
                        emit ApproveHash(hashToApprove, msg.sender);
                    }
                    /// @dev Returns the chain id used by this contract.
                    function getChainId() public view returns (uint256) {
                        uint256 id;
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            id := chainid()
                        }
                        return id;
                    }
                    function domainSeparator() public view returns (bytes32) {
                        return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, getChainId(), this));
                    }
                    /// @dev Returns the bytes that are hashed to be signed by owners.
                    /// @param to Destination address.
                    /// @param value Ether value.
                    /// @param data Data payload.
                    /// @param operation Operation type.
                    /// @param safeTxGas Gas that should be used for the safe transaction.
                    /// @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
                    /// @param gasPrice Maximum gas price that should be used for this transaction.
                    /// @param gasToken Token address (or 0 if ETH) that is used for the payment.
                    /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
                    /// @param _nonce Transaction nonce.
                    /// @return Transaction hash bytes.
                    function encodeTransactionData(
                        address to,
                        uint256 value,
                        bytes calldata data,
                        Enum.Operation operation,
                        uint256 safeTxGas,
                        uint256 baseGas,
                        uint256 gasPrice,
                        address gasToken,
                        address refundReceiver,
                        uint256 _nonce
                    ) public view returns (bytes memory) {
                        bytes32 safeTxHash =
                            keccak256(
                                abi.encode(
                                    SAFE_TX_TYPEHASH,
                                    to,
                                    value,
                                    keccak256(data),
                                    operation,
                                    safeTxGas,
                                    baseGas,
                                    gasPrice,
                                    gasToken,
                                    refundReceiver,
                                    _nonce
                                )
                            );
                        return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash);
                    }
                    /// @dev Returns hash to be signed by owners.
                    /// @param to Destination address.
                    /// @param value Ether value.
                    /// @param data Data payload.
                    /// @param operation Operation type.
                    /// @param safeTxGas Fas that should be used for the safe transaction.
                    /// @param baseGas Gas costs for data used to trigger the safe transaction.
                    /// @param gasPrice Maximum gas price that should be used for this transaction.
                    /// @param gasToken Token address (or 0 if ETH) that is used for the payment.
                    /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
                    /// @param _nonce Transaction nonce.
                    /// @return Transaction hash.
                    function getTransactionHash(
                        address to,
                        uint256 value,
                        bytes calldata data,
                        Enum.Operation operation,
                        uint256 safeTxGas,
                        uint256 baseGas,
                        uint256 gasPrice,
                        address gasToken,
                        address refundReceiver,
                        uint256 _nonce
                    ) public view returns (bytes32) {
                        return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce));
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity >=0.7.0 <0.9.0;
                import "../common/Enum.sol";
                /// @title Executor - A contract that can execute transactions
                /// @author Richard Meissner - <[email protected]>
                contract Executor {
                    function execute(
                        address to,
                        uint256 value,
                        bytes memory data,
                        Enum.Operation operation,
                        uint256 txGas
                    ) internal returns (bool success) {
                        if (operation == Enum.Operation.DelegateCall) {
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0)
                            }
                        } else {
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0)
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity >=0.7.0 <0.9.0;
                import "../common/SelfAuthorized.sol";
                /// @title Fallback Manager - A contract that manages fallback calls made to this contract
                /// @author Richard Meissner - <[email protected]>
                contract FallbackManager is SelfAuthorized {
                    event ChangedFallbackHandler(address handler);
                    // keccak256("fallback_manager.handler.address")
                    bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5;
                    function internalSetFallbackHandler(address handler) internal {
                        bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            sstore(slot, handler)
                        }
                    }
                    /// @dev Allows to add a contract to handle fallback calls.
                    ///      Only fallback calls without value and with data will be forwarded.
                    ///      This can only be done via a Safe transaction.
                    /// @param handler contract to handle fallbacks calls.
                    function setFallbackHandler(address handler) public authorized {
                        internalSetFallbackHandler(handler);
                        emit ChangedFallbackHandler(handler);
                    }
                    // solhint-disable-next-line payable-fallback,no-complex-fallback
                    fallback() external {
                        bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            let handler := sload(slot)
                            if iszero(handler) {
                                return(0, 0)
                            }
                            calldatacopy(0, 0, calldatasize())
                            // The msg.sender address is shifted to the left by 12 bytes to remove the padding
                            // Then the address without padding is stored right after the calldata
                            mstore(calldatasize(), shl(96, caller()))
                            // Add 20 bytes for the address appended add the end
                            let success := call(gas(), handler, 0, 0, add(calldatasize(), 20), 0, 0)
                            returndatacopy(0, 0, returndatasize())
                            if iszero(success) {
                                revert(0, returndatasize())
                            }
                            return(0, returndatasize())
                        }
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity >=0.7.0 <0.9.0;
                import "../common/Enum.sol";
                import "../common/SelfAuthorized.sol";
                interface Guard {
                    function checkTransaction(
                        address to,
                        uint256 value,
                        bytes memory data,
                        Enum.Operation operation,
                        uint256 safeTxGas,
                        uint256 baseGas,
                        uint256 gasPrice,
                        address gasToken,
                        address payable refundReceiver,
                        bytes memory signatures,
                        address msgSender
                    ) external;
                    function checkAfterExecution(bytes32 txHash, bool success) external;
                }
                /// @title Fallback Manager - A contract that manages fallback calls made to this contract
                /// @author Richard Meissner - <[email protected]>
                contract GuardManager is SelfAuthorized {
                    event ChangedGuard(address guard);
                    // keccak256("guard_manager.guard.address")
                    bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;
                    /// @dev Set a guard that checks transactions before execution
                    /// @param guard The address of the guard to be used or the 0 address to disable the guard
                    function setGuard(address guard) external authorized {
                        bytes32 slot = GUARD_STORAGE_SLOT;
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            sstore(slot, guard)
                        }
                        emit ChangedGuard(guard);
                    }
                    function getGuard() internal view returns (address guard) {
                        bytes32 slot = GUARD_STORAGE_SLOT;
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            guard := sload(slot)
                        }
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity >=0.7.0 <0.9.0;
                import "../common/Enum.sol";
                import "../common/SelfAuthorized.sol";
                import "./Executor.sol";
                /// @title Module Manager - A contract that manages modules that can execute transactions via this contract
                /// @author Stefan George - <[email protected]>
                /// @author Richard Meissner - <[email protected]>
                contract ModuleManager is SelfAuthorized, Executor {
                    event EnabledModule(address module);
                    event DisabledModule(address module);
                    event ExecutionFromModuleSuccess(address indexed module);
                    event ExecutionFromModuleFailure(address indexed module);
                    address internal constant SENTINEL_MODULES = address(0x1);
                    mapping(address => address) internal modules;
                    function setupModules(address to, bytes memory data) internal {
                        require(modules[SENTINEL_MODULES] == address(0), "GS100");
                        modules[SENTINEL_MODULES] = SENTINEL_MODULES;
                        if (to != address(0))
                            // Setup has to complete successfully or transaction fails.
                            require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000");
                    }
                    /// @dev Allows to add a module to the whitelist.
                    ///      This can only be done via a Safe transaction.
                    /// @notice Enables the module `module` for the Safe.
                    /// @param module Module to be whitelisted.
                    function enableModule(address module) public authorized {
                        // Module address cannot be null or sentinel.
                        require(module != address(0) && module != SENTINEL_MODULES, "GS101");
                        // Module cannot be added twice.
                        require(modules[module] == address(0), "GS102");
                        modules[module] = modules[SENTINEL_MODULES];
                        modules[SENTINEL_MODULES] = module;
                        emit EnabledModule(module);
                    }
                    /// @dev Allows to remove a module from the whitelist.
                    ///      This can only be done via a Safe transaction.
                    /// @notice Disables the module `module` for the Safe.
                    /// @param prevModule Module that pointed to the module to be removed in the linked list
                    /// @param module Module to be removed.
                    function disableModule(address prevModule, address module) public authorized {
                        // Validate module address and check that it corresponds to module index.
                        require(module != address(0) && module != SENTINEL_MODULES, "GS101");
                        require(modules[prevModule] == module, "GS103");
                        modules[prevModule] = modules[module];
                        modules[module] = address(0);
                        emit DisabledModule(module);
                    }
                    /// @dev Allows a Module to execute a Safe transaction without any further confirmations.
                    /// @param to Destination address of module transaction.
                    /// @param value Ether value of module transaction.
                    /// @param data Data payload of module transaction.
                    /// @param operation Operation type of module transaction.
                    function execTransactionFromModule(
                        address to,
                        uint256 value,
                        bytes memory data,
                        Enum.Operation operation
                    ) public virtual returns (bool success) {
                        // Only whitelisted modules are allowed.
                        require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), "GS104");
                        // Execute transaction without further confirmations.
                        success = execute(to, value, data, operation, gasleft());
                        if (success) emit ExecutionFromModuleSuccess(msg.sender);
                        else emit ExecutionFromModuleFailure(msg.sender);
                    }
                    /// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data
                    /// @param to Destination address of module transaction.
                    /// @param value Ether value of module transaction.
                    /// @param data Data payload of module transaction.
                    /// @param operation Operation type of module transaction.
                    function execTransactionFromModuleReturnData(
                        address to,
                        uint256 value,
                        bytes memory data,
                        Enum.Operation operation
                    ) public returns (bool success, bytes memory returnData) {
                        success = execTransactionFromModule(to, value, data, operation);
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            // Load free memory location
                            let ptr := mload(0x40)
                            // We allocate memory for the return data by setting the free memory location to
                            // current free memory location + data size + 32 bytes for data size value
                            mstore(0x40, add(ptr, add(returndatasize(), 0x20)))
                            // Store the size
                            mstore(ptr, returndatasize())
                            // Store the data
                            returndatacopy(add(ptr, 0x20), 0, returndatasize())
                            // Point the return data to the correct memory location
                            returnData := ptr
                        }
                    }
                    /// @dev Returns if an module is enabled
                    /// @return True if the module is enabled
                    function isModuleEnabled(address module) public view returns (bool) {
                        return SENTINEL_MODULES != module && modules[module] != address(0);
                    }
                    /// @dev Returns array of modules.
                    /// @param start Start of the page.
                    /// @param pageSize Maximum number of modules that should be returned.
                    /// @return array Array of modules.
                    /// @return next Start of the next page.
                    function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) {
                        // Init array with max page size
                        array = new address[](pageSize);
                        // Populate return array
                        uint256 moduleCount = 0;
                        address currentModule = modules[start];
                        while (currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize) {
                            array[moduleCount] = currentModule;
                            currentModule = modules[currentModule];
                            moduleCount++;
                        }
                        next = currentModule;
                        // Set correct size of returned array
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            mstore(array, moduleCount)
                        }
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity >=0.7.0 <0.9.0;
                import "../common/SelfAuthorized.sol";
                /// @title OwnerManager - Manages a set of owners and a threshold to perform actions.
                /// @author Stefan George - <[email protected]>
                /// @author Richard Meissner - <[email protected]>
                contract OwnerManager is SelfAuthorized {
                    event AddedOwner(address owner);
                    event RemovedOwner(address owner);
                    event ChangedThreshold(uint256 threshold);
                    address internal constant SENTINEL_OWNERS = address(0x1);
                    mapping(address => address) internal owners;
                    uint256 internal ownerCount;
                    uint256 internal threshold;
                    /// @dev Setup function sets initial storage of contract.
                    /// @param _owners List of Safe owners.
                    /// @param _threshold Number of required confirmations for a Safe transaction.
                    function setupOwners(address[] memory _owners, uint256 _threshold) internal {
                        // Threshold can only be 0 at initialization.
                        // Check ensures that setup function can only be called once.
                        require(threshold == 0, "GS200");
                        // Validate that threshold is smaller than number of added owners.
                        require(_threshold <= _owners.length, "GS201");
                        // There has to be at least one Safe owner.
                        require(_threshold >= 1, "GS202");
                        // Initializing Safe owners.
                        address currentOwner = SENTINEL_OWNERS;
                        for (uint256 i = 0; i < _owners.length; i++) {
                            // Owner address cannot be null.
                            address owner = _owners[i];
                            require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this) && currentOwner != owner, "GS203");
                            // No duplicate owners allowed.
                            require(owners[owner] == address(0), "GS204");
                            owners[currentOwner] = owner;
                            currentOwner = owner;
                        }
                        owners[currentOwner] = SENTINEL_OWNERS;
                        ownerCount = _owners.length;
                        threshold = _threshold;
                    }
                    /// @dev Allows to add a new owner to the Safe and update the threshold at the same time.
                    ///      This can only be done via a Safe transaction.
                    /// @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`.
                    /// @param owner New owner address.
                    /// @param _threshold New threshold.
                    function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized {
                        // Owner address cannot be null, the sentinel or the Safe itself.
                        require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this), "GS203");
                        // No duplicate owners allowed.
                        require(owners[owner] == address(0), "GS204");
                        owners[owner] = owners[SENTINEL_OWNERS];
                        owners[SENTINEL_OWNERS] = owner;
                        ownerCount++;
                        emit AddedOwner(owner);
                        // Change threshold if threshold was changed.
                        if (threshold != _threshold) changeThreshold(_threshold);
                    }
                    /// @dev Allows to remove an owner from the Safe and update the threshold at the same time.
                    ///      This can only be done via a Safe transaction.
                    /// @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`.
                    /// @param prevOwner Owner that pointed to the owner to be removed in the linked list
                    /// @param owner Owner address to be removed.
                    /// @param _threshold New threshold.
                    function removeOwner(
                        address prevOwner,
                        address owner,
                        uint256 _threshold
                    ) public authorized {
                        // Only allow to remove an owner, if threshold can still be reached.
                        require(ownerCount - 1 >= _threshold, "GS201");
                        // Validate owner address and check that it corresponds to owner index.
                        require(owner != address(0) && owner != SENTINEL_OWNERS, "GS203");
                        require(owners[prevOwner] == owner, "GS205");
                        owners[prevOwner] = owners[owner];
                        owners[owner] = address(0);
                        ownerCount--;
                        emit RemovedOwner(owner);
                        // Change threshold if threshold was changed.
                        if (threshold != _threshold) changeThreshold(_threshold);
                    }
                    /// @dev Allows to swap/replace an owner from the Safe with another address.
                    ///      This can only be done via a Safe transaction.
                    /// @notice Replaces the owner `oldOwner` in the Safe with `newOwner`.
                    /// @param prevOwner Owner that pointed to the owner to be replaced in the linked list
                    /// @param oldOwner Owner address to be replaced.
                    /// @param newOwner New owner address.
                    function swapOwner(
                        address prevOwner,
                        address oldOwner,
                        address newOwner
                    ) public authorized {
                        // Owner address cannot be null, the sentinel or the Safe itself.
                        require(newOwner != address(0) && newOwner != SENTINEL_OWNERS && newOwner != address(this), "GS203");
                        // No duplicate owners allowed.
                        require(owners[newOwner] == address(0), "GS204");
                        // Validate oldOwner address and check that it corresponds to owner index.
                        require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "GS203");
                        require(owners[prevOwner] == oldOwner, "GS205");
                        owners[newOwner] = owners[oldOwner];
                        owners[prevOwner] = newOwner;
                        owners[oldOwner] = address(0);
                        emit RemovedOwner(oldOwner);
                        emit AddedOwner(newOwner);
                    }
                    /// @dev Allows to update the number of required confirmations by Safe owners.
                    ///      This can only be done via a Safe transaction.
                    /// @notice Changes the threshold of the Safe to `_threshold`.
                    /// @param _threshold New threshold.
                    function changeThreshold(uint256 _threshold) public authorized {
                        // Validate that threshold is smaller than number of owners.
                        require(_threshold <= ownerCount, "GS201");
                        // There has to be at least one Safe owner.
                        require(_threshold >= 1, "GS202");
                        threshold = _threshold;
                        emit ChangedThreshold(threshold);
                    }
                    function getThreshold() public view returns (uint256) {
                        return threshold;
                    }
                    function isOwner(address owner) public view returns (bool) {
                        return owner != SENTINEL_OWNERS && owners[owner] != address(0);
                    }
                    /// @dev Returns array of owners.
                    /// @return Array of Safe owners.
                    function getOwners() public view returns (address[] memory) {
                        address[] memory array = new address[](ownerCount);
                        // populate return array
                        uint256 index = 0;
                        address currentOwner = owners[SENTINEL_OWNERS];
                        while (currentOwner != SENTINEL_OWNERS) {
                            array[index] = currentOwner;
                            currentOwner = owners[currentOwner];
                            index++;
                        }
                        return array;
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity >=0.7.0 <0.9.0;
                /// @title Enum - Collection of enums
                /// @author Richard Meissner - <[email protected]>
                contract Enum {
                    enum Operation {Call, DelegateCall}
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity >=0.7.0 <0.9.0;
                /// @title EtherPaymentFallback - A contract that has a fallback to accept ether payments
                /// @author Richard Meissner - <[email protected]>
                contract EtherPaymentFallback {
                    event SafeReceived(address indexed sender, uint256 value);
                    /// @dev Fallback function accepts Ether transactions.
                    receive() external payable {
                        emit SafeReceived(msg.sender, msg.value);
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity >=0.7.0 <0.9.0;
                /// @title SecuredTokenTransfer - Secure token transfer
                /// @author Richard Meissner - <[email protected]>
                contract SecuredTokenTransfer {
                    /// @dev Transfers a token and returns if it was a success
                    /// @param token Token that should be transferred
                    /// @param receiver Receiver to whom the token should be transferred
                    /// @param amount The amount of tokens that should be transferred
                    function transferToken(
                        address token,
                        address receiver,
                        uint256 amount
                    ) internal returns (bool transferred) {
                        // 0xa9059cbb - keccack("transfer(address,uint256)")
                        bytes memory data = abi.encodeWithSelector(0xa9059cbb, receiver, amount);
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            // We write the return value to scratch space.
                            // See https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory
                            let success := call(sub(gas(), 10000), token, 0, add(data, 0x20), mload(data), 0, 0x20)
                            switch returndatasize()
                                case 0 {
                                    transferred := success
                                }
                                case 0x20 {
                                    transferred := iszero(or(iszero(success), iszero(mload(0))))
                                }
                                default {
                                    transferred := 0
                                }
                        }
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity >=0.7.0 <0.9.0;
                /// @title SelfAuthorized - authorizes current contract to perform actions
                /// @author Richard Meissner - <[email protected]>
                contract SelfAuthorized {
                    function requireSelfCall() private view {
                        require(msg.sender == address(this), "GS031");
                    }
                    modifier authorized() {
                        // This is a function call as it minimized the bytecode size
                        requireSelfCall();
                        _;
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity >=0.7.0 <0.9.0;
                /// @title SignatureDecoder - Decodes signatures that a encoded as bytes
                /// @author Richard Meissner - <[email protected]>
                contract SignatureDecoder {
                    /// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`.
                    /// @notice Make sure to peform a bounds check for @param pos, to avoid out of bounds access on @param signatures
                    /// @param pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access
                    /// @param signatures concatenated rsv signatures
                    function signatureSplit(bytes memory signatures, uint256 pos)
                        internal
                        pure
                        returns (
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        )
                    {
                        // The signature format is a compact form of:
                        //   {bytes32 r}{bytes32 s}{uint8 v}
                        // Compact means, uint8 is not padded to 32 bytes.
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            let signaturePos := mul(0x41, pos)
                            r := mload(add(signatures, add(signaturePos, 0x20)))
                            s := mload(add(signatures, add(signaturePos, 0x40)))
                            // Here we are loading the last 32 bytes, including 31 bytes
                            // of 's'. There is no 'mload8' to do this.
                            //
                            // 'byte' is not working due to the Solidity parser, so lets
                            // use the second best option, 'and'
                            v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff)
                        }
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity >=0.7.0 <0.9.0;
                /// @title Singleton - Base for singleton contracts (should always be first super contract)
                ///         This contract is tightly coupled to our proxy contract (see `proxies/GnosisSafeProxy.sol`)
                /// @author Richard Meissner - <[email protected]>
                contract Singleton {
                    // singleton always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract.
                    // It should also always be ensured that the address is stored alone (uses a full word)
                    address private singleton;
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity >=0.7.0 <0.9.0;
                /// @title StorageAccessible - generic base contract that allows callers to access all internal storage.
                /// @notice See https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol
                contract StorageAccessible {
                    /**
                     * @dev Reads `length` bytes of storage in the currents contract
                     * @param offset - the offset in the current contract's storage in words to start reading from
                     * @param length - the number of words (32 bytes) of data to read
                     * @return the bytes that were read.
                     */
                    function getStorageAt(uint256 offset, uint256 length) public view returns (bytes memory) {
                        bytes memory result = new bytes(length * 32);
                        for (uint256 index = 0; index < length; index++) {
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                let word := sload(add(offset, index))
                                mstore(add(add(result, 0x20), mul(index, 0x20)), word)
                            }
                        }
                        return result;
                    }
                    /**
                     * @dev Performs a delegetecall on a targetContract in the context of self.
                     * Internally reverts execution to avoid side effects (making it static).
                     *
                     * This method reverts with data equal to `abi.encode(bool(success), bytes(response))`.
                     * Specifically, the `returndata` after a call to this method will be:
                     * `success:bool || response.length:uint256 || response:bytes`.
                     *
                     * @param targetContract Address of the contract containing the code to execute.
                     * @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments).
                     */
                    function simulateAndRevert(address targetContract, bytes memory calldataPayload) external {
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            let success := delegatecall(gas(), targetContract, add(calldataPayload, 0x20), mload(calldataPayload), 0, 0)
                            mstore(0x00, success)
                            mstore(0x20, returndatasize())
                            returndatacopy(0x40, 0, returndatasize())
                            revert(0, add(returndatasize(), 0x40))
                        }
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity >=0.7.0 <0.9.0;
                /**
                 * @title GnosisSafeMath
                 * @dev Math operations with safety checks that revert on error
                 * Renamed from SafeMath to GnosisSafeMath to avoid conflicts
                 * TODO: remove once open zeppelin update to solc 0.5.0
                 */
                library GnosisSafeMath {
                    /**
                     * @dev Multiplies two numbers, reverts on overflow.
                     */
                    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                        // benefit is lost if 'b' is also tested.
                        // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
                        if (a == 0) {
                            return 0;
                        }
                        uint256 c = a * b;
                        require(c / a == b);
                        return c;
                    }
                    /**
                     * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
                     */
                    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                        require(b <= a);
                        uint256 c = a - b;
                        return c;
                    }
                    /**
                     * @dev Adds two numbers, reverts on overflow.
                     */
                    function add(uint256 a, uint256 b) internal pure returns (uint256) {
                        uint256 c = a + b;
                        require(c >= a);
                        return c;
                    }
                    /**
                     * @dev Returns the largest of two numbers.
                     */
                    function max(uint256 a, uint256 b) internal pure returns (uint256) {
                        return a >= b ? a : b;
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity >=0.7.0 <0.9.0;
                contract ISignatureValidatorConstants {
                    // bytes4(keccak256("isValidSignature(bytes,bytes)")
                    bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b;
                }
                abstract contract ISignatureValidator is ISignatureValidatorConstants {
                    /**
                     * @dev Should return whether the signature provided is valid for the provided data
                     * @param _data Arbitrary length data signed on the behalf of address(this)
                     * @param _signature Signature byte array associated with _data
                     *
                     * MUST return the bytes4 magic value 0x20c13b0b when function passes.
                     * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
                     * MUST allow external calls
                     */
                    function isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4);
                }
                

                File 4 of 7: HopFacetPacked
                // // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                import { IHopBridge, IL2AmmWrapper, ISwap } from "../Interfaces/IHopBridge.sol";
                import { ILiFi } from "../Interfaces/ILiFi.sol";
                import { ERC20, SafeTransferLib } from "solmate/utils/SafeTransferLib.sol";
                import { LibAsset, IERC20 } from "../Libraries/LibAsset.sol";
                import { TransferrableOwnership } from "../Helpers/TransferrableOwnership.sol";
                import { HopFacetOptimized } from "lifi/Facets/HopFacetOptimized.sol";
                import { WETH } from "solmate/tokens/WETH.sol";
                /// @title Hop Facet (Optimized for Rollups)
                /// @author LI.FI (https://li.fi)
                /// @notice Provides functionality for bridging through Hop
                /// @custom:version 1.0.6
                contract HopFacetPacked is ILiFi, TransferrableOwnership {
                    using SafeTransferLib for ERC20;
                    /// Storage ///
                    address public immutable nativeBridge;
                    address public immutable nativeL2CanonicalToken;
                    address public immutable nativeHToken;
                    address public immutable nativeExchangeAddress;
                    /// Errors ///
                    error Invalid();
                    /// Events ///
                    event LiFiHopTransfer(bytes8 _transactionId);
                    /// Constructor ///
                    /// @notice Initialize the contract.
                    /// @param _owner The contract owner to approve tokens.
                    /// @param _wrapper The address of Hop L2_AmmWrapper for native asset.
                    constructor(
                        address _owner,
                        address _wrapper
                    ) TransferrableOwnership(_owner) {
                        bool wrapperIsSet = _wrapper != address(0);
                        if (block.chainid == 1 && wrapperIsSet) {
                            revert Invalid();
                        }
                        nativeL2CanonicalToken = wrapperIsSet
                            ? IL2AmmWrapper(_wrapper).l2CanonicalToken()
                            : address(0);
                        nativeHToken = wrapperIsSet
                            ? IL2AmmWrapper(_wrapper).hToken()
                            : address(0);
                        nativeExchangeAddress = wrapperIsSet
                            ? IL2AmmWrapper(_wrapper).exchangeAddress()
                            : address(0);
                        nativeBridge = wrapperIsSet
                            ? IL2AmmWrapper(_wrapper).bridge()
                            : address(0);
                    }
                    /// External Methods ///
                    /// @dev Only meant to be called outside of the context of the diamond
                    /// @notice Sets approval for the Hop Bridge to spend the specified token
                    /// @param bridges The Hop Bridges to approve
                    /// @param tokensToApprove The tokens to approve to approve to the Hop Bridges
                    function setApprovalForHopBridges(
                        address[] calldata bridges,
                        address[] calldata tokensToApprove
                    ) external onlyOwner {
                        uint256 numBridges = bridges.length;
                        for (uint256 i; i < numBridges; i++) {
                            // Give Hop approval to bridge tokens
                            LibAsset.maxApproveERC20(
                                IERC20(tokensToApprove[i]),
                                address(bridges[i]),
                                type(uint256).max
                            );
                        }
                    }
                    /// @notice Bridges Native tokens via Hop Protocol from L2
                    /// No params, all data will be extracted from manually encoded callData
                    function startBridgeTokensViaHopL2NativePacked() external payable {
                        // first 4 bytes are function signature
                        // transactionId: bytes8(msg.data[4:12]),
                        // receiver: address(bytes20(msg.data[12:32])),
                        // destinationChainId: uint256(uint32(bytes4(msg.data[32:36]))),
                        // bonderFee: uint256(uint128(bytes16(msg.data[36:52]))),
                        // amountOutMin: uint256(uint128(bytes16(msg.data[52:68])))
                        // => total calldata length required: 68
                        uint256 destinationChainId = uint256(uint32(bytes4(msg.data[32:36])));
                        uint256 amountOutMin = uint256(uint128(bytes16(msg.data[52:68])));
                        bool toL1 = destinationChainId == 1;
                        // Wrap ETH
                        WETH(payable(nativeL2CanonicalToken)).deposit{ value: msg.value }();
                        // Exchange WETH for hToken
                        uint256 swapAmount = ISwap(nativeExchangeAddress).swap(
                            0,
                            1,
                            msg.value,
                            amountOutMin,
                            block.timestamp
                        );
                        // Bridge assets
                        // solhint-disable-next-line check-send-result
                        IHopBridge(nativeBridge).send(
                            destinationChainId,
                            address(bytes20(msg.data[12:32])), // receiver
                            swapAmount,
                            uint256(uint128(bytes16(msg.data[36:52]))), // bonderFee
                            toL1 ? 0 : amountOutMin,
                            toL1 ? 0 : block.timestamp + 7 * 24 * 60 * 60
                        );
                        emit LiFiHopTransfer(
                            bytes8(msg.data[4:12]) // transactionId
                        );
                    }
                    /// @notice Bridges Native tokens via Hop Protocol from L2
                    /// @param transactionId Custom transaction ID for tracking
                    /// @param receiver Receiving wallet address
                    /// @param destinationChainId Receiving chain
                    /// @param bonderFee Fees payed to hop bonder
                    /// @param amountOutMin Source swap minimal accepted amount
                    /// @param destinationAmountOutMin Destination swap minimal accepted amount
                    /// @param destinationDeadline Destination swap maximal time
                    /// @param hopBridge Address of the Hop L2_AmmWrapper
                    function startBridgeTokensViaHopL2NativeMin(
                        bytes8 transactionId,
                        address receiver,
                        uint256 destinationChainId,
                        uint256 bonderFee,
                        uint256 amountOutMin,
                        uint256 destinationAmountOutMin,
                        uint256 destinationDeadline,
                        address hopBridge
                    ) external payable {
                        // Bridge assets
                        IHopBridge(hopBridge).swapAndSend{ value: msg.value }(
                            destinationChainId,
                            receiver,
                            msg.value,
                            bonderFee,
                            amountOutMin,
                            block.timestamp,
                            destinationAmountOutMin,
                            destinationDeadline
                        );
                        emit LiFiHopTransfer(transactionId);
                    }
                    /// @notice Bridges Native tokens via Hop Protocol from L2
                    /// @param transactionId Custom transaction ID for tracking
                    /// @param receiver Receiving wallet address
                    /// @param destinationChainId Receiving chain
                    /// @param bonderFee Fees payed to hop bonder
                    /// @param amountOutMin Source swap minimal accepted amount
                    function encode_startBridgeTokensViaHopL2NativePacked(
                        bytes8 transactionId,
                        address receiver,
                        uint256 destinationChainId,
                        uint256 bonderFee,
                        uint256 amountOutMin
                    ) external pure returns (bytes memory) {
                        require(
                            destinationChainId <= type(uint32).max,
                            "destinationChainId value passed too big to fit in uint32"
                        );
                        require(
                            bonderFee <= type(uint128).max,
                            "bonderFee value passed too big to fit in uint128"
                        );
                        require(
                            amountOutMin <= type(uint128).max,
                            "amountOutMin value passed too big to fit in uint128"
                        );
                        return
                            bytes.concat(
                                HopFacetPacked.startBridgeTokensViaHopL2NativePacked.selector,
                                bytes8(transactionId),
                                bytes20(receiver),
                                bytes4(uint32(destinationChainId)),
                                bytes16(uint128(bonderFee)),
                                bytes16(uint128(amountOutMin))
                            );
                    }
                    /// @notice Decodes calldata for startBridgeTokensViaHopL2NativePacked
                    /// @param _data the calldata to decode
                    function decode_startBridgeTokensViaHopL2NativePacked(
                        bytes calldata _data
                    )
                        external
                        pure
                        returns (BridgeData memory, HopFacetOptimized.HopData memory)
                    {
                        require(
                            _data.length >= 68,
                            "data passed in is not the correct length"
                        );
                        BridgeData memory bridgeData;
                        HopFacetOptimized.HopData memory hopData;
                        bridgeData.transactionId = bytes32(bytes8(_data[4:12]));
                        bridgeData.receiver = address(bytes20(_data[12:32]));
                        bridgeData.destinationChainId = uint256(uint32(bytes4(_data[32:36])));
                        hopData.bonderFee = uint256(uint128(bytes16(_data[36:52])));
                        hopData.amountOutMin = uint256(uint128(bytes16(_data[52:68])));
                        return (bridgeData, hopData);
                    }
                    /// @notice Bridges ERC20 tokens via Hop Protocol from L2
                    /// No params, all data will be extracted from manually encoded callData
                    function startBridgeTokensViaHopL2ERC20Packed() external {
                        // first 4 bytes are function signature
                        // transactionId: bytes8(msg.data[4:12]),
                        // receiver: address(bytes20(msg.data[12:32])),
                        // destinationChainId: uint256(uint32(bytes4(msg.data[32:36]))),
                        // sendingAssetId: address(bytes20(msg.data[36:56])),
                        // amount: uint256(uint128(bytes16(msg.data[56:72]))),
                        // bonderFee: uint256(uint128(bytes16(msg.data[72:88]))),
                        // amountOutMin: uint256(uint128(bytes16(msg.data[88:104]))),
                        // destinationAmountOutMin: uint256(uint128(bytes16(msg.data[104:120]))),
                        // destinationDeadline: uint256(uint32(bytes4(msg.data[120:124]))),
                        // wrapper: address(bytes20(msg.data[124:144]))
                        // => total calldata length required: 144
                        uint256 destinationChainId = uint256(uint32(bytes4(msg.data[32:36])));
                        uint256 amount = uint256(uint128(bytes16(msg.data[56:72])));
                        uint256 amountOutMin = uint256(uint128(bytes16(msg.data[88:104])));
                        bool toL1 = destinationChainId == 1;
                        IL2AmmWrapper wrapper = IL2AmmWrapper(
                            address(bytes20(msg.data[124:144]))
                        );
                        // Deposit assets
                        ERC20(address(bytes20(msg.data[36:56]))).safeTransferFrom(
                            msg.sender,
                            address(this),
                            amount
                        );
                        // Exchange sending asset to hToken
                        uint256 swapAmount = ISwap(wrapper.exchangeAddress()).swap(
                            0,
                            1,
                            amount,
                            amountOutMin,
                            block.timestamp
                        );
                        // Bridge assets
                        // solhint-disable-next-line check-send-result
                        IHopBridge(wrapper.bridge()).send(
                            destinationChainId,
                            address(bytes20(msg.data[12:32])),
                            swapAmount,
                            uint256(uint128(bytes16(msg.data[72:88]))),
                            toL1 ? 0 : uint256(uint128(bytes16(msg.data[104:120]))),
                            toL1 ? 0 : uint256(uint32(bytes4(msg.data[120:124])))
                        );
                        emit LiFiHopTransfer(bytes8(msg.data[4:12]));
                    }
                    /// @notice Bridges ERC20 tokens via Hop Protocol from L2
                    /// @param transactionId Custom transaction ID for tracking
                    /// @param receiver Receiving wallet address
                    /// @param destinationChainId Receiving chain
                    /// @param sendingAssetId Address of the source asset to bridge
                    /// @param minAmount Amount of the source asset to bridge
                    /// @param bonderFee Fees payed to hop bonder
                    /// @param amountOutMin Source swap minimal accepted amount
                    /// @param destinationAmountOutMin Destination swap minimal accepted amount
                    /// @param destinationDeadline Destination swap maximal time
                    /// @param hopBridge Address of the Hop L2_AmmWrapper
                    function startBridgeTokensViaHopL2ERC20Min(
                        bytes8 transactionId,
                        address receiver,
                        uint256 destinationChainId,
                        address sendingAssetId,
                        uint256 minAmount,
                        uint256 bonderFee,
                        uint256 amountOutMin,
                        uint256 destinationAmountOutMin,
                        uint256 destinationDeadline,
                        address hopBridge
                    ) external {
                        // Deposit assets
                        ERC20(sendingAssetId).safeTransferFrom(
                            msg.sender,
                            address(this),
                            minAmount
                        );
                        // Bridge assets
                        IHopBridge(hopBridge).swapAndSend(
                            destinationChainId,
                            receiver,
                            minAmount,
                            bonderFee,
                            amountOutMin,
                            block.timestamp,
                            destinationAmountOutMin,
                            destinationDeadline
                        );
                        emit LiFiHopTransfer(transactionId);
                    }
                    /// @notice Bridges ERC20 tokens via Hop Protocol from L2
                    /// @param transactionId Custom transaction ID for tracking
                    /// @param receiver Receiving wallet address
                    /// @param destinationChainId Receiving chain
                    /// @param sendingAssetId Address of the source asset to bridge
                    /// @param minAmount Amount of the source asset to bridge
                    /// @param bonderFee Fees payed to hop bonder
                    /// @param amountOutMin Source swap minimal accepted amount
                    /// @param destinationAmountOutMin Destination swap minimal accepted amount
                    /// @param destinationDeadline Destination swap maximal time
                    /// @param wrapper Address of the Hop L2_AmmWrapper
                    function encode_startBridgeTokensViaHopL2ERC20Packed(
                        bytes32 transactionId,
                        address receiver,
                        uint256 destinationChainId,
                        address sendingAssetId,
                        uint256 minAmount,
                        uint256 bonderFee,
                        uint256 amountOutMin,
                        uint256 destinationAmountOutMin,
                        uint256 destinationDeadline,
                        address wrapper
                    ) external pure returns (bytes memory) {
                        require(
                            destinationChainId <= type(uint32).max,
                            "destinationChainId value passed too big to fit in uint32"
                        );
                        require(
                            minAmount <= type(uint128).max,
                            "amount value passed too big to fit in uint128"
                        );
                        require(
                            bonderFee <= type(uint128).max,
                            "bonderFee value passed too big to fit in uint128"
                        );
                        require(
                            amountOutMin <= type(uint128).max,
                            "amountOutMin value passed too big to fit in uint128"
                        );
                        require(
                            destinationAmountOutMin <= type(uint128).max,
                            "destinationAmountOutMin value passed too big to fit in uint128"
                        );
                        require(
                            destinationDeadline <= type(uint32).max,
                            "destinationDeadline value passed too big to fit in uint32"
                        );
                        return
                            bytes.concat(
                                HopFacetPacked.startBridgeTokensViaHopL2ERC20Packed.selector,
                                bytes8(transactionId),
                                bytes20(receiver),
                                bytes4(uint32(destinationChainId)),
                                bytes20(sendingAssetId),
                                bytes16(uint128(minAmount)),
                                bytes16(uint128(bonderFee)),
                                bytes16(uint128(amountOutMin)),
                                bytes16(uint128(destinationAmountOutMin)),
                                bytes4(uint32(destinationDeadline)),
                                bytes20(wrapper)
                            );
                    }
                    /// @notice Decodes calldata for startBridgeTokensViaHopL2ERC20Packed
                    /// @param _data the calldata to decode
                    function decode_startBridgeTokensViaHopL2ERC20Packed(
                        bytes calldata _data
                    )
                        external
                        pure
                        returns (BridgeData memory, HopFacetOptimized.HopData memory)
                    {
                        require(
                            _data.length >= 144,
                            "data passed in is not the correct length"
                        );
                        BridgeData memory bridgeData;
                        HopFacetOptimized.HopData memory hopData;
                        bridgeData.transactionId = bytes32(bytes8(_data[4:12]));
                        bridgeData.receiver = address(bytes20(_data[12:32]));
                        bridgeData.destinationChainId = uint256(uint32(bytes4(_data[32:36])));
                        bridgeData.sendingAssetId = address(bytes20(_data[36:56]));
                        bridgeData.minAmount = uint256(uint128(bytes16(_data[56:72])));
                        hopData.bonderFee = uint256(uint128(bytes16(_data[72:88])));
                        hopData.amountOutMin = uint256(uint128(bytes16(_data[88:104])));
                        hopData.destinationAmountOutMin = uint256(
                            uint128(bytes16(_data[104:120]))
                        );
                        hopData.destinationDeadline = uint256(uint32(bytes4(_data[120:124])));
                        hopData.hopBridge = IHopBridge(address(bytes20(_data[124:144])));
                        return (bridgeData, hopData);
                    }
                    /// @notice Bridges Native tokens via Hop Protocol from L1
                    /// No params, all data will be extracted from manually encoded callData
                    function startBridgeTokensViaHopL1NativePacked() external payable {
                        // first 4 bytes are function signature
                        // transactionId: bytes8(msg.data[4:12]),
                        // receiver: address(bytes20(msg.data[12:32])),
                        // destinationChainId: uint256(uint32(bytes4(msg.data[32:36]))),
                        // destinationAmountOutMin: uint256(uint128(bytes16(msg.data[36:52]))),
                        // relayer: address(bytes20(msg.data[52:72])),
                        // relayerFee: uint256(uint128(bytes16(msg.data[72:88]))),
                        // hopBridge: address(bytes20(msg.data[88:108]))
                        // => total calldata length required: 108
                        // Bridge assets
                        IHopBridge(address(bytes20(msg.data[88:108]))).sendToL2{
                            value: msg.value
                        }(
                            uint256(uint32(bytes4(msg.data[32:36]))),
                            address(bytes20(msg.data[12:32])),
                            msg.value,
                            uint256(uint128(bytes16(msg.data[36:52]))),
                            block.timestamp + 7 * 24 * 60 * 60,
                            address(bytes20(msg.data[52:72])),
                            uint256(uint128(bytes16(msg.data[72:88])))
                        );
                        emit LiFiHopTransfer(bytes8(msg.data[4:12]));
                    }
                    /// @notice Bridges Native tokens via Hop Protocol from L1
                    /// @param transactionId Custom transaction ID for tracking
                    /// @param receiver Receiving wallet address
                    /// @param destinationChainId Receiving chain
                    /// @param destinationAmountOutMin Destination swap minimal accepted amount
                    /// @param relayer needed for gas spikes
                    /// @param relayerFee needed for gas spikes
                    /// @param hopBridge Address of the Hop Bridge
                    function startBridgeTokensViaHopL1NativeMin(
                        bytes8 transactionId,
                        address receiver,
                        uint256 destinationChainId,
                        uint256 destinationAmountOutMin,
                        address relayer,
                        uint256 relayerFee,
                        address hopBridge
                    ) external payable {
                        // Bridge assets
                        IHopBridge(hopBridge).sendToL2{ value: msg.value }(
                            destinationChainId,
                            receiver,
                            msg.value,
                            destinationAmountOutMin,
                            block.timestamp + 7 * 24 * 60 * 60,
                            relayer,
                            relayerFee
                        );
                        emit LiFiHopTransfer(transactionId);
                    }
                    /// @notice Bridges Native tokens via Hop Protocol from L1
                    /// @param transactionId Custom transaction ID for tracking
                    /// @param receiver Receiving wallet address
                    /// @param destinationChainId Receiving chain
                    /// @param destinationAmountOutMin Destination swap minimal accepted amount
                    /// @param relayer needed for gas spikes
                    /// @param relayerFee needed for gas spikes
                    /// @param hopBridge Address of the Hop Bridge
                    function encode_startBridgeTokensViaHopL1NativePacked(
                        bytes8 transactionId,
                        address receiver,
                        uint256 destinationChainId,
                        uint256 destinationAmountOutMin,
                        address relayer,
                        uint256 relayerFee,
                        address hopBridge
                    ) external pure returns (bytes memory) {
                        require(
                            destinationChainId <= type(uint32).max,
                            "destinationChainId value passed too big to fit in uint32"
                        );
                        require(
                            destinationAmountOutMin <= type(uint128).max,
                            "destinationAmountOutMin value passed too big to fit in uint128"
                        );
                        require(
                            relayerFee <= type(uint128).max,
                            "relayerFee value passed too big to fit in uint128"
                        );
                        return
                            bytes.concat(
                                HopFacetPacked.startBridgeTokensViaHopL1NativePacked.selector,
                                bytes8(transactionId),
                                bytes20(receiver),
                                bytes4(uint32(destinationChainId)),
                                bytes16(uint128(destinationAmountOutMin)),
                                bytes20(relayer),
                                bytes16(uint128(relayerFee)),
                                bytes20(hopBridge)
                            );
                    }
                    /// @notice Decodes calldata for startBridgeTokensViaHopL1NativePacked
                    /// @param _data the calldata to decode
                    function decode_startBridgeTokensViaHopL1NativePacked(
                        bytes calldata _data
                    )
                        external
                        pure
                        returns (BridgeData memory, HopFacetOptimized.HopData memory)
                    {
                        require(
                            _data.length >= 108,
                            "data passed in is not the correct length"
                        );
                        BridgeData memory bridgeData;
                        HopFacetOptimized.HopData memory hopData;
                        bridgeData.transactionId = bytes32(bytes8(_data[4:12]));
                        bridgeData.receiver = address(bytes20(_data[12:32]));
                        bridgeData.destinationChainId = uint256(uint32(bytes4(_data[32:36])));
                        hopData.destinationAmountOutMin = uint256(
                            uint128(bytes16(_data[36:52]))
                        );
                        // relayer = address(bytes20(_data[52:72]));
                        // relayerFee = uint256(uint128(bytes16(_data[72:88])));
                        hopData.hopBridge = IHopBridge(address(bytes20(_data[88:108])));
                        return (bridgeData, hopData);
                    }
                    /// @notice Bridges Native tokens via Hop Protocol from L1
                    /// No params, all data will be extracted from manually encoded callData
                    function startBridgeTokensViaHopL1ERC20Packed() external payable {
                        // first 4 bytes are function signature
                        // transactionId: bytes8(msg.data[4:12]),
                        // receiver: address(bytes20(msg.data[12:32])),
                        // destinationChainId: uint256(uint32(bytes4(msg.data[32:36]))),
                        // sendingAssetId: address(bytes20(msg.data[36:56])),
                        // amount: uint256(uint128(bytes16(msg.data[56:72]))),
                        // destinationAmountOutMin: uint256(uint128(bytes16(msg.data[72:88]))),
                        // relayer: address(bytes20(msg.data[88:108])),
                        // relayerFee: uint256(uint128(bytes16(msg.data[108:124]))),
                        // hopBridge: address(bytes20(msg.data[124:144]))
                        // => total calldata length required: 144
                        uint256 amount = uint256(uint128(bytes16(msg.data[56:72])));
                        // Deposit assets
                        ERC20(address(bytes20(msg.data[36:56]))).safeTransferFrom(
                            msg.sender,
                            address(this),
                            amount
                        );
                        // Bridge assets
                        IHopBridge(address(bytes20(msg.data[124:144]))).sendToL2(
                            uint256(uint32(bytes4(msg.data[32:36]))),
                            address(bytes20(msg.data[12:32])),
                            amount,
                            uint256(uint128(bytes16(msg.data[72:88]))),
                            block.timestamp + 7 * 24 * 60 * 60,
                            address(bytes20(msg.data[88:108])),
                            uint256(uint128(bytes16(msg.data[108:124])))
                        );
                        emit LiFiHopTransfer(bytes8(msg.data[4:12]));
                    }
                    /// @notice Bridges ERC20 tokens via Hop Protocol from L1
                    /// @param transactionId Custom transaction ID for tracking
                    /// @param receiver Receiving wallet address
                    /// @param destinationChainId Receiving chain
                    /// @param sendingAssetId Address of the source asset to bridge
                    /// @param minAmount Amount of the source asset to bridge
                    /// @param destinationAmountOutMin Destination swap minimal accepted amount
                    /// @param relayer needed for gas spikes
                    /// @param relayerFee needed for gas spikes
                    /// @param hopBridge Address of the Hop Bridge
                    function startBridgeTokensViaHopL1ERC20Min(
                        bytes8 transactionId,
                        address receiver,
                        uint256 destinationChainId,
                        address sendingAssetId,
                        uint256 minAmount,
                        uint256 destinationAmountOutMin,
                        address relayer,
                        uint256 relayerFee,
                        address hopBridge
                    ) external {
                        // Deposit assets
                        ERC20(sendingAssetId).safeTransferFrom(
                            msg.sender,
                            address(this),
                            minAmount
                        );
                        // Bridge assets
                        IHopBridge(hopBridge).sendToL2(
                            destinationChainId,
                            receiver,
                            minAmount,
                            destinationAmountOutMin,
                            block.timestamp + 7 * 24 * 60 * 60,
                            relayer,
                            relayerFee
                        );
                        emit LiFiHopTransfer(transactionId);
                    }
                    /// @notice Bridges ERC20 tokens via Hop Protocol from L1
                    /// @param transactionId Custom transaction ID for tracking
                    /// @param receiver Receiving wallet address
                    /// @param destinationChainId Receiving chain
                    /// @param sendingAssetId Address of the source asset to bridge
                    /// @param minAmount Amount of the source asset to bridge
                    /// @param destinationAmountOutMin Destination swap minimal accepted amount
                    /// @param relayer needed for gas spikes
                    /// @param relayerFee needed for gas spikes
                    /// @param hopBridge Address of the Hop Bridge
                    function encode_startBridgeTokensViaHopL1ERC20Packed(
                        bytes8 transactionId,
                        address receiver,
                        uint256 destinationChainId,
                        address sendingAssetId,
                        uint256 minAmount,
                        uint256 destinationAmountOutMin,
                        address relayer,
                        uint256 relayerFee,
                        address hopBridge
                    ) external pure returns (bytes memory) {
                        require(
                            destinationChainId <= type(uint32).max,
                            "destinationChainId value passed too big to fit in uint32"
                        );
                        require(
                            minAmount <= type(uint128).max,
                            "amount value passed too big to fit in uint128"
                        );
                        require(
                            destinationAmountOutMin <= type(uint128).max,
                            "destinationAmountOutMin value passed too big to fit in uint128"
                        );
                        require(
                            relayerFee <= type(uint128).max,
                            "relayerFee value passed too big to fit in uint128"
                        );
                        return
                            bytes.concat(
                                HopFacetPacked.startBridgeTokensViaHopL1ERC20Packed.selector,
                                bytes8(transactionId),
                                bytes20(receiver),
                                bytes4(uint32(destinationChainId)),
                                bytes20(sendingAssetId),
                                bytes16(uint128(minAmount)),
                                bytes16(uint128(destinationAmountOutMin)),
                                bytes20(relayer),
                                bytes16(uint128(relayerFee)),
                                bytes20(hopBridge)
                            );
                    }
                    /// @notice Decodes calldata for startBridgeTokensViaHopL1ERC20Packed
                    /// @param _data the calldata to decode
                    function decode_startBridgeTokensViaHopL1ERC20Packed(
                        bytes calldata _data
                    )
                        external
                        pure
                        returns (BridgeData memory, HopFacetOptimized.HopData memory)
                    {
                        require(
                            _data.length >= 144,
                            "data passed in is not the correct length"
                        );
                        BridgeData memory bridgeData;
                        HopFacetOptimized.HopData memory hopData;
                        bridgeData.transactionId = bytes32(bytes8(_data[4:12]));
                        bridgeData.receiver = address(bytes20(_data[12:32]));
                        bridgeData.destinationChainId = uint256(uint32(bytes4(_data[32:36])));
                        bridgeData.sendingAssetId = address(bytes20(_data[36:56]));
                        bridgeData.minAmount = uint256(uint128(bytes16(_data[56:72])));
                        hopData.destinationAmountOutMin = uint256(
                            uint128(bytes16(_data[72:88]))
                        );
                        // relayer = address(bytes20(_data[88:108]));
                        // relayerFee = uint256(uint128(bytes16(_data[108:124])));
                        hopData.hopBridge = IHopBridge(address(bytes20(_data[124:144])));
                        return (bridgeData, hopData);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                interface IHopBridge {
                    function sendToL2(
                        uint256 chainId,
                        address recipient,
                        uint256 amount,
                        uint256 amountOutMin,
                        uint256 deadline,
                        address relayer,
                        uint256 relayerFee
                    ) external payable;
                    function swapAndSend(
                        uint256 chainId,
                        address recipient,
                        uint256 amount,
                        uint256 bonderFee,
                        uint256 amountOutMin,
                        uint256 deadline,
                        uint256 destinationAmountOutMin,
                        uint256 destinationDeadline
                    ) external payable;
                    function send(
                        uint256 chainId,
                        address recipient,
                        uint256 amount,
                        uint256 bonderFee,
                        uint256 amountOutMin,
                        uint256 deadline
                    ) external;
                }
                interface IL2AmmWrapper {
                    function bridge() external view returns (address);
                    function l2CanonicalToken() external view returns (address);
                    function hToken() external view returns (address);
                    function exchangeAddress() external view returns (address);
                }
                interface ISwap {
                    function swap(
                        uint8 tokenIndexFrom,
                        uint8 tokenIndexTo,
                        uint256 dx,
                        uint256 minDy,
                        uint256 deadline
                    ) external returns (uint256);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                interface ILiFi {
                    /// Structs ///
                    struct BridgeData {
                        bytes32 transactionId;
                        string bridge;
                        string integrator;
                        address referrer;
                        address sendingAssetId;
                        address receiver;
                        uint256 minAmount;
                        uint256 destinationChainId;
                        bool hasSourceSwaps;
                        bool hasDestinationCall;
                    }
                    /// Events ///
                    event LiFiTransferStarted(ILiFi.BridgeData bridgeData);
                    event LiFiTransferCompleted(
                        bytes32 indexed transactionId,
                        address receivingAssetId,
                        address receiver,
                        uint256 amount,
                        uint256 timestamp
                    );
                    event LiFiTransferRecovered(
                        bytes32 indexed transactionId,
                        address receivingAssetId,
                        address receiver,
                        uint256 amount,
                        uint256 timestamp
                    );
                    event LiFiGenericSwapCompleted(
                        bytes32 indexed transactionId,
                        string integrator,
                        string referrer,
                        address receiver,
                        address fromAssetId,
                        address toAssetId,
                        uint256 fromAmount,
                        uint256 toAmount
                    );
                    // Deprecated but kept here to include in ABI to parse historic events
                    event LiFiSwappedGeneric(
                        bytes32 indexed transactionId,
                        string integrator,
                        string referrer,
                        address fromAssetId,
                        address toAssetId,
                        uint256 fromAmount,
                        uint256 toAmount
                    );
                }
                // SPDX-License-Identifier: AGPL-3.0-only
                pragma solidity >=0.8.0;
                import {ERC20} from "../tokens/ERC20.sol";
                /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
                /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
                /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
                /// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
                library SafeTransferLib {
                    /*//////////////////////////////////////////////////////////////
                                             ETH OPERATIONS
                    //////////////////////////////////////////////////////////////*/
                    function safeTransferETH(address to, uint256 amount) internal {
                        bool success;
                        /// @solidity memory-safe-assembly
                        assembly {
                            // Transfer the ETH and store if it succeeded or not.
                            success := call(gas(), to, amount, 0, 0, 0, 0)
                        }
                        require(success, "ETH_TRANSFER_FAILED");
                    }
                    /*//////////////////////////////////////////////////////////////
                                            ERC20 OPERATIONS
                    //////////////////////////////////////////////////////////////*/
                    function safeTransferFrom(
                        ERC20 token,
                        address from,
                        address to,
                        uint256 amount
                    ) internal {
                        bool success;
                        /// @solidity memory-safe-assembly
                        assembly {
                            // Get a pointer to some free memory.
                            let freeMemoryPointer := mload(0x40)
                            // Write the abi-encoded calldata into memory, beginning with the function selector.
                            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
                            mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
                            mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
                            mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.
                            success := and(
                                // Set success to whether the call reverted, if not we check it either
                                // returned exactly 1 (can't just be non-zero data), or had no return data.
                                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                                // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
                                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                                // Counterintuitively, this call must be positioned second to the or() call in the
                                // surrounding and() call or else returndatasize() will be zero during the computation.
                                call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
                            )
                        }
                        require(success, "TRANSFER_FROM_FAILED");
                    }
                    function safeTransfer(
                        ERC20 token,
                        address to,
                        uint256 amount
                    ) internal {
                        bool success;
                        /// @solidity memory-safe-assembly
                        assembly {
                            // Get a pointer to some free memory.
                            let freeMemoryPointer := mload(0x40)
                            // Write the abi-encoded calldata into memory, beginning with the function selector.
                            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
                            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
                            success := and(
                                // Set success to whether the call reverted, if not we check it either
                                // returned exactly 1 (can't just be non-zero data), or had no return data.
                                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                                // Counterintuitively, this call must be positioned second to the or() call in the
                                // surrounding and() call or else returndatasize() will be zero during the computation.
                                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
                            )
                        }
                        require(success, "TRANSFER_FAILED");
                    }
                    function safeApprove(
                        ERC20 token,
                        address to,
                        uint256 amount
                    ) internal {
                        bool success;
                        /// @solidity memory-safe-assembly
                        assembly {
                            // Get a pointer to some free memory.
                            let freeMemoryPointer := mload(0x40)
                            // Write the abi-encoded calldata into memory, beginning with the function selector.
                            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
                            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
                            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
                            success := and(
                                // Set success to whether the call reverted, if not we check it either
                                // returned exactly 1 (can't just be non-zero data), or had no return data.
                                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                                // Counterintuitively, this call must be positioned second to the or() call in the
                                // surrounding and() call or else returndatasize() will be zero during the computation.
                                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
                            )
                        }
                        require(success, "APPROVE_FAILED");
                    }
                }
                // SPDX-License-Identifier: UNLICENSED
                pragma solidity 0.8.17;
                import { InsufficientBalance, NullAddrIsNotAnERC20Token, NullAddrIsNotAValidSpender, NoTransferToNullAddress, InvalidAmount, NativeAssetTransferFailed } from "../Errors/GenericErrors.sol";
                import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
                import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                import { LibSwap } from "./LibSwap.sol";
                /// @title LibAsset
                /// @notice This library contains helpers for dealing with onchain transfers
                ///         of assets, including accounting for the native asset `assetId`
                ///         conventions and any noncompliant ERC20 transfers
                library LibAsset {
                    uint256 private constant MAX_UINT = type(uint256).max;
                    address internal constant NULL_ADDRESS = address(0);
                    /// @dev All native assets use the empty address for their asset id
                    ///      by convention
                    address internal constant NATIVE_ASSETID = NULL_ADDRESS; //address(0)
                    /// @notice Gets the balance of the inheriting contract for the given asset
                    /// @param assetId The asset identifier to get the balance of
                    /// @return Balance held by contracts using this library
                    function getOwnBalance(address assetId) internal view returns (uint256) {
                        return
                            isNativeAsset(assetId)
                                ? address(this).balance
                                : IERC20(assetId).balanceOf(address(this));
                    }
                    /// @notice Transfers ether from the inheriting contract to a given
                    ///         recipient
                    /// @param recipient Address to send ether to
                    /// @param amount Amount to send to given recipient
                    function transferNativeAsset(
                        address payable recipient,
                        uint256 amount
                    ) private {
                        if (recipient == NULL_ADDRESS) revert NoTransferToNullAddress();
                        if (amount > address(this).balance)
                            revert InsufficientBalance(amount, address(this).balance);
                        // solhint-disable-next-line avoid-low-level-calls
                        (bool success, ) = recipient.call{ value: amount }("");
                        if (!success) revert NativeAssetTransferFailed();
                    }
                    /// @notice If the current allowance is insufficient, the allowance for a given spender
                    /// is set to MAX_UINT.
                    /// @param assetId Token address to transfer
                    /// @param spender Address to give spend approval to
                    /// @param amount Amount to approve for spending
                    function maxApproveERC20(
                        IERC20 assetId,
                        address spender,
                        uint256 amount
                    ) internal {
                        if (isNativeAsset(address(assetId))) {
                            return;
                        }
                        if (spender == NULL_ADDRESS) {
                            revert NullAddrIsNotAValidSpender();
                        }
                        if (assetId.allowance(address(this), spender) < amount) {
                            SafeERC20.safeApprove(IERC20(assetId), spender, 0);
                            SafeERC20.safeApprove(IERC20(assetId), spender, MAX_UINT);
                        }
                    }
                    /// @notice Transfers tokens from the inheriting contract to a given
                    ///         recipient
                    /// @param assetId Token address to transfer
                    /// @param recipient Address to send token to
                    /// @param amount Amount to send to given recipient
                    function transferERC20(
                        address assetId,
                        address recipient,
                        uint256 amount
                    ) private {
                        if (isNativeAsset(assetId)) {
                            revert NullAddrIsNotAnERC20Token();
                        }
                        if (recipient == NULL_ADDRESS) {
                            revert NoTransferToNullAddress();
                        }
                        uint256 assetBalance = IERC20(assetId).balanceOf(address(this));
                        if (amount > assetBalance) {
                            revert InsufficientBalance(amount, assetBalance);
                        }
                        SafeERC20.safeTransfer(IERC20(assetId), recipient, amount);
                    }
                    /// @notice Transfers tokens from a sender to a given recipient
                    /// @param assetId Token address to transfer
                    /// @param from Address of sender/owner
                    /// @param to Address of recipient/spender
                    /// @param amount Amount to transfer from owner to spender
                    function transferFromERC20(
                        address assetId,
                        address from,
                        address to,
                        uint256 amount
                    ) internal {
                        if (isNativeAsset(assetId)) {
                            revert NullAddrIsNotAnERC20Token();
                        }
                        if (to == NULL_ADDRESS) {
                            revert NoTransferToNullAddress();
                        }
                        IERC20 asset = IERC20(assetId);
                        uint256 prevBalance = asset.balanceOf(to);
                        SafeERC20.safeTransferFrom(asset, from, to, amount);
                        if (asset.balanceOf(to) - prevBalance != amount) {
                            revert InvalidAmount();
                        }
                    }
                    function depositAsset(address assetId, uint256 amount) internal {
                        if (amount == 0) revert InvalidAmount();
                        if (isNativeAsset(assetId)) {
                            if (msg.value < amount) revert InvalidAmount();
                        } else {
                            uint256 balance = IERC20(assetId).balanceOf(msg.sender);
                            if (balance < amount) revert InsufficientBalance(amount, balance);
                            transferFromERC20(assetId, msg.sender, address(this), amount);
                        }
                    }
                    function depositAssets(LibSwap.SwapData[] calldata swaps) internal {
                        for (uint256 i = 0; i < swaps.length; ) {
                            LibSwap.SwapData calldata swap = swaps[i];
                            if (swap.requiresDeposit) {
                                depositAsset(swap.sendingAssetId, swap.fromAmount);
                            }
                            unchecked {
                                i++;
                            }
                        }
                    }
                    /// @notice Determines whether the given assetId is the native asset
                    /// @param assetId The asset identifier to evaluate
                    /// @return Boolean indicating if the asset is the native asset
                    function isNativeAsset(address assetId) internal pure returns (bool) {
                        return assetId == NATIVE_ASSETID;
                    }
                    /// @notice Wrapper function to transfer a given asset (native or erc20) to
                    ///         some recipient. Should handle all non-compliant return value
                    ///         tokens as well by using the SafeERC20 contract by open zeppelin.
                    /// @param assetId Asset id for transfer (address(0) for native asset,
                    ///                token address for erc20s)
                    /// @param recipient Address to send asset to
                    /// @param amount Amount to send to given recipient
                    function transferAsset(
                        address assetId,
                        address payable recipient,
                        uint256 amount
                    ) internal {
                        isNativeAsset(assetId)
                            ? transferNativeAsset(recipient, amount)
                            : transferERC20(assetId, recipient, amount);
                    }
                    /// @dev Checks whether the given address is a contract and contains code
                    function isContract(address _contractAddr) internal view returns (bool) {
                        uint256 size;
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            size := extcodesize(_contractAddr)
                        }
                        return size > 0;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                import { IERC173 } from "../Interfaces/IERC173.sol";
                import { LibAsset } from "../Libraries/LibAsset.sol";
                contract TransferrableOwnership is IERC173 {
                    address public owner;
                    address public pendingOwner;
                    /// Errors ///
                    error UnAuthorized();
                    error NoNullOwner();
                    error NewOwnerMustNotBeSelf();
                    error NoPendingOwnershipTransfer();
                    error NotPendingOwner();
                    /// Events ///
                    event OwnershipTransferRequested(
                        address indexed _from,
                        address indexed _to
                    );
                    constructor(address initialOwner) {
                        owner = initialOwner;
                    }
                    modifier onlyOwner() {
                        if (msg.sender != owner) revert UnAuthorized();
                        _;
                    }
                    /// @notice Initiates transfer of ownership to a new address
                    /// @param _newOwner the address to transfer ownership to
                    function transferOwnership(address _newOwner) external onlyOwner {
                        if (_newOwner == LibAsset.NULL_ADDRESS) revert NoNullOwner();
                        if (_newOwner == msg.sender) revert NewOwnerMustNotBeSelf();
                        pendingOwner = _newOwner;
                        emit OwnershipTransferRequested(msg.sender, pendingOwner);
                    }
                    /// @notice Cancel transfer of ownership
                    function cancelOwnershipTransfer() external onlyOwner {
                        if (pendingOwner == LibAsset.NULL_ADDRESS)
                            revert NoPendingOwnershipTransfer();
                        pendingOwner = LibAsset.NULL_ADDRESS;
                    }
                    /// @notice Confirms transfer of ownership to the calling address (msg.sender)
                    function confirmOwnershipTransfer() external {
                        address _pendingOwner = pendingOwner;
                        if (msg.sender != _pendingOwner) revert NotPendingOwner();
                        emit OwnershipTransferred(owner, _pendingOwner);
                        owner = _pendingOwner;
                        pendingOwner = LibAsset.NULL_ADDRESS;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                import { ILiFi } from "../Interfaces/ILiFi.sol";
                import { IHopBridge } from "../Interfaces/IHopBridge.sol";
                import { LibAsset, IERC20 } from "../Libraries/LibAsset.sol";
                import { SwapperV2, LibSwap } from "../Helpers/SwapperV2.sol";
                import { LibDiamond } from "../Libraries/LibDiamond.sol";
                /// @title Hop Facet (Optimized)
                /// @author LI.FI (https://li.fi)
                /// @notice Provides functionality for bridging through Hop
                /// @custom:version 2.0.0
                contract HopFacetOptimized is ILiFi, SwapperV2 {
                    /// Types ///
                    struct HopData {
                        uint256 bonderFee;
                        uint256 amountOutMin;
                        uint256 deadline;
                        uint256 destinationAmountOutMin;
                        uint256 destinationDeadline;
                        IHopBridge hopBridge;
                        address relayer;
                        uint256 relayerFee;
                        uint256 nativeFee;
                    }
                    /// External Methods ///
                    /// @notice Sets approval for the Hop Bridge to spend the specified token
                    /// @param bridges The Hop Bridges to approve
                    /// @param tokensToApprove The tokens to approve to approve to the Hop Bridges
                    function setApprovalForBridges(
                        address[] calldata bridges,
                        address[] calldata tokensToApprove
                    ) external {
                        LibDiamond.enforceIsContractOwner();
                        for (uint256 i; i < bridges.length; i++) {
                            // Give Hop approval to bridge tokens
                            LibAsset.maxApproveERC20(
                                IERC20(tokensToApprove[i]),
                                address(bridges[i]),
                                type(uint256).max
                            );
                        }
                    }
                    /// @notice Bridges ERC20 tokens via Hop Protocol from L1
                    /// @param _bridgeData the core information needed for bridging
                    /// @param _hopData data specific to Hop Protocol
                    function startBridgeTokensViaHopL1ERC20(
                        ILiFi.BridgeData calldata _bridgeData,
                        HopData calldata _hopData
                    ) external payable {
                        // Deposit assets
                        LibAsset.transferFromERC20(
                            _bridgeData.sendingAssetId,
                            msg.sender,
                            address(this),
                            _bridgeData.minAmount
                        );
                        // Bridge assets
                        _hopData.hopBridge.sendToL2{ value: _hopData.nativeFee }(
                            _bridgeData.destinationChainId,
                            _bridgeData.receiver,
                            _bridgeData.minAmount,
                            _hopData.destinationAmountOutMin,
                            _hopData.destinationDeadline,
                            _hopData.relayer,
                            _hopData.relayerFee
                        );
                        emit LiFiTransferStarted(_bridgeData);
                    }
                    /// @notice Bridges Native tokens via Hop Protocol from L1
                    /// @param _bridgeData the core information needed for bridging
                    /// @param _hopData data specific to Hop Protocol
                    function startBridgeTokensViaHopL1Native(
                        ILiFi.BridgeData calldata _bridgeData,
                        HopData calldata _hopData
                    ) external payable {
                        // Bridge assets
                        _hopData.hopBridge.sendToL2{
                            value: _bridgeData.minAmount + _hopData.nativeFee
                        }(
                            _bridgeData.destinationChainId,
                            _bridgeData.receiver,
                            _bridgeData.minAmount,
                            _hopData.destinationAmountOutMin,
                            _hopData.destinationDeadline,
                            _hopData.relayer,
                            _hopData.relayerFee
                        );
                        emit LiFiTransferStarted(_bridgeData);
                    }
                    /// @notice Performs a swap before bridging ERC20 tokens via Hop Protocol from L1
                    /// @param _bridgeData the core information needed for bridging
                    /// @param _swapData an array of swap related data for performing swaps before bridging
                    /// @param _hopData data specific to Hop Protocol
                    function swapAndStartBridgeTokensViaHopL1ERC20(
                        ILiFi.BridgeData memory _bridgeData,
                        LibSwap.SwapData[] calldata _swapData,
                        HopData calldata _hopData
                    ) external payable {
                        // Deposit and swap assets
                        _bridgeData.minAmount = _depositAndSwap(
                            _bridgeData.transactionId,
                            _bridgeData.minAmount,
                            _swapData,
                            payable(msg.sender),
                            _hopData.nativeFee
                        );
                        // Bridge assets
                        _hopData.hopBridge.sendToL2{ value: _hopData.nativeFee }(
                            _bridgeData.destinationChainId,
                            _bridgeData.receiver,
                            _bridgeData.minAmount,
                            _hopData.destinationAmountOutMin,
                            _hopData.destinationDeadline,
                            _hopData.relayer,
                            _hopData.relayerFee
                        );
                        emit LiFiTransferStarted(_bridgeData);
                    }
                    /// @notice Performs a swap before bridging Native tokens via Hop Protocol from L1
                    /// @param _bridgeData the core information needed for bridging
                    /// @param _swapData an array of swap related data for performing swaps before bridging
                    /// @param _hopData data specific to Hop Protocol
                    function swapAndStartBridgeTokensViaHopL1Native(
                        ILiFi.BridgeData memory _bridgeData,
                        LibSwap.SwapData[] calldata _swapData,
                        HopData calldata _hopData
                    ) external payable {
                        // Deposit and swap assets
                        _bridgeData.minAmount = _depositAndSwap(
                            _bridgeData.transactionId,
                            _bridgeData.minAmount,
                            _swapData,
                            payable(msg.sender),
                            _hopData.nativeFee
                        );
                        // Bridge assets
                        _hopData.hopBridge.sendToL2{
                            value: _bridgeData.minAmount + _hopData.nativeFee
                        }(
                            _bridgeData.destinationChainId,
                            _bridgeData.receiver,
                            _bridgeData.minAmount,
                            _hopData.destinationAmountOutMin,
                            _hopData.destinationDeadline,
                            _hopData.relayer,
                            _hopData.relayerFee
                        );
                        emit LiFiTransferStarted(_bridgeData);
                    }
                    /// @notice Bridges ERC20 tokens via Hop Protocol from L2
                    /// @param _bridgeData the core information needed for bridging
                    /// @param _hopData data specific to Hop Protocol
                    function startBridgeTokensViaHopL2ERC20(
                        ILiFi.BridgeData calldata _bridgeData,
                        HopData calldata _hopData
                    ) external {
                        // Deposit assets
                        LibAsset.transferFromERC20(
                            _bridgeData.sendingAssetId,
                            msg.sender,
                            address(this),
                            _bridgeData.minAmount
                        );
                        // Bridge assets
                        _hopData.hopBridge.swapAndSend(
                            _bridgeData.destinationChainId,
                            _bridgeData.receiver,
                            _bridgeData.minAmount,
                            _hopData.bonderFee,
                            _hopData.amountOutMin,
                            _hopData.deadline,
                            _hopData.destinationAmountOutMin,
                            _hopData.destinationDeadline
                        );
                        emit LiFiTransferStarted(_bridgeData);
                    }
                    /// @notice Bridges Native tokens via Hop Protocol from L2
                    /// @param _bridgeData the core information needed for bridging
                    /// @param _hopData data specific to Hop Protocol
                    function startBridgeTokensViaHopL2Native(
                        ILiFi.BridgeData calldata _bridgeData,
                        HopData calldata _hopData
                    ) external payable {
                        // Bridge assets
                        _hopData.hopBridge.swapAndSend{ value: _bridgeData.minAmount }(
                            _bridgeData.destinationChainId,
                            _bridgeData.receiver,
                            _bridgeData.minAmount,
                            _hopData.bonderFee,
                            _hopData.amountOutMin,
                            _hopData.deadline,
                            _hopData.destinationAmountOutMin,
                            _hopData.destinationDeadline
                        );
                        emit LiFiTransferStarted(_bridgeData);
                    }
                    /// @notice Performs a swap before bridging ERC20 tokens via Hop Protocol from L2
                    /// @param _bridgeData the core information needed for bridging
                    /// @param _swapData an array of swap related data for performing swaps before bridging
                    /// @param _hopData data specific to Hop Protocol
                    function swapAndStartBridgeTokensViaHopL2ERC20(
                        ILiFi.BridgeData memory _bridgeData,
                        LibSwap.SwapData[] calldata _swapData,
                        HopData calldata _hopData
                    ) external payable {
                        // Deposit and swap assets
                        _bridgeData.minAmount = _depositAndSwap(
                            _bridgeData.transactionId,
                            _bridgeData.minAmount,
                            _swapData,
                            payable(msg.sender)
                        );
                        // Bridge assets
                        _hopData.hopBridge.swapAndSend(
                            _bridgeData.destinationChainId,
                            _bridgeData.receiver,
                            _bridgeData.minAmount,
                            _hopData.bonderFee,
                            _hopData.amountOutMin,
                            _hopData.deadline,
                            _hopData.destinationAmountOutMin,
                            _hopData.destinationDeadline
                        );
                        emit LiFiTransferStarted(_bridgeData);
                    }
                    /// @notice Performs a swap before bridging Native tokens via Hop Protocol from L2
                    /// @param _bridgeData the core information needed for bridging
                    /// @param _swapData an array of swap related data for performing swaps before bridging
                    /// @param _hopData data specific to Hop Protocol
                    function swapAndStartBridgeTokensViaHopL2Native(
                        ILiFi.BridgeData memory _bridgeData,
                        LibSwap.SwapData[] calldata _swapData,
                        HopData calldata _hopData
                    ) external payable {
                        // Deposit and swap assets
                        _bridgeData.minAmount = _depositAndSwap(
                            _bridgeData.transactionId,
                            _bridgeData.minAmount,
                            _swapData,
                            payable(msg.sender)
                        );
                        // Bridge assets
                        _hopData.hopBridge.swapAndSend{ value: _bridgeData.minAmount }(
                            _bridgeData.destinationChainId,
                            _bridgeData.receiver,
                            _bridgeData.minAmount,
                            _hopData.bonderFee,
                            _hopData.amountOutMin,
                            _hopData.deadline,
                            _hopData.destinationAmountOutMin,
                            _hopData.destinationDeadline
                        );
                        emit LiFiTransferStarted(_bridgeData);
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0-only
                pragma solidity >=0.8.0;
                import {ERC20} from "./ERC20.sol";
                import {SafeTransferLib} from "../utils/SafeTransferLib.sol";
                /// @notice Minimalist and modern Wrapped Ether implementation.
                /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/WETH.sol)
                /// @author Inspired by WETH9 (https://github.com/dapphub/ds-weth/blob/master/src/weth9.sol)
                contract WETH is ERC20("Wrapped Ether", "WETH", 18) {
                    using SafeTransferLib for address;
                    event Deposit(address indexed from, uint256 amount);
                    event Withdrawal(address indexed to, uint256 amount);
                    function deposit() public payable virtual {
                        _mint(msg.sender, msg.value);
                        emit Deposit(msg.sender, msg.value);
                    }
                    function withdraw(uint256 amount) public virtual {
                        _burn(msg.sender, amount);
                        emit Withdrawal(msg.sender, amount);
                        msg.sender.safeTransferETH(amount);
                    }
                    receive() external payable virtual {
                        deposit();
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0-only
                pragma solidity >=0.8.0;
                /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
                /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
                /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
                /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
                abstract contract ERC20 {
                    /*//////////////////////////////////////////////////////////////
                                                 EVENTS
                    //////////////////////////////////////////////////////////////*/
                    event Transfer(address indexed from, address indexed to, uint256 amount);
                    event Approval(address indexed owner, address indexed spender, uint256 amount);
                    /*//////////////////////////////////////////////////////////////
                                            METADATA STORAGE
                    //////////////////////////////////////////////////////////////*/
                    string public name;
                    string public symbol;
                    uint8 public immutable decimals;
                    /*//////////////////////////////////////////////////////////////
                                              ERC20 STORAGE
                    //////////////////////////////////////////////////////////////*/
                    uint256 public totalSupply;
                    mapping(address => uint256) public balanceOf;
                    mapping(address => mapping(address => uint256)) public allowance;
                    /*//////////////////////////////////////////////////////////////
                                            EIP-2612 STORAGE
                    //////////////////////////////////////////////////////////////*/
                    uint256 internal immutable INITIAL_CHAIN_ID;
                    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
                    mapping(address => uint256) public nonces;
                    /*//////////////////////////////////////////////////////////////
                                               CONSTRUCTOR
                    //////////////////////////////////////////////////////////////*/
                    constructor(
                        string memory _name,
                        string memory _symbol,
                        uint8 _decimals
                    ) {
                        name = _name;
                        symbol = _symbol;
                        decimals = _decimals;
                        INITIAL_CHAIN_ID = block.chainid;
                        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
                    }
                    /*//////////////////////////////////////////////////////////////
                                               ERC20 LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function approve(address spender, uint256 amount) public virtual returns (bool) {
                        allowance[msg.sender][spender] = amount;
                        emit Approval(msg.sender, spender, amount);
                        return true;
                    }
                    function transfer(address to, uint256 amount) public virtual returns (bool) {
                        balanceOf[msg.sender] -= amount;
                        // Cannot overflow because the sum of all user
                        // balances can't exceed the max uint256 value.
                        unchecked {
                            balanceOf[to] += amount;
                        }
                        emit Transfer(msg.sender, to, amount);
                        return true;
                    }
                    function transferFrom(
                        address from,
                        address to,
                        uint256 amount
                    ) public virtual returns (bool) {
                        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
                        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
                        balanceOf[from] -= amount;
                        // Cannot overflow because the sum of all user
                        // balances can't exceed the max uint256 value.
                        unchecked {
                            balanceOf[to] += amount;
                        }
                        emit Transfer(from, to, amount);
                        return true;
                    }
                    /*//////////////////////////////////////////////////////////////
                                             EIP-2612 LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function permit(
                        address owner,
                        address spender,
                        uint256 value,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) public virtual {
                        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
                        // Unchecked because the only math done is incrementing
                        // the owner's nonce which cannot realistically overflow.
                        unchecked {
                            address recoveredAddress = ecrecover(
                                keccak256(
                                    abi.encodePacked(
                                        "\\x19\\x01",
                                        DOMAIN_SEPARATOR(),
                                        keccak256(
                                            abi.encode(
                                                keccak256(
                                                    "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                                ),
                                                owner,
                                                spender,
                                                value,
                                                nonces[owner]++,
                                                deadline
                                            )
                                        )
                                    )
                                ),
                                v,
                                r,
                                s
                            );
                            require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
                            allowance[recoveredAddress][spender] = value;
                        }
                        emit Approval(owner, spender, value);
                    }
                    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
                        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
                    }
                    function computeDomainSeparator() internal view virtual returns (bytes32) {
                        return
                            keccak256(
                                abi.encode(
                                    keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                    keccak256(bytes(name)),
                                    keccak256("1"),
                                    block.chainid,
                                    address(this)
                                )
                            );
                    }
                    /*//////////////////////////////////////////////////////////////
                                        INTERNAL MINT/BURN LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function _mint(address to, uint256 amount) internal virtual {
                        totalSupply += amount;
                        // Cannot overflow because the sum of all user
                        // balances can't exceed the max uint256 value.
                        unchecked {
                            balanceOf[to] += amount;
                        }
                        emit Transfer(address(0), to, amount);
                    }
                    function _burn(address from, uint256 amount) internal virtual {
                        balanceOf[from] -= amount;
                        // Cannot underflow because a user's balance
                        // will never be larger than the total supply.
                        unchecked {
                            totalSupply -= amount;
                        }
                        emit Transfer(from, address(0), amount);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                error AlreadyInitialized();
                error CannotAuthoriseSelf();
                error CannotBridgeToSameNetwork();
                error ContractCallNotAllowed();
                error CumulativeSlippageTooHigh(uint256 minAmount, uint256 receivedAmount);
                error ExternalCallFailed();
                error InformationMismatch();
                error InsufficientBalance(uint256 required, uint256 balance);
                error InvalidAmount();
                error InvalidCallData();
                error InvalidConfig();
                error InvalidContract();
                error InvalidDestinationChain();
                error InvalidFallbackAddress();
                error InvalidReceiver();
                error InvalidSendingToken();
                error NativeAssetNotSupported();
                error NativeAssetTransferFailed();
                error NoSwapDataProvided();
                error NoSwapFromZeroBalance();
                error NotAContract();
                error NotInitialized();
                error NoTransferToNullAddress();
                error NullAddrIsNotAnERC20Token();
                error NullAddrIsNotAValidSpender();
                error OnlyContractOwner();
                error RecoveryAddressCannotBeZero();
                error ReentrancyError();
                error TokenNotSupported();
                error UnAuthorized();
                error UnsupportedChainId(uint256 chainId);
                error WithdrawFailed();
                error ZeroAmount();
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (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. Compatible with tokens that require the approval to be set to
                     * 0 before setting it to a non-zero value.
                     */
                    function forceApprove(IERC20 token, address spender, uint256 value) internal {
                        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
                        if (!_callOptionalReturnBool(token, approvalCall)) {
                            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
                            _callOptionalReturn(token, approvalCall);
                        }
                    }
                    /**
                     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
                     * Revert on invalid signature.
                     */
                    function safePermit(
                        IERC20Permit token,
                        address owner,
                        address spender,
                        uint256 value,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) internal {
                        uint256 nonceBefore = token.nonces(owner);
                        token.permit(owner, spender, value, deadline, v, r, s);
                        uint256 nonceAfter = token.nonces(owner);
                        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
                    }
                    /**
                     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                     * on the return value: the return value is optional (but if data is returned, it must not be false).
                     * @param token The token targeted by the call.
                     * @param data The call data (encoded using abi.encode or one of its variants).
                     */
                    function _callOptionalReturn(IERC20 token, bytes memory data) private {
                        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                        // the target address contains contract code and also asserts for success in the low-level call.
                        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                    }
                    /**
                     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                     * on the return value: the return value is optional (but if data is returned, it must not be false).
                     * @param token The token targeted by the call.
                     * @param data The call data (encoded using abi.encode or one of its variants).
                     *
                     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
                     */
                    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
                        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
                        // and not revert is the subcall reverts.
                        (bool success, bytes memory returndata) = address(token).call(data);
                        return
                            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (token/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
                pragma solidity 0.8.17;
                import { LibAsset } from "./LibAsset.sol";
                import { LibUtil } from "./LibUtil.sol";
                import { InvalidContract, NoSwapFromZeroBalance, InsufficientBalance } from "../Errors/GenericErrors.sol";
                import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                library LibSwap {
                    struct SwapData {
                        address callTo;
                        address approveTo;
                        address sendingAssetId;
                        address receivingAssetId;
                        uint256 fromAmount;
                        bytes callData;
                        bool requiresDeposit;
                    }
                    event AssetSwapped(
                        bytes32 transactionId,
                        address dex,
                        address fromAssetId,
                        address toAssetId,
                        uint256 fromAmount,
                        uint256 toAmount,
                        uint256 timestamp
                    );
                    function swap(bytes32 transactionId, SwapData calldata _swap) internal {
                        if (!LibAsset.isContract(_swap.callTo)) revert InvalidContract();
                        uint256 fromAmount = _swap.fromAmount;
                        if (fromAmount == 0) revert NoSwapFromZeroBalance();
                        uint256 nativeValue = LibAsset.isNativeAsset(_swap.sendingAssetId)
                            ? _swap.fromAmount
                            : 0;
                        uint256 initialSendingAssetBalance = LibAsset.getOwnBalance(
                            _swap.sendingAssetId
                        );
                        uint256 initialReceivingAssetBalance = LibAsset.getOwnBalance(
                            _swap.receivingAssetId
                        );
                        if (nativeValue == 0) {
                            LibAsset.maxApproveERC20(
                                IERC20(_swap.sendingAssetId),
                                _swap.approveTo,
                                _swap.fromAmount
                            );
                        }
                        if (initialSendingAssetBalance < _swap.fromAmount) {
                            revert InsufficientBalance(
                                _swap.fromAmount,
                                initialSendingAssetBalance
                            );
                        }
                        // solhint-disable-next-line avoid-low-level-calls
                        (bool success, bytes memory res) = _swap.callTo.call{
                            value: nativeValue
                        }(_swap.callData);
                        if (!success) {
                            string memory reason = LibUtil.getRevertMsg(res);
                            revert(reason);
                        }
                        uint256 newBalance = LibAsset.getOwnBalance(_swap.receivingAssetId);
                        emit AssetSwapped(
                            transactionId,
                            _swap.callTo,
                            _swap.sendingAssetId,
                            _swap.receivingAssetId,
                            _swap.fromAmount,
                            newBalance > initialReceivingAssetBalance
                                ? newBalance - initialReceivingAssetBalance
                                : newBalance,
                            block.timestamp
                        );
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                /// @title ERC-173 Contract Ownership Standard
                ///  Note: the ERC-165 identifier for this interface is 0x7f5828d0
                /* is ERC165 */
                interface IERC173 {
                    /// @dev This emits when ownership of a contract changes.
                    event OwnershipTransferred(
                        address indexed previousOwner,
                        address indexed newOwner
                    );
                    /// @notice Get the address of the owner
                    /// @return owner_ The address of the owner.
                    function owner() external view returns (address owner_);
                    /// @notice Set the address of the new owner of the contract
                    /// @dev Set _newOwner to address(0) to renounce any ownership.
                    /// @param _newOwner The address of the new owner of the contract
                    function transferOwnership(address _newOwner) external;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                import { ILiFi } from "../Interfaces/ILiFi.sol";
                import { LibSwap } from "../Libraries/LibSwap.sol";
                import { LibAsset } from "../Libraries/LibAsset.sol";
                import { LibAllowList } from "../Libraries/LibAllowList.sol";
                import { ContractCallNotAllowed, NoSwapDataProvided, CumulativeSlippageTooHigh } from "../Errors/GenericErrors.sol";
                /// @title Swapper
                /// @author LI.FI (https://li.fi)
                /// @notice Abstract contract to provide swap functionality
                contract SwapperV2 is ILiFi {
                    /// Types ///
                    /// @dev only used to get around "Stack Too Deep" errors
                    struct ReserveData {
                        bytes32 transactionId;
                        address payable leftoverReceiver;
                        uint256 nativeReserve;
                    }
                    /// Modifiers ///
                    /// @dev Sends any leftover balances back to the user
                    /// @notice Sends any leftover balances to the user
                    /// @param _swaps Swap data array
                    /// @param _leftoverReceiver Address to send leftover tokens to
                    /// @param _initialBalances Array of initial token balances
                    modifier noLeftovers(
                        LibSwap.SwapData[] calldata _swaps,
                        address payable _leftoverReceiver,
                        uint256[] memory _initialBalances
                    ) {
                        uint256 numSwaps = _swaps.length;
                        if (numSwaps != 1) {
                            address finalAsset = _swaps[numSwaps - 1].receivingAssetId;
                            uint256 curBalance;
                            _;
                            for (uint256 i = 0; i < numSwaps - 1; ) {
                                address curAsset = _swaps[i].receivingAssetId;
                                // Handle multi-to-one swaps
                                if (curAsset != finalAsset) {
                                    curBalance =
                                        LibAsset.getOwnBalance(curAsset) -
                                        _initialBalances[i];
                                    if (curBalance > 0) {
                                        LibAsset.transferAsset(
                                            curAsset,
                                            _leftoverReceiver,
                                            curBalance
                                        );
                                    }
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                        } else {
                            _;
                        }
                    }
                    /// @dev Sends any leftover balances back to the user reserving native tokens
                    /// @notice Sends any leftover balances to the user
                    /// @param _swaps Swap data array
                    /// @param _leftoverReceiver Address to send leftover tokens to
                    /// @param _initialBalances Array of initial token balances
                    modifier noLeftoversReserve(
                        LibSwap.SwapData[] calldata _swaps,
                        address payable _leftoverReceiver,
                        uint256[] memory _initialBalances,
                        uint256 _nativeReserve
                    ) {
                        uint256 numSwaps = _swaps.length;
                        if (numSwaps != 1) {
                            address finalAsset = _swaps[numSwaps - 1].receivingAssetId;
                            uint256 curBalance;
                            _;
                            for (uint256 i = 0; i < numSwaps - 1; ) {
                                address curAsset = _swaps[i].receivingAssetId;
                                // Handle multi-to-one swaps
                                if (curAsset != finalAsset) {
                                    curBalance =
                                        LibAsset.getOwnBalance(curAsset) -
                                        _initialBalances[i];
                                    uint256 reserve = LibAsset.isNativeAsset(curAsset)
                                        ? _nativeReserve
                                        : 0;
                                    if (curBalance > 0) {
                                        LibAsset.transferAsset(
                                            curAsset,
                                            _leftoverReceiver,
                                            curBalance - reserve
                                        );
                                    }
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                        } else {
                            _;
                        }
                    }
                    /// @dev Refunds any excess native asset sent to the contract after the main function
                    /// @notice Refunds any excess native asset sent to the contract after the main function
                    /// @param _refundReceiver Address to send refunds to
                    modifier refundExcessNative(address payable _refundReceiver) {
                        uint256 initialBalance = address(this).balance - msg.value;
                        _;
                        uint256 finalBalance = address(this).balance;
                        if (finalBalance > initialBalance) {
                            LibAsset.transferAsset(
                                LibAsset.NATIVE_ASSETID,
                                _refundReceiver,
                                finalBalance - initialBalance
                            );
                        }
                    }
                    /// Internal Methods ///
                    /// @dev Deposits value, executes swaps, and performs minimum amount check
                    /// @param _transactionId the transaction id associated with the operation
                    /// @param _minAmount the minimum amount of the final asset to receive
                    /// @param _swaps Array of data used to execute swaps
                    /// @param _leftoverReceiver The address to send leftover funds to
                    /// @return uint256 result of the swap
                    function _depositAndSwap(
                        bytes32 _transactionId,
                        uint256 _minAmount,
                        LibSwap.SwapData[] calldata _swaps,
                        address payable _leftoverReceiver
                    ) internal returns (uint256) {
                        uint256 numSwaps = _swaps.length;
                        if (numSwaps == 0) {
                            revert NoSwapDataProvided();
                        }
                        address finalTokenId = _swaps[numSwaps - 1].receivingAssetId;
                        uint256 initialBalance = LibAsset.getOwnBalance(finalTokenId);
                        if (LibAsset.isNativeAsset(finalTokenId)) {
                            initialBalance -= msg.value;
                        }
                        uint256[] memory initialBalances = _fetchBalances(_swaps);
                        LibAsset.depositAssets(_swaps);
                        _executeSwaps(
                            _transactionId,
                            _swaps,
                            _leftoverReceiver,
                            initialBalances
                        );
                        uint256 newBalance = LibAsset.getOwnBalance(finalTokenId) -
                            initialBalance;
                        if (newBalance < _minAmount) {
                            revert CumulativeSlippageTooHigh(_minAmount, newBalance);
                        }
                        return newBalance;
                    }
                    /// @dev Deposits value, executes swaps, and performs minimum amount check and reserves native token for fees
                    /// @param _transactionId the transaction id associated with the operation
                    /// @param _minAmount the minimum amount of the final asset to receive
                    /// @param _swaps Array of data used to execute swaps
                    /// @param _leftoverReceiver The address to send leftover funds to
                    /// @param _nativeReserve Amount of native token to prevent from being swept back to the caller
                    function _depositAndSwap(
                        bytes32 _transactionId,
                        uint256 _minAmount,
                        LibSwap.SwapData[] calldata _swaps,
                        address payable _leftoverReceiver,
                        uint256 _nativeReserve
                    ) internal returns (uint256) {
                        uint256 numSwaps = _swaps.length;
                        if (numSwaps == 0) {
                            revert NoSwapDataProvided();
                        }
                        address finalTokenId = _swaps[numSwaps - 1].receivingAssetId;
                        uint256 initialBalance = LibAsset.getOwnBalance(finalTokenId);
                        if (LibAsset.isNativeAsset(finalTokenId)) {
                            initialBalance -= msg.value;
                        }
                        uint256[] memory initialBalances = _fetchBalances(_swaps);
                        LibAsset.depositAssets(_swaps);
                        ReserveData memory rd = ReserveData(
                            _transactionId,
                            _leftoverReceiver,
                            _nativeReserve
                        );
                        _executeSwaps(rd, _swaps, initialBalances);
                        uint256 newBalance = LibAsset.getOwnBalance(finalTokenId) -
                            initialBalance;
                        if (LibAsset.isNativeAsset(finalTokenId)) {
                            newBalance -= _nativeReserve;
                        }
                        if (newBalance < _minAmount) {
                            revert CumulativeSlippageTooHigh(_minAmount, newBalance);
                        }
                        return newBalance;
                    }
                    /// Private Methods ///
                    /// @dev Executes swaps and checks that DEXs used are in the allowList
                    /// @param _transactionId the transaction id associated with the operation
                    /// @param _swaps Array of data used to execute swaps
                    /// @param _leftoverReceiver Address to send leftover tokens to
                    /// @param _initialBalances Array of initial balances
                    function _executeSwaps(
                        bytes32 _transactionId,
                        LibSwap.SwapData[] calldata _swaps,
                        address payable _leftoverReceiver,
                        uint256[] memory _initialBalances
                    ) internal noLeftovers(_swaps, _leftoverReceiver, _initialBalances) {
                        uint256 numSwaps = _swaps.length;
                        for (uint256 i = 0; i < numSwaps; ) {
                            LibSwap.SwapData calldata currentSwap = _swaps[i];
                            if (
                                !((LibAsset.isNativeAsset(currentSwap.sendingAssetId) ||
                                    LibAllowList.contractIsAllowed(currentSwap.approveTo)) &&
                                    LibAllowList.contractIsAllowed(currentSwap.callTo) &&
                                    LibAllowList.selectorIsAllowed(
                                        bytes4(currentSwap.callData[:4])
                                    ))
                            ) revert ContractCallNotAllowed();
                            LibSwap.swap(_transactionId, currentSwap);
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /// @dev Executes swaps and checks that DEXs used are in the allowList
                    /// @param _reserveData Data passed used to reserve native tokens
                    /// @param _swaps Array of data used to execute swaps
                    function _executeSwaps(
                        ReserveData memory _reserveData,
                        LibSwap.SwapData[] calldata _swaps,
                        uint256[] memory _initialBalances
                    )
                        internal
                        noLeftoversReserve(
                            _swaps,
                            _reserveData.leftoverReceiver,
                            _initialBalances,
                            _reserveData.nativeReserve
                        )
                    {
                        uint256 numSwaps = _swaps.length;
                        for (uint256 i = 0; i < numSwaps; ) {
                            LibSwap.SwapData calldata currentSwap = _swaps[i];
                            if (
                                !((LibAsset.isNativeAsset(currentSwap.sendingAssetId) ||
                                    LibAllowList.contractIsAllowed(currentSwap.approveTo)) &&
                                    LibAllowList.contractIsAllowed(currentSwap.callTo) &&
                                    LibAllowList.selectorIsAllowed(
                                        bytes4(currentSwap.callData[:4])
                                    ))
                            ) revert ContractCallNotAllowed();
                            LibSwap.swap(_reserveData.transactionId, currentSwap);
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /// @dev Fetches balances of tokens to be swapped before swapping.
                    /// @param _swaps Array of data used to execute swaps
                    /// @return uint256[] Array of token balances.
                    function _fetchBalances(
                        LibSwap.SwapData[] calldata _swaps
                    ) private view returns (uint256[] memory) {
                        uint256 numSwaps = _swaps.length;
                        uint256[] memory balances = new uint256[](numSwaps);
                        address asset;
                        for (uint256 i = 0; i < numSwaps; ) {
                            asset = _swaps[i].receivingAssetId;
                            balances[i] = LibAsset.getOwnBalance(asset);
                            if (LibAsset.isNativeAsset(asset)) {
                                balances[i] -= msg.value;
                            }
                            unchecked {
                                ++i;
                            }
                        }
                        return balances;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                import { IDiamondCut } from "../Interfaces/IDiamondCut.sol";
                import { LibUtil } from "../Libraries/LibUtil.sol";
                import { OnlyContractOwner } from "../Errors/GenericErrors.sol";
                /// Implementation of EIP-2535 Diamond Standard
                /// https://eips.ethereum.org/EIPS/eip-2535
                library LibDiamond {
                    bytes32 internal constant DIAMOND_STORAGE_POSITION =
                        keccak256("diamond.standard.diamond.storage");
                    // Diamond specific errors
                    error IncorrectFacetCutAction();
                    error NoSelectorsInFace();
                    error FunctionAlreadyExists();
                    error FacetAddressIsZero();
                    error FacetAddressIsNotZero();
                    error FacetContainsNoCode();
                    error FunctionDoesNotExist();
                    error FunctionIsImmutable();
                    error InitZeroButCalldataNotEmpty();
                    error CalldataEmptyButInitNotZero();
                    error InitReverted();
                    // ----------------
                    struct FacetAddressAndPosition {
                        address facetAddress;
                        uint96 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array
                    }
                    struct FacetFunctionSelectors {
                        bytes4[] functionSelectors;
                        uint256 facetAddressPosition; // position of facetAddress in facetAddresses array
                    }
                    struct DiamondStorage {
                        // maps function selector to the facet address and
                        // the position of the selector in the facetFunctionSelectors.selectors array
                        mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition;
                        // maps facet addresses to function selectors
                        mapping(address => FacetFunctionSelectors) facetFunctionSelectors;
                        // facet addresses
                        address[] facetAddresses;
                        // Used to query if a contract implements an interface.
                        // Used to implement ERC-165.
                        mapping(bytes4 => bool) supportedInterfaces;
                        // owner of the contract
                        address contractOwner;
                    }
                    function diamondStorage()
                        internal
                        pure
                        returns (DiamondStorage storage ds)
                    {
                        bytes32 position = DIAMOND_STORAGE_POSITION;
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            ds.slot := position
                        }
                    }
                    event OwnershipTransferred(
                        address indexed previousOwner,
                        address indexed newOwner
                    );
                    function setContractOwner(address _newOwner) internal {
                        DiamondStorage storage ds = diamondStorage();
                        address previousOwner = ds.contractOwner;
                        ds.contractOwner = _newOwner;
                        emit OwnershipTransferred(previousOwner, _newOwner);
                    }
                    function contractOwner() internal view returns (address contractOwner_) {
                        contractOwner_ = diamondStorage().contractOwner;
                    }
                    function enforceIsContractOwner() internal view {
                        if (msg.sender != diamondStorage().contractOwner)
                            revert OnlyContractOwner();
                    }
                    event DiamondCut(
                        IDiamondCut.FacetCut[] _diamondCut,
                        address _init,
                        bytes _calldata
                    );
                    // Internal function version of diamondCut
                    function diamondCut(
                        IDiamondCut.FacetCut[] memory _diamondCut,
                        address _init,
                        bytes memory _calldata
                    ) internal {
                        for (uint256 facetIndex; facetIndex < _diamondCut.length; ) {
                            IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action;
                            if (action == IDiamondCut.FacetCutAction.Add) {
                                addFunctions(
                                    _diamondCut[facetIndex].facetAddress,
                                    _diamondCut[facetIndex].functionSelectors
                                );
                            } else if (action == IDiamondCut.FacetCutAction.Replace) {
                                replaceFunctions(
                                    _diamondCut[facetIndex].facetAddress,
                                    _diamondCut[facetIndex].functionSelectors
                                );
                            } else if (action == IDiamondCut.FacetCutAction.Remove) {
                                removeFunctions(
                                    _diamondCut[facetIndex].facetAddress,
                                    _diamondCut[facetIndex].functionSelectors
                                );
                            } else {
                                revert IncorrectFacetCutAction();
                            }
                            unchecked {
                                ++facetIndex;
                            }
                        }
                        emit DiamondCut(_diamondCut, _init, _calldata);
                        initializeDiamondCut(_init, _calldata);
                    }
                    function addFunctions(
                        address _facetAddress,
                        bytes4[] memory _functionSelectors
                    ) internal {
                        if (_functionSelectors.length == 0) {
                            revert NoSelectorsInFace();
                        }
                        DiamondStorage storage ds = diamondStorage();
                        if (LibUtil.isZeroAddress(_facetAddress)) {
                            revert FacetAddressIsZero();
                        }
                        uint96 selectorPosition = uint96(
                            ds.facetFunctionSelectors[_facetAddress].functionSelectors.length
                        );
                        // add new facet address if it does not exist
                        if (selectorPosition == 0) {
                            addFacet(ds, _facetAddress);
                        }
                        for (
                            uint256 selectorIndex;
                            selectorIndex < _functionSelectors.length;
                        ) {
                            bytes4 selector = _functionSelectors[selectorIndex];
                            address oldFacetAddress = ds
                                .selectorToFacetAndPosition[selector]
                                .facetAddress;
                            if (!LibUtil.isZeroAddress(oldFacetAddress)) {
                                revert FunctionAlreadyExists();
                            }
                            addFunction(ds, selector, selectorPosition, _facetAddress);
                            unchecked {
                                ++selectorPosition;
                                ++selectorIndex;
                            }
                        }
                    }
                    function replaceFunctions(
                        address _facetAddress,
                        bytes4[] memory _functionSelectors
                    ) internal {
                        if (_functionSelectors.length == 0) {
                            revert NoSelectorsInFace();
                        }
                        DiamondStorage storage ds = diamondStorage();
                        if (LibUtil.isZeroAddress(_facetAddress)) {
                            revert FacetAddressIsZero();
                        }
                        uint96 selectorPosition = uint96(
                            ds.facetFunctionSelectors[_facetAddress].functionSelectors.length
                        );
                        // add new facet address if it does not exist
                        if (selectorPosition == 0) {
                            addFacet(ds, _facetAddress);
                        }
                        for (
                            uint256 selectorIndex;
                            selectorIndex < _functionSelectors.length;
                        ) {
                            bytes4 selector = _functionSelectors[selectorIndex];
                            address oldFacetAddress = ds
                                .selectorToFacetAndPosition[selector]
                                .facetAddress;
                            if (oldFacetAddress == _facetAddress) {
                                revert FunctionAlreadyExists();
                            }
                            removeFunction(ds, oldFacetAddress, selector);
                            addFunction(ds, selector, selectorPosition, _facetAddress);
                            unchecked {
                                ++selectorPosition;
                                ++selectorIndex;
                            }
                        }
                    }
                    function removeFunctions(
                        address _facetAddress,
                        bytes4[] memory _functionSelectors
                    ) internal {
                        if (_functionSelectors.length == 0) {
                            revert NoSelectorsInFace();
                        }
                        DiamondStorage storage ds = diamondStorage();
                        // if function does not exist then do nothing and return
                        if (!LibUtil.isZeroAddress(_facetAddress)) {
                            revert FacetAddressIsNotZero();
                        }
                        for (
                            uint256 selectorIndex;
                            selectorIndex < _functionSelectors.length;
                        ) {
                            bytes4 selector = _functionSelectors[selectorIndex];
                            address oldFacetAddress = ds
                                .selectorToFacetAndPosition[selector]
                                .facetAddress;
                            removeFunction(ds, oldFacetAddress, selector);
                            unchecked {
                                ++selectorIndex;
                            }
                        }
                    }
                    function addFacet(
                        DiamondStorage storage ds,
                        address _facetAddress
                    ) internal {
                        enforceHasContractCode(_facetAddress);
                        ds.facetFunctionSelectors[_facetAddress].facetAddressPosition = ds
                            .facetAddresses
                            .length;
                        ds.facetAddresses.push(_facetAddress);
                    }
                    function addFunction(
                        DiamondStorage storage ds,
                        bytes4 _selector,
                        uint96 _selectorPosition,
                        address _facetAddress
                    ) internal {
                        ds
                            .selectorToFacetAndPosition[_selector]
                            .functionSelectorPosition = _selectorPosition;
                        ds.facetFunctionSelectors[_facetAddress].functionSelectors.push(
                            _selector
                        );
                        ds.selectorToFacetAndPosition[_selector].facetAddress = _facetAddress;
                    }
                    function removeFunction(
                        DiamondStorage storage ds,
                        address _facetAddress,
                        bytes4 _selector
                    ) internal {
                        if (LibUtil.isZeroAddress(_facetAddress)) {
                            revert FunctionDoesNotExist();
                        }
                        // an immutable function is a function defined directly in a diamond
                        if (_facetAddress == address(this)) {
                            revert FunctionIsImmutable();
                        }
                        // replace selector with last selector, then delete last selector
                        uint256 selectorPosition = ds
                            .selectorToFacetAndPosition[_selector]
                            .functionSelectorPosition;
                        uint256 lastSelectorPosition = ds
                            .facetFunctionSelectors[_facetAddress]
                            .functionSelectors
                            .length - 1;
                        // if not the same then replace _selector with lastSelector
                        if (selectorPosition != lastSelectorPosition) {
                            bytes4 lastSelector = ds
                                .facetFunctionSelectors[_facetAddress]
                                .functionSelectors[lastSelectorPosition];
                            ds.facetFunctionSelectors[_facetAddress].functionSelectors[
                                selectorPosition
                            ] = lastSelector;
                            ds
                                .selectorToFacetAndPosition[lastSelector]
                                .functionSelectorPosition = uint96(selectorPosition);
                        }
                        // delete the last selector
                        ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop();
                        delete ds.selectorToFacetAndPosition[_selector];
                        // if no more selectors for facet address then delete the facet address
                        if (lastSelectorPosition == 0) {
                            // replace facet address with last facet address and delete last facet address
                            uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1;
                            uint256 facetAddressPosition = ds
                                .facetFunctionSelectors[_facetAddress]
                                .facetAddressPosition;
                            if (facetAddressPosition != lastFacetAddressPosition) {
                                address lastFacetAddress = ds.facetAddresses[
                                    lastFacetAddressPosition
                                ];
                                ds.facetAddresses[facetAddressPosition] = lastFacetAddress;
                                ds
                                    .facetFunctionSelectors[lastFacetAddress]
                                    .facetAddressPosition = facetAddressPosition;
                            }
                            ds.facetAddresses.pop();
                            delete ds
                                .facetFunctionSelectors[_facetAddress]
                                .facetAddressPosition;
                        }
                    }
                    function initializeDiamondCut(
                        address _init,
                        bytes memory _calldata
                    ) internal {
                        if (LibUtil.isZeroAddress(_init)) {
                            if (_calldata.length != 0) {
                                revert InitZeroButCalldataNotEmpty();
                            }
                        } else {
                            if (_calldata.length == 0) {
                                revert CalldataEmptyButInitNotZero();
                            }
                            if (_init != address(this)) {
                                enforceHasContractCode(_init);
                            }
                            // solhint-disable-next-line avoid-low-level-calls
                            (bool success, bytes memory error) = _init.delegatecall(_calldata);
                            if (!success) {
                                if (error.length > 0) {
                                    // bubble up the error
                                    revert(string(error));
                                } else {
                                    revert InitReverted();
                                }
                            }
                        }
                    }
                    function enforceHasContractCode(address _contract) internal view {
                        uint256 contractSize;
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            contractSize := extcodesize(_contract)
                        }
                        if (contractSize == 0) {
                            revert FacetContainsNoCode();
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
                pragma solidity ^0.8.0;
                /**
                 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
                 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
                 *
                 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
                 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
                 * need to send a transaction, and thus is not required to hold Ether at all.
                 */
                interface IERC20Permit {
                    /**
                     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                     * given ``owner``'s signed approval.
                     *
                     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
                     * ordering also apply here.
                     *
                     * Emits an {Approval} event.
                     *
                     * Requirements:
                     *
                     * - `spender` cannot be the zero address.
                     * - `deadline` must be a timestamp in the future.
                     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
                     * over the EIP712-formatted function arguments.
                     * - the signature must use ``owner``'s current nonce (see {nonces}).
                     *
                     * For more information on the signature format, see the
                     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
                     * section].
                     */
                    function permit(
                        address owner,
                        address spender,
                        uint256 value,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) external;
                    /**
                     * @dev Returns the current nonce for `owner`. This value must be
                     * included whenever a signature is generated for {permit}.
                     *
                     * Every successful call to {permit} increases ``owner``'s nonce by one. This
                     * prevents a signature from being used multiple times.
                     */
                    function nonces(address owner) external view returns (uint256);
                    /**
                     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
                     */
                    // solhint-disable-next-line func-name-mixedcase
                    function DOMAIN_SEPARATOR() external view returns (bytes32);
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
                pragma solidity ^0.8.1;
                /**
                 * @dev Collection of functions related to the address type
                 */
                library Address {
                    /**
                     * @dev Returns true if `account` is a contract.
                     *
                     * [IMPORTANT]
                     * ====
                     * It is unsafe to assume that an address for which this function returns
                     * false is an externally-owned account (EOA) and not a contract.
                     *
                     * Among others, `isContract` will return false for the following
                     * types of addresses:
                     *
                     *  - an externally-owned account
                     *  - a contract in construction
                     *  - an address where a contract will be created
                     *  - an address where a contract lived, but was destroyed
                     *
                     * Furthermore, `isContract` will also return true if the target contract within
                     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
                     * which only has an effect at the end of a transaction.
                     * ====
                     *
                     * [IMPORTANT]
                     * ====
                     * You shouldn't rely on `isContract` to protect against flash loan attacks!
                     *
                     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
                     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
                     * constructor.
                     * ====
                     */
                    function isContract(address account) internal view returns (bool) {
                        // This method relies on extcodesize/address.code.length, which returns 0
                        // for contracts in construction, since the code is only stored at the end
                        // of the constructor execution.
                        return account.code.length > 0;
                    }
                    /**
                     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                     * `recipient`, forwarding all available gas and reverting on errors.
                     *
                     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                     * of certain opcodes, possibly making contracts go over the 2300 gas limit
                     * imposed by `transfer`, making them unable to receive funds via
                     * `transfer`. {sendValue} removes this limitation.
                     *
                     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                     *
                     * IMPORTANT: because control is transferred to `recipient`, care must be
                     * taken to not create reentrancy vulnerabilities. Consider using
                     * {ReentrancyGuard} or the
                     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                     */
                    function sendValue(address payable recipient, uint256 amount) internal {
                        require(address(this).balance >= amount, "Address: insufficient balance");
                        (bool success, ) = recipient.call{value: amount}("");
                        require(success, "Address: unable to send value, recipient may have reverted");
                    }
                    /**
                     * @dev Performs a Solidity function call using a low level `call`. A
                     * plain `call` is an unsafe replacement for a function call: use this
                     * function instead.
                     *
                     * If `target` reverts with a revert reason, it is bubbled up by this
                     * function (like regular Solidity function calls).
                     *
                     * Returns the raw returned data. To convert to the expected return value,
                     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                     *
                     * Requirements:
                     *
                     * - `target` must be a contract.
                     * - calling `target` with `data` must not revert.
                     *
                     * _Available since v3.1._
                     */
                    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                     * `errorMessage` as a fallback revert reason when `target` reverts.
                     *
                     * _Available since v3.1._
                     */
                    function functionCall(
                        address target,
                        bytes memory data,
                        string memory errorMessage
                    ) internal returns (bytes memory) {
                        return functionCallWithValue(target, data, 0, errorMessage);
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                     * but also transferring `value` wei to `target`.
                     *
                     * Requirements:
                     *
                     * - the calling contract must have an ETH balance of at least `value`.
                     * - the called Solidity function must be `payable`.
                     *
                     * _Available since v3.1._
                     */
                    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                    }
                    /**
                     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                     * with `errorMessage` as a fallback revert reason when `target` reverts.
                     *
                     * _Available since v3.1._
                     */
                    function functionCallWithValue(
                        address target,
                        bytes memory data,
                        uint256 value,
                        string memory errorMessage
                    ) internal returns (bytes memory) {
                        require(address(this).balance >= value, "Address: insufficient balance for call");
                        (bool success, bytes memory returndata) = target.call{value: value}(data);
                        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                     * but performing a static call.
                     *
                     * _Available since v3.3._
                     */
                    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                        return functionStaticCall(target, data, "Address: low-level static call failed");
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                     * but performing a static call.
                     *
                     * _Available since v3.3._
                     */
                    function functionStaticCall(
                        address target,
                        bytes memory data,
                        string memory errorMessage
                    ) internal view returns (bytes memory) {
                        (bool success, bytes memory returndata) = target.staticcall(data);
                        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                     * but performing a delegate call.
                     *
                     * _Available since v3.4._
                     */
                    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                     * but performing a delegate call.
                     *
                     * _Available since v3.4._
                     */
                    function functionDelegateCall(
                        address target,
                        bytes memory data,
                        string memory errorMessage
                    ) internal returns (bytes memory) {
                        (bool success, bytes memory returndata) = target.delegatecall(data);
                        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                    }
                    /**
                     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
                     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
                     *
                     * _Available since v4.8._
                     */
                    function verifyCallResultFromTarget(
                        address target,
                        bool success,
                        bytes memory returndata,
                        string memory errorMessage
                    ) internal view returns (bytes memory) {
                        if (success) {
                            if (returndata.length == 0) {
                                // only check isContract if the call was successful and the return data is empty
                                // otherwise we already know that it was a contract
                                require(isContract(target), "Address: call to non-contract");
                            }
                            return returndata;
                        } else {
                            _revert(returndata, errorMessage);
                        }
                    }
                    /**
                     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
                     * revert reason or using the provided one.
                     *
                     * _Available since v4.3._
                     */
                    function verifyCallResult(
                        bool success,
                        bytes memory returndata,
                        string memory errorMessage
                    ) internal pure returns (bytes memory) {
                        if (success) {
                            return returndata;
                        } else {
                            _revert(returndata, errorMessage);
                        }
                    }
                    function _revert(bytes memory returndata, string memory errorMessage) private pure {
                        // Look for revert reason and bubble it up if present
                        if (returndata.length > 0) {
                            // The easiest way to bubble the revert reason is using memory via assembly
                            /// @solidity memory-safe-assembly
                            assembly {
                                let returndata_size := mload(returndata)
                                revert(add(32, returndata), returndata_size)
                            }
                        } else {
                            revert(errorMessage);
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                import "./LibBytes.sol";
                library LibUtil {
                    using LibBytes for bytes;
                    function getRevertMsg(
                        bytes memory _res
                    ) internal pure returns (string memory) {
                        // If the _res length is less than 68, then the transaction failed silently (without a revert message)
                        if (_res.length < 68) return "Transaction reverted silently";
                        bytes memory revertData = _res.slice(4, _res.length - 4); // Remove the selector which is the first 4 bytes
                        return abi.decode(revertData, (string)); // All that remains is the revert string
                    }
                    /// @notice Determines whether the given address is the zero address
                    /// @param addr The address to verify
                    /// @return Boolean indicating if the address is the zero address
                    function isZeroAddress(address addr) internal pure returns (bool) {
                        return addr == address(0);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                import { InvalidContract } from "../Errors/GenericErrors.sol";
                /// @title Lib Allow List
                /// @author LI.FI (https://li.fi)
                /// @notice Library for managing and accessing the conract address allow list
                library LibAllowList {
                    /// Storage ///
                    bytes32 internal constant NAMESPACE =
                        keccak256("com.lifi.library.allow.list");
                    struct AllowListStorage {
                        mapping(address => bool) allowlist;
                        mapping(bytes4 => bool) selectorAllowList;
                        address[] contracts;
                    }
                    /// @dev Adds a contract address to the allow list
                    /// @param _contract the contract address to add
                    function addAllowedContract(address _contract) internal {
                        _checkAddress(_contract);
                        AllowListStorage storage als = _getStorage();
                        if (als.allowlist[_contract]) return;
                        als.allowlist[_contract] = true;
                        als.contracts.push(_contract);
                    }
                    /// @dev Checks whether a contract address has been added to the allow list
                    /// @param _contract the contract address to check
                    function contractIsAllowed(
                        address _contract
                    ) internal view returns (bool) {
                        return _getStorage().allowlist[_contract];
                    }
                    /// @dev Remove a contract address from the allow list
                    /// @param _contract the contract address to remove
                    function removeAllowedContract(address _contract) internal {
                        AllowListStorage storage als = _getStorage();
                        if (!als.allowlist[_contract]) {
                            return;
                        }
                        als.allowlist[_contract] = false;
                        uint256 length = als.contracts.length;
                        // Find the contract in the list
                        for (uint256 i = 0; i < length; i++) {
                            if (als.contracts[i] == _contract) {
                                // Move the last element into the place to delete
                                als.contracts[i] = als.contracts[length - 1];
                                // Remove the last element
                                als.contracts.pop();
                                break;
                            }
                        }
                    }
                    /// @dev Fetch contract addresses from the allow list
                    function getAllowedContracts() internal view returns (address[] memory) {
                        return _getStorage().contracts;
                    }
                    /// @dev Add a selector to the allow list
                    /// @param _selector the selector to add
                    function addAllowedSelector(bytes4 _selector) internal {
                        _getStorage().selectorAllowList[_selector] = true;
                    }
                    /// @dev Removes a selector from the allow list
                    /// @param _selector the selector to remove
                    function removeAllowedSelector(bytes4 _selector) internal {
                        _getStorage().selectorAllowList[_selector] = false;
                    }
                    /// @dev Returns if selector has been added to the allow list
                    /// @param _selector the selector to check
                    function selectorIsAllowed(bytes4 _selector) internal view returns (bool) {
                        return _getStorage().selectorAllowList[_selector];
                    }
                    /// @dev Fetch local storage struct
                    function _getStorage()
                        internal
                        pure
                        returns (AllowListStorage storage als)
                    {
                        bytes32 position = NAMESPACE;
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            als.slot := position
                        }
                    }
                    /// @dev Contains business logic for validating a contract address.
                    /// @param _contract address of the dex to check
                    function _checkAddress(address _contract) private view {
                        if (_contract == address(0)) revert InvalidContract();
                        if (_contract.code.length == 0) revert InvalidContract();
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                interface IDiamondCut {
                    enum FacetCutAction {
                        Add,
                        Replace,
                        Remove
                    }
                    // Add=0, Replace=1, Remove=2
                    struct FacetCut {
                        address facetAddress;
                        FacetCutAction action;
                        bytes4[] functionSelectors;
                    }
                    /// @notice Add/replace/remove any number of functions and optionally execute
                    ///         a function with delegatecall
                    /// @param _diamondCut Contains the facet addresses and function selectors
                    /// @param _init The address of the contract or facet to execute _calldata
                    /// @param _calldata A function call, including function selector and arguments
                    ///                  _calldata is executed with delegatecall on _init
                    function diamondCut(
                        FacetCut[] calldata _diamondCut,
                        address _init,
                        bytes calldata _calldata
                    ) external;
                    event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                library LibBytes {
                    // solhint-disable no-inline-assembly
                    // LibBytes specific errors
                    error SliceOverflow();
                    error SliceOutOfBounds();
                    error AddressOutOfBounds();
                    bytes16 private constant _SYMBOLS = "0123456789abcdef";
                    // -------------------------
                    function slice(
                        bytes memory _bytes,
                        uint256 _start,
                        uint256 _length
                    ) internal pure returns (bytes memory) {
                        if (_length + 31 < _length) revert SliceOverflow();
                        if (_bytes.length < _start + _length) revert SliceOutOfBounds();
                        bytes memory tempBytes;
                        assembly {
                            switch iszero(_length)
                            case 0 {
                                // Get a location of some free memory and store it in tempBytes as
                                // Solidity does for memory variables.
                                tempBytes := mload(0x40)
                                // The first word of the slice result is potentially a partial
                                // word read from the original array. To read it, we calculate
                                // the length of that partial word and start copying that many
                                // bytes into the array. The first word we copy will start with
                                // data we don't care about, but the last `lengthmod` bytes will
                                // land at the beginning of the contents of the new array. When
                                // we're done copying, we overwrite the full first word with
                                // the actual length of the slice.
                                let lengthmod := and(_length, 31)
                                // The multiplication in the next line is necessary
                                // because when slicing multiples of 32 bytes (lengthmod == 0)
                                // the following copy loop was copying the origin's length
                                // and then ending prematurely not copying everything it should.
                                let mc := add(
                                    add(tempBytes, lengthmod),
                                    mul(0x20, iszero(lengthmod))
                                )
                                let end := add(mc, _length)
                                for {
                                    // The multiplication in the next line has the same exact purpose
                                    // as the one above.
                                    let cc := add(
                                        add(
                                            add(_bytes, lengthmod),
                                            mul(0x20, iszero(lengthmod))
                                        ),
                                        _start
                                    )
                                } lt(mc, end) {
                                    mc := add(mc, 0x20)
                                    cc := add(cc, 0x20)
                                } {
                                    mstore(mc, mload(cc))
                                }
                                mstore(tempBytes, _length)
                                //update free-memory pointer
                                //allocating the array padded to 32 bytes like the compiler does now
                                mstore(0x40, and(add(mc, 31), not(31)))
                            }
                            //if we want a zero-length slice let's just return a zero-length array
                            default {
                                tempBytes := mload(0x40)
                                //zero out the 32 bytes slice we are about to return
                                //we need to do it because Solidity does not garbage collect
                                mstore(tempBytes, 0)
                                mstore(0x40, add(tempBytes, 0x20))
                            }
                        }
                        return tempBytes;
                    }
                    function toAddress(
                        bytes memory _bytes,
                        uint256 _start
                    ) internal pure returns (address) {
                        if (_bytes.length < _start + 20) {
                            revert AddressOutOfBounds();
                        }
                        address tempAddress;
                        assembly {
                            tempAddress := div(
                                mload(add(add(_bytes, 0x20), _start)),
                                0x1000000000000000000000000
                            )
                        }
                        return tempAddress;
                    }
                    /// Copied from OpenZeppelin's `Strings.sol` utility library.
                    /// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/8335676b0e99944eef6a742e16dcd9ff6e68e609/contracts/utils/Strings.sol
                    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);
                    }
                }
                

                File 5 of 7: L1_ETH_Bridge
                // SPDX-License-Identifier: MIT
                pragma solidity 0.6.12;
                pragma experimental ABIEncoderV2;
                import "./L1_Bridge.sol";
                /**
                 * @dev A L1_Bridge that uses an ETH as the canonical token
                 */
                contract L1_ETH_Bridge is L1_Bridge {
                    constructor (address[] memory bonders, address _governance) public L1_Bridge(bonders, _governance) {}
                    /* ========== Override Functions ========== */
                    function _transferFromBridge(address recipient, uint256 amount) internal override {
                        (bool success, ) = recipient.call{value: amount}(new bytes(0));
                        require(success, 'L1_ETH_BRG: ETH transfer failed');
                    }
                    function _transferToBridge(address /*from*/, uint256 amount) internal override {
                        require(msg.value == amount, "L1_ETH_BRG: Value does not match amount");
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.6.12;
                pragma experimental ABIEncoderV2;
                import "./Bridge.sol";
                import "../interfaces/IMessengerWrapper.sol";
                /**
                 * @dev L1_Bridge is responsible for the bonding and challenging of TransferRoots. All TransferRoots
                 * originate in the L1_Bridge through `bondTransferRoot` and are propagated up to destination L2s.
                 */
                abstract contract L1_Bridge is Bridge {
                    struct TransferBond {
                        address bonder;
                        uint256 createdAt;
                        uint256 totalAmount;
                        uint256 challengeStartTime;
                        address challenger;
                        bool challengeResolved;
                    }
                    /* ========== State ========== */
                    mapping(uint256 => mapping(bytes32 => uint256)) public transferRootCommittedAt;
                    mapping(bytes32 => TransferBond) public transferBonds;
                    mapping(uint256 => mapping(address => uint256)) public timeSlotToAmountBonded;
                    mapping(uint256 => uint256) public chainBalance;
                    /* ========== Config State ========== */
                    address public governance;
                    mapping(uint256 => IMessengerWrapper) public crossDomainMessengerWrappers;
                    mapping(uint256 => bool) public isChainIdPaused;
                    uint256 public challengePeriod = 1 days;
                    uint256 public challengeResolutionPeriod = 10 days;
                    uint256 public minTransferRootBondDelay = 15 minutes;
                    
                    uint256 public constant CHALLENGE_AMOUNT_DIVISOR = 10;
                    uint256 public constant TIME_SLOT_SIZE = 4 hours;
                    /* ========== Events ========== */
                    event TransferSentToL2(
                        uint256 indexed chainId,
                        address indexed recipient,
                        uint256 amount,
                        uint256 amountOutMin,
                        uint256 deadline,
                        address indexed relayer,
                        uint256 relayerFee
                    );
                    event TransferRootBonded (
                        bytes32 indexed root,
                        uint256 amount
                    );
                    event TransferRootConfirmed(
                        uint256 indexed originChainId,
                        uint256 indexed destinationChainId,
                        bytes32 indexed rootHash,
                        uint256 totalAmount
                    );
                    event TransferBondChallenged(
                        bytes32 indexed transferRootId,
                        bytes32 indexed rootHash,
                        uint256 originalAmount
                    );
                    event ChallengeResolved(
                        bytes32 indexed transferRootId,
                        bytes32 indexed rootHash,
                        uint256 originalAmount
                    );
                    /* ========== Modifiers ========== */
                    modifier onlyL2Bridge(uint256 chainId) {
                        IMessengerWrapper messengerWrapper = crossDomainMessengerWrappers[chainId];
                        messengerWrapper.verifySender(msg.sender, msg.data);
                        _;
                    }
                    constructor (address[] memory bonders, address _governance) public Bridge(bonders) {
                        governance = _governance;
                    }
                    /* ========== Send Functions ========== */
                    /**
                     * @notice `amountOutMin` and `deadline` should be 0 when no swap is intended at the destination.
                     * @notice `amount` is the total amount the user wants to send including the relayer fee
                     * @dev Send tokens to a supported layer-2 to mint hToken and optionally swap the hToken in the
                     * AMM at the destination.
                     * @param chainId The chainId of the destination chain
                     * @param recipient The address receiving funds at the destination
                     * @param amount The amount being sent
                     * @param amountOutMin The minimum amount received after attempting to swap in the destination
                     * AMM market. 0 if no swap is intended.
                     * @param deadline The deadline for swapping in the destination AMM market. 0 if no
                     * swap is intended.
                     * @param relayer The address of the relayer at the destination.
                     * @param relayerFee The amount distributed to the relayer at the destination. This is subtracted from the `amount`.
                     */
                    function sendToL2(
                        uint256 chainId,
                        address recipient,
                        uint256 amount,
                        uint256 amountOutMin,
                        uint256 deadline,
                        address relayer,
                        uint256 relayerFee
                    )
                        external
                        payable
                    {
                        IMessengerWrapper messengerWrapper = crossDomainMessengerWrappers[chainId];
                        require(messengerWrapper != IMessengerWrapper(0), "L1_BRG: chainId not supported");
                        require(isChainIdPaused[chainId] == false, "L1_BRG: Sends to this chainId are paused");
                        require(amount > 0, "L1_BRG: Must transfer a non-zero amount");
                        require(amount >= relayerFee, "L1_BRG: Relayer fee cannot exceed amount");
                        _transferToBridge(msg.sender, amount);
                        bytes memory message = abi.encodeWithSignature(
                            "distribute(address,uint256,uint256,uint256,address,uint256)",
                            recipient,
                            amount,
                            amountOutMin,
                            deadline,
                            relayer,
                            relayerFee
                        );
                        chainBalance[chainId] = chainBalance[chainId].add(amount);
                        messengerWrapper.sendCrossDomainMessage(message);
                        emit TransferSentToL2(
                            chainId,
                            recipient,
                            amount,
                            amountOutMin,
                            deadline,
                            relayer,
                            relayerFee
                        );
                    }
                    /* ========== TransferRoot Functions ========== */
                    /**
                     * @dev Setting a TransferRoot is a two step process.
                     * @dev   1. The TransferRoot is bonded with `bondTransferRoot`. Withdrawals can now begin on L1
                     * @dev      and recipient L2's
                     * @dev   2. The TransferRoot is confirmed after `confirmTransferRoot` is called by the l2 bridge
                     * @dev      where the TransferRoot originated.
                     */
                    /**
                     * @dev Used by the Bonder to bond a TransferRoot and propagate it up to destination L2s
                     * @param rootHash The Merkle root of the TransferRoot Merkle tree
                     * @param destinationChainId The id of the destination chain
                     * @param totalAmount The amount destined for the destination chain
                     */
                    function bondTransferRoot(
                        bytes32 rootHash,
                        uint256 destinationChainId,
                        uint256 totalAmount
                    )
                        external
                        onlyBonder
                        requirePositiveBalance
                    {
                        bytes32 transferRootId = getTransferRootId(rootHash, totalAmount);
                        require(transferRootCommittedAt[destinationChainId][transferRootId] == 0, "L1_BRG: TransferRoot has already been confirmed");
                        require(transferBonds[transferRootId].createdAt == 0, "L1_BRG: TransferRoot has already been bonded");
                        uint256 currentTimeSlot = getTimeSlot(block.timestamp);
                        uint256 bondAmount = getBondForTransferAmount(totalAmount);
                        timeSlotToAmountBonded[currentTimeSlot][msg.sender] = timeSlotToAmountBonded[currentTimeSlot][msg.sender].add(bondAmount);
                        transferBonds[transferRootId] = TransferBond(
                            msg.sender,
                            block.timestamp,
                            totalAmount,
                            uint256(0),
                            address(0),
                            false
                        );
                        _distributeTransferRoot(rootHash, destinationChainId, totalAmount);
                        emit TransferRootBonded(rootHash, totalAmount);
                    }
                    /**
                     * @dev Used by an L2 bridge to confirm a TransferRoot via cross-domain message. Once a TransferRoot
                     * has been confirmed, any challenge against that TransferRoot can be resolved as unsuccessful.
                     * @param originChainId The id of the origin chain
                     * @param rootHash The Merkle root of the TransferRoot Merkle tree
                     * @param destinationChainId The id of the destination chain
                     * @param totalAmount The amount destined for each destination chain
                     * @param rootCommittedAt The block timestamp when the TransferRoot was committed on its origin chain
                     */
                    function confirmTransferRoot(
                        uint256 originChainId,
                        bytes32 rootHash,
                        uint256 destinationChainId,
                        uint256 totalAmount,
                        uint256 rootCommittedAt
                    )
                        external
                        onlyL2Bridge(originChainId)
                    {
                        bytes32 transferRootId = getTransferRootId(rootHash, totalAmount);
                        require(transferRootCommittedAt[destinationChainId][transferRootId] == 0, "L1_BRG: TransferRoot already confirmed");
                        require(rootCommittedAt > 0, "L1_BRG: rootCommittedAt must be greater than 0");
                        transferRootCommittedAt[destinationChainId][transferRootId] = rootCommittedAt;
                        chainBalance[originChainId] = chainBalance[originChainId].sub(totalAmount, "L1_BRG: Amount exceeds chainBalance. This indicates a layer-2 failure.");
                        // If the TransferRoot was never bonded, distribute the TransferRoot.
                        TransferBond storage transferBond = transferBonds[transferRootId];
                        if (transferBond.createdAt == 0) {
                            _distributeTransferRoot(rootHash, destinationChainId, totalAmount);
                        }
                        emit TransferRootConfirmed(originChainId, destinationChainId, rootHash, totalAmount);
                    }
                    function _distributeTransferRoot(
                        bytes32 rootHash,
                        uint256 chainId,
                        uint256 totalAmount
                    )
                        internal
                    {
                        // Set TransferRoot on recipient Bridge
                        if (chainId == getChainId()) {
                            // Set L1 TransferRoot
                            _setTransferRoot(rootHash, totalAmount);
                        } else {
                            chainBalance[chainId] = chainBalance[chainId].add(totalAmount);
                            IMessengerWrapper messengerWrapper = crossDomainMessengerWrappers[chainId];
                            require(messengerWrapper != IMessengerWrapper(0), "L1_BRG: chainId not supported");
                            // Set L2 TransferRoot
                            bytes memory setTransferRootMessage = abi.encodeWithSignature(
                                "setTransferRoot(bytes32,uint256)",
                                rootHash,
                                totalAmount
                            );
                            messengerWrapper.sendCrossDomainMessage(setTransferRootMessage);
                        }
                    }
                    /* ========== External TransferRoot Challenges ========== */
                    /**
                     * @dev Challenge a TransferRoot believed to be fraudulent
                     * @param rootHash The Merkle root of the TransferRoot Merkle tree
                     * @param originalAmount The total amount bonded for this TransferRoot
                     * @param destinationChainId The id of the destination chain
                     */
                    function challengeTransferBond(bytes32 rootHash, uint256 originalAmount, uint256 destinationChainId) external payable {
                        bytes32 transferRootId = getTransferRootId(rootHash, originalAmount);
                        TransferBond storage transferBond = transferBonds[transferRootId];
                        require(transferRootCommittedAt[destinationChainId][transferRootId] == 0, "L1_BRG: TransferRoot has already been confirmed");
                        require(transferBond.createdAt != 0, "L1_BRG: TransferRoot has not been bonded");
                        uint256 challengePeriodEnd = transferBond.createdAt.add(challengePeriod);
                        require(challengePeriodEnd >= block.timestamp, "L1_BRG: TransferRoot cannot be challenged after challenge period");
                        require(transferBond.challengeStartTime == 0, "L1_BRG: TransferRoot already challenged");
                        transferBond.challengeStartTime = block.timestamp;
                        transferBond.challenger = msg.sender;
                        // Move amount from timeSlotToAmountBonded to debit
                        uint256 timeSlot = getTimeSlot(transferBond.createdAt);
                        uint256 bondAmount = getBondForTransferAmount(originalAmount);
                        address bonder = transferBond.bonder;
                        timeSlotToAmountBonded[timeSlot][bonder] = timeSlotToAmountBonded[timeSlot][bonder].sub(bondAmount);
                        _addDebit(transferBond.bonder, bondAmount);
                        // Get stake for challenge
                        uint256 challengeStakeAmount = getChallengeAmountForTransferAmount(originalAmount);
                        _transferToBridge(msg.sender, challengeStakeAmount);
                        emit TransferBondChallenged(transferRootId, rootHash, originalAmount);
                    }
                    /**
                     * @dev Resolve a challenge after the `challengeResolutionPeriod` has passed
                     * @param rootHash The Merkle root of the TransferRoot Merkle tree
                     * @param originalAmount The total amount originally bonded for this TransferRoot
                     * @param destinationChainId The id of the destination chain
                     */
                    function resolveChallenge(bytes32 rootHash, uint256 originalAmount, uint256 destinationChainId) external {
                        bytes32 transferRootId = getTransferRootId(rootHash, originalAmount);
                        TransferBond storage transferBond = transferBonds[transferRootId];
                        require(transferBond.challengeStartTime != 0, "L1_BRG: TransferRoot has not been challenged");
                        require(block.timestamp > transferBond.challengeStartTime.add(challengeResolutionPeriod), "L1_BRG: Challenge period has not ended");
                        require(transferBond.challengeResolved == false, "L1_BRG: TransferRoot already resolved");
                        transferBond.challengeResolved = true;
                        uint256 challengeStakeAmount = getChallengeAmountForTransferAmount(originalAmount);
                        if (transferRootCommittedAt[destinationChainId][transferRootId] > 0) {
                            // Invalid challenge
                            if (transferBond.createdAt > transferRootCommittedAt[destinationChainId][transferRootId].add(minTransferRootBondDelay)) {
                                // Credit the bonder back with the bond amount plus the challenger's stake
                                _addCredit(transferBond.bonder, getBondForTransferAmount(originalAmount).add(challengeStakeAmount));
                            } else {
                                // If the TransferRoot was bonded before it was committed, the challenger and Bonder
                                // get their stake back. This discourages Bonders from tricking challengers into
                                // challenging a valid TransferRoots that haven't yet been committed. It also ensures
                                // that Bonders are not punished if a TransferRoot is bonded too soon in error.
                                // Return the challenger's stake
                                _addCredit(transferBond.challenger, challengeStakeAmount);
                                // Credit the bonder back with the bond amount
                                _addCredit(transferBond.bonder, getBondForTransferAmount(originalAmount));
                            }
                        } else {
                            // Valid challenge
                            // Burn 25% of the challengers stake
                            _transferFromBridge(address(0xdead), challengeStakeAmount.mul(1).div(4));
                            // Reward challenger with the remaining 75% of their stake plus 100% of the Bonder's stake
                            _addCredit(transferBond.challenger, challengeStakeAmount.mul(7).div(4));
                        }
                        emit ChallengeResolved(transferRootId, rootHash, originalAmount);
                    }
                    /* ========== Override Functions ========== */
                    function _additionalDebit(address bonder) internal view override returns (uint256) {
                        uint256 currentTimeSlot = getTimeSlot(block.timestamp);
                        uint256 bonded = 0;
                        uint256 numTimeSlots = challengePeriod / TIME_SLOT_SIZE;
                        for (uint256 i = 0; i < numTimeSlots; i++) {
                            bonded = bonded.add(timeSlotToAmountBonded[currentTimeSlot - i][bonder]);
                        }
                        return bonded;
                    }
                    function _requireIsGovernance() internal override {
                        require(governance == msg.sender, "L1_BRG: Caller is not the owner");
                    }
                    /* ========== External Config Management Setters ========== */
                    function setGovernance(address _newGovernance) external onlyGovernance {
                        require(_newGovernance != address(0), "L1_BRG: _newGovernance cannot be address(0)");
                        governance = _newGovernance;
                    }
                    function setCrossDomainMessengerWrapper(uint256 chainId, IMessengerWrapper _crossDomainMessengerWrapper) external onlyGovernance {
                        crossDomainMessengerWrappers[chainId] = _crossDomainMessengerWrapper;
                    }
                    function setChainIdDepositsPaused(uint256 chainId, bool isPaused) external onlyGovernance {
                        isChainIdPaused[chainId] = isPaused;
                    }
                    function setChallengePeriod(uint256 _challengePeriod) external onlyGovernance {
                        require(_challengePeriod % TIME_SLOT_SIZE == 0, "L1_BRG: challengePeriod must be divisible by TIME_SLOT_SIZE");
                        challengePeriod = _challengePeriod;
                    }
                    function setChallengeResolutionPeriod(uint256 _challengeResolutionPeriod) external onlyGovernance {
                        challengeResolutionPeriod = _challengeResolutionPeriod;
                    }
                    function setMinTransferRootBondDelay(uint256 _minTransferRootBondDelay) external onlyGovernance {
                        minTransferRootBondDelay = _minTransferRootBondDelay;
                    }
                    /* ========== Public Getters ========== */
                    function getBondForTransferAmount(uint256 amount) public pure returns (uint256) {
                        // Bond covers amount plus a bounty to pay a potential challenger
                        return amount.add(getChallengeAmountForTransferAmount(amount));
                    }
                    function getChallengeAmountForTransferAmount(uint256 amount) public pure returns (uint256) {
                        // Bond covers amount plus a bounty to pay a potential challenger
                        return amount.div(CHALLENGE_AMOUNT_DIVISOR);
                    }
                    function getTimeSlot(uint256 time) public pure returns (uint256) {
                        return time / TIME_SLOT_SIZE;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.6.12;
                pragma experimental ABIEncoderV2;
                import "./Accounting.sol";
                import "../libraries/Lib_MerkleTree.sol";
                /**
                 * @dev Bridge extends the accounting system and encapsulates the logic that is shared by both the
                 * L1 and L2 Bridges. It allows to TransferRoots to be set by parent contracts and for those
                 * TransferRoots to be withdrawn against. It also allows the bonder to bond and withdraw Transfers
                 * directly through `bondWithdrawal` and then settle those bonds against their TransferRoot once it
                 * has been set.
                 */
                abstract contract Bridge is Accounting {
                    using Lib_MerkleTree for bytes32;
                    struct TransferRoot {
                        uint256 total;
                        uint256 amountWithdrawn;
                        uint256 createdAt;
                    }
                    /* ========== Events ========== */
                    event Withdrew(
                        bytes32 indexed transferId,
                        address indexed recipient,
                        uint256 amount,
                        bytes32 transferNonce
                    );
                    event WithdrawalBonded(
                        bytes32 indexed transferId,
                        uint256 amount
                    );
                    event WithdrawalBondSettled(
                        address indexed bonder,
                        bytes32 indexed transferId,
                        bytes32 indexed rootHash
                    );
                    event MultipleWithdrawalsSettled(
                        address indexed bonder,
                        bytes32 indexed rootHash,
                        uint256 totalBondsSettled
                    );
                    event TransferRootSet(
                        bytes32 indexed rootHash,
                        uint256 totalAmount
                    );
                    /* ========== State ========== */
                    mapping(bytes32 => TransferRoot) private _transferRoots;
                    mapping(bytes32 => bool) private _spentTransferIds;
                    mapping(address => mapping(bytes32 => uint256)) private _bondedWithdrawalAmounts;
                    uint256 constant RESCUE_DELAY = 8 weeks;
                    constructor(address[] memory bonders) public Accounting(bonders) {}
                    /* ========== Public Getters ========== */
                    /**
                     * @dev Get the hash that represents an individual Transfer.
                     * @param chainId The id of the destination chain
                     * @param recipient The address receiving the Transfer
                     * @param amount The amount being transferred including the `_bonderFee`
                     * @param transferNonce Used to avoid transferId collisions
                     * @param bonderFee The amount paid to the address that withdraws the Transfer
                     * @param amountOutMin The minimum amount received after attempting to swap in the destination
                     * AMM market. 0 if no swap is intended.
                     * @param deadline The deadline for swapping in the destination AMM market. 0 if no
                     * swap is intended.
                     */
                    function getTransferId(
                        uint256 chainId,
                        address recipient,
                        uint256 amount,
                        bytes32 transferNonce,
                        uint256 bonderFee,
                        uint256 amountOutMin,
                        uint256 deadline
                    )
                        public
                        pure
                        returns (bytes32)
                    {
                        return keccak256(abi.encode(
                            chainId,
                            recipient,
                            amount,
                            transferNonce,
                            bonderFee,
                            amountOutMin,
                            deadline
                        ));
                    }
                    /**
                     * @notice getChainId can be overridden by subclasses if needed for compatibility or testing purposes.
                     * @dev Get the current chainId
                     * @return chainId The current chainId
                     */
                    function getChainId() public virtual view returns (uint256 chainId) {
                        this; // Silence state mutability warning without generating any additional byte code
                        assembly {
                            chainId := chainid()
                        }
                    }
                    /**
                     * @dev Get the TransferRoot id for a given rootHash and totalAmount
                     * @param rootHash The Merkle root of the TransferRoot
                     * @param totalAmount The total of all Transfers in the TransferRoot
                     * @return The calculated transferRootId
                     */
                    function getTransferRootId(bytes32 rootHash, uint256 totalAmount) public pure returns (bytes32) {
                        return keccak256(abi.encodePacked(rootHash, totalAmount));
                    }
                    /**
                     * @dev Get the TransferRoot for a given rootHash and totalAmount
                     * @param rootHash The Merkle root of the TransferRoot
                     * @param totalAmount The total of all Transfers in the TransferRoot
                     * @return The TransferRoot with the calculated transferRootId
                     */
                    function getTransferRoot(bytes32 rootHash, uint256 totalAmount) public view returns (TransferRoot memory) {
                        return _transferRoots[getTransferRootId(rootHash, totalAmount)];
                    }
                    /**
                     * @dev Get the amount bonded for the withdrawal of a transfer
                     * @param bonder The Bonder of the withdrawal
                     * @param transferId The Transfer's unique identifier
                     * @return The amount bonded for a Transfer withdrawal
                     */
                    function getBondedWithdrawalAmount(address bonder, bytes32 transferId) external view returns (uint256) {
                        return _bondedWithdrawalAmounts[bonder][transferId];
                    }
                    /**
                     * @dev Get the spent status of a transfer ID
                     * @param transferId The transfer's unique identifier
                     * @return True if the transferId has been spent
                     */
                    function isTransferIdSpent(bytes32 transferId) external view returns (bool) {
                        return _spentTransferIds[transferId];
                    }
                    /* ========== User/Relayer External Functions ========== */
                    /**
                     * @notice Can be called by anyone (recipient or relayer)
                     * @dev Withdraw a Transfer from its destination bridge
                     * @param recipient The address receiving the Transfer
                     * @param amount The amount being transferred including the `_bonderFee`
                     * @param transferNonce Used to avoid transferId collisions
                     * @param bonderFee The amount paid to the address that withdraws the Transfer
                     * @param amountOutMin The minimum amount received after attempting to swap in the destination
                     * AMM market. 0 if no swap is intended. (only used to calculate `transferId` in this function)
                     * @param deadline The deadline for swapping in the destination AMM market. 0 if no
                     * swap is intended. (only used to calculate `transferId` in this function)
                     * @param rootHash The Merkle root of the TransferRoot
                     * @param transferRootTotalAmount The total amount being transferred in a TransferRoot
                     * @param transferIdTreeIndex The index of the transferId in the Merkle tree
                     * @param siblings The siblings of the transferId in the Merkle tree
                     * @param totalLeaves The total number of leaves in the Merkle tree
                     */
                    function withdraw(
                        address recipient,
                        uint256 amount,
                        bytes32 transferNonce,
                        uint256 bonderFee,
                        uint256 amountOutMin,
                        uint256 deadline,
                        bytes32 rootHash,
                        uint256 transferRootTotalAmount,
                        uint256 transferIdTreeIndex,
                        bytes32[] calldata siblings,
                        uint256 totalLeaves
                    )
                        external
                        nonReentrant
                    {
                        bytes32 transferId = getTransferId(
                            getChainId(),
                            recipient,
                            amount,
                            transferNonce,
                            bonderFee,
                            amountOutMin,
                            deadline
                        );
                        require(
                            rootHash.verify(
                                transferId,
                                transferIdTreeIndex,
                                siblings,
                                totalLeaves
                            )
                        , "BRG: Invalid transfer proof");
                        bytes32 transferRootId = getTransferRootId(rootHash, transferRootTotalAmount);
                        _addToAmountWithdrawn(transferRootId, amount);
                        _fulfillWithdraw(transferId, recipient, amount, uint256(0));
                        emit Withdrew(transferId, recipient, amount, transferNonce);
                    }
                    /**
                     * @dev Allows the bonder to bond individual withdrawals before their TransferRoot has been committed.
                     * @param recipient The address receiving the Transfer
                     * @param amount The amount being transferred including the `_bonderFee`
                     * @param transferNonce Used to avoid transferId collisions
                     * @param bonderFee The amount paid to the address that withdraws the Transfer
                     */
                    function bondWithdrawal(
                        address recipient,
                        uint256 amount,
                        bytes32 transferNonce,
                        uint256 bonderFee
                    )
                        external
                        onlyBonder
                        requirePositiveBalance
                        nonReentrant
                    {
                        bytes32 transferId = getTransferId(
                            getChainId(),
                            recipient,
                            amount,
                            transferNonce,
                            bonderFee,
                            0,
                            0
                        );
                        _bondWithdrawal(transferId, amount);
                        _fulfillWithdraw(transferId, recipient, amount, bonderFee);
                    }
                    /**
                     * @dev Refunds the Bonder's stake from a bonded withdrawal and counts that withdrawal against
                     * its TransferRoot.
                     * @param bonder The Bonder of the withdrawal
                     * @param transferId The Transfer's unique identifier
                     * @param rootHash The Merkle root of the TransferRoot
                     * @param transferRootTotalAmount The total amount being transferred in a TransferRoot
                     * @param transferIdTreeIndex The index of the transferId in the Merkle tree
                     * @param siblings The siblings of the transferId in the Merkle tree
                     * @param totalLeaves The total number of leaves in the Merkle tree
                     */
                    function settleBondedWithdrawal(
                        address bonder,
                        bytes32 transferId,
                        bytes32 rootHash,
                        uint256 transferRootTotalAmount,
                        uint256 transferIdTreeIndex,
                        bytes32[] calldata siblings,
                        uint256 totalLeaves
                    )
                        external
                    {
                        require(
                            rootHash.verify(
                                transferId,
                                transferIdTreeIndex,
                                siblings,
                                totalLeaves
                            )
                        , "BRG: Invalid transfer proof");
                        bytes32 transferRootId = getTransferRootId(rootHash, transferRootTotalAmount);
                        uint256 amount = _bondedWithdrawalAmounts[bonder][transferId];
                        require(amount > 0, "L2_BRG: transferId has no bond");
                        _bondedWithdrawalAmounts[bonder][transferId] = 0;
                        _addToAmountWithdrawn(transferRootId, amount);
                        _addCredit(bonder, amount);
                        emit WithdrawalBondSettled(bonder, transferId, rootHash);
                    }
                    /**
                     * @dev Refunds the Bonder for all withdrawals that they bonded in a TransferRoot.
                     * @param bonder The address of the Bonder being refunded
                     * @param transferIds All transferIds in the TransferRoot in order
                     * @param totalAmount The totalAmount of the TransferRoot
                     */
                    function settleBondedWithdrawals(
                        address bonder,
                        // transferIds _must_ be calldata or it will be mutated by Lib_MerkleTree.getMerkleRoot
                        bytes32[] calldata transferIds,
                        uint256 totalAmount
                    )
                        external
                    {
                        bytes32 rootHash = Lib_MerkleTree.getMerkleRoot(transferIds);
                        bytes32 transferRootId = getTransferRootId(rootHash, totalAmount);
                        uint256 totalBondsSettled = 0;
                        for(uint256 i = 0; i < transferIds.length; i++) {
                            uint256 transferBondAmount = _bondedWithdrawalAmounts[bonder][transferIds[i]];
                            if (transferBondAmount > 0) {
                                totalBondsSettled = totalBondsSettled.add(transferBondAmount);
                                _bondedWithdrawalAmounts[bonder][transferIds[i]] = 0;
                            }
                        }
                        _addToAmountWithdrawn(transferRootId, totalBondsSettled);
                        _addCredit(bonder, totalBondsSettled);
                        emit MultipleWithdrawalsSettled(bonder, rootHash, totalBondsSettled);
                    }
                    /* ========== External TransferRoot Rescue ========== */
                    /**
                     * @dev Allows governance to withdraw the remaining amount from a TransferRoot after the rescue delay has passed.
                     * @param rootHash the Merkle root of the TransferRoot
                     * @param originalAmount The TransferRoot's recorded total
                     * @param recipient The address receiving the remaining balance
                     */
                    function rescueTransferRoot(bytes32 rootHash, uint256 originalAmount, address recipient) external onlyGovernance {
                        bytes32 transferRootId = getTransferRootId(rootHash, originalAmount);
                        TransferRoot memory transferRoot = getTransferRoot(rootHash, originalAmount);
                        require(transferRoot.createdAt != 0, "BRG: TransferRoot not found");
                        assert(transferRoot.total == originalAmount);
                        uint256 rescueDelayEnd = transferRoot.createdAt.add(RESCUE_DELAY);
                        require(block.timestamp >= rescueDelayEnd, "BRG: TransferRoot cannot be rescued before the Rescue Delay");
                        uint256 remainingAmount = transferRoot.total.sub(transferRoot.amountWithdrawn);
                        _addToAmountWithdrawn(transferRootId, remainingAmount);
                        _transferFromBridge(recipient, remainingAmount);
                    }
                    /* ========== Internal Functions ========== */
                    function _markTransferSpent(bytes32 transferId) internal {
                        require(!_spentTransferIds[transferId], "BRG: The transfer has already been withdrawn");
                        _spentTransferIds[transferId] = true;
                    }
                    function _addToAmountWithdrawn(bytes32 transferRootId, uint256 amount) internal {
                        TransferRoot storage transferRoot = _transferRoots[transferRootId];
                        require(transferRoot.total > 0, "BRG: Transfer root not found");
                        uint256 newAmountWithdrawn = transferRoot.amountWithdrawn.add(amount);
                        require(newAmountWithdrawn <= transferRoot.total, "BRG: Withdrawal exceeds TransferRoot total");
                        transferRoot.amountWithdrawn = newAmountWithdrawn;
                    }
                    function _setTransferRoot(bytes32 rootHash, uint256 totalAmount) internal {
                        bytes32 transferRootId = getTransferRootId(rootHash, totalAmount);
                        require(_transferRoots[transferRootId].total == 0, "BRG: Transfer root already set");
                        require(totalAmount > 0, "BRG: Cannot set TransferRoot totalAmount of 0");
                        _transferRoots[transferRootId] = TransferRoot(totalAmount, 0, block.timestamp);
                        emit TransferRootSet(rootHash, totalAmount);
                    }
                    function _bondWithdrawal(bytes32 transferId, uint256 amount) internal {
                        require(_bondedWithdrawalAmounts[msg.sender][transferId] == 0, "BRG: Withdrawal has already been bonded");
                        _addDebit(msg.sender, amount);
                        _bondedWithdrawalAmounts[msg.sender][transferId] = amount;
                        emit WithdrawalBonded(transferId, amount);
                    }
                    /* ========== Private Functions ========== */
                    /// @dev Completes the Transfer, distributes the Bonder fee and marks the Transfer as spent.
                    function _fulfillWithdraw(
                        bytes32 transferId,
                        address recipient,
                        uint256 amount,
                        uint256 bonderFee
                    ) private {
                        _markTransferSpent(transferId);
                        _transferFromBridge(recipient, amount.sub(bonderFee));
                        if (bonderFee > 0) {
                            _transferFromBridge(msg.sender, bonderFee);
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.6.12 <0.8.0;
                pragma experimental ABIEncoderV2;
                interface IMessengerWrapper {
                    function sendCrossDomainMessage(bytes memory _calldata) external;
                    function verifySender(address l1BridgeCaller, bytes memory _data) external;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.6.12;
                pragma experimental ABIEncoderV2;
                import "@openzeppelin/contracts/math/SafeMath.sol";
                import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
                /**
                 * @dev Accounting is an abstract contract that encapsulates the most critical logic in the Hop contracts.
                 * The accounting system works by using two balances that can only increase `_credit` and `_debit`.
                 * A bonder's available balance is the total credit minus the total debit. The contract exposes
                 * two external functions that allows a bonder to stake and unstake and exposes two internal
                 * functions to its child contracts that allow the child contract to add to the credit 
                 * and debit balance. In addition, child contracts can override `_additionalDebit` to account
                 * for any additional debit balance in an alternative way. Lastly, it exposes a modifier,
                 * `requirePositiveBalance`, that can be used by child contracts to ensure the bonder does not
                 * use more than its available stake.
                 */
                abstract contract Accounting is ReentrancyGuard {
                    using SafeMath for uint256;
                    mapping(address => bool) private _isBonder;
                    mapping(address => uint256) private _credit;
                    mapping(address => uint256) private _debit;
                    event Stake (
                        address indexed account,
                        uint256 amount
                    );
                    event Unstake (
                        address indexed account,
                        uint256 amount
                    );
                    event BonderAdded (
                        address indexed newBonder
                    );
                    event BonderRemoved (
                        address indexed previousBonder
                    );
                    /* ========== Modifiers ========== */
                    modifier onlyBonder {
                        require(_isBonder[msg.sender], "ACT: Caller is not bonder");
                        _;
                    }
                    modifier onlyGovernance {
                        _requireIsGovernance();
                        _;
                    }
                    /// @dev Used by parent contract to ensure that the Bonder is solvent at the end of the transaction.
                    modifier requirePositiveBalance {
                        _;
                        require(getCredit(msg.sender) >= getDebitAndAdditionalDebit(msg.sender), "ACT: Not enough available credit");
                    }
                    /// @dev Sets the Bonder addresses
                    constructor(address[] memory bonders) public {
                        for (uint256 i = 0; i < bonders.length; i++) {
                            require(_isBonder[bonders[i]] == false, "ACT: Cannot add duplicate bonder");
                            _isBonder[bonders[i]] = true;
                            emit BonderAdded(bonders[i]);
                        }
                    }
                    /* ========== Virtual functions ========== */
                    /**
                     * @dev The following functions are overridden in L1_Bridge and L2_Bridge
                     */
                    function _transferFromBridge(address recipient, uint256 amount) internal virtual;
                    function _transferToBridge(address from, uint256 amount) internal virtual;
                    function _requireIsGovernance() internal virtual;
                    /**
                     * @dev This function can be optionally overridden by a parent contract to track any additional
                     * debit balance in an alternative way.
                     */
                    function _additionalDebit(address /*bonder*/) internal view virtual returns (uint256) {
                        this; // Silence state mutability warning without generating any additional byte code
                        return 0;
                    }
                    /* ========== Public/external getters ========== */
                    /**
                     * @dev Check if address is a Bonder
                     * @param maybeBonder The address being checked
                     * @return true if address is a Bonder
                     */
                    function getIsBonder(address maybeBonder) public view returns (bool) {
                        return _isBonder[maybeBonder];
                    }
                    /**
                     * @dev Get the Bonder's credit balance
                     * @param bonder The owner of the credit balance being checked
                     * @return The credit balance for the Bonder
                     */
                    function getCredit(address bonder) public view returns (uint256) {
                        return _credit[bonder];
                    }
                    /**
                     * @dev Gets the debit balance tracked by `_debit` and does not include `_additionalDebit()`
                     * @param bonder The owner of the debit balance being checked
                     * @return The debit amount for the Bonder
                     */
                    function getRawDebit(address bonder) external view returns (uint256) {
                        return _debit[bonder];
                    }
                    /**
                     * @dev Get the Bonder's total debit
                     * @param bonder The owner of the debit balance being checked
                     * @return The Bonder's total debit balance
                     */
                    function getDebitAndAdditionalDebit(address bonder) public view returns (uint256) {
                        return _debit[bonder].add(_additionalDebit(bonder));
                    }
                    /* ========== Bonder external functions ========== */
                    /** 
                     * @dev Allows the Bonder to deposit tokens and increase its credit balance
                     * @param bonder The address being staked on
                     * @param amount The amount being staked
                     */
                    function stake(address bonder, uint256 amount) external payable nonReentrant {
                        require(_isBonder[bonder] == true, "ACT: Address is not bonder");
                        _transferToBridge(msg.sender, amount);
                        _addCredit(bonder, amount);
                        emit Stake(bonder, amount);
                    }
                    /**
                     * @dev Allows the caller to withdraw any available balance and add to their debit balance
                     * @param amount The amount being unstaked
                     */
                    function unstake(uint256 amount) external requirePositiveBalance nonReentrant {
                        _addDebit(msg.sender, amount);
                        _transferFromBridge(msg.sender, amount);
                        emit Unstake(msg.sender, amount);
                    }
                    /**
                     * @dev Add Bonder to allowlist
                     * @param bonder The address being added as a Bonder
                     */
                    function addBonder(address bonder) external onlyGovernance {
                        require(_isBonder[bonder] == false, "ACT: Address is already bonder");
                        _isBonder[bonder] = true;
                        emit BonderAdded(bonder);
                    }
                    /**
                     * @dev Remove Bonder from allowlist
                     * @param bonder The address being removed as a Bonder
                     */
                    function removeBonder(address bonder) external onlyGovernance {
                        require(_isBonder[bonder] == true, "ACT: Address is not bonder");
                        _isBonder[bonder] = false;
                        emit BonderRemoved(bonder);
                    }
                    /* ========== Internal functions ========== */
                    function _addCredit(address bonder, uint256 amount) internal {
                        _credit[bonder] = _credit[bonder].add(amount);
                    }
                    function _addDebit(address bonder, uint256 amount) internal {
                        _debit[bonder] = _debit[bonder].add(amount);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >0.5.0 <0.8.0;
                /**
                 * @title Lib_MerkleTree
                 * @author River Keefer
                 */
                library Lib_MerkleTree {
                    /**********************
                     * Internal Functions *
                     **********************/
                    /**
                     * Calculates a merkle root for a list of 32-byte leaf hashes.  WARNING: If the number
                     * of leaves passed in is not a power of two, it pads out the tree with zero hashes.
                     * If you do not know the original length of elements for the tree you are verifying,
                     * then this may allow empty leaves past _elements.length to pass a verification check down the line.
                     * Note that the _elements argument is modified, therefore it must not be used again afterwards
                     * @param _elements Array of hashes from which to generate a merkle root.
                     * @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above).
                     */
                    function getMerkleRoot(
                        bytes32[] memory _elements
                    )
                        internal
                        pure
                        returns (
                            bytes32
                        )
                    {
                        require(
                            _elements.length > 0,
                            "Lib_MerkleTree: Must provide at least one leaf hash."
                        );
                        if (_elements.length == 1) {
                            return _elements[0];
                        }
                        uint256[16] memory defaults = [
                            0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563,
                            0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d,
                            0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d,
                            0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8,
                            0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da,
                            0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5,
                            0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7,
                            0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead,
                            0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10,
                            0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82,
                            0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516,
                            0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c,
                            0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e,
                            0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab,
                            0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862,
                            0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10
                        ];
                        // Reserve memory space for our hashes.
                        bytes memory buf = new bytes(64);
                        // We'll need to keep track of left and right siblings.
                        bytes32 leftSibling;
                        bytes32 rightSibling;
                        // Number of non-empty nodes at the current depth.
                        uint256 rowSize = _elements.length;
                        // Current depth, counting from 0 at the leaves
                        uint256 depth = 0;
                        // Common sub-expressions
                        uint256 halfRowSize;         // rowSize / 2
                        bool rowSizeIsOdd;           // rowSize % 2 == 1
                        while (rowSize > 1) {
                            halfRowSize = rowSize / 2;
                            rowSizeIsOdd = rowSize % 2 == 1;
                            for (uint256 i = 0; i < halfRowSize; i++) {
                                leftSibling  = _elements[(2 * i)    ];
                                rightSibling = _elements[(2 * i) + 1];
                                assembly {
                                    mstore(add(buf, 32), leftSibling )
                                    mstore(add(buf, 64), rightSibling)
                                }
                                _elements[i] = keccak256(buf);
                            }
                            if (rowSizeIsOdd) {
                                leftSibling  = _elements[rowSize - 1];
                                rightSibling = bytes32(defaults[depth]);
                                assembly {
                                    mstore(add(buf, 32), leftSibling)
                                    mstore(add(buf, 64), rightSibling)
                                }
                                _elements[halfRowSize] = keccak256(buf);
                            }
                            rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0);
                            depth++;
                        }
                        return _elements[0];
                    }
                    /**
                     * Verifies a merkle branch for the given leaf hash.  Assumes the original length
                     * of leaves generated is a known, correct input, and does not return true for indices
                     * extending past that index (even if _siblings would be otherwise valid.)
                     * @param _root The Merkle root to verify against.
                     * @param _leaf The leaf hash to verify inclusion of.
                     * @param _index The index in the tree of this leaf.
                     * @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0 (bottom of the tree).
                     * @param _totalLeaves The total number of leaves originally passed into.
                     * @return Whether or not the merkle branch and leaf passes verification.
                     */
                    function verify(
                        bytes32 _root,
                        bytes32 _leaf,
                        uint256 _index,
                        bytes32[] memory _siblings,
                        uint256 _totalLeaves
                    )
                        internal
                        pure
                        returns (
                            bool
                        )
                    {
                        require(
                            _totalLeaves > 0,
                            "Lib_MerkleTree: Total leaves must be greater than zero."
                        );
                        require(
                            _index < _totalLeaves,
                            "Lib_MerkleTree: Index out of bounds."
                        );
                        require(
                            _siblings.length == _ceilLog2(_totalLeaves),
                            "Lib_MerkleTree: Total siblings does not correctly correspond to total leaves."
                        );
                        bytes32 computedRoot = _leaf;
                        for (uint256 i = 0; i < _siblings.length; i++) {
                            if ((_index & 1) == 1) {
                                computedRoot = keccak256(
                                    abi.encodePacked(
                                        _siblings[i],
                                        computedRoot
                                    )
                                );
                            } else {
                                computedRoot = keccak256(
                                    abi.encodePacked(
                                        computedRoot,
                                        _siblings[i]
                                    )
                                );
                            }
                            _index >>= 1;
                        }
                        return _root == computedRoot;
                    }
                    /*********************
                     * Private Functions *
                     *********************/
                    /**
                     * Calculates the integer ceiling of the log base 2 of an input.
                     * @param _in Unsigned input to calculate the log.
                     * @return ceil(log_base_2(_in))
                     */
                    function _ceilLog2(
                        uint256 _in
                    )
                        private
                        pure
                        returns (
                            uint256
                        )
                    {
                        require(
                            _in > 0,
                            "Lib_MerkleTree: Cannot compute ceil(log_2) of 0."
                        );
                        if (_in == 1) {
                            return 0;
                        }
                        // Find the highest set bit (will be floor(log_2)).
                        // Borrowed with <3 from https://github.com/ethereum/solidity-examples
                        uint256 val = _in;
                        uint256 highest = 0;
                        for (uint256 i = 128; i >= 1; i >>= 1) {
                            if (val & (uint(1) << i) - 1 << i != 0) {
                                highest += i;
                                val >>= i;
                            }
                        }
                        // Increment by one if this is not a perfect logarithm.
                        if ((uint(1) << highest) != _in) {
                            highest += 1;
                        }
                        return highest;
                    }
                }// SPDX-License-Identifier: MIT
                pragma solidity >=0.6.0 <0.8.0;
                /**
                 * @dev Wrappers over Solidity's arithmetic operations with added overflow
                 * checks.
                 *
                 * Arithmetic operations in Solidity wrap on overflow. This can easily result
                 * in bugs, because programmers usually assume that an overflow raises an
                 * error, which is the standard behavior in high level programming languages.
                 * `SafeMath` restores this intuition by reverting the transaction when an
                 * operation overflows.
                 *
                 * Using this library instead of the unchecked operations eliminates an entire
                 * class of bugs, so it's recommended to use it always.
                 */
                library SafeMath {
                    /**
                     * @dev Returns the addition of two unsigned integers, with an overflow flag.
                     *
                     * _Available since v3.4._
                     */
                    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                        uint256 c = a + b;
                        if (c < a) return (false, 0);
                        return (true, c);
                    }
                    /**
                     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                     *
                     * _Available since v3.4._
                     */
                    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                        if (b > a) return (false, 0);
                        return (true, a - b);
                    }
                    /**
                     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                     *
                     * _Available since v3.4._
                     */
                    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                        // benefit is lost if 'b' is also tested.
                        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                        if (a == 0) return (true, 0);
                        uint256 c = a * b;
                        if (c / a != b) return (false, 0);
                        return (true, c);
                    }
                    /**
                     * @dev Returns the division of two unsigned integers, with a division by zero flag.
                     *
                     * _Available since v3.4._
                     */
                    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                        if (b == 0) return (false, 0);
                        return (true, a / b);
                    }
                    /**
                     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                     *
                     * _Available since v3.4._
                     */
                    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                        if (b == 0) return (false, 0);
                        return (true, a % b);
                    }
                    /**
                     * @dev Returns the addition of two unsigned integers, reverting on
                     * overflow.
                     *
                     * Counterpart to Solidity's `+` operator.
                     *
                     * Requirements:
                     *
                     * - Addition cannot overflow.
                     */
                    function add(uint256 a, uint256 b) internal pure returns (uint256) {
                        uint256 c = a + b;
                        require(c >= a, "SafeMath: addition overflow");
                        return c;
                    }
                    /**
                     * @dev Returns the subtraction of two unsigned integers, reverting on
                     * overflow (when the result is negative).
                     *
                     * Counterpart to Solidity's `-` operator.
                     *
                     * Requirements:
                     *
                     * - Subtraction cannot overflow.
                     */
                    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                        require(b <= a, "SafeMath: subtraction overflow");
                        return a - b;
                    }
                    /**
                     * @dev Returns the multiplication of two unsigned integers, reverting on
                     * overflow.
                     *
                     * Counterpart to Solidity's `*` operator.
                     *
                     * Requirements:
                     *
                     * - Multiplication cannot overflow.
                     */
                    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                        if (a == 0) return 0;
                        uint256 c = a * b;
                        require(c / a == b, "SafeMath: multiplication overflow");
                        return c;
                    }
                    /**
                     * @dev Returns the integer division of two unsigned integers, reverting on
                     * division by zero. The result is rounded towards zero.
                     *
                     * Counterpart to Solidity's `/` operator. Note: this function uses a
                     * `revert` opcode (which leaves remaining gas untouched) while Solidity
                     * uses an invalid opcode to revert (consuming all remaining gas).
                     *
                     * Requirements:
                     *
                     * - The divisor cannot be zero.
                     */
                    function div(uint256 a, uint256 b) internal pure returns (uint256) {
                        require(b > 0, "SafeMath: division by zero");
                        return a / b;
                    }
                    /**
                     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                     * reverting when dividing by zero.
                     *
                     * Counterpart to Solidity's `%` operator. This function uses a `revert`
                     * opcode (which leaves remaining gas untouched) while Solidity uses an
                     * invalid opcode to revert (consuming all remaining gas).
                     *
                     * Requirements:
                     *
                     * - The divisor cannot be zero.
                     */
                    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                        require(b > 0, "SafeMath: modulo by zero");
                        return a % b;
                    }
                    /**
                     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                     * overflow (when the result is negative).
                     *
                     * CAUTION: This function is deprecated because it requires allocating memory for the error
                     * message unnecessarily. For custom revert reasons use {trySub}.
                     *
                     * Counterpart to Solidity's `-` operator.
                     *
                     * Requirements:
                     *
                     * - Subtraction cannot overflow.
                     */
                    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                        require(b <= a, errorMessage);
                        return a - b;
                    }
                    /**
                     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                     * division by zero. The result is rounded towards zero.
                     *
                     * CAUTION: This function is deprecated because it requires allocating memory for the error
                     * message unnecessarily. For custom revert reasons use {tryDiv}.
                     *
                     * Counterpart to Solidity's `/` operator. Note: this function uses a
                     * `revert` opcode (which leaves remaining gas untouched) while Solidity
                     * uses an invalid opcode to revert (consuming all remaining gas).
                     *
                     * Requirements:
                     *
                     * - The divisor cannot be zero.
                     */
                    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                        require(b > 0, errorMessage);
                        return a / b;
                    }
                    /**
                     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                     * reverting with custom message when dividing by zero.
                     *
                     * CAUTION: This function is deprecated because it requires allocating memory for the error
                     * message unnecessarily. For custom revert reasons use {tryMod}.
                     *
                     * Counterpart to Solidity's `%` operator. This function uses a `revert`
                     * opcode (which leaves remaining gas untouched) while Solidity uses an
                     * invalid opcode to revert (consuming all remaining gas).
                     *
                     * Requirements:
                     *
                     * - The divisor cannot be zero.
                     */
                    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                        require(b > 0, errorMessage);
                        return a % b;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.6.0 <0.8.0;
                /**
                 * @dev Contract module that helps prevent reentrant calls to a function.
                 *
                 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
                 * available, which can be applied to functions to make sure there are no nested
                 * (reentrant) calls to them.
                 *
                 * Note that because there is a single `nonReentrant` guard, functions marked as
                 * `nonReentrant` may not call one another. This can be worked around by making
                 * those functions `private`, and then adding `external` `nonReentrant` entry
                 * points to them.
                 *
                 * TIP: If you would like to learn more about reentrancy and alternative ways
                 * to protect against it, check out our blog post
                 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
                 */
                abstract contract ReentrancyGuard {
                    // Booleans are more expensive than uint256 or any type that takes up a full
                    // word because each write operation emits an extra SLOAD to first read the
                    // slot's contents, replace the bits taken up by the boolean, and then write
                    // back. This is the compiler's defense against contract upgrades and
                    // pointer aliasing, and it cannot be disabled.
                    // The values being non-zero value makes deployment a bit more expensive,
                    // but in exchange the refund on every call to nonReentrant will be lower in
                    // amount. Since refunds are capped to a percentage of the total
                    // transaction's gas, it is best to keep them low in cases like this one, to
                    // increase the likelihood of the full refund coming into effect.
                    uint256 private constant _NOT_ENTERED = 1;
                    uint256 private constant _ENTERED = 2;
                    uint256 private _status;
                    constructor () internal {
                        _status = _NOT_ENTERED;
                    }
                    /**
                     * @dev Prevents a contract from calling itself, directly or indirectly.
                     * Calling a `nonReentrant` function from another `nonReentrant`
                     * function is not supported. It is possible to prevent this from happening
                     * by making the `nonReentrant` function external, and make it call a
                     * `private` function that does the actual work.
                     */
                    modifier nonReentrant() {
                        // On the first call to nonReentrant, _notEntered will be true
                        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                        // Any calls to nonReentrant after this point will fail
                        _status = _ENTERED;
                        _;
                        // By storing the original value once again, a refund is triggered (see
                        // https://eips.ethereum.org/EIPS/eip-2200)
                        _status = _NOT_ENTERED;
                    }
                }
                

                File 6 of 7: OptimismMessengerWrapper
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.6.0 <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 () internal {
                        address msgSender = _msgSender();
                        _owner = msgSender;
                        emit OwnershipTransferred(address(0), msgSender);
                    }
                    /**
                     * @dev Returns the address of the current owner.
                     */
                    function owner() public view virtual returns (address) {
                        return _owner;
                    }
                    /**
                     * @dev Throws if called by any account other than the owner.
                     */
                    modifier onlyOwner() {
                        require(owner() == _msgSender(), "Ownable: caller is not the owner");
                        _;
                    }
                    /**
                     * @dev Leaves the contract without owner. It will not be possible to call
                     * `onlyOwner` functions anymore. Can only be called by the current owner.
                     *
                     * NOTE: Renouncing ownership will leave the contract without an owner,
                     * thereby removing any functionality that is only available to the owner.
                     */
                    function renounceOwnership() public virtual onlyOwner {
                        emit OwnershipTransferred(_owner, address(0));
                        _owner = 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");
                        emit OwnershipTransferred(_owner, newOwner);
                        _owner = newOwner;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.6.0 <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 GSN 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 payable) {
                        return msg.sender;
                    }
                    function _msgData() internal view virtual returns (bytes memory) {
                        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                        return msg.data;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.6.12 <=0.8.9;
                pragma experimental ABIEncoderV2;
                interface IMessengerWrapper {
                    function sendCrossDomainMessage(bytes memory _calldata) external;
                    function verifySender(address l1BridgeCaller, bytes memory _data) external;
                    function confirmRoots(
                        bytes32[] calldata rootHashes,
                        uint256[] calldata destinationChainIds,
                        uint256[] calldata totalAmounts,
                        uint256[] calldata rootCommittedAts
                    ) external;
                }
                // SPDX-License-Identifier: MIT
                // +build ovm
                pragma solidity >0.5.0 <0.8.0;
                pragma experimental ABIEncoderV2;
                /**
                 * @title iOVM_BaseCrossDomainMessenger
                 */
                interface iOVM_BaseCrossDomainMessenger {
                    /**********
                     * Events *
                     **********/
                    event SentMessage(bytes message);
                    event RelayedMessage(bytes32 msgHash);
                    /**********************
                     * Contract Variables *
                     **********************/
                    function xDomainMessageSender() external view returns (address);
                    /********************
                     * Public Functions *
                     ********************/
                    /**
                     * Sends a cross domain message to the target messenger.
                     * @param _target Target contract address.
                     * @param _message Message to send to the target.
                     * @param _gasLimit Gas limit for the provided message.
                     */
                    function sendMessage(
                        address _target,
                        bytes calldata _message,
                        uint32 _gasLimit
                    ) external;
                    function deposit(
                        address _depositor,
                        uint256 _amount,
                        bool _send
                    ) external;
                }// SPDX-License-Identifier: MIT
                pragma solidity >0.5.0 <0.8.0;
                pragma experimental ABIEncoderV2;
                import { iOVM_BaseCrossDomainMessenger } from "./iOVM_BaseCrossDomainMessenger.sol";
                /**
                 * @title iOVM_L1CrossDomainMessenger
                 */
                interface iOVM_L1CrossDomainMessenger is iOVM_BaseCrossDomainMessenger {}// SPDX-License-Identifier: MIT
                pragma solidity >=0.6.12 <=0.8.9;
                pragma experimental ABIEncoderV2;
                import "../interfaces/IMessengerWrapper.sol";
                contract IL1Bridge {
                    struct TransferBond {
                        address bonder;
                        uint256 createdAt;
                        uint256 totalAmount;
                        uint256 challengeStartTime;
                        address challenger;
                        bool challengeResolved;
                    }
                    uint256 public challengePeriod;
                    mapping(bytes32 => TransferBond) public transferBonds;
                    function getIsBonder(address maybeBonder) public view returns (bool) {}
                    function getTransferRootId(bytes32 rootHash, uint256 totalAmount) public pure returns (bytes32) {}
                    function confirmTransferRoot(
                        uint256 originChainId,
                        bytes32 rootHash,
                        uint256 destinationChainId,
                        uint256 totalAmount,
                        uint256 rootCommittedAt
                    )
                        external
                    {}
                }
                abstract contract MessengerWrapper is IMessengerWrapper {
                    address public immutable l1BridgeAddress;
                    uint256 public immutable l2ChainId;
                    bool public isRootConfirmation = false;
                    constructor(address _l1BridgeAddress, uint256 _l2ChainId) internal {
                        l1BridgeAddress = _l1BridgeAddress;
                        l2ChainId = _l2ChainId;
                    }
                    modifier onlyL1Bridge {
                        require(msg.sender == l1BridgeAddress, "MW: Sender must be the L1 Bridge");
                        _;
                    }
                    modifier rootConfirmation {
                        isRootConfirmation = true;
                        _;
                        isRootConfirmation = false;
                    }
                    /**
                     * @dev Confirm roots that have bonded on L1 and passed the challenge period with no challenge
                     * @param rootHashes The root hashes to confirm
                     * @param destinationChainIds The destinationChainId of the roots to confirm
                     * @param totalAmounts The totalAmount of the roots to confirm
                     * @param rootCommittedAts The rootCommittedAt of the roots to confirm
                     */
                    function confirmRoots (
                        bytes32[] calldata rootHashes,
                        uint256[] calldata destinationChainIds,
                        uint256[] calldata totalAmounts,
                        uint256[] calldata rootCommittedAts
                    ) external override rootConfirmation {
                        IL1Bridge l1Bridge = IL1Bridge(l1BridgeAddress);
                        require(l1Bridge.getIsBonder(msg.sender), "MW: Sender must be a bonder");
                        require(rootHashes.length == totalAmounts.length, "MW: rootHashes and totalAmounts must be the same length");
                        uint256 challengePeriod = l1Bridge.challengePeriod();
                        for (uint256 i = 0; i < rootHashes.length; i++) {
                            bool canConfirm = canConfirmRoot(l1Bridge, rootHashes[i], totalAmounts[i], challengePeriod);
                            require(canConfirm, "MW: Root cannot be confirmed");
                            l1Bridge.confirmTransferRoot(
                                l2ChainId,
                                rootHashes[i],
                                destinationChainIds[i],
                                totalAmounts[i],
                                rootCommittedAts[i]
                            );
                        }
                    }
                    
                    function canConfirmRoot (IL1Bridge l1Bridge, bytes32 rootHash, uint256 totalAmount, uint256 challengePeriod) public view returns (bool) {
                        bytes32 transferRootId = l1Bridge.getTransferRootId(rootHash, totalAmount);
                        (,uint256 createdAt,,uint256 challengeStartTime,,) = l1Bridge.transferBonds(transferRootId);
                        uint256 timeSinceBondCreation = block.timestamp - createdAt;
                        if (
                            createdAt != 0 &&
                            challengeStartTime == 0 &&
                            timeSinceBondCreation > challengePeriod
                        ) {
                            return true;
                        }
                        return false;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.6.12;
                pragma experimental ABIEncoderV2;
                import "@openzeppelin/contracts/access/Ownable.sol";
                import "../interfaces/optimism/messengers/iOVM_L1CrossDomainMessenger.sol";
                import "./MessengerWrapper.sol";
                /**
                 * @dev A MessengerWrapper for Optimism - https://community.optimism.io/docs/
                 * @notice Deployed on layer-1
                 */
                contract OptimismMessengerWrapper is MessengerWrapper, Ownable {
                    iOVM_L1CrossDomainMessenger public immutable l1MessengerAddress;
                    address public immutable l2BridgeAddress;
                    uint256 public defaultL2GasLimit;
                    mapping (bytes4 => uint256) public l2GasLimitForSignature;
                    constructor(
                        address _l1BridgeAddress,
                        address _l2BridgeAddress,
                        iOVM_L1CrossDomainMessenger _l1MessengerAddress,
                        uint256 _l2ChainId,
                        uint256 _defaultL2GasLimit
                    )
                        public
                        MessengerWrapper(_l1BridgeAddress, _l2ChainId)
                    {
                        l2BridgeAddress = _l2BridgeAddress;
                        l1MessengerAddress = _l1MessengerAddress;
                        defaultL2GasLimit = _defaultL2GasLimit;
                    }
                    /** 
                     * @dev Sends a message to the l2BridgeAddress from layer-1
                     * @param _calldata The data that l2BridgeAddress will be called with
                     */
                    function sendCrossDomainMessage(bytes memory _calldata) public override onlyL1Bridge {
                        uint256 l2GasLimit = l2GasLimitForCalldata(_calldata);
                        l1MessengerAddress.sendMessage(
                            l2BridgeAddress,
                            _calldata,
                            uint32(l2GasLimit)
                        );
                    }
                    function verifySender(address l1BridgeCaller, bytes memory /*_data*/) public override {
                        if (isRootConfirmation) return;
                        require(l1BridgeCaller == address(l1MessengerAddress), "OVM_MSG_WPR: Caller is not l1MessengerAddress");
                        // Verify that cross-domain sender is l2BridgeAddress
                        require(l1MessengerAddress.xDomainMessageSender() == l2BridgeAddress, "OVM_MSG_WPR: Invalid cross-domain sender");
                    }
                    function setDefaultL2GasLimit(uint256 _l2GasLimit) external onlyOwner {
                        defaultL2GasLimit = _l2GasLimit;
                    }
                    function setL2GasLimitForSignature(uint256 _l2GasLimit, bytes4 signature) external onlyOwner {
                        l2GasLimitForSignature[signature] = _l2GasLimit;
                    }
                    // Private functions
                    function l2GasLimitForCalldata(bytes memory _calldata) private view returns (uint256) {
                        uint256 l2GasLimit;
                        if (_calldata.length >= 4) {
                            bytes4 functionSignature = bytes4(toUint32(_calldata, 0));
                            l2GasLimit = l2GasLimitForSignature[functionSignature];
                        }
                        if (l2GasLimit == 0) {
                            l2GasLimit = defaultL2GasLimit;
                        }
                        return l2GasLimit;
                    }
                    // source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
                    function toUint32(bytes memory _bytes, uint256 _start) private pure returns (uint32) {
                        require(_bytes.length >= _start + 4, "OVM_MSG_WPR: out of bounds");
                        uint32 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x4), _start))
                        }
                        return tempUint;
                    }
                }
                

                File 7 of 7: Lib_ResolvedDelegateProxy
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.6.0 <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 () internal {
                        address msgSender = _msgSender();
                        _owner = msgSender;
                        emit OwnershipTransferred(address(0), msgSender);
                    }
                    /**
                     * @dev Returns the address of the current owner.
                     */
                    function owner() public view virtual returns (address) {
                        return _owner;
                    }
                    /**
                     * @dev Throws if called by any account other than the owner.
                     */
                    modifier onlyOwner() {
                        require(owner() == _msgSender(), "Ownable: caller is not the owner");
                        _;
                    }
                    /**
                     * @dev Leaves the contract without owner. It will not be possible to call
                     * `onlyOwner` functions anymore. Can only be called by the current owner.
                     *
                     * NOTE: Renouncing ownership will leave the contract without an owner,
                     * thereby removing any functionality that is only available to the owner.
                     */
                    function renounceOwnership() public virtual onlyOwner {
                        emit OwnershipTransferred(_owner, address(0));
                        _owner = 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");
                        emit OwnershipTransferred(_owner, newOwner);
                        _owner = newOwner;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.6.0 <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 GSN 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 payable) {
                        return msg.sender;
                    }
                    function _msgData() internal view virtual returns (bytes memory) {
                        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                        return msg.data;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >0.5.0 <0.8.0;
                /* External Imports */
                import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
                /**
                 * @title Lib_AddressManager
                 */
                contract Lib_AddressManager is Ownable {
                    /**********
                     * Events *
                     **********/
                    event AddressSet(
                        string indexed _name,
                        address _newAddress,
                        address _oldAddress
                    );
                    /*************
                     * Variables *
                     *************/
                    mapping (bytes32 => address) private addresses;
                    /********************
                     * Public Functions *
                     ********************/
                    /**
                     * Changes the address associated with a particular name.
                     * @param _name String name to associate an address with.
                     * @param _address Address to associate with the name.
                     */
                    function setAddress(
                        string memory _name,
                        address _address
                    )
                        external
                        onlyOwner
                    {
                        bytes32 nameHash = _getNameHash(_name);
                        address oldAddress = addresses[nameHash];
                        addresses[nameHash] = _address;
                        emit AddressSet(
                            _name,
                            _address,
                            oldAddress
                        );
                    }
                    /**
                     * Retrieves the address associated with a given name.
                     * @param _name Name to retrieve an address for.
                     * @return Address associated with the given name.
                     */
                    function getAddress(
                        string memory _name
                    )
                        external
                        view
                        returns (
                            address
                        )
                    {
                        return addresses[_getNameHash(_name)];
                    }
                    /**********************
                     * Internal Functions *
                     **********************/
                    /**
                     * Computes the hash of a name.
                     * @param _name Name to compute a hash for.
                     * @return Hash of the given name.
                     */
                    function _getNameHash(
                        string memory _name
                    )
                        internal
                        pure
                        returns (
                            bytes32
                        )
                    {
                        return keccak256(abi.encodePacked(_name));
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >0.5.0 <0.8.0;
                /* Library Imports */
                import { Lib_AddressManager } from "./Lib_AddressManager.sol";
                /**
                 * @title Lib_ResolvedDelegateProxy
                 */
                contract Lib_ResolvedDelegateProxy {
                    /*************
                     * Variables *
                     *************/
                    // Using mappings to store fields to avoid overwriting storage slots in the
                    // implementation contract. For example, instead of storing these fields at
                    // storage slot `0` & `1`, they are stored at `keccak256(key + slot)`.
                    // See: https://solidity.readthedocs.io/en/v0.7.0/internals/layout_in_storage.html
                    // NOTE: Do not use this code in your own contract system.
                    //      There is a known flaw in this contract, and we will remove it from the repository
                    //      in the near future. Due to the very limited way that we are using it, this flaw is
                    //      not an issue in our system.
                    mapping (address => string) private implementationName;
                    mapping (address => Lib_AddressManager) private addressManager;
                    /***************
                     * Constructor *
                     ***************/
                    /**
                     * @param _libAddressManager Address of the Lib_AddressManager.
                     * @param _implementationName implementationName of the contract to proxy to.
                     */
                    constructor(
                        address _libAddressManager,
                        string memory _implementationName
                    ) {
                        addressManager[address(this)] = Lib_AddressManager(_libAddressManager);
                        implementationName[address(this)] = _implementationName;
                    }
                    /*********************
                     * Fallback Function *
                     *********************/
                    fallback()
                        external
                        payable
                    {
                        address target = addressManager[address(this)].getAddress(
                            (implementationName[address(this)])
                        );
                        require(
                            target != address(0),
                            "Target address must be initialized."
                        );
                        (bool success, bytes memory returndata) = target.delegatecall(msg.data);
                        if (success == true) {
                            assembly {
                                return(add(returndata, 0x20), mload(returndata))
                            }
                        } else {
                            assembly {
                                revert(add(returndata, 0x20), mload(returndata))
                            }
                        }
                    }
                }