ETH Price: $2,288.58 (-3.88%)

Contract

0x0E10307dF6F69298642b462A7C42fEd19828298C
 

Overview

ETH Balance

0.034134010955888201 ETH

Eth Value

$78.12 (@ $2,288.58/ETH)
Transaction Hash
Method
Block
From
To
Proxy Pass207583422024-09-15 20:14:5922 hrs ago1726431299IN
0x0E10307d...19828298C
0.00559586 ETH0.000552822.25745211
Proxy Pass207567402024-09-15 14:53:4727 hrs ago1726412027IN
0x0E10307d...19828298C
0.00560107 ETH0.000565862.30021125
Proxy Pass207423822024-09-13 14:46:473 days ago1726238807IN
0x0E10307d...19828298C
0.00396694 ETH0.000994454.06129118
Proxy Pass207379262024-09-12 23:52:113 days ago1726185131IN
0x0E10307d...19828298C
0.01432002 ETH0.000578622.3418726
Proxy Pass207375312024-09-12 22:32:113 days ago1726180331IN
0x0E10307d...19828298C
0.0015641 ETH0.000805583.26107126
Proxy Pass207221892024-09-10 19:06:355 days ago1725995195IN
0x0E10307d...19828298C
9.00718317 ETH0.001566726.25720001
Proxy Pass207059022024-09-08 12:30:598 days ago1725798659IN
0x0E10307d...19828298C
0.00539864 ETH0.000458891.8738771
Proxy Pass206923382024-09-06 15:06:3510 days ago1725635195IN
0x0E10307d...19828298C
9.30058452 ETH0.004237517.46185325
Proxy Pass206862212024-09-05 18:36:5910 days ago1725561419IN
0x0E10307d...19828298C
0.02278641 ETH0.000968823.93840947
Proxy Pass206858692024-09-05 17:26:3511 days ago1725557195IN
0x0E10307d...19828298C
0.03072485 ETH0.001054.28784655
Proxy Pass206840262024-09-05 11:16:2311 days ago1725534983IN
0x0E10307d...19828298C
1.01470943 ETH0.001167714.81188831
Proxy Pass206803162024-09-04 22:50:2311 days ago1725490223IN
0x0E10307d...19828298C
0.00060027 ETH0.00115724.34880916
Proxy Pass206770112024-09-04 11:46:2312 days ago1725450383IN
0x0E10307d...19828298C
0.00059497 ETH0.00051941.97761634
Proxy Pass206769802024-09-04 11:40:1112 days ago1725450011IN
0x0E10307d...19828298C
0.00059554 ETH0.000630242.38965016
Proxy Pass206769352024-09-04 11:31:1112 days ago1725449471IN
0x0E10307d...19828298C
0.00209026 ETH0.000613962.50710605
Proxy Pass206767552024-09-04 10:55:1112 days ago1725447311IN
0x0E10307d...19828298C
0.00559503 ETH0.000908543.71029019
Proxy Pass206696002024-09-03 10:57:5913 days ago1725361079IN
0x0E10307d...19828298C
0.0047003 ETH0.000428971.74383722
Proxy Pass206579912024-09-01 20:04:4714 days ago1725221087IN
0x0E10307d...19828298C
0.00384231 ETH0.000312021.27405378
Proxy Pass206484202024-08-31 12:01:2316 days ago1725105683IN
0x0E10307d...19828298C
0.00436586 ETH0.000201320.76545926
Proxy Pass206457502024-08-31 3:05:1116 days ago1725073511IN
0x0E10307d...19828298C
0.00436586 ETH0.000183530.6977679
Proxy Pass206421412024-08-30 14:58:3517 days ago1725029915IN
0x0E10307d...19828298C
0.00059508 ETH0.001193684.5014364
Proxy Pass206292792024-08-28 19:48:4718 days ago1724874527IN
0x0E10307d...19828298C
0.00069611 ETH0.000475671.81097701
Proxy Pass206150602024-08-26 20:09:2320 days ago1724702963IN
0x0E10307d...19828298C
3.52262652 ETH0.000446371.78268101
Proxy Pass206147282024-08-26 19:02:3520 days ago1724698955IN
0x0E10307d...19828298C
0.10064236 ETH0.000454521.79149875
Proxy Pass206146422024-08-26 18:44:5920 days ago1724697899IN
0x0E10307d...19828298C
1.00062652 ETH0.000591992.36457021
View all transactions

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
207583862024-09-15 20:23:4722 hrs ago1726431827
0x0E10307d...19828298C
0.17928481 ETH
207583862024-09-15 20:23:4722 hrs ago1726431827
0x0E10307d...19828298C
0.17928481 ETH
207583862024-09-15 20:23:4722 hrs ago1726431827
0x0E10307d...19828298C
0 ETH
207583862024-09-15 20:23:4722 hrs ago1726431827
0x0E10307d...19828298C
0 ETH
207583422024-09-15 20:14:5922 hrs ago1726431299
0x0E10307d...19828298C
0.0001686 ETH
207583422024-09-15 20:14:5922 hrs ago1726431299
0x0E10307d...19828298C
0 ETH
207583422024-09-15 20:14:5922 hrs ago1726431299
0x0E10307d...19828298C
0 ETH
207583422024-09-15 20:14:5922 hrs ago1726431299
0x0E10307d...19828298C
0 ETH
207583422024-09-15 20:14:5922 hrs ago1726431299
0x0E10307d...19828298C
0.005 ETH
207567402024-09-15 14:53:4727 hrs ago1726412027
0x0E10307d...19828298C
0.0001734 ETH
207567402024-09-15 14:53:4727 hrs ago1726412027
0x0E10307d...19828298C
0 ETH
207567402024-09-15 14:53:4727 hrs ago1726412027
0x0E10307d...19828298C
0 ETH
207567402024-09-15 14:53:4727 hrs ago1726412027
0x0E10307d...19828298C
0 ETH
207567402024-09-15 14:53:4727 hrs ago1726412027
0x0E10307d...19828298C
0.005 ETH
207423822024-09-13 14:46:473 days ago1726238807
0x0E10307d...19828298C
0.0001686 ETH
207423822024-09-13 14:46:473 days ago1726238807
0x0E10307d...19828298C
0 ETH
207423822024-09-13 14:46:473 days ago1726238807
0x0E10307d...19828298C
0 ETH
207423822024-09-13 14:46:473 days ago1726238807
0x0E10307d...19828298C
0 ETH
207423822024-09-13 14:46:473 days ago1726238807
0x0E10307d...19828298C
0.0033716 ETH
207412222024-09-13 10:53:113 days ago1726224791
0x0E10307d...19828298C
0.05528484 ETH
207412222024-09-13 10:53:113 days ago1726224791
0x0E10307d...19828298C
0.05528484 ETH
207412222024-09-13 10:53:113 days ago1726224791
0x0E10307d...19828298C
0 ETH
207412222024-09-13 10:53:113 days ago1726224791
0x0E10307d...19828298C
0 ETH
207379262024-09-12 23:52:113 days ago1726185131
0x0E10307d...19828298C
0.0001782 ETH
207379262024-09-12 23:52:113 days ago1726185131
0x0E10307d...19828298C
0 ETH
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
MultichainEndpoint

Compiler Version
v0.8.17+commit.8df45f5f

Optimization Enabled:
Yes with 300 runs

Other Settings:
default evmVersion
File 1 of 36 : MultichainEndpoint.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import "./celer/message/interfaces/IMessageBus.sol";
import "../../interfaces/ILuminexRouterV1.sol";
import '../../interfaces/IWROSE.sol';
import "../../libraries/FeesCollector.sol";
import "../chainvault/CrossChainVaultApp.sol";
import "./IMultichainEndpoint.sol";

contract MultichainEndpoint is IMultichainEndpoint, FeesCollector {
    using SafeMath for uint;
    using SafeERC20 for IERC20;

    uint64 public constant SAPPHIRE_CHAINID = 0x5afe;

    enum MultichainCommandType {
        ProxyPass,
        Receive
    }

    enum MessageStoreType {
        MessageReceived,
        MultichainMessageSent,
        QueueUnwrapped
    }

    struct ConnectEndpointParams {
        uint64 chainId;
        address contractAddress;
    }

    struct EndpointFee {
        uint256 settlementCost; // tx total cost on dst chain in dst chain currency
        uint256 settlementCostInLocalCurrency; // tx total cost on dst chain in current chain's currency
    }

    struct SetEndpointFee {
        uint64 chainId;
        EndpointFee fee;
    }

    struct OFACEntry {
        address addr;
        bool isOfacListed;
    }

    address public nativeWrapper;
    address public feeSetter;

    mapping(uint64 => address) public connectedEndpoints;
    mapping(address => uint64) public chainIdByEndpointAddress;

    mapping(MessageStoreType => mapping(bytes32 => bool)) public settledMessages;
    mapping(address => bool) public ofacBlocklist;

    mapping(bytes32 => bool) internal _executedMessages;
    mapping(bytes32 => bool) public _failedMessages;
    mapping(bytes32 => address) private _messageRawHashToSender;
    mapping(bytes32 => address) internal _dataHashToSender;

    address public complianceManager;

    mapping(uint64 => EndpointFee) public endpointsDestinationFees;

    CrossChainVaultApp public immutable vaultApp;
    address public immutable messageBus;

    event MessageReceived(bytes32 indexed hashedEventKey, bool hasFailed);
    event MultichainMessageSent(bytes32 indexed hashedEventKey);
    event FeeUpdated(SetEndpointFee[] feeData);
    event UpdateOFACList(OFACEntry[] list);
    event ChangeComplianceManager(address newManager, address oldManager);

    constructor(address payable _vaultApp) {
        vaultApp = CrossChainVaultApp(_vaultApp);
        messageBus = CrossChainVaultApp(_vaultApp).messageBus();
        feeSetter = msg.sender;
        complianceManager = msg.sender;
    }

    modifier onlyComplianceManager() {
        require(msg.sender == complianceManager, "Not a compliance manager");
        _;
    }

    function setComplianceManager(address newManager) public onlyComplianceManager {
        emit ChangeComplianceManager(newManager, complianceManager);
        complianceManager = newManager;
    }

    function setNativeWrapper(address _wrapper) public onlyOwner {
        nativeWrapper = _wrapper;
    }

    function updateOFACList(OFACEntry[] memory list) public onlyComplianceManager {
        require(block.chainid != SAPPHIRE_CHAINID);
        emit UpdateOFACList(list);

        for (uint i = 0; i < list.length; i++) {
            ofacBlocklist[list[i].addr] = list[i].isOfacListed;
        }
    }

    function setConnectedEndpoints(ConnectEndpointParams[] memory _endpoints) public onlyOwner {
        for (uint i = 0; i < _endpoints.length; i++) {
            require(_endpoints[i].chainId != block.chainid, "Can't add an endpoint to the current chain");
            connectedEndpoints[_endpoints[i].chainId] = _endpoints[i].contractAddress;
            chainIdByEndpointAddress[_endpoints[i].contractAddress] = _endpoints[i].chainId;
        }
    }

    function setFeeSetter(address _feeSetter) public onlyOwner {
        feeSetter = _feeSetter;
    }

    function setFixedFee(SetEndpointFee[] calldata feeData) public {
        require(msg.sender == feeSetter, "Not allowed");

        for (uint i = 0; i < feeData.length; i++) {
            endpointsDestinationFees[feeData[i].chainId] = feeData[i].fee;
        }

        emit FeeUpdated(feeData);
    }

    function _multichainProxyPass(address token, uint256 amount, bytes memory data, uint256 fees) private {
        address sapphireEndpoint = connectedEndpoints[SAPPHIRE_CHAINID];
        require(sapphireEndpoint != address(0), "Sapphire endpoint is not yet configured");

        bytes memory celerData = abi.encode(
            msg.sender,
            fees,
            data
        );

        bytes memory bridgeTemplate = abi.encode(uint8(0), address(0), uint256(0));

        uint _feesByCeler = IMessageBus(messageBus).calcFee(abi.encode(bridgeTemplate, celerData));
        require(fees >= _feesByCeler + endpointsDestinationFees[SAPPHIRE_CHAINID].settlementCostInLocalCurrency, "Value is too low");

        celerData = abi.encode(
            msg.sender,
            fees - _feesByCeler,
            data
        );

        _depositFees(fees - _feesByCeler);

        IERC20(token).safeIncreaseAllowance(address(vaultApp), amount);
        vaultApp.lockAndMint{value: _feesByCeler}(
            connectedEndpoints[SAPPHIRE_CHAINID],
            SAPPHIRE_CHAINID,
            token,
            amount,
            celerData
        );

        _messageRawHashToSender[keccak256(celerData)] = msg.sender;

        settledMessages[MessageStoreType.MultichainMessageSent][keccak256(data)] = true;
        emit MultichainMessageSent(keccak256(data));
    }

    function proxyPass(address token, uint256 amount, bytes memory encodedParams) public virtual payable {
        require(!ofacBlocklist[msg.sender], "OFAC prohibited");

        uint256 feesValue = msg.value;
        if (token == nativeWrapper) {
            require(msg.value >= amount, "Insufficient native amount");
            IWROSE(nativeWrapper).deposit{value: amount}();
            feesValue -= amount;
        } else {
            IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
        }

        require(block.chainid != SAPPHIRE_CHAINID, "Can't proxy pass from Sapphire");
        _multichainProxyPass(token, amount, encodedParams, feesValue);
    }

    function executeMessageWithTransfer(
        address _token,
        uint256 _amount,
        uint64 srcChainId,
        bytes memory _message
    ) external override payable returns (CallbackExecutionStatus) {
        require(msg.sender == address(vaultApp), "Unauthorized vault app");
        require(!_executedMessages[keccak256(_message)], "Callback already executed");

        (address sender, uint256 fee, bytes memory data) = _preprocessPayloadData(_message);

        (bytes memory header,) = abi.decode(data, (bytes, bytes));
        (uint8 commandTypeRaw) = abi.decode(header, (uint8));
        MultichainCommandType commandType = MultichainCommandType(commandTypeRaw);

        _executedMessages[keccak256(_message)] = true;
        _dataHashToSender[keccak256(data)] = sender;

        if (commandType == MultichainCommandType.ProxyPass) {
            return _handleProxyPass(
                data, 
                _amount, 
                _token, 
                fee * endpointsDestinationFees[srcChainId].settlementCostInLocalCurrency / endpointsDestinationFees[srcChainId].settlementCost
            );
        } else if (commandType == MultichainCommandType.Receive) {
            return _handleReceive(data, _token, _amount, false);
        }

        return CallbackExecutionStatus.Failed;
    }

    function executeMessageWithTransferFallback(
        address _token,
        uint256 _amount,
        bytes calldata _message
    ) external payable virtual override returns (CallbackExecutionStatus) {
        require(msg.sender == address(vaultApp), "Unauthorized vault app");

        require(!_executedMessages[keccak256(_message)], "Callback already executed");

        (address sender,,) = _preprocessPayloadData(_message);

        _transferTokensTo(sender, _token, _amount);

        _executedMessages[keccak256(_message)] = true;
        _failedMessages[keccak256(_message)] = true;

        return CallbackExecutionStatus.Success;
    }

    function _preprocessPayloadData(bytes memory data) internal virtual view returns(address, uint256, bytes memory) {
        return (address(0), 0, data);
    }

    function _beforeCommandExecution(MultichainCommandType cmd, bytes memory data, address token, uint256 amount) internal virtual {}

    function _decodeProxyPassCommand(bytes memory _entry) internal pure returns (uint64, address, uint256, uint256, uint8) {
        return abi.decode(_entry, (uint64, address, uint256, uint256, uint8));
    }

    function _encodeReceiveCommand(address dstAddress, bytes32 keyIndex) internal pure returns (bytes memory) {
        return abi.encode(abi.encode(uint8(MultichainCommandType.Receive)), abi.encode(keyIndex, dstAddress));
    }

    receive() external payable {}

    function _transferTokensTo(address _to, address _token, uint256 _amount) internal {
        if (_token == nativeWrapper) {
            IWROSE(_token).withdraw(_amount);
            payable(_to).transfer(_amount);

            return;
        }

        IERC20(_token).safeTransfer(_to, _amount);
    }

    function _handleReceive(bytes memory _data, address _token, uint256 _amount, bool failure) internal returns (CallbackExecutionStatus) {
        (, bytes memory body) = abi.decode(_data, (bytes, bytes));
        (bytes32 keyIndex, address dstAddress) = abi.decode(body, (bytes32, address));

        emit MessageReceived(keyIndex, failure);
        settledMessages[MessageStoreType.MessageReceived][keyIndex] = true;

        _transferTokensTo(dstAddress, _token, _amount);

        return CallbackExecutionStatus.Success;
    }

    function _handleProxyPass(bytes memory, uint256, address, uint256) internal virtual returns (CallbackExecutionStatus) {
        return CallbackExecutionStatus.Success;
    }
}

File 2 of 36 : ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(address from, address to, uint256 amount) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}

File 3 of 36 : IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

File 4 of 36 : IERC20Permit.sol
// 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);
}

File 5 of 36 : IERC20.sol
// 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);
}

File 6 of 36 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

File 7 of 36 : Address.sol
// 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);
        }
    }
}

File 8 of 36 : Context.sol
// 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;
    }
}

File 9 of 36 : SafeMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/SafeMath.sol)

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
 * now has built in overflow checking.
 */
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) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            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) {
        unchecked {
            // 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) {
        unchecked {
            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) {
        unchecked {
            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) {
        return a + b;
    }

    /**
     * @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) {
        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) {
        return a * b;
    }

    /**
     * @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.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        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) {
        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) {
        unchecked {
            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.
     *
     * 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) {
        unchecked {
            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) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}

File 10 of 36 : CrossChainERC20.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract CrossChainERC20 is IERC20 {
    struct CrossChainERC20Config {
        string name;
        string symbol;
        uint8 decimals;

        uint64 originalChainId;
        address originalAddress;
    }

    mapping(address => uint256) internal _balances;
    mapping(address => mapping(address => uint256)) internal _allowances;

    string public name;
    string public symbol;
    uint8 public decimals;

    address public originalAddress;
    uint64 public originalChainId;

    address public immutable deployer;

    uint256 public totalSupply;

    constructor(CrossChainERC20Config memory _config) {
        name = _config.name;
        symbol = _config.symbol;
        decimals = _config.decimals;
        originalChainId = _config.originalChainId;
        originalAddress = _config.originalAddress;

        deployer = msg.sender;
    }

    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
    }

    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = msg.sender;
        _approve(owner, spender, amount);
        return true;
    }

    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = _allowances[owner][spender];
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
        }

        _balances[to] += amount;
    }

    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = msg.sender;
        _transfer(owner, to, amount);
        return true;
    }

    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = msg.sender;
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    function mint(address to, uint256 amount) public {
        require(msg.sender == deployer);

        _balances[to] += amount;
        totalSupply += amount;
    }

    function burn(address from, uint256 amount) public {
        require(msg.sender == deployer);

        _balances[from] -= amount;
        totalSupply -= amount;
    }
}

File 11 of 36 : CrossChainVaultApp.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import "./CrossChainERC20.sol";
import "./ICrossChainVault.sol";
import "../op/IMultichainEndpoint.sol";
import "../op/celer/message/framework/MessageApp.sol";

contract CrossChainVaultApp is MessageApp, Ownable {
    using SafeERC20 for ERC20;

    enum CrossChainVaultMessageType {
        LockAndMint,
        BurnAndUnlock
    }

    struct SetAllowedSender {
        address sender;
        uint64 srcChainId;
        bool isAllowed;
    }

    struct CrossChainAssetData {
        bool isDataSet;
        address token;
        string name;
        string symbol;
        uint8 decimals;
        uint64 chainId;
    }

    event SetAuthorisedSender(address indexed sender, uint64 indexed chainId, bool isSet);
    event ActualEndpointChange(address prev, address updated);
    event EndpointExecutionReverted(bytes reason);

    ICrossChainVault public immutable vault;
    IMultichainEndpoint public endpoint;

    mapping(uint64 => mapping(address => CrossChainERC20)) public mintedTokenByOriginal;
    mapping(uint64 => mapping(CrossChainERC20 => address)) public originalTokenByMinted;

    mapping(address => mapping(uint64 => bool)) public allowedSenders;
    mapping(uint64 => bool) public allowedSenderSetup;
    mapping(address => mapping(uint64 => CrossChainAssetData)) public crossChainAssetsData;

    constructor(address _vault, address _messageBus) MessageApp(_messageBus) {
        vault = ICrossChainVault(_vault);
    }

    function setActualEndpoint(address _endpoint) public onlyOwner {
        require(address(endpoint) == address(0), "The endpoint is already configured");

        emit ActualEndpointChange(address(endpoint), _endpoint);
        endpoint = IMultichainEndpoint(_endpoint);
    }

    function setCrossChainAssets(CrossChainAssetData[] calldata assets) public onlyOwner {
        for (uint i = 0; i < assets.length; i++) {
            crossChainAssetsData[assets[i].token][assets[i].chainId] = assets[i];
        }
    }

    function setAllowedSenders(SetAllowedSender[] calldata senders) public onlyOwner {
        for (uint i = 0; i < senders.length; i++) {
            // We can't add new senders for same chain id otherwise it would be dangerous
            require(!allowedSenderSetup[senders[i].srcChainId], "Sender is already setup");

            emit SetAuthorisedSender(senders[i].sender, senders[i].srcChainId, senders[i].isAllowed);
            allowedSenders[senders[i].sender][senders[i].srcChainId] = senders[i].isAllowed;
            allowedSenderSetup[senders[i].srcChainId] = true;
        }
    }

    function executeMessage(
        address srcContract,
        uint64 _srcChainId,
        bytes calldata _message,
        address
    ) external payable override onlyMessageBus returns (ExecutionStatus) {
        require(allowedSenders[srcContract][_srcChainId], "Unauthorised sender");

        (bytes memory lockData, bytes memory _data) = abi.decode(_message, (bytes, bytes));
        (address token, uint256 amount) = _processVaultCommand(_srcChainId, lockData);

        ERC20(token).safeTransfer(address(endpoint), amount);
        IMultichainEndpoint.CallbackExecutionStatus status = IMultichainEndpoint.CallbackExecutionStatus.Failed;

        try endpoint.executeMessageWithTransfer(
            token,
            amount,
            _srcChainId,
            _data
        ) returns (IMultichainEndpoint.CallbackExecutionStatus _status) {
            status = _status;
        } catch (bytes memory reason) {
            emit EndpointExecutionReverted(reason);
            status = endpoint.executeMessageWithTransferFallback(
                token,
                amount,
                _data
            );
        }

        if (status == IMultichainEndpoint.CallbackExecutionStatus.Success) {
            return ExecutionStatus.Success;
        } else if (status == IMultichainEndpoint.CallbackExecutionStatus.Failed) {
            return ExecutionStatus.Fail;
        } else if (status == IMultichainEndpoint.CallbackExecutionStatus.Retry) {
            return ExecutionStatus.Retry;
        }

        return ExecutionStatus.Fail;
    }

    function _processVaultCommand(uint64 srcChainId, bytes memory rawCommand) private returns (address token, uint256 amt) {
        (uint8 _type, address srcAddress, uint256 amount) = abi.decode(rawCommand, (uint8, address, uint256));
        CrossChainVaultMessageType cmdType = CrossChainVaultMessageType(_type);

        amt = amount;

        if (cmdType == CrossChainVaultMessageType.LockAndMint) {
            CrossChainAssetData memory data = crossChainAssetsData[srcAddress][srcChainId];
            require(data.isDataSet, "Metadata is not set");

            token = _mintTokens(CrossChainERC20.CrossChainERC20Config(
                data.name,
                data.symbol,
                data.decimals,
                srcChainId,
                srcAddress
            ), amount);
        } else if (cmdType == CrossChainVaultMessageType.BurnAndUnlock) {
            vault.unlock(srcAddress, amount);
            token = srcAddress;
        } else {
            revert();
        }
    }

    function _mintTokens(CrossChainERC20.CrossChainERC20Config memory originalTokenDetails, uint256 amount) private returns (address) {
        CrossChainERC20 minted = mintedTokenByOriginal[originalTokenDetails.originalChainId][originalTokenDetails.originalAddress];
        if (address(minted) == address(0)) {
            minted = new CrossChainERC20(originalTokenDetails);

            mintedTokenByOriginal[originalTokenDetails.originalChainId][originalTokenDetails.originalAddress] = minted;
            originalTokenByMinted[originalTokenDetails.originalChainId][minted] = originalTokenDetails.originalAddress;
        }

        minted.mint(address(this), amount);

        return address(minted);
    }

    receive() external payable {}

    function lockAndMint(address to, uint64 chainId, address token, uint256 amount, bytes memory message) public payable {
        require(msg.sender == address(endpoint), "Invalid endpoint");

        ERC20(token).safeTransferFrom(msg.sender, address(this), amount);

        ERC20(token).safeIncreaseAllowance(address(vault), amount);
        amount = vault.lock(token, amount);

        bytes memory lockData = abi.encode(uint8(CrossChainVaultMessageType.LockAndMint), token, amount);
        bytes memory payload = abi.encode(lockData, message);

        sendMessage(to, chainId, payload, IMessageBus(messageBus).calcFee(payload));
    }

    function burnAndUnlock(address to, uint64 chainId, address token, uint256 amount, bytes memory message) public payable {
        require(msg.sender == address(endpoint), "Invalid endpoint");
        require(originalTokenByMinted[chainId][CrossChainERC20(token)] != address(0), "Invalid cross-chain token");

        ERC20(token).safeTransferFrom(msg.sender, address(this), amount);

        CrossChainERC20 crossChainToken = CrossChainERC20(token);
        crossChainToken.burn(address(this), amount);

        bytes memory unlockData = abi.encode(uint8(CrossChainVaultMessageType.BurnAndUnlock), crossChainToken.originalAddress(), amount);
        bytes memory payload = abi.encode(unlockData, message);

        sendMessage(to, chainId, payload, IMessageBus(messageBus).calcFee(payload));
    }
}

File 12 of 36 : ICrossChainVault.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

interface ICrossChainVault {
    function lock(address asset, uint256 amount) external returns (uint256);

    function unlock(address asset, uint256 amount) external;
}

File 13 of 36 : IBridge.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IBridge {
    function send(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage
    ) external;

    function sendNative(
        address _receiver,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage
    ) external payable;

    function relay(
        bytes calldata _relayRequest,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external;

    function transfers(bytes32 transferId) external view returns (bool);

    function withdraws(bytes32 withdrawId) external view returns (bool);

    function withdraw(
        bytes calldata _wdmsg,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external;

    /**
     * @notice Verifies that a message is signed by a quorum among the signers.
     * @param _msg signed message
     * @param _sigs list of signatures sorted by signer addresses in ascending order
     * @param _signers sorted list of current signers
     * @param _powers powers of current signers
     */
    function verifySigs(
        bytes memory _msg,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external view;
}

File 14 of 36 : IDelayedTransfer.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.17;

interface IDelayedTransfer {
    struct delayedTransfer {
        address receiver;
        address token;
        uint256 amount;
        uint256 timestamp;
    }

    function delayedTransfers(bytes32 transferId) external view returns (delayedTransfer memory);
}

File 15 of 36 : IOriginalTokenVault.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IOriginalTokenVault {
    /**
     * @notice Lock original tokens to trigger mint at a remote chain's PeggedTokenBridge
     * @param _token local token address
     * @param _amount locked token amount
     * @param _mintChainId destination chainId to mint tokens
     * @param _mintAccount destination account to receive minted tokens
     * @param _nonce user input to guarantee unique depositId
     */
    function deposit(
        address _token,
        uint256 _amount,
        uint64 _mintChainId,
        address _mintAccount,
        uint64 _nonce
    ) external;

    /**
     * @notice Lock native token as original token to trigger mint at a remote chain's PeggedTokenBridge
     * @param _amount locked token amount
     * @param _mintChainId destination chainId to mint tokens
     * @param _mintAccount destination account to receive minted tokens
     * @param _nonce user input to guarantee unique depositId
     */
    function depositNative(
        uint256 _amount,
        uint64 _mintChainId,
        address _mintAccount,
        uint64 _nonce
    ) external payable;

    /**
     * @notice Withdraw locked original tokens triggered by a burn at a remote chain's PeggedTokenBridge.
     * @param _request The serialized Withdraw protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the bridge's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function withdraw(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external;

    function records(bytes32 recordId) external view returns (bool);
}

File 16 of 36 : IOriginalTokenVaultV2.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IOriginalTokenVaultV2 {
    /**
     * @notice Lock original tokens to trigger mint at a remote chain's PeggedTokenBridge
     * @param _token local token address
     * @param _amount locked token amount
     * @param _mintChainId destination chainId to mint tokens
     * @param _mintAccount destination account to receive minted tokens
     * @param _nonce user input to guarantee unique depositId
     */
    function deposit(
        address _token,
        uint256 _amount,
        uint64 _mintChainId,
        address _mintAccount,
        uint64 _nonce
    ) external returns (bytes32);

    /**
     * @notice Lock native token as original token to trigger mint at a remote chain's PeggedTokenBridge
     * @param _amount locked token amount
     * @param _mintChainId destination chainId to mint tokens
     * @param _mintAccount destination account to receive minted tokens
     * @param _nonce user input to guarantee unique depositId
     */
    function depositNative(
        uint256 _amount,
        uint64 _mintChainId,
        address _mintAccount,
        uint64 _nonce
    ) external payable returns (bytes32);

    /**
     * @notice Withdraw locked original tokens triggered by a burn at a remote chain's PeggedTokenBridge.
     * @param _request The serialized Withdraw protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the bridge's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function withdraw(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external returns (bytes32);

    function records(bytes32 recordId) external view returns (bool);
}

File 17 of 36 : IPeggedTokenBridge.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IPeggedTokenBridge {
    /**
     * @notice Burn tokens to trigger withdrawal at a remote chain's OriginalTokenVault
     * @param _token local token address
     * @param _amount locked token amount
     * @param _withdrawAccount account who withdraw original tokens on the remote chain
     * @param _nonce user input to guarantee unique depositId
     */
    function burn(
        address _token,
        uint256 _amount,
        address _withdrawAccount,
        uint64 _nonce
    ) external;

    /**
     * @notice Mint tokens triggered by deposit at a remote chain's OriginalTokenVault.
     * @param _request The serialized Mint protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function mint(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external;

    function records(bytes32 recordId) external view returns (bool);
}

File 18 of 36 : IPeggedTokenBridgeV2.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IPeggedTokenBridgeV2 {
    /**
     * @notice Burn pegged tokens to trigger a cross-chain withdrawal of the original tokens at a remote chain's
     * OriginalTokenVault, or mint at another remote chain
     * @param _token The pegged token address.
     * @param _amount The amount to burn.
     * @param _toChainId If zero, withdraw from original vault; otherwise, the remote chain to mint tokens.
     * @param _toAccount The account to receive tokens on the remote chain
     * @param _nonce A number to guarantee unique depositId. Can be timestamp in practice.
     */
    function burn(
        address _token,
        uint256 _amount,
        uint64 _toChainId,
        address _toAccount,
        uint64 _nonce
    ) external returns (bytes32);

    // same with `burn` above, use openzeppelin ERC20Burnable interface
    function burnFrom(
        address _token,
        uint256 _amount,
        uint64 _toChainId,
        address _toAccount,
        uint64 _nonce
    ) external returns (bytes32);

    /**
     * @notice Mint tokens triggered by deposit at a remote chain's OriginalTokenVault.
     * @param _request The serialized Mint protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function mint(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external returns (bytes32);

    function records(bytes32 recordId) external view returns (bool);
}

File 19 of 36 : ISigsVerifier.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface ISigsVerifier {
    /**
     * @notice Verifies that a message is signed by a quorum among the signers.
     * @param _msg signed message
     * @param _sigs list of signatures sorted by signer addresses in ascending order
     * @param _signers sorted list of current signers
     * @param _powers powers of current signers
     */
    function verifySigs(
        bytes memory _msg,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external view;
}

File 20 of 36 : Utils.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

library Utils {
    // https://ethereum.stackexchange.com/a/83577
    // https://github.com/Uniswap/v3-periphery/blob/v1.0.0/contracts/base/Multicall.sol
    function getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
        // If the _res length is less than 68, then the transaction failed silently (without a revert message)
        if (_returnData.length < 68) return "Transaction reverted silently";
        assembly {
            // Slice the sighash.
            _returnData := add(_returnData, 0x04)
        }
        return abi.decode(_returnData, (string)); // All that remains is the revert string
    }
}

File 21 of 36 : MessageApp.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

import "./MessageSenderApp.sol";
import "./MessageReceiverApp.sol";

abstract contract MessageApp is MessageSenderApp, MessageReceiverApp {
    constructor(address _messageBus) {
        messageBus = _messageBus;
    }
}

File 22 of 36 : MessageBusAddress.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

abstract contract MessageBusAddress {
    address public messageBus;
}

File 23 of 36 : MessageReceiverApp.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

import "../interfaces/IMessageReceiverApp.sol";
import "../libraries/MsgDataTypes.sol";
import "./MessageBusAddress.sol";

abstract contract MessageReceiverApp is IMessageReceiverApp, MessageBusAddress {
    modifier onlyMessageBus() {
        require(msg.sender == messageBus, "caller is not message bus");
        _;
    }

    // Add abort prefix in the reason string for require or revert.
    // This will abort (revert) the message execution without markig it as failed state,
    // making it possible to retry later.
    function _abortReason(string memory reason) internal pure returns (string memory) {
        return MsgDataTypes.abortReason(reason);
    }

    /**
     * @notice Called by MessageBus to execute a message
     * @param _sender The address of the source app contract
     * @param _srcChainId The source chain ID where the transfer is originated from
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _executor Address who called the MessageBus execution function
     */
    function executeMessage(
        address _sender,
        uint64 _srcChainId,
        bytes calldata _message,
        address _executor
    ) external payable virtual override onlyMessageBus returns (ExecutionStatus) {}

    // execute message from non-evm chain with bytes for sender address,
    // otherwise same as above.
    function executeMessage(
        bytes calldata _sender,
        uint64 _srcChainId,
        bytes calldata _message,
        address _executor
    ) external payable virtual override onlyMessageBus returns (ExecutionStatus) {}

    /**
     * @notice Called by MessageBus to execute a message with an associated token transfer.
     * The contract is guaranteed to have received the right amount of tokens before this function is called.
     * @param _sender The address of the source app contract
     * @param _token The address of the token that comes out of the bridge
     * @param _amount The amount of tokens received at this contract through the cross-chain bridge.
     * @param _srcChainId The source chain ID where the transfer is originated from
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _executor Address who called the MessageBus execution function
     */
    function executeMessageWithTransfer(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes calldata _message,
        address _executor
    ) external payable virtual override onlyMessageBus returns (ExecutionStatus) {}

    /**
     * @notice Only called by MessageBus if
     *         1. executeMessageWithTransfer reverts, or
     *         2. executeMessageWithTransfer returns ExecutionStatus.Fail
     * The contract is guaranteed to have received the right amount of tokens before this function is called.
     * @param _sender The address of the source app contract
     * @param _token The address of the token that comes out of the bridge
     * @param _amount The amount of tokens received at this contract through the cross-chain bridge.
     * @param _srcChainId The source chain ID where the transfer is originated from
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _executor Address who called the MessageBus execution function
     */
    function executeMessageWithTransferFallback(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes calldata _message,
        address _executor
    ) external payable virtual override onlyMessageBus returns (ExecutionStatus) {}

    /**
     * @notice Called by MessageBus to process refund of the original transfer from this contract.
     * The contract is guaranteed to have received the refund before this function is called.
     * @param _token The token address of the original transfer
     * @param _amount The amount of the original transfer
     * @param _message The same message associated with the original transfer
     * @param _executor Address who called the MessageBus execution function
     */
    function executeMessageWithTransferRefund(
        address _token,
        uint256 _amount,
        bytes calldata _message,
        address _executor
    ) external payable virtual override onlyMessageBus returns (ExecutionStatus) {}
}

File 24 of 36 : MessageSenderApp.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import "../libraries/MsgDataTypes.sol";
import "../libraries/MessageSenderLib.sol";
import "../messagebus/MessageBus.sol";
import "./MessageBusAddress.sol";

abstract contract MessageSenderApp is MessageBusAddress {
    using SafeERC20 for IERC20;

    // ============== Utility functions called by apps ==============

    /**
     * @notice Sends a message to a contract on another chain.
     * Sender needs to make sure the uniqueness of the message Id, which is computed as
     * hash(type.MessageOnly, sender, receiver, srcChainId, srcTxHash, dstChainId, message).
     * If messages with the same Id are sent, only one of them will succeed at dst chain.
     * @param _receiver The address of the destination app contract.
     * @param _dstChainId The destination chain ID.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     * @param _fee The fee amount to pay to MessageBus.
     */
    function sendMessage(
        address _receiver,
        uint64 _dstChainId,
        bytes memory _message,
        uint256 _fee
    ) internal {
        MessageSenderLib.sendMessage(_receiver, _dstChainId, _message, messageBus, _fee);
    }

    // Send message to non-evm chain with bytes for receiver address,
    // otherwise same as above.
    function sendMessage(
        bytes calldata _receiver,
        uint64 _dstChainId,
        bytes memory _message,
        uint256 _fee
    ) internal {
        MessageSenderLib.sendMessage(_receiver, _dstChainId, _message, messageBus, _fee);
    }

    /**
     * @notice Sends a message associated with a transfer to a contract on another chain.
     * @param _receiver The address of the destination app contract.
     * @param _token The address of the token to be sent.
     * @param _amount The amount of tokens to be sent.
     * @param _dstChainId The destination chain ID.
     * @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
     * @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
     *        Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least
     *        (100% - max slippage percentage) * amount or the transfer can be refunded.
     *        Only applicable to the {MsgDataTypes.BridgeSendType.Liquidity}.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     *        If message is empty, only the token transfer will be sent
     * @param _bridgeSendType One of the {BridgeSendType} enum.
     * @param _fee The fee amount to pay to MessageBus.
     * @return The transfer ID.
     */
    function sendMessageWithTransfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage,
        bytes memory _message,
        MsgDataTypes.BridgeSendType _bridgeSendType,
        uint256 _fee
    ) internal returns (bytes32) {
        return
            MessageSenderLib.sendMessageWithTransfer(
                _receiver,
                _token,
                _amount,
                _dstChainId,
                _nonce,
                _maxSlippage,
                _message,
                _bridgeSendType,
                messageBus,
                _fee
            );
    }

    /**
     * @notice Sends a token transfer via a bridge.
     * @dev sendMessageWithTransfer with empty message
     * @param _receiver The address of the destination app contract.
     * @param _token The address of the token to be sent.
     * @param _amount The amount of tokens to be sent.
     * @param _dstChainId The destination chain ID.
     * @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
     * @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
     *        Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least
     *        (100% - max slippage percentage) * amount or the transfer can be refunded.
     *        Only applicable to the {MsgDataTypes.BridgeSendType.Liquidity}.
     * @param _bridgeSendType One of the {BridgeSendType} enum.
     */
    function sendTokenTransfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage,
        MsgDataTypes.BridgeSendType _bridgeSendType
    ) internal returns (bytes32) {
        return
            MessageSenderLib.sendMessageWithTransfer(
                _receiver,
                _token,
                _amount,
                _dstChainId,
                _nonce,
                _maxSlippage,
                "", // empty message, which will not trigger sendMessage
                _bridgeSendType,
                messageBus,
                0
            );
    }
}

File 25 of 36 : IMessageBus.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

import "../libraries/MsgDataTypes.sol";

interface IMessageBus {
    /**
     * @notice Send a message to a contract on another chain.
     * Sender needs to make sure the uniqueness of the message Id, which is computed as
     * hash(type.MessageOnly, sender, receiver, srcChainId, srcTxHash, dstChainId, message).
     * If messages with the same Id are sent, only one of them will succeed at dst chain..
     * A fee is charged in the native gas token.
     * @param _receiver The address of the destination app contract.
     * @param _dstChainId The destination chain ID.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     */
    function sendMessage(
        address _receiver,
        uint256 _dstChainId,
        bytes calldata _message
    ) external payable;

    // same as above, except that receiver is an non-evm chain address,
    function sendMessage(
        bytes calldata _receiver,
        uint256 _dstChainId,
        bytes calldata _message
    ) external payable;

    /**
     * @notice Send a message associated with a token transfer to a contract on another chain.
     * If messages with the same srcTransferId are sent, only one of them will succeed at dst chain..
     * A fee is charged in the native token.
     * @param _receiver The address of the destination app contract.
     * @param _dstChainId The destination chain ID.
     * @param _srcBridge The bridge contract to send the transfer with.
     * @param _srcTransferId The transfer ID.
     * @param _dstChainId The destination chain ID.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     */
    function sendMessageWithTransfer(
        address _receiver,
        uint256 _dstChainId,
        address _srcBridge,
        bytes32 _srcTransferId,
        bytes calldata _message
    ) external payable;

    /**
     * @notice Execute a message not associated with a transfer.
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function executeMessage(
        bytes calldata _message,
        MsgDataTypes.RouteInfo calldata _route,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external payable;

    /**
     * @notice Execute a message with a successful transfer.
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _transfer The transfer info.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function executeMessageWithTransfer(
        bytes calldata _message,
        MsgDataTypes.TransferInfo calldata _transfer,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external payable;

    /**
     * @notice Execute a message with a refunded transfer.
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _transfer The transfer info.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function executeMessageWithTransferRefund(
        bytes calldata _message, // the same message associated with the original transfer
        MsgDataTypes.TransferInfo calldata _transfer,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external payable;

    /**
     * @notice Withdraws message fee in the form of native gas token.
     * @param _account The address receiving the fee.
     * @param _cumulativeFee The cumulative fee credited to the account. Tracked by SGN.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A withdrawal must be
     * signed-off by +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function withdrawFee(
        address _account,
        uint256 _cumulativeFee,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external;

    /**
     * @notice Calculates the required fee for the message.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     @ @return The required fee.
     */
    function calcFee(bytes calldata _message) external view returns (uint256);

    function liquidityBridge() external view returns (address);

    function pegBridge() external view returns (address);

    function pegBridgeV2() external view returns (address);

    function pegVault() external view returns (address);

    function pegVaultV2() external view returns (address);
}

File 26 of 36 : IMessageReceiverApp.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IMessageReceiverApp {
    enum ExecutionStatus {
        Fail, // execution failed, finalized
        Success, // execution succeeded, finalized
        Retry // execution rejected, can retry later
    }

    /**
     * @notice Called by MessageBus to execute a message
     * @param _sender The address of the source app contract
     * @param _srcChainId The source chain ID where the transfer is originated from
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _executor Address who called the MessageBus execution function
     */
    function executeMessage(
        address _sender,
        uint64 _srcChainId,
        bytes calldata _message,
        address _executor
    ) external payable returns (ExecutionStatus);

    // same as above, except that sender is an non-evm chain address,
    // otherwise same as above.
    function executeMessage(
        bytes calldata _sender,
        uint64 _srcChainId,
        bytes calldata _message,
        address _executor
    ) external payable returns (ExecutionStatus);

    /**
     * @notice Called by MessageBus to execute a message with an associated token transfer.
     * The contract is guaranteed to have received the right amount of tokens before this function is called.
     * @param _sender The address of the source app contract
     * @param _token The address of the token that comes out of the bridge
     * @param _amount The amount of tokens received at this contract through the cross-chain bridge.
     * @param _srcChainId The source chain ID where the transfer is originated from
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _executor Address who called the MessageBus execution function
     */
    function executeMessageWithTransfer(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes calldata _message,
        address _executor
    ) external payable returns (ExecutionStatus);

    /**
     * @notice Only called by MessageBus if
     *         1. executeMessageWithTransfer reverts, or
     *         2. executeMessageWithTransfer returns ExecutionStatus.Fail
     * The contract is guaranteed to have received the right amount of tokens before this function is called.
     * @param _sender The address of the source app contract
     * @param _token The address of the token that comes out of the bridge
     * @param _amount The amount of tokens received at this contract through the cross-chain bridge.
     * @param _srcChainId The source chain ID where the transfer is originated from
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _executor Address who called the MessageBus execution function
     */
    function executeMessageWithTransferFallback(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes calldata _message,
        address _executor
    ) external payable returns (ExecutionStatus);

    /**
     * @notice Called by MessageBus to process refund of the original transfer from this contract.
     * The contract is guaranteed to have received the refund before this function is called.
     * @param _token The token address of the original transfer
     * @param _amount The amount of the original transfer
     * @param _message The same message associated with the original transfer
     * @param _executor Address who called the MessageBus execution function
     */
    function executeMessageWithTransferRefund(
        address _token,
        uint256 _amount,
        bytes calldata _message,
        address _executor
    ) external payable returns (ExecutionStatus);
}

File 27 of 36 : MessageSenderLib.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../../interfaces/IBridge.sol";
import "../../interfaces/IOriginalTokenVault.sol";
import "../../interfaces/IOriginalTokenVaultV2.sol";
import "../../interfaces/IPeggedTokenBridge.sol";
import "../../interfaces/IPeggedTokenBridgeV2.sol";
import "../interfaces/IMessageBus.sol";
import "./MsgDataTypes.sol";

library MessageSenderLib {
    using SafeERC20 for IERC20;

    // ============== Internal library functions called by apps ==============

    /**
     * @notice Sends a message to an app on another chain via MessageBus without an associated transfer.
     * @param _receiver The address of the destination app contract.
     * @param _dstChainId The destination chain ID.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     * @param _messageBus The address of the MessageBus on this chain.
     * @param _fee The fee amount to pay to MessageBus.
     */
    function sendMessage(
        address _receiver,
        uint64 _dstChainId,
        bytes memory _message,
        address _messageBus,
        uint256 _fee
    ) internal {
        IMessageBus(_messageBus).sendMessage{value: _fee}(_receiver, _dstChainId, _message);
    }

    // Send message to non-evm chain with bytes for receiver address,
    // otherwise same as above.
    function sendMessage(
        bytes calldata _receiver,
        uint64 _dstChainId,
        bytes memory _message,
        address _messageBus,
        uint256 _fee
    ) internal {
        IMessageBus(_messageBus).sendMessage{value: _fee}(_receiver, _dstChainId, _message);
    }

    /**
     * @notice Sends a message to an app on another chain via MessageBus with an associated transfer.
     * @param _receiver The address of the destination app contract.
     * @param _token The address of the token to be sent.
     * @param _amount The amount of tokens to be sent.
     * @param _dstChainId The destination chain ID.
     * @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
     * @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
     * Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least (100% - max slippage percentage) * amount or the
     * transfer can be refunded. Only applicable to the {MsgDataTypes.BridgeSendType.Liquidity}.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     * @param _bridgeSendType One of the {MsgDataTypes.BridgeSendType} enum.
     * @param _messageBus The address of the MessageBus on this chain.
     * @param _fee The fee amount to pay to MessageBus.
     * @return The transfer ID.
     */
    function sendMessageWithTransfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage,
        bytes memory _message,
        MsgDataTypes.BridgeSendType _bridgeSendType,
        address _messageBus,
        uint256 _fee
    ) internal returns (bytes32) {
        (bytes32 transferId, address bridge) = sendTokenTransfer(
            _receiver,
            _token,
            _amount,
            _dstChainId,
            _nonce,
            _maxSlippage,
            _bridgeSendType,
            _messageBus
        );
        if (_message.length > 0) {
            IMessageBus(_messageBus).sendMessageWithTransfer{value: _fee}(
                _receiver,
                _dstChainId,
                bridge,
                transferId,
                _message
            );
        }
        return transferId;
    }

    /**
     * @notice Sends a token transfer via a bridge.
     * @param _receiver The address of the destination app contract.
     * @param _token The address of the token to be sent.
     * @param _amount The amount of tokens to be sent.
     * @param _dstChainId The destination chain ID.
     * @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
     * @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
     * Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least (100% - max slippage percentage) * amount or the
     * transfer can be refunded.
     * @param _bridgeSendType One of the {MsgDataTypes.BridgeSendType} enum.
     */
    function sendTokenTransfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage,
        MsgDataTypes.BridgeSendType _bridgeSendType,
        address _messageBus
    ) internal returns (bytes32 transferId, address bridge) {
        if (_bridgeSendType == MsgDataTypes.BridgeSendType.Liquidity) {
            bridge = IMessageBus(_messageBus).liquidityBridge();
            IERC20(_token).safeIncreaseAllowance(bridge, _amount);
            IBridge(bridge).send(_receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage);
            transferId = computeLiqBridgeTransferId(_receiver, _token, _amount, _dstChainId, _nonce);
        } else if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegDeposit) {
            bridge = IMessageBus(_messageBus).pegVault();
            IERC20(_token).safeIncreaseAllowance(bridge, _amount);
            IOriginalTokenVault(bridge).deposit(_token, _amount, _dstChainId, _receiver, _nonce);
            transferId = computePegV1DepositId(_receiver, _token, _amount, _dstChainId, _nonce);
        } else if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegBurn) {
            bridge = IMessageBus(_messageBus).pegBridge();
            IERC20(_token).safeIncreaseAllowance(bridge, _amount);
            IPeggedTokenBridge(bridge).burn(_token, _amount, _receiver, _nonce);
            // handle cases where certain tokens do not spend allowance for role-based burn
            IERC20(_token).safeApprove(bridge, 0);
            transferId = computePegV1BurnId(_receiver, _token, _amount, _nonce);
        } else if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegV2Deposit) {
            bridge = IMessageBus(_messageBus).pegVaultV2();
            IERC20(_token).safeIncreaseAllowance(bridge, _amount);
            transferId = IOriginalTokenVaultV2(bridge).deposit(_token, _amount, _dstChainId, _receiver, _nonce);
        } else if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegV2Burn) {
            bridge = IMessageBus(_messageBus).pegBridgeV2();
            IERC20(_token).safeIncreaseAllowance(bridge, _amount);
            transferId = IPeggedTokenBridgeV2(bridge).burn(_token, _amount, _dstChainId, _receiver, _nonce);
            // handle cases where certain tokens do not spend allowance for role-based burn
            IERC20(_token).safeApprove(bridge, 0);
        } else if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegV2BurnFrom) {
            bridge = IMessageBus(_messageBus).pegBridgeV2();
            IERC20(_token).safeIncreaseAllowance(bridge, _amount);
            transferId = IPeggedTokenBridgeV2(bridge).burnFrom(_token, _amount, _dstChainId, _receiver, _nonce);
            // handle cases where certain tokens do not spend allowance for role-based burn
            IERC20(_token).safeApprove(bridge, 0);
        } else {
            revert("bridge type not supported");
        }
    }

    function computeLiqBridgeTransferId(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce
    ) internal view returns (bytes32) {
        return
            keccak256(
                abi.encodePacked(address(this), _receiver, _token, _amount, _dstChainId, _nonce, uint64(block.chainid))
            );
    }

    function computePegV1DepositId(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce
    ) internal view returns (bytes32) {
        return
            keccak256(
                abi.encodePacked(address(this), _token, _amount, _dstChainId, _receiver, _nonce, uint64(block.chainid))
            );
    }

    function computePegV1BurnId(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _nonce
    ) internal view returns (bytes32) {
        return keccak256(abi.encodePacked(address(this), _token, _amount, _receiver, _nonce, uint64(block.chainid)));
    }
}

File 28 of 36 : MsgDataTypes.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

library MsgDataTypes {
    string constant ABORT_PREFIX = "MSG::ABORT:";

    // Add abort prefix in the reason string for require or revert.
    // This will abort (revert) the message execution without markig it as failed state,
    // making it possible to retry later.
    function abortReason(string memory reason) internal pure returns (string memory) {
        return string.concat(MsgDataTypes.ABORT_PREFIX, reason);
    }

    // bridge operation type at the sender side (src chain)
    enum BridgeSendType {
        Null,
        Liquidity,
        PegDeposit,
        PegBurn,
        PegV2Deposit,
        PegV2Burn,
        PegV2BurnFrom
    }

    // bridge operation type at the receiver side (dst chain)
    enum TransferType {
        Null,
        LqRelay, // relay through liquidity bridge
        LqWithdraw, // withdraw from liquidity bridge
        PegMint, // mint through pegged token bridge
        PegWithdraw, // withdraw from original token vault
        PegV2Mint, // mint through pegged token bridge v2
        PegV2Withdraw // withdraw from original token vault v2
    }

    enum MsgType {
        MessageWithTransfer,
        MessageOnly
    }

    enum TxStatus {
        Null,
        Success,
        Fail,
        Fallback,
        Pending // transient state within a transaction
    }

    struct TransferInfo {
        TransferType t;
        address sender;
        address receiver;
        address token;
        uint256 amount;
        uint64 wdseq; // only needed for LqWithdraw (refund)
        uint64 srcChainId;
        bytes32 refId;
        bytes32 srcTxHash; // src chain msg tx hash
    }

    struct RouteInfo {
        address sender;
        address receiver;
        uint64 srcChainId;
        bytes32 srcTxHash; // src chain msg tx hash
    }

    // used for msg from non-evm chains with longer-bytes address
    struct RouteInfo2 {
        bytes sender;
        address receiver;
        uint64 srcChainId;
        bytes32 srcTxHash;
    }

    // combination of RouteInfo and RouteInfo2 for easier processing
    struct Route {
        address sender; // from RouteInfo
        bytes senderBytes; // from RouteInfo2
        address receiver;
        uint64 srcChainId;
        bytes32 srcTxHash;
    }

    struct MsgWithTransferExecutionParams {
        bytes message;
        TransferInfo transfer;
        bytes[] sigs;
        address[] signers;
        uint256[] powers;
    }

    struct BridgeTransferParams {
        bytes request;
        bytes[] sigs;
        address[] signers;
        uint256[] powers;
    }
}

File 29 of 36 : MessageBus.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.17;

import "./MessageBusSender.sol";
import "./MessageBusReceiver.sol";

contract MessageBus is MessageBusSender, MessageBusReceiver {
    constructor(
        ISigsVerifier _sigsVerifier,
        address _liquidityBridge,
        address _pegBridge,
        address _pegVault,
        address _pegBridgeV2,
        address _pegVaultV2
    )
        MessageBusSender(_sigsVerifier)
        MessageBusReceiver(_liquidityBridge, _pegBridge, _pegVault, _pegBridgeV2, _pegVaultV2)
    {}

    // this is only to be called by Proxy via delegateCall as initOwner will require _owner is 0.
    // so calling init on this contract directly will guarantee to fail
    function init(
        address _liquidityBridge,
        address _pegBridge,
        address _pegVault,
        address _pegBridgeV2,
        address _pegVaultV2
    ) external {
        // MUST manually call ownable init and must only call once
        initOwner();
        // we don't need sender init as _sigsVerifier is immutable so already in the deployed code
        initReceiver(_liquidityBridge, _pegBridge, _pegVault, _pegBridgeV2, _pegVaultV2);
    }
}

File 30 of 36 : MessageBusReceiver.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.17;

import "../libraries/MsgDataTypes.sol";
import "../interfaces/IMessageReceiverApp.sol";
import "../../interfaces/IBridge.sol";
import "../../interfaces/IOriginalTokenVault.sol";
import "../../interfaces/IOriginalTokenVaultV2.sol";
import "../../interfaces/IPeggedTokenBridge.sol";
import "../../interfaces/IPeggedTokenBridgeV2.sol";
import "../../interfaces/IDelayedTransfer.sol";
import "../../safeguard/Ownable.sol";
import "../../libraries/Utils.sol";

contract MessageBusReceiver is Ownable {
    mapping(bytes32 => MsgDataTypes.TxStatus) public executedMessages;

    address public liquidityBridge; // liquidity bridge address
    address public pegBridge; // peg bridge address
    address public pegVault; // peg original vault address
    address public pegBridgeV2; // peg bridge address
    address public pegVaultV2; // peg original vault address

    // minimum amount of gas needed by this contract before it tries to
    // deliver a message to the target contract.
    uint256 public preExecuteMessageGasUsage;

    event Executed(
        MsgDataTypes.MsgType msgType,
        bytes32 msgId,
        MsgDataTypes.TxStatus status,
        address indexed receiver,
        uint64 srcChainId,
        bytes32 srcTxHash
    );
    event NeedRetry(MsgDataTypes.MsgType msgType, bytes32 msgId, uint64 srcChainId, bytes32 srcTxHash);
    event CallReverted(string reason); // help debug

    event LiquidityBridgeUpdated(address liquidityBridge);
    event PegBridgeUpdated(address pegBridge);
    event PegVaultUpdated(address pegVault);
    event PegBridgeV2Updated(address pegBridgeV2);
    event PegVaultV2Updated(address pegVaultV2);

    constructor(
        address _liquidityBridge,
        address _pegBridge,
        address _pegVault,
        address _pegBridgeV2,
        address _pegVaultV2
    ) {
        liquidityBridge = _liquidityBridge;
        pegBridge = _pegBridge;
        pegVault = _pegVault;
        pegBridgeV2 = _pegBridgeV2;
        pegVaultV2 = _pegVaultV2;
    }

    function initReceiver(
        address _liquidityBridge,
        address _pegBridge,
        address _pegVault,
        address _pegBridgeV2,
        address _pegVaultV2
    ) internal {
        require(liquidityBridge == address(0), "liquidityBridge already set");
        liquidityBridge = _liquidityBridge;
        pegBridge = _pegBridge;
        pegVault = _pegVault;
        pegBridgeV2 = _pegBridgeV2;
        pegVaultV2 = _pegVaultV2;
    }

    // ============== functions called by executor ==============

    /**
     * @notice Execute a message with a successful transfer.
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _transfer The transfer info.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function executeMessageWithTransfer(
        bytes calldata _message,
        MsgDataTypes.TransferInfo calldata _transfer,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) public payable {
        // For message with token transfer, message Id is computed through transfer info
        // in order to guarantee that each transfer can only be used once.
        bytes32 messageId = verifyTransfer(_transfer);
        require(executedMessages[messageId] == MsgDataTypes.TxStatus.Null, "transfer already executed");
        executedMessages[messageId] = MsgDataTypes.TxStatus.Pending;

        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "MessageWithTransfer"));
        IBridge(liquidityBridge).verifySigs(
            abi.encodePacked(domain, messageId, _message, _transfer.srcTxHash),
            _sigs,
            _signers,
            _powers
        );
        MsgDataTypes.TxStatus status;
        IMessageReceiverApp.ExecutionStatus est = executeMessageWithTransfer(_transfer, _message);
        if (est == IMessageReceiverApp.ExecutionStatus.Success) {
            status = MsgDataTypes.TxStatus.Success;
        } else if (est == IMessageReceiverApp.ExecutionStatus.Retry) {
            executedMessages[messageId] = MsgDataTypes.TxStatus.Null;
            emit NeedRetry(
                MsgDataTypes.MsgType.MessageWithTransfer,
                messageId,
                _transfer.srcChainId,
                _transfer.srcTxHash
            );
            return;
        } else {
            est = executeMessageWithTransferFallback(_transfer, _message);
            if (est == IMessageReceiverApp.ExecutionStatus.Success) {
                status = MsgDataTypes.TxStatus.Fallback;
            } else {
                status = MsgDataTypes.TxStatus.Fail;
            }
        }
        executedMessages[messageId] = status;
        emitMessageWithTransferExecutedEvent(messageId, status, _transfer);
    }

    /**
     * @notice Execute a message with a refunded transfer.
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _transfer The transfer info.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function executeMessageWithTransferRefund(
        bytes calldata _message, // the same message associated with the original transfer
        MsgDataTypes.TransferInfo calldata _transfer,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) public payable {
        // similar to executeMessageWithTransfer
        bytes32 messageId = verifyTransfer(_transfer);
        require(executedMessages[messageId] == MsgDataTypes.TxStatus.Null, "transfer already executed");
        executedMessages[messageId] = MsgDataTypes.TxStatus.Pending;

        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "MessageWithTransferRefund"));
        IBridge(liquidityBridge).verifySigs(
            abi.encodePacked(domain, messageId, _message, _transfer.srcTxHash),
            _sigs,
            _signers,
            _powers
        );
        MsgDataTypes.TxStatus status;
        IMessageReceiverApp.ExecutionStatus est = executeMessageWithTransferRefund(_transfer, _message);
        if (est == IMessageReceiverApp.ExecutionStatus.Success) {
            status = MsgDataTypes.TxStatus.Success;
        } else if (est == IMessageReceiverApp.ExecutionStatus.Retry) {
            executedMessages[messageId] = MsgDataTypes.TxStatus.Null;
            emit NeedRetry(
                MsgDataTypes.MsgType.MessageWithTransfer,
                messageId,
                _transfer.srcChainId,
                _transfer.srcTxHash
            );
            return;
        } else {
            status = MsgDataTypes.TxStatus.Fail;
        }
        executedMessages[messageId] = status;
        emitMessageWithTransferExecutedEvent(messageId, status, _transfer);
    }

    /**
     * @notice Execute a message not associated with a transfer.
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _route The info about the sender and the receiver.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function executeMessage(
        bytes calldata _message,
        MsgDataTypes.RouteInfo calldata _route,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external payable {
        MsgDataTypes.Route memory route = getRouteInfo(_route);
        executeMessage(_message, route, _sigs, _signers, _powers, "Message");
    }

    // execute message from non-evm chain with bytes for sender address,
    // otherwise same as above.
    function executeMessage(
        bytes calldata _message,
        MsgDataTypes.RouteInfo2 calldata _route,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external payable {
        MsgDataTypes.Route memory route = getRouteInfo(_route);
        executeMessage(_message, route, _sigs, _signers, _powers, "Message2");
    }

    function executeMessage(
        bytes calldata _message,
        MsgDataTypes.Route memory _route,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers,
        string memory domainName
    ) private {
        // For message without associated token transfer, message Id is computed through message info,
        // in order to guarantee that each message can only be applied once
        bytes32 messageId = computeMessageOnlyId(_route, _message);
        require(executedMessages[messageId] == MsgDataTypes.TxStatus.Null, "message already executed");
        executedMessages[messageId] = MsgDataTypes.TxStatus.Pending;

        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), domainName));
        IBridge(liquidityBridge).verifySigs(abi.encodePacked(domain, messageId), _sigs, _signers, _powers);
        MsgDataTypes.TxStatus status;
        IMessageReceiverApp.ExecutionStatus est = executeMessage(_route, _message);
        if (est == IMessageReceiverApp.ExecutionStatus.Success) {
            status = MsgDataTypes.TxStatus.Success;
        } else if (est == IMessageReceiverApp.ExecutionStatus.Retry) {
            executedMessages[messageId] = MsgDataTypes.TxStatus.Null;
            emit NeedRetry(MsgDataTypes.MsgType.MessageOnly, messageId, _route.srcChainId, _route.srcTxHash);
            return;
        } else {
            status = MsgDataTypes.TxStatus.Fail;
        }
        executedMessages[messageId] = status;
        emitMessageOnlyExecutedEvent(messageId, status, _route);
    }

    // ================= utils (to avoid stack too deep) =================

    function emitMessageWithTransferExecutedEvent(
        bytes32 _messageId,
        MsgDataTypes.TxStatus _status,
        MsgDataTypes.TransferInfo calldata _transfer
    ) private {
        emit Executed(
            MsgDataTypes.MsgType.MessageWithTransfer,
            _messageId,
            _status,
            _transfer.receiver,
            _transfer.srcChainId,
            _transfer.srcTxHash
        );
    }

    function emitMessageOnlyExecutedEvent(
        bytes32 _messageId,
        MsgDataTypes.TxStatus _status,
        MsgDataTypes.Route memory _route
    ) private {
        emit Executed(
            MsgDataTypes.MsgType.MessageOnly,
            _messageId,
            _status,
            _route.receiver,
            _route.srcChainId,
            _route.srcTxHash
        );
    }

    function executeMessageWithTransfer(MsgDataTypes.TransferInfo calldata _transfer, bytes calldata _message)
        private
        returns (IMessageReceiverApp.ExecutionStatus)
    {
        uint256 gasLeftBeforeExecution = gasleft();
        (bool ok, bytes memory res) = address(_transfer.receiver).call{value: msg.value}(
            abi.encodeWithSelector(
                IMessageReceiverApp.executeMessageWithTransfer.selector,
                _transfer.sender,
                _transfer.token,
                _transfer.amount,
                _transfer.srcChainId,
                _message,
                msg.sender
            )
        );
        if (ok) {
            return abi.decode((res), (IMessageReceiverApp.ExecutionStatus));
        }
        handleExecutionRevert(gasLeftBeforeExecution, res);
        return IMessageReceiverApp.ExecutionStatus.Fail;
    }

    function executeMessageWithTransferFallback(MsgDataTypes.TransferInfo calldata _transfer, bytes calldata _message)
        private
        returns (IMessageReceiverApp.ExecutionStatus)
    {
        uint256 gasLeftBeforeExecution = gasleft();
        (bool ok, bytes memory res) = address(_transfer.receiver).call{value: msg.value}(
            abi.encodeWithSelector(
                IMessageReceiverApp.executeMessageWithTransferFallback.selector,
                _transfer.sender,
                _transfer.token,
                _transfer.amount,
                _transfer.srcChainId,
                _message,
                msg.sender
            )
        );
        if (ok) {
            return abi.decode((res), (IMessageReceiverApp.ExecutionStatus));
        }
        handleExecutionRevert(gasLeftBeforeExecution, res);
        return IMessageReceiverApp.ExecutionStatus.Fail;
    }

    function executeMessageWithTransferRefund(MsgDataTypes.TransferInfo calldata _transfer, bytes calldata _message)
        private
        returns (IMessageReceiverApp.ExecutionStatus)
    {
        uint256 gasLeftBeforeExecution = gasleft();
        (bool ok, bytes memory res) = address(_transfer.receiver).call{value: msg.value}(
            abi.encodeWithSelector(
                IMessageReceiverApp.executeMessageWithTransferRefund.selector,
                _transfer.token,
                _transfer.amount,
                _message,
                msg.sender
            )
        );
        if (ok) {
            return abi.decode((res), (IMessageReceiverApp.ExecutionStatus));
        }
        handleExecutionRevert(gasLeftBeforeExecution, res);
        return IMessageReceiverApp.ExecutionStatus.Fail;
    }

    function verifyTransfer(MsgDataTypes.TransferInfo calldata _transfer) private view returns (bytes32) {
        bytes32 transferId;
        address bridgeAddr;
        MsgDataTypes.TransferType t = _transfer.t;
        if (t == MsgDataTypes.TransferType.LqRelay) {
            bridgeAddr = liquidityBridge;
            transferId = keccak256(
                abi.encodePacked(
                    _transfer.sender,
                    _transfer.receiver,
                    _transfer.token,
                    _transfer.amount,
                    _transfer.srcChainId,
                    uint64(block.chainid),
                    _transfer.refId
                )
            );
            require(IBridge(bridgeAddr).transfers(transferId) == true, "relay not exist");
        } else if (t == MsgDataTypes.TransferType.LqWithdraw) {
            bridgeAddr = liquidityBridge;
            transferId = keccak256(
                abi.encodePacked(
                    uint64(block.chainid),
                    _transfer.wdseq,
                    _transfer.receiver,
                    _transfer.token,
                    _transfer.amount
                )
            );
            require(IBridge(bridgeAddr).withdraws(transferId) == true, "withdraw not exist");
        } else {
            if (t == MsgDataTypes.TransferType.PegMint || t == MsgDataTypes.TransferType.PegWithdraw) {
                bridgeAddr = (t == MsgDataTypes.TransferType.PegMint) ? pegBridge : pegVault;
                transferId = keccak256(
                    abi.encodePacked(
                        _transfer.receiver,
                        _transfer.token,
                        _transfer.amount,
                        _transfer.sender,
                        _transfer.srcChainId,
                        _transfer.refId
                    )
                );
            } else {
                bridgeAddr = (t == MsgDataTypes.TransferType.PegV2Mint) ? pegBridgeV2 : pegVaultV2;
                transferId = keccak256(
                    abi.encodePacked(
                        _transfer.receiver,
                        _transfer.token,
                        _transfer.amount,
                        _transfer.sender,
                        _transfer.srcChainId,
                        _transfer.refId,
                        bridgeAddr
                    )
                );
            }
            // function is same for peg, peg2, vault, vault2
            require(IPeggedTokenBridge(bridgeAddr).records(transferId) == true, "record not exist");
        }
        require(IDelayedTransfer(bridgeAddr).delayedTransfers(transferId).timestamp == 0, "transfer delayed");
        return keccak256(abi.encodePacked(MsgDataTypes.MsgType.MessageWithTransfer, bridgeAddr, transferId));
    }

    function computeMessageOnlyId(MsgDataTypes.Route memory _route, bytes calldata _message)
        private
        view
        returns (bytes32)
    {
        bytes memory sender = _route.senderBytes;
        if (sender.length == 0) {
            sender = abi.encodePacked(_route.sender);
        }
        return
            keccak256(
                abi.encodePacked(
                    MsgDataTypes.MsgType.MessageOnly,
                    sender,
                    _route.receiver,
                    _route.srcChainId,
                    _route.srcTxHash,
                    uint64(block.chainid),
                    _message
                )
            );
    }

    function executeMessage(MsgDataTypes.Route memory _route, bytes calldata _message)
        private
        returns (IMessageReceiverApp.ExecutionStatus)
    {
        uint256 gasLeftBeforeExecution = gasleft();
        bool ok;
        bytes memory res;
        if (_route.senderBytes.length == 0) {
            (ok, res) = address(_route.receiver).call{value: msg.value}(
                abi.encodeWithSelector(
                    bytes4(keccak256(bytes("executeMessage(address,uint64,bytes,address)"))),
                    _route.sender,
                    _route.srcChainId,
                    _message,
                    msg.sender
                )
            );
        } else {
            (ok, res) = address(_route.receiver).call{value: msg.value}(
                abi.encodeWithSelector(
                    bytes4(keccak256(bytes("executeMessage(bytes,uint64,bytes,address)"))),
                    _route.senderBytes,
                    _route.srcChainId,
                    _message,
                    msg.sender
                )
            );
        }
        if (ok) {
            return abi.decode((res), (IMessageReceiverApp.ExecutionStatus));
        }
        handleExecutionRevert(gasLeftBeforeExecution, res);
        return IMessageReceiverApp.ExecutionStatus.Fail;
    }

    function handleExecutionRevert(uint256 _gasLeftBeforeExecution, bytes memory _returnData) private {
        uint256 gasLeftAfterExecution = gasleft();
        uint256 maxTargetGasLimit = block.gaslimit - preExecuteMessageGasUsage;
        if (_gasLeftBeforeExecution < maxTargetGasLimit && gasLeftAfterExecution <= _gasLeftBeforeExecution / 64) {
            // if this happens, the executor must have not provided sufficient gas limit,
            // then the tx should revert instead of recording a non-retryable failure status
            // https://github.com/wolflo/evm-opcodes/blob/main/gas.md#aa-f-gas-to-send-with-call-operations
            assembly {
                invalid()
            }
        }
        string memory revertMsg = Utils.getRevertMsg(_returnData);
        // revert the execution if the revert message has the ABORT prefix
        checkAbortPrefix(revertMsg);
        // otherwiase, emit revert message, return and mark the execution as failed (non-retryable)
        emit CallReverted(revertMsg);
    }

    function checkAbortPrefix(string memory _revertMsg) private pure {
        bytes memory prefixBytes = bytes(MsgDataTypes.ABORT_PREFIX);
        bytes memory msgBytes = bytes(_revertMsg);
        if (msgBytes.length >= prefixBytes.length) {
            for (uint256 i = 0; i < prefixBytes.length; i++) {
                if (msgBytes[i] != prefixBytes[i]) {
                    return; // prefix not match, return
                }
            }
            revert(_revertMsg); // prefix match, revert
        }
    }

    function getRouteInfo(MsgDataTypes.RouteInfo calldata _route) private pure returns (MsgDataTypes.Route memory) {
        return MsgDataTypes.Route(_route.sender, "", _route.receiver, _route.srcChainId, _route.srcTxHash);
    }

    function getRouteInfo(MsgDataTypes.RouteInfo2 calldata _route) private pure returns (MsgDataTypes.Route memory) {
        return MsgDataTypes.Route(address(0), _route.sender, _route.receiver, _route.srcChainId, _route.srcTxHash);
    }

    // ================= helper functions =====================

    /**
     * @notice combine bridge transfer and msg execution calls into a single tx
     * @dev caller needs to get the required input params from SGN
     * @param _tp params to call bridge transfer
     * @param _mp params to execute message
     */
    function transferAndExecuteMsg(
        MsgDataTypes.BridgeTransferParams calldata _tp,
        MsgDataTypes.MsgWithTransferExecutionParams calldata _mp
    ) external {
        _bridgeTransfer(_mp.transfer.t, _tp);
        executeMessageWithTransfer(_mp.message, _mp.transfer, _mp.sigs, _mp.signers, _mp.powers);
    }

    /**
     * @notice combine bridge refund and msg execution calls into a single tx
     * @dev caller needs to get the required input params from SGN
     * @param _tp params to call bridge transfer for refund
     * @param _mp params to execute message for refund
     */
    function refundAndExecuteMsg(
        MsgDataTypes.BridgeTransferParams calldata _tp,
        MsgDataTypes.MsgWithTransferExecutionParams calldata _mp
    ) external {
        _bridgeTransfer(_mp.transfer.t, _tp);
        executeMessageWithTransferRefund(_mp.message, _mp.transfer, _mp.sigs, _mp.signers, _mp.powers);
    }

    function _bridgeTransfer(MsgDataTypes.TransferType t, MsgDataTypes.BridgeTransferParams calldata _params) private {
        if (t == MsgDataTypes.TransferType.LqRelay) {
            IBridge(liquidityBridge).relay(_params.request, _params.sigs, _params.signers, _params.powers);
        } else if (t == MsgDataTypes.TransferType.LqWithdraw) {
            IBridge(liquidityBridge).withdraw(_params.request, _params.sigs, _params.signers, _params.powers);
        } else if (t == MsgDataTypes.TransferType.PegMint) {
            IPeggedTokenBridge(pegBridge).mint(_params.request, _params.sigs, _params.signers, _params.powers);
        } else if (t == MsgDataTypes.TransferType.PegV2Mint) {
            IPeggedTokenBridgeV2(pegBridgeV2).mint(_params.request, _params.sigs, _params.signers, _params.powers);
        } else if (t == MsgDataTypes.TransferType.PegWithdraw) {
            IOriginalTokenVault(pegVault).withdraw(_params.request, _params.sigs, _params.signers, _params.powers);
        } else if (t == MsgDataTypes.TransferType.PegV2Withdraw) {
            IOriginalTokenVaultV2(pegVaultV2).withdraw(_params.request, _params.sigs, _params.signers, _params.powers);
        }
    }

    // ================= contract config =================

    function setLiquidityBridge(address _addr) public onlyOwner {
        require(_addr != address(0), "invalid address");
        liquidityBridge = _addr;
        emit LiquidityBridgeUpdated(liquidityBridge);
    }

    function setPegBridge(address _addr) public onlyOwner {
        require(_addr != address(0), "invalid address");
        pegBridge = _addr;
        emit PegBridgeUpdated(pegBridge);
    }

    function setPegVault(address _addr) public onlyOwner {
        require(_addr != address(0), "invalid address");
        pegVault = _addr;
        emit PegVaultUpdated(pegVault);
    }

    function setPegBridgeV2(address _addr) public onlyOwner {
        require(_addr != address(0), "invalid address");
        pegBridgeV2 = _addr;
        emit PegBridgeV2Updated(pegBridgeV2);
    }

    function setPegVaultV2(address _addr) public onlyOwner {
        require(_addr != address(0), "invalid address");
        pegVaultV2 = _addr;
        emit PegVaultV2Updated(pegVaultV2);
    }

    function setPreExecuteMessageGasUsage(uint256 _usage) public onlyOwner {
        preExecuteMessageGasUsage = _usage;
    }
}

File 31 of 36 : MessageBusSender.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.17;

import "../../safeguard/Ownable.sol";
import "../../interfaces/ISigsVerifier.sol";

contract MessageBusSender is Ownable {
    ISigsVerifier public immutable sigsVerifier;

    uint256 public feeBase;
    uint256 public feePerByte;
    mapping(address => uint256) public withdrawnFees;

    event Message(address indexed sender, address receiver, uint256 dstChainId, bytes message, uint256 fee);
    // message to non-evm chain with >20 bytes addr
    event Message2(address indexed sender, bytes receiver, uint256 dstChainId, bytes message, uint256 fee);

    event MessageWithTransfer(
        address indexed sender,
        address receiver,
        uint256 dstChainId,
        address bridge,
        bytes32 srcTransferId,
        bytes message,
        uint256 fee
    );

    event FeeWithdrawn(address receiver, uint256 amount);

    event FeeBaseUpdated(uint256 feeBase);
    event FeePerByteUpdated(uint256 feePerByte);

    constructor(ISigsVerifier _sigsVerifier) {
        sigsVerifier = _sigsVerifier;
    }

    /**
     * @notice Sends a message to a contract on another chain.
     * Sender needs to make sure the uniqueness of the message Id, which is computed as
     * hash(type.MessageOnly, sender, receiver, srcChainId, srcTxHash, dstChainId, message).
     * If messages with the same Id are sent, only one of them will succeed at dst chain.
     * A fee is charged in the native gas token.
     * @param _receiver The address of the destination app contract.
     * @param _dstChainId The destination chain ID.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     */
    function sendMessage(
        address _receiver,
        uint256 _dstChainId,
        bytes calldata _message
    ) external payable {
        _sendMessage(_dstChainId, _message);
        emit Message(msg.sender, _receiver, _dstChainId, _message, msg.value);
    }

    // Send message to non-evm chain with bytes for receiver address,
    // otherwise same as above.
    function sendMessage(
        bytes calldata _receiver,
        uint256 _dstChainId,
        bytes calldata _message
    ) external payable {
        _sendMessage(_dstChainId, _message);
        emit Message2(msg.sender, _receiver, _dstChainId, _message, msg.value);
    }

    function _sendMessage(uint256 _dstChainId, bytes calldata _message) private {
        require(_dstChainId != block.chainid, "Invalid chainId");
        uint256 minFee = calcFee(_message);
        require(msg.value >= minFee, "Insufficient fee");
    }

    /**
     * @notice Sends a message associated with a transfer to a contract on another chain.
     * If messages with the same srcTransferId are sent, only one of them will succeed.
     * A fee is charged in the native token.
     * @param _receiver The address of the destination app contract.
     * @param _dstChainId The destination chain ID.
     * @param _srcBridge The bridge contract to send the transfer with.
     * @param _srcTransferId The transfer ID.
     * @param _dstChainId The destination chain ID.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     */
    function sendMessageWithTransfer(
        address _receiver,
        uint256 _dstChainId,
        address _srcBridge,
        bytes32 _srcTransferId,
        bytes calldata _message
    ) external payable {
        require(_dstChainId != block.chainid, "Invalid chainId");
        uint256 minFee = calcFee(_message);
        require(msg.value >= minFee, "Insufficient fee");
        // SGN needs to verify
        // 1. msg.sender matches sender of the src transfer
        // 2. dstChainId matches dstChainId of the src transfer
        // 3. bridge is either liquidity bridge, peg src vault, or peg dst bridge
        emit MessageWithTransfer(msg.sender, _receiver, _dstChainId, _srcBridge, _srcTransferId, _message, msg.value);
    }

    /**
     * @notice Withdraws message fee in the form of native gas token.
     * @param _account The address receiving the fee.
     * @param _cumulativeFee The cumulative fee credited to the account. Tracked by SGN.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A withdrawal must be
     * signed-off by +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function withdrawFee(
        address _account,
        uint256 _cumulativeFee,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "withdrawFee"));
        sigsVerifier.verifySigs(abi.encodePacked(domain, _account, _cumulativeFee), _sigs, _signers, _powers);
        uint256 amount = _cumulativeFee - withdrawnFees[_account];
        require(amount > 0, "No new amount to withdraw");
        withdrawnFees[_account] = _cumulativeFee;
        (bool sent, ) = _account.call{value: amount, gas: 50000}("");
        require(sent, "failed to withdraw fee");
        emit FeeWithdrawn(_account, amount);
    }

    /**
     * @notice Calculates the required fee for the message.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     @ @return The required fee.
     */
    function calcFee(bytes calldata _message) public view returns (uint256) {
        return feeBase + _message.length * feePerByte;
    }

    // -------------------- Admin --------------------

    function setFeePerByte(uint256 _fee) external onlyOwner {
        feePerByte = _fee;
        emit FeePerByteUpdated(feePerByte);
    }

    function setFeeBase(uint256 _fee) external onlyOwner {
        feeBase = _fee;
        emit FeeBaseUpdated(feeBase);
    }
}

File 32 of 36 : Ownable.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity ^0.8.0;

/**
 * @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.
 *
 * This adds a normal func that setOwner if _owner is address(0). So we can't allow
 * renounceOwnership. So we can support Proxy based upgradable contract
 */
abstract contract Ownable {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _setOwner(msg.sender);
    }

    /**
     * @dev Only to be called by inherit contracts, in their init func called by Proxy
     * we require _owner == address(0), which is only possible when it's a delegateCall
     * because constructor sets _owner in contract state.
     */
    function initOwner() internal {
        require(_owner == address(0), "owner already set");
        _setOwner(msg.sender);
    }

    /**
     * @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() == msg.sender, "Ownable: caller is not the owner");
        _;
    }

    /**
     * @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");
        _setOwner(newOwner);
    }

    function _setOwner(address newOwner) private {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

File 33 of 36 : IMultichainEndpoint.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

interface IMultichainEndpoint {
    enum CallbackExecutionStatus {
        Success,
        Failed,
        Retry
    }

    function executeMessageWithTransfer(
        address _token,
        uint256 _amount,
        uint64 srcChainId,
        bytes memory _message
    ) external payable returns (CallbackExecutionStatus);

    function executeMessageWithTransferFallback(
        address _token,
        uint256 _amount,
        bytes calldata _message
    ) external payable returns (CallbackExecutionStatus);
}

File 34 of 36 : ILuminexRouterV1.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

interface ILuminexRouterV1 {
    function factory() external view returns (address);
    function WROSE() external view returns (address);

    function precalculateAmounts(
        address tokenA,
        address tokenB,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin
    ) external view returns (uint amountA, uint amountB);

    function addLiquidity(
        address tokenA,
        address tokenB,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB, uint liquidity);
    function addLiquidityROSE(
        address token,
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountROSEMin,
        address to,
        uint deadline
    ) external payable returns (uint amountToken, uint amountROSE, uint liquidity);
    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityROSE(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountROSEMin,
        address to,
        uint deadline
    ) external returns (uint amountToken, uint amountROSE);
    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapTokensForExactTokens(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapExactROSEForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);
    function swapTokensForExactROSE(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapExactTokensForROSE(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapROSEForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);

    function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
    function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
    function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);

    function removeLiquidityROSESupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountROSEMin,
        address to,
        uint deadline
    ) external returns (uint amountROSE);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
    function swapExactROSEForTokensSupportingFeeOnTransferTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable;
    function swapExactTokensForROSESupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
}

File 35 of 36 : IWROSE.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

interface IWROSE {
    function deposit() external payable;
    function transfer(address to, uint value) external returns (bool);
    function withdraw(uint) external;
}

File 36 of 36 : FeesCollector.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import "../illuminex/op/celer/safeguard/Ownable.sol";

contract FeesCollector is Ownable {
    uint256 private _feesCollected;

    event FeesCollected(address indexed to, uint256 amount);
    event FeesDeposited(uint256 amount);

    function collectFees(address payable to, uint256 amount) public onlyOwner {
        require(amount <= _feesCollected, "Insufficient fees collected");

        _feesCollected -= amount;
        to.transfer(amount);

        emit FeesCollected(to, amount);
    }

    function _depositFees(uint256 amount) internal {
        _feesCollected += amount;
        emit FeesDeposited(amount);
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 300
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"address payable","name":"_vaultApp","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newManager","type":"address"},{"indexed":false,"internalType":"address","name":"oldManager","type":"address"}],"name":"ChangeComplianceManager","type":"event"},{"anonymous":false,"inputs":[{"components":[{"internalType":"uint64","name":"chainId","type":"uint64"},{"components":[{"internalType":"uint256","name":"settlementCost","type":"uint256"},{"internalType":"uint256","name":"settlementCostInLocalCurrency","type":"uint256"}],"internalType":"struct MultichainEndpoint.EndpointFee","name":"fee","type":"tuple"}],"indexed":false,"internalType":"struct MultichainEndpoint.SetEndpointFee[]","name":"feeData","type":"tuple[]"}],"name":"FeeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"FeesCollected","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"FeesDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"hashedEventKey","type":"bytes32"},{"indexed":false,"internalType":"bool","name":"hasFailed","type":"bool"}],"name":"MessageReceived","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"hashedEventKey","type":"bytes32"}],"name":"MultichainMessageSent","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"components":[{"internalType":"address","name":"addr","type":"address"},{"internalType":"bool","name":"isOfacListed","type":"bool"}],"indexed":false,"internalType":"struct MultichainEndpoint.OFACEntry[]","name":"list","type":"tuple[]"}],"name":"UpdateOFACList","type":"event"},{"inputs":[],"name":"SAPPHIRE_CHAINID","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"_failedMessages","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"chainIdByEndpointAddress","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address payable","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"collectFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"complianceManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint64","name":"","type":"uint64"}],"name":"connectedEndpoints","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint64","name":"","type":"uint64"}],"name":"endpointsDestinationFees","outputs":[{"internalType":"uint256","name":"settlementCost","type":"uint256"},{"internalType":"uint256","name":"settlementCostInLocalCurrency","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint64","name":"srcChainId","type":"uint64"},{"internalType":"bytes","name":"_message","type":"bytes"}],"name":"executeMessageWithTransfer","outputs":[{"internalType":"enum IMultichainEndpoint.CallbackExecutionStatus","name":"","type":"uint8"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"bytes","name":"_message","type":"bytes"}],"name":"executeMessageWithTransferFallback","outputs":[{"internalType":"enum IMultichainEndpoint.CallbackExecutionStatus","name":"","type":"uint8"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"feeSetter","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"messageBus","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nativeWrapper","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"ofacBlocklist","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"encodedParams","type":"bytes"}],"name":"proxyPass","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"newManager","type":"address"}],"name":"setComplianceManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint64","name":"chainId","type":"uint64"},{"internalType":"address","name":"contractAddress","type":"address"}],"internalType":"struct MultichainEndpoint.ConnectEndpointParams[]","name":"_endpoints","type":"tuple[]"}],"name":"setConnectedEndpoints","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_feeSetter","type":"address"}],"name":"setFeeSetter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint64","name":"chainId","type":"uint64"},{"components":[{"internalType":"uint256","name":"settlementCost","type":"uint256"},{"internalType":"uint256","name":"settlementCostInLocalCurrency","type":"uint256"}],"internalType":"struct MultichainEndpoint.EndpointFee","name":"fee","type":"tuple"}],"internalType":"struct MultichainEndpoint.SetEndpointFee[]","name":"feeData","type":"tuple[]"}],"name":"setFixedFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_wrapper","type":"address"}],"name":"setNativeWrapper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"enum MultichainEndpoint.MessageStoreType","name":"","type":"uint8"},{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"settledMessages","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"addr","type":"address"},{"internalType":"bool","name":"isOfacListed","type":"bool"}],"internalType":"struct MultichainEndpoint.OFACEntry[]","name":"list","type":"tuple[]"}],"name":"updateOFACList","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"vaultApp","outputs":[{"internalType":"contract CrossChainVaultApp","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]

60c06040523480156200001157600080fd5b50604051620027923803806200279283398101604081905262000034916200014e565b6200003f33620000e5565b6001600160a01b0381166080819052604080516350d113fd60e11b8152905163a1a227fa916004808201926020929091908290030181865afa1580156200008a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620000b091906200014e565b6001600160a01b031660a0525060038054336001600160a01b03199182168117909255600c8054909116909117905562000175565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6001600160a01b03811681146200014b57600080fd5b50565b6000602082840312156200016157600080fd5b81516200016e8162000135565b9392505050565b60805160a0516125d4620001be6000396000818161035701526115f001526000818161038b015281816105ff01528181610ba90152818161176901526117d601526125d46000f3fe60806040526004361061018f5760003560e01c8063a576b5da116100d6578063e211ed5e1161007f578063fa88bb4c11610059578063fa88bb4c146104f9578063fae86d3814610534578063ff7bce231461055457600080fd5b8063e211ed5e14610496578063e25c58cc146104a9578063f2fde38b146104d957600080fd5b8063bc886f65116100b0578063bc886f651461042d578063c9f808b614610440578063d0dbf80a1461046057600080fd5b8063a576b5da146103ad578063b100a46d146103cd578063b19805af1461040d57600080fd5b80638da5cb5b11610138578063a033fcd411610112578063a033fcd414610325578063a1a227fa14610345578063a1cab6a01461037957600080fd5b80638da5cb5b1461029e5780638dfab61a146102bc57806392a8e5e6146102dc57600080fd5b8063573fe09611610169578063573fe096146102305780637c5141fb1461025e57806387cf3ef41461027e57600080fd5b80630b48a8b81461019b578063211016b7146101d85780634578a439146101fa57600080fd5b3661019657005b600080fd5b3480156101a757600080fd5b506002546101bb906001600160a01b031681565b6040516001600160a01b0390911681526020015b60405180910390f35b3480156101e457600080fd5b506101f86101f3366004611c71565b610574565b005b34801561020657600080fd5b506101bb610215366004611cb1565b6004602052600090815260409020546001600160a01b031681565b34801561023c57600080fd5b50610246615afe81565b6040516001600160401b0390911681526020016101cf565b61027161026c366004611db7565b6105f2565b6040516101cf9190611e36565b34801561028a57600080fd5b506003546101bb906001600160a01b031681565b3480156102aa57600080fd5b506000546001600160a01b03166101bb565b3480156102c857600080fd5b506101f86102d7366004611e5e565b610816565b3480156102e857600080fd5b506103106102f7366004611cb1565b600d602052600090815260409020805460019091015482565b604080519283526020830191909152016101cf565b34801561033157600080fd5b506101f8610340366004611ed2565b610927565b34801561035157600080fd5b506101bb7f000000000000000000000000000000000000000000000000000000000000000081565b34801561038557600080fd5b506101bb7f000000000000000000000000000000000000000000000000000000000000000081565b3480156103b957600080fd5b506101f86103c8366004611c71565b610a65565b3480156103d957600080fd5b506103fd6103e8366004611c71565b60076020526000908152604090205460ff1681565b60405190151581526020016101cf565b34801561041957600080fd5b506101f8610428366004611c71565b610b23565b61027161043b366004611efe565b610b9c565b34801561044c57600080fd5b506101f861045b366004611fb7565b610d70565b34801561046c57600080fd5b5061024661047b366004611c71565b6005602052600090815260409020546001600160401b031681565b6101f86104a4366004612074565b610e94565b3480156104b557600080fd5b506103fd6104c43660046120cc565b60096020526000908152604090205460ff1681565b3480156104e557600080fd5b506101f86104f4366004611c71565b611043565b34801561050557600080fd5b506103fd6105143660046120e5565b600660209081526000928352604080842090915290825290205460ff1681565b34801561054057600080fd5b506101f861054f366004612107565b61110b565b34801561056057600080fd5b50600c546101bb906001600160a01b031681565b336105876000546001600160a01b031690565b6001600160a01b0316146105d05760405162461bcd60e51b8152602060048201819052602482015260008051602061257f83398151915260448201526064015b60405180910390fd5b600280546001600160a01b0319166001600160a01b0392909216919091179055565b6000336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146106655760405162461bcd60e51b81526020600482015260166024820152750556e617574686f72697a6564207661756c74206170760541b60448201526064016105c7565b815160208084019190912060009081526008909152604090205460ff16156106cf5760405162461bcd60e51b815260206004820152601960248201527f43616c6c6261636b20616c72656164792065786563757465640000000000000060448201526064016105c7565b81516000908190849082906106ed908301602090810190840161222b565b509050600081806020019051810190610706919061228e565b905060008160ff16600181111561071f5761071f611e20565b88516020808b01919091206000908152600882526040808220805460ff191660011790558751888401208252600b90925290812080546001600160a01b038a166001600160a01b031990911617905590915081600181111561078357610783611e20565b036107dd576001600160401b0389166000908152600d6020526040902080546001909101546107d09186918d918f916107bc908b6122c7565b6107c691906122e4565b6000949350505050565b965050505050505061080e565b60018160018111156107f1576107f1611e20565b03610803576107d0848c8c6000611319565b600196505050505050505b949350505050565b6003546001600160a01b0316331461085e5760405162461bcd60e51b815260206004820152600b60248201526a139bdd08185b1b1bddd95960aa1b60448201526064016105c7565b60005b818110156108e95782828281811061087b5761087b612306565b905060600201602001600d600085858581811061089a5761089a612306565b6108b09260206060909202019081019150611cb1565b6001600160401b0316815260208082019290925260400160002082358155910135600190910155806108e18161231c565b915050610861565b507fe0583791041146b94f96ed3ebb01c8d616626aa2572f026d3be192180f3613e8828260405161091b929190612335565b60405180910390a15050565b3361093a6000546001600160a01b031690565b6001600160a01b03161461097e5760405162461bcd60e51b8152602060048201819052602482015260008051602061257f83398151915260448201526064016105c7565b6001548111156109d05760405162461bcd60e51b815260206004820152601b60248201527f496e73756666696369656e74206665657320636f6c6c6563746564000000000060448201526064016105c7565b80600160008282546109e29190612396565b90915550506040516001600160a01b0383169082156108fc029083906000818181858888f19350505050158015610a1d573d6000803e3d6000fd5b50816001600160a01b03167f9dc46f23cfb5ddcad0ae7ea2be38d47fec07bb9382ec7e564efc69e036dd66ce82604051610a5991815260200190565b60405180910390a25050565b600c546001600160a01b03163314610aba5760405162461bcd60e51b81526020600482015260186024820152772737ba10309031b7b6b83634b0b731b29036b0b730b3b2b960411b60448201526064016105c7565b600c54604080516001600160a01b03808516825290921660208301527f4af7e8d23c32ea7e07d618391c5b0b002c54cbb836ac109b440aa7a223561a1c910160405180910390a1600c80546001600160a01b0319166001600160a01b0392909216919091179055565b33610b366000546001600160a01b031690565b6001600160a01b031614610b7a5760405162461bcd60e51b8152602060048201819052602482015260008051602061257f83398151915260448201526064016105c7565b600380546001600160a01b0319166001600160a01b0392909216919091179055565b6000336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614610c0f5760405162461bcd60e51b81526020600482015260166024820152750556e617574686f72697a6564207661756c74206170760541b60448201526064016105c7565b600860008484604051610c239291906123a9565b604080519182900390912082526020820192909252016000205460ff1615610c8d5760405162461bcd60e51b815260206004820152601960248201527f43616c6c6261636b20616c72656164792065786563757465640000000000000060448201526064016105c7565b6000610cce84848080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061131192505050565b50509050610cdd8187876113db565b6001600860008686604051610cf39291906123a9565b6040518091039020815260200190815260200160002060006101000a81548160ff0219169083151502179055506001600960008686604051610d369291906123a9565b6040518091039020815260200190815260200160002060006101000a81548160ff0219169083151502179055506000915050949350505050565b600c546001600160a01b03163314610dc55760405162461bcd60e51b81526020600482015260186024820152772737ba10309031b7b6b83634b0b731b29036b0b730b3b2b960411b60448201526064016105c7565b615afd194601610dd457600080fd5b7f0edda34aed4c9b3a2fa7acd49cc8fa9ae5688d5061c30c6a57e8934f06146d6281604051610e0391906123b9565b60405180910390a160005b8151811015610e9057818181518110610e2957610e29612306565b60200260200101516020015160076000848481518110610e4b57610e4b612306565b602090810291909101810151516001600160a01b03168252810191909152604001600020805460ff191691151591909117905580610e888161231c565b915050610e0e565b5050565b3360009081526007602052604090205460ff1615610ee65760405162461bcd60e51b815260206004820152600f60248201526e13d19050c81c1c9bda1a589a5d1959608a1b60448201526064016105c7565b60025434906001600160a01b0390811690851603610fca5782341015610f4e5760405162461bcd60e51b815260206004820152601a60248201527f496e73756666696369656e74206e617469766520616d6f756e7400000000000060448201526064016105c7565b600260009054906101000a90046001600160a01b03166001600160a01b031663d0e30db0846040518263ffffffff1660e01b81526004016000604051808303818588803b158015610f9e57600080fd5b505af1158015610fb2573d6000803e3d6000fd5b50505050508281610fc39190612396565b9050610fdf565b610fdf6001600160a01b03851633308661149a565b615afd1946016110315760405162461bcd60e51b815260206004820152601e60248201527f43616e27742070726f787920706173732066726f6d205361707068697265000060448201526064016105c7565b61103d84848484611505565b50505050565b336110566000546001600160a01b031690565b6001600160a01b03161461109a5760405162461bcd60e51b8152602060048201819052602482015260008051602061257f83398151915260448201526064016105c7565b6001600160a01b0381166110ff5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b60648201526084016105c7565b611108816118ea565b50565b3361111e6000546001600160a01b031690565b6001600160a01b0316146111625760405162461bcd60e51b8152602060048201819052602482015260008051602061257f83398151915260448201526064016105c7565b60005b8151811015610e90574682828151811061118157611181612306565b6020026020010151600001516001600160401b0316036111f65760405162461bcd60e51b815260206004820152602a60248201527f43616e27742061646420616e20656e64706f696e7420746f20746865206375726044820152693932b73a1031b430b4b760b11b60648201526084016105c7565b81818151811061120857611208612306565b6020026020010151602001516004600084848151811061122a5761122a612306565b6020026020010151600001516001600160401b03166001600160401b0316815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b0316021790555081818151811061128c5761128c612306565b602002602001015160000151600560008484815181106112ae576112ae612306565b6020026020010151602001516001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a8154816001600160401b0302191690836001600160401b0316021790555080806113099061231c565b915050611165565b600091829190565b60008085806020019051810190611330919061222b565b9150506000808280602001905181019061134a9190612413565b91509150817fb1e855b7d4b49a91d1087196705073db569ebba9cff1cc0903fc4778e05a2fb086604051611382911515815260200190565b60405180910390a260008281527f54cdd369e4e8a8515e52ca72ec816c2101831ad1f18bf44102ed171459c9b4f860205260409020805460ff191660011790556113cd8188886113db565b506000979650505050505050565b6002546001600160a01b039081169083160361148157604051632e1a7d4d60e01b8152600481018290526001600160a01b03831690632e1a7d4d90602401600060405180830381600087803b15801561143357600080fd5b505af1158015611447573d6000803e3d6000fd5b50506040516001600160a01b038616925083156108fc02915083906000818181858888f1935050505015801561103d573d6000803e3d6000fd5b6114956001600160a01b038316848361193a565b505050565b6040516001600160a01b038085166024830152831660448201526064810182905261103d9085906323b872dd60e01b906084015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915261196a565b615afe60005260046020527fb4179405bfb78576241f1105fffdb36eac5eddd96ced8fdbce44e3bf94593698546001600160a01b0316806115985760405162461bcd60e51b815260206004820152602760248201527f536170706869726520656e64706f696e74206973206e6f742079657420636f6e604482015266199a59dd5c995960ca1b60648201526084016105c7565b60003383856040516020016115af9392919061246f565b60408051601f1981840301815282825260006020840181905291830182905260608301829052925090608001604051602081830303815290604052905060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635335dca283856040516020016116309291906124a0565b6040516020818303038152906040526040518263ffffffff1660e01b815260040161165b91906124c5565b602060405180830381865afa158015611678573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061169c91906124d8565b615afe600052600d6020527f7b72ab06470fed590ac056fa5b73c58a808bcf54f867dd173a32299af6c06339549091506116d690826124f1565b8510156117185760405162461bcd60e51b815260206004820152601060248201526f56616c756520697320746f6f206c6f7760801b60448201526064016105c7565b336117238287612396565b876040516020016117369392919061246f565b60408051601f19818403018152919052925061175a6117558287612396565b611a3f565b61178e6001600160a01b0389167f000000000000000000000000000000000000000000000000000000000000000089611a8c565b615afe6000819052600460208190527fb4179405bfb78576241f1105fffdb36eac5eddd96ced8fdbce44e3bf945936985460405163aaf477d160e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081169463aaf477d1948794611813949316928f918f918c9101612504565b6000604051808303818588803b15801561182c57600080fd5b505af1158015611840573d6000803e3d6000fd5b505085516020808801919091206000908152600a8252604080822080546001600160a01b031916331790556001808352600684528c518d850190812084527f3e5fec24aa4dc4e5aee2e025e51e1392c72a2500577559fae9665c6d52bd6a31909452818320805460ff191690911790558b5190922091519194507f82812468bd5a285f6132f6f5e6d8f7cd1082f95dcddcfd6f93ab52e7ecde84b093509150a25050505050505050565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6040516001600160a01b03831660248201526044810182905261149590849063a9059cbb60e01b906064016114ce565b60006119bf826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316611b399092919063ffffffff16565b90508051600014806119e05750808060200190518101906119e09190612545565b6114955760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016105c7565b8060016000828254611a5191906124f1565b90915550506040518181527f02bede6503f7c3293d6eac9b0f4981900471e18774a84ccc98715aa5433017949060200160405180910390a150565b604051636eb1769f60e11b81523060048201526001600160a01b0383811660248301526000919085169063dd62ed3e90604401602060405180830381865afa158015611adc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b0091906124d8565b905061103d8463095ea7b360e01b85611b1986866124f1565b6040516001600160a01b03909216602483015260448201526064016114ce565b606061080e848460008585600080866001600160a01b03168587604051611b609190612562565b60006040518083038185875af1925050503d8060008114611b9d576040519150601f19603f3d011682016040523d82523d6000602084013e611ba2565b606091505b5091509150611bb387838387611bbe565b979650505050505050565b60608315611c2d578251600003611c26576001600160a01b0385163b611c265760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016105c7565b508161080e565b61080e8383815115611c425781518083602001fd5b8060405162461bcd60e51b81526004016105c791906124c5565b6001600160a01b038116811461110857600080fd5b600060208284031215611c8357600080fd5b8135611c8e81611c5c565b9392505050565b80356001600160401b0381168114611cac57600080fd5b919050565b600060208284031215611cc357600080fd5b611c8e82611c95565b634e487b7160e01b600052604160045260246000fd5b604080519081016001600160401b0381118282101715611d0457611d04611ccc565b60405290565b604051601f8201601f191681016001600160401b0381118282101715611d3257611d32611ccc565b604052919050565b60006001600160401b03821115611d5357611d53611ccc565b50601f01601f191660200190565b600082601f830112611d7257600080fd5b8135611d85611d8082611d3a565b611d0a565b818152846020838601011115611d9a57600080fd5b816020850160208301376000918101602001919091529392505050565b60008060008060808587031215611dcd57600080fd5b8435611dd881611c5c565b935060208501359250611ded60408601611c95565b915060608501356001600160401b03811115611e0857600080fd5b611e1487828801611d61565b91505092959194509250565b634e487b7160e01b600052602160045260246000fd5b6020810160038310611e5857634e487b7160e01b600052602160045260246000fd5b91905290565b60008060208385031215611e7157600080fd5b82356001600160401b0380821115611e8857600080fd5b818501915085601f830112611e9c57600080fd5b813581811115611eab57600080fd5b866020606083028501011115611ec057600080fd5b60209290920196919550909350505050565b60008060408385031215611ee557600080fd5b8235611ef081611c5c565b946020939093013593505050565b60008060008060608587031215611f1457600080fd5b8435611f1f81611c5c565b93506020850135925060408501356001600160401b0380821115611f4257600080fd5b818701915087601f830112611f5657600080fd5b813581811115611f6557600080fd5b886020828501011115611f7757600080fd5b95989497505060200194505050565b60006001600160401b03821115611f9f57611f9f611ccc565b5060051b60200190565b801515811461110857600080fd5b60006020808385031215611fca57600080fd5b82356001600160401b03811115611fe057600080fd5b8301601f81018513611ff157600080fd5b8035611fff611d8082611f86565b81815260069190911b8201830190838101908783111561201e57600080fd5b928401925b82841015611bb3576040848903121561203c5760008081fd5b612044611ce2565b843561204f81611c5c565b81528486013561205e81611fa9565b8187015282526040939093019290840190612023565b60008060006060848603121561208957600080fd5b833561209481611c5c565b92506020840135915060408401356001600160401b038111156120b657600080fd5b6120c286828701611d61565b9150509250925092565b6000602082840312156120de57600080fd5b5035919050565b600080604083850312156120f857600080fd5b823560038110611ef057600080fd5b6000602080838503121561211a57600080fd5b82356001600160401b0381111561213057600080fd5b8301601f8101851361214157600080fd5b803561214f611d8082611f86565b81815260069190911b8201830190838101908783111561216e57600080fd5b928401925b82841015611bb3576040848903121561218c5760008081fd5b612194611ce2565b61219d85611c95565b8152858501356121ac81611c5c565b8187015282526040939093019290840190612173565b60005b838110156121dd5781810151838201526020016121c5565b50506000910152565b600082601f8301126121f757600080fd5b8151612205611d8082611d3a565b81815284602083860101111561221a57600080fd5b61080e8260208301602087016121c2565b6000806040838503121561223e57600080fd5b82516001600160401b038082111561225557600080fd5b612261868387016121e6565b9350602085015191508082111561227757600080fd5b50612284858286016121e6565b9150509250929050565b6000602082840312156122a057600080fd5b815160ff81168114611c8e57600080fd5b634e487b7160e01b600052601160045260246000fd5b80820281158282048414176122de576122de6122b1565b92915050565b60008261230157634e487b7160e01b600052601260045260246000fd5b500490565b634e487b7160e01b600052603260045260246000fd5b60006001820161232e5761232e6122b1565b5060010190565b6020808252818101839052600090604080840186845b87811015612389576001600160401b0361236483611c95565b168352818501358584015283820135848401526060928301929091019060010161234b565b5090979650505050505050565b818103818111156122de576122de6122b1565b8183823760009101908152919050565b602080825282518282018190526000919060409081850190868401855b8281101561240657815180516001600160a01b0316855286015115158685015292840192908501906001016123d6565b5091979650505050505050565b6000806040838503121561242657600080fd5b82519150602083015161243881611c5c565b809150509250929050565b6000815180845261245b8160208601602086016121c2565b601f01601f19169290920160200192915050565b6001600160a01b03841681528260208201526060604082015260006124976060830184612443565b95945050505050565b6040815260006124b36040830185612443565b82810360208401526124978185612443565b602081526000611c8e6020830184612443565b6000602082840312156124ea57600080fd5b5051919050565b808201808211156122de576122de6122b1565b60006001600160a01b0380881683526001600160401b038716602084015280861660408401525083606083015260a06080830152611bb360a0830184612443565b60006020828403121561255757600080fd5b8151611c8e81611fa9565b600082516125748184602087016121c2565b919091019291505056fe4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572a264697066735822122065e984bf036ce83c43fb8f241868a2c36d252979cdff327c90d22377e7011a3a64736f6c634300081100330000000000000000000000007c71a87b3e4d5f02281815c137de90baa44cd0c6

Deployed Bytecode

0x60806040526004361061018f5760003560e01c8063a576b5da116100d6578063e211ed5e1161007f578063fa88bb4c11610059578063fa88bb4c146104f9578063fae86d3814610534578063ff7bce231461055457600080fd5b8063e211ed5e14610496578063e25c58cc146104a9578063f2fde38b146104d957600080fd5b8063bc886f65116100b0578063bc886f651461042d578063c9f808b614610440578063d0dbf80a1461046057600080fd5b8063a576b5da146103ad578063b100a46d146103cd578063b19805af1461040d57600080fd5b80638da5cb5b11610138578063a033fcd411610112578063a033fcd414610325578063a1a227fa14610345578063a1cab6a01461037957600080fd5b80638da5cb5b1461029e5780638dfab61a146102bc57806392a8e5e6146102dc57600080fd5b8063573fe09611610169578063573fe096146102305780637c5141fb1461025e57806387cf3ef41461027e57600080fd5b80630b48a8b81461019b578063211016b7146101d85780634578a439146101fa57600080fd5b3661019657005b600080fd5b3480156101a757600080fd5b506002546101bb906001600160a01b031681565b6040516001600160a01b0390911681526020015b60405180910390f35b3480156101e457600080fd5b506101f86101f3366004611c71565b610574565b005b34801561020657600080fd5b506101bb610215366004611cb1565b6004602052600090815260409020546001600160a01b031681565b34801561023c57600080fd5b50610246615afe81565b6040516001600160401b0390911681526020016101cf565b61027161026c366004611db7565b6105f2565b6040516101cf9190611e36565b34801561028a57600080fd5b506003546101bb906001600160a01b031681565b3480156102aa57600080fd5b506000546001600160a01b03166101bb565b3480156102c857600080fd5b506101f86102d7366004611e5e565b610816565b3480156102e857600080fd5b506103106102f7366004611cb1565b600d602052600090815260409020805460019091015482565b604080519283526020830191909152016101cf565b34801561033157600080fd5b506101f8610340366004611ed2565b610927565b34801561035157600080fd5b506101bb7f0000000000000000000000004066d196a423b2b3b8b054f4f40efb47a74e200c81565b34801561038557600080fd5b506101bb7f0000000000000000000000007c71a87b3e4d5f02281815c137de90baa44cd0c681565b3480156103b957600080fd5b506101f86103c8366004611c71565b610a65565b3480156103d957600080fd5b506103fd6103e8366004611c71565b60076020526000908152604090205460ff1681565b60405190151581526020016101cf565b34801561041957600080fd5b506101f8610428366004611c71565b610b23565b61027161043b366004611efe565b610b9c565b34801561044c57600080fd5b506101f861045b366004611fb7565b610d70565b34801561046c57600080fd5b5061024661047b366004611c71565b6005602052600090815260409020546001600160401b031681565b6101f86104a4366004612074565b610e94565b3480156104b557600080fd5b506103fd6104c43660046120cc565b60096020526000908152604090205460ff1681565b3480156104e557600080fd5b506101f86104f4366004611c71565b611043565b34801561050557600080fd5b506103fd6105143660046120e5565b600660209081526000928352604080842090915290825290205460ff1681565b34801561054057600080fd5b506101f861054f366004612107565b61110b565b34801561056057600080fd5b50600c546101bb906001600160a01b031681565b336105876000546001600160a01b031690565b6001600160a01b0316146105d05760405162461bcd60e51b8152602060048201819052602482015260008051602061257f83398151915260448201526064015b60405180910390fd5b600280546001600160a01b0319166001600160a01b0392909216919091179055565b6000336001600160a01b037f0000000000000000000000007c71a87b3e4d5f02281815c137de90baa44cd0c616146106655760405162461bcd60e51b81526020600482015260166024820152750556e617574686f72697a6564207661756c74206170760541b60448201526064016105c7565b815160208084019190912060009081526008909152604090205460ff16156106cf5760405162461bcd60e51b815260206004820152601960248201527f43616c6c6261636b20616c72656164792065786563757465640000000000000060448201526064016105c7565b81516000908190849082906106ed908301602090810190840161222b565b509050600081806020019051810190610706919061228e565b905060008160ff16600181111561071f5761071f611e20565b88516020808b01919091206000908152600882526040808220805460ff191660011790558751888401208252600b90925290812080546001600160a01b038a166001600160a01b031990911617905590915081600181111561078357610783611e20565b036107dd576001600160401b0389166000908152600d6020526040902080546001909101546107d09186918d918f916107bc908b6122c7565b6107c691906122e4565b6000949350505050565b965050505050505061080e565b60018160018111156107f1576107f1611e20565b03610803576107d0848c8c6000611319565b600196505050505050505b949350505050565b6003546001600160a01b0316331461085e5760405162461bcd60e51b815260206004820152600b60248201526a139bdd08185b1b1bddd95960aa1b60448201526064016105c7565b60005b818110156108e95782828281811061087b5761087b612306565b905060600201602001600d600085858581811061089a5761089a612306565b6108b09260206060909202019081019150611cb1565b6001600160401b0316815260208082019290925260400160002082358155910135600190910155806108e18161231c565b915050610861565b507fe0583791041146b94f96ed3ebb01c8d616626aa2572f026d3be192180f3613e8828260405161091b929190612335565b60405180910390a15050565b3361093a6000546001600160a01b031690565b6001600160a01b03161461097e5760405162461bcd60e51b8152602060048201819052602482015260008051602061257f83398151915260448201526064016105c7565b6001548111156109d05760405162461bcd60e51b815260206004820152601b60248201527f496e73756666696369656e74206665657320636f6c6c6563746564000000000060448201526064016105c7565b80600160008282546109e29190612396565b90915550506040516001600160a01b0383169082156108fc029083906000818181858888f19350505050158015610a1d573d6000803e3d6000fd5b50816001600160a01b03167f9dc46f23cfb5ddcad0ae7ea2be38d47fec07bb9382ec7e564efc69e036dd66ce82604051610a5991815260200190565b60405180910390a25050565b600c546001600160a01b03163314610aba5760405162461bcd60e51b81526020600482015260186024820152772737ba10309031b7b6b83634b0b731b29036b0b730b3b2b960411b60448201526064016105c7565b600c54604080516001600160a01b03808516825290921660208301527f4af7e8d23c32ea7e07d618391c5b0b002c54cbb836ac109b440aa7a223561a1c910160405180910390a1600c80546001600160a01b0319166001600160a01b0392909216919091179055565b33610b366000546001600160a01b031690565b6001600160a01b031614610b7a5760405162461bcd60e51b8152602060048201819052602482015260008051602061257f83398151915260448201526064016105c7565b600380546001600160a01b0319166001600160a01b0392909216919091179055565b6000336001600160a01b037f0000000000000000000000007c71a87b3e4d5f02281815c137de90baa44cd0c61614610c0f5760405162461bcd60e51b81526020600482015260166024820152750556e617574686f72697a6564207661756c74206170760541b60448201526064016105c7565b600860008484604051610c239291906123a9565b604080519182900390912082526020820192909252016000205460ff1615610c8d5760405162461bcd60e51b815260206004820152601960248201527f43616c6c6261636b20616c72656164792065786563757465640000000000000060448201526064016105c7565b6000610cce84848080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061131192505050565b50509050610cdd8187876113db565b6001600860008686604051610cf39291906123a9565b6040518091039020815260200190815260200160002060006101000a81548160ff0219169083151502179055506001600960008686604051610d369291906123a9565b6040518091039020815260200190815260200160002060006101000a81548160ff0219169083151502179055506000915050949350505050565b600c546001600160a01b03163314610dc55760405162461bcd60e51b81526020600482015260186024820152772737ba10309031b7b6b83634b0b731b29036b0b730b3b2b960411b60448201526064016105c7565b615afd194601610dd457600080fd5b7f0edda34aed4c9b3a2fa7acd49cc8fa9ae5688d5061c30c6a57e8934f06146d6281604051610e0391906123b9565b60405180910390a160005b8151811015610e9057818181518110610e2957610e29612306565b60200260200101516020015160076000848481518110610e4b57610e4b612306565b602090810291909101810151516001600160a01b03168252810191909152604001600020805460ff191691151591909117905580610e888161231c565b915050610e0e565b5050565b3360009081526007602052604090205460ff1615610ee65760405162461bcd60e51b815260206004820152600f60248201526e13d19050c81c1c9bda1a589a5d1959608a1b60448201526064016105c7565b60025434906001600160a01b0390811690851603610fca5782341015610f4e5760405162461bcd60e51b815260206004820152601a60248201527f496e73756666696369656e74206e617469766520616d6f756e7400000000000060448201526064016105c7565b600260009054906101000a90046001600160a01b03166001600160a01b031663d0e30db0846040518263ffffffff1660e01b81526004016000604051808303818588803b158015610f9e57600080fd5b505af1158015610fb2573d6000803e3d6000fd5b50505050508281610fc39190612396565b9050610fdf565b610fdf6001600160a01b03851633308661149a565b615afd1946016110315760405162461bcd60e51b815260206004820152601e60248201527f43616e27742070726f787920706173732066726f6d205361707068697265000060448201526064016105c7565b61103d84848484611505565b50505050565b336110566000546001600160a01b031690565b6001600160a01b03161461109a5760405162461bcd60e51b8152602060048201819052602482015260008051602061257f83398151915260448201526064016105c7565b6001600160a01b0381166110ff5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b60648201526084016105c7565b611108816118ea565b50565b3361111e6000546001600160a01b031690565b6001600160a01b0316146111625760405162461bcd60e51b8152602060048201819052602482015260008051602061257f83398151915260448201526064016105c7565b60005b8151811015610e90574682828151811061118157611181612306565b6020026020010151600001516001600160401b0316036111f65760405162461bcd60e51b815260206004820152602a60248201527f43616e27742061646420616e20656e64706f696e7420746f20746865206375726044820152693932b73a1031b430b4b760b11b60648201526084016105c7565b81818151811061120857611208612306565b6020026020010151602001516004600084848151811061122a5761122a612306565b6020026020010151600001516001600160401b03166001600160401b0316815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b0316021790555081818151811061128c5761128c612306565b602002602001015160000151600560008484815181106112ae576112ae612306565b6020026020010151602001516001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a8154816001600160401b0302191690836001600160401b0316021790555080806113099061231c565b915050611165565b600091829190565b60008085806020019051810190611330919061222b565b9150506000808280602001905181019061134a9190612413565b91509150817fb1e855b7d4b49a91d1087196705073db569ebba9cff1cc0903fc4778e05a2fb086604051611382911515815260200190565b60405180910390a260008281527f54cdd369e4e8a8515e52ca72ec816c2101831ad1f18bf44102ed171459c9b4f860205260409020805460ff191660011790556113cd8188886113db565b506000979650505050505050565b6002546001600160a01b039081169083160361148157604051632e1a7d4d60e01b8152600481018290526001600160a01b03831690632e1a7d4d90602401600060405180830381600087803b15801561143357600080fd5b505af1158015611447573d6000803e3d6000fd5b50506040516001600160a01b038616925083156108fc02915083906000818181858888f1935050505015801561103d573d6000803e3d6000fd5b6114956001600160a01b038316848361193a565b505050565b6040516001600160a01b038085166024830152831660448201526064810182905261103d9085906323b872dd60e01b906084015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915261196a565b615afe60005260046020527fb4179405bfb78576241f1105fffdb36eac5eddd96ced8fdbce44e3bf94593698546001600160a01b0316806115985760405162461bcd60e51b815260206004820152602760248201527f536170706869726520656e64706f696e74206973206e6f742079657420636f6e604482015266199a59dd5c995960ca1b60648201526084016105c7565b60003383856040516020016115af9392919061246f565b60408051601f1981840301815282825260006020840181905291830182905260608301829052925090608001604051602081830303815290604052905060007f0000000000000000000000004066d196a423b2b3b8b054f4f40efb47a74e200c6001600160a01b0316635335dca283856040516020016116309291906124a0565b6040516020818303038152906040526040518263ffffffff1660e01b815260040161165b91906124c5565b602060405180830381865afa158015611678573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061169c91906124d8565b615afe600052600d6020527f7b72ab06470fed590ac056fa5b73c58a808bcf54f867dd173a32299af6c06339549091506116d690826124f1565b8510156117185760405162461bcd60e51b815260206004820152601060248201526f56616c756520697320746f6f206c6f7760801b60448201526064016105c7565b336117238287612396565b876040516020016117369392919061246f565b60408051601f19818403018152919052925061175a6117558287612396565b611a3f565b61178e6001600160a01b0389167f0000000000000000000000007c71a87b3e4d5f02281815c137de90baa44cd0c689611a8c565b615afe6000819052600460208190527fb4179405bfb78576241f1105fffdb36eac5eddd96ced8fdbce44e3bf945936985460405163aaf477d160e01b81526001600160a01b037f0000000000000000000000007c71a87b3e4d5f02281815c137de90baa44cd0c681169463aaf477d1948794611813949316928f918f918c9101612504565b6000604051808303818588803b15801561182c57600080fd5b505af1158015611840573d6000803e3d6000fd5b505085516020808801919091206000908152600a8252604080822080546001600160a01b031916331790556001808352600684528c518d850190812084527f3e5fec24aa4dc4e5aee2e025e51e1392c72a2500577559fae9665c6d52bd6a31909452818320805460ff191690911790558b5190922091519194507f82812468bd5a285f6132f6f5e6d8f7cd1082f95dcddcfd6f93ab52e7ecde84b093509150a25050505050505050565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6040516001600160a01b03831660248201526044810182905261149590849063a9059cbb60e01b906064016114ce565b60006119bf826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316611b399092919063ffffffff16565b90508051600014806119e05750808060200190518101906119e09190612545565b6114955760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016105c7565b8060016000828254611a5191906124f1565b90915550506040518181527f02bede6503f7c3293d6eac9b0f4981900471e18774a84ccc98715aa5433017949060200160405180910390a150565b604051636eb1769f60e11b81523060048201526001600160a01b0383811660248301526000919085169063dd62ed3e90604401602060405180830381865afa158015611adc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b0091906124d8565b905061103d8463095ea7b360e01b85611b1986866124f1565b6040516001600160a01b03909216602483015260448201526064016114ce565b606061080e848460008585600080866001600160a01b03168587604051611b609190612562565b60006040518083038185875af1925050503d8060008114611b9d576040519150601f19603f3d011682016040523d82523d6000602084013e611ba2565b606091505b5091509150611bb387838387611bbe565b979650505050505050565b60608315611c2d578251600003611c26576001600160a01b0385163b611c265760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016105c7565b508161080e565b61080e8383815115611c425781518083602001fd5b8060405162461bcd60e51b81526004016105c791906124c5565b6001600160a01b038116811461110857600080fd5b600060208284031215611c8357600080fd5b8135611c8e81611c5c565b9392505050565b80356001600160401b0381168114611cac57600080fd5b919050565b600060208284031215611cc357600080fd5b611c8e82611c95565b634e487b7160e01b600052604160045260246000fd5b604080519081016001600160401b0381118282101715611d0457611d04611ccc565b60405290565b604051601f8201601f191681016001600160401b0381118282101715611d3257611d32611ccc565b604052919050565b60006001600160401b03821115611d5357611d53611ccc565b50601f01601f191660200190565b600082601f830112611d7257600080fd5b8135611d85611d8082611d3a565b611d0a565b818152846020838601011115611d9a57600080fd5b816020850160208301376000918101602001919091529392505050565b60008060008060808587031215611dcd57600080fd5b8435611dd881611c5c565b935060208501359250611ded60408601611c95565b915060608501356001600160401b03811115611e0857600080fd5b611e1487828801611d61565b91505092959194509250565b634e487b7160e01b600052602160045260246000fd5b6020810160038310611e5857634e487b7160e01b600052602160045260246000fd5b91905290565b60008060208385031215611e7157600080fd5b82356001600160401b0380821115611e8857600080fd5b818501915085601f830112611e9c57600080fd5b813581811115611eab57600080fd5b866020606083028501011115611ec057600080fd5b60209290920196919550909350505050565b60008060408385031215611ee557600080fd5b8235611ef081611c5c565b946020939093013593505050565b60008060008060608587031215611f1457600080fd5b8435611f1f81611c5c565b93506020850135925060408501356001600160401b0380821115611f4257600080fd5b818701915087601f830112611f5657600080fd5b813581811115611f6557600080fd5b886020828501011115611f7757600080fd5b95989497505060200194505050565b60006001600160401b03821115611f9f57611f9f611ccc565b5060051b60200190565b801515811461110857600080fd5b60006020808385031215611fca57600080fd5b82356001600160401b03811115611fe057600080fd5b8301601f81018513611ff157600080fd5b8035611fff611d8082611f86565b81815260069190911b8201830190838101908783111561201e57600080fd5b928401925b82841015611bb3576040848903121561203c5760008081fd5b612044611ce2565b843561204f81611c5c565b81528486013561205e81611fa9565b8187015282526040939093019290840190612023565b60008060006060848603121561208957600080fd5b833561209481611c5c565b92506020840135915060408401356001600160401b038111156120b657600080fd5b6120c286828701611d61565b9150509250925092565b6000602082840312156120de57600080fd5b5035919050565b600080604083850312156120f857600080fd5b823560038110611ef057600080fd5b6000602080838503121561211a57600080fd5b82356001600160401b0381111561213057600080fd5b8301601f8101851361214157600080fd5b803561214f611d8082611f86565b81815260069190911b8201830190838101908783111561216e57600080fd5b928401925b82841015611bb3576040848903121561218c5760008081fd5b612194611ce2565b61219d85611c95565b8152858501356121ac81611c5c565b8187015282526040939093019290840190612173565b60005b838110156121dd5781810151838201526020016121c5565b50506000910152565b600082601f8301126121f757600080fd5b8151612205611d8082611d3a565b81815284602083860101111561221a57600080fd5b61080e8260208301602087016121c2565b6000806040838503121561223e57600080fd5b82516001600160401b038082111561225557600080fd5b612261868387016121e6565b9350602085015191508082111561227757600080fd5b50612284858286016121e6565b9150509250929050565b6000602082840312156122a057600080fd5b815160ff81168114611c8e57600080fd5b634e487b7160e01b600052601160045260246000fd5b80820281158282048414176122de576122de6122b1565b92915050565b60008261230157634e487b7160e01b600052601260045260246000fd5b500490565b634e487b7160e01b600052603260045260246000fd5b60006001820161232e5761232e6122b1565b5060010190565b6020808252818101839052600090604080840186845b87811015612389576001600160401b0361236483611c95565b168352818501358584015283820135848401526060928301929091019060010161234b565b5090979650505050505050565b818103818111156122de576122de6122b1565b8183823760009101908152919050565b602080825282518282018190526000919060409081850190868401855b8281101561240657815180516001600160a01b0316855286015115158685015292840192908501906001016123d6565b5091979650505050505050565b6000806040838503121561242657600080fd5b82519150602083015161243881611c5c565b809150509250929050565b6000815180845261245b8160208601602086016121c2565b601f01601f19169290920160200192915050565b6001600160a01b03841681528260208201526060604082015260006124976060830184612443565b95945050505050565b6040815260006124b36040830185612443565b82810360208401526124978185612443565b602081526000611c8e6020830184612443565b6000602082840312156124ea57600080fd5b5051919050565b808201808211156122de576122de6122b1565b60006001600160a01b0380881683526001600160401b038716602084015280861660408401525083606083015260a06080830152611bb360a0830184612443565b60006020828403121561255757600080fd5b8151611c8e81611fa9565b600082516125748184602087016121c2565b919091019291505056fe4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572a264697066735822122065e984bf036ce83c43fb8f241868a2c36d252979cdff327c90d22377e7011a3a64736f6c63430008110033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

0000000000000000000000007c71a87b3e4d5f02281815c137de90baa44cd0c6

-----Decoded View---------------
Arg [0] : _vaultApp (address): 0x7C71A87B3E4D5f02281815c137de90baA44Cd0C6

-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 0000000000000000000000007c71a87b3e4d5f02281815c137de90baa44cd0c6


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.