Contract 0xf5c6825015280cdfd0b56903f9f8b5a2233476f5 13

Contract Overview

Balance:
0 MATIC
Txn Hash
Method
Block
From
To
Value [Txn Fee]
0x01091a627cd98f4713d2cd58b7f33a5c07f5484cc8965afff2774007b4ba885c0x60a06040242083472022-01-24 8:16:35491 days 12 hrs ago0x58b529f9084d7eaa598eb3477fe36064c5b7bbc1 IN  Create: MessageBus0 MATIC0.004427026 2
[ Download CSV Export 
Parent Txn Hash Block From To Value
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
MessageBus

Compiler Version
v0.8.9+commit.e5eed63a

Optimization Enabled:
Yes with 800 runs

Other Settings:
default evmVersion, GNU GPLv3 license
File 1 of 75 : Bridge.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

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

contract Bridge is Pool {
    using SafeERC20 for IERC20;

    // liquidity events
    event Send(
        bytes32 transferId,
        address sender,
        address receiver,
        address token,
        uint256 amount,
        uint64 dstChainId,
        uint64 nonce,
        uint32 maxSlippage
    );
    event Relay(
        bytes32 transferId,
        address sender,
        address receiver,
        address token,
        uint256 amount,
        uint64 srcChainId,
        bytes32 srcTransferId
    );
    // gov events
    event MinSendUpdated(address token, uint256 amount);
    event MaxSendUpdated(address token, uint256 amount);

    mapping(bytes32 => bool) public transfers;
    mapping(address => uint256) public minSend; // send _amount must > minSend
    mapping(address => uint256) public maxSend;

    // min allowed max slippage uint32 value is slippage * 1M, eg. 0.5% -> 5000
    uint32 public minimalMaxSlippage;

    /**
     * @notice Send a cross-chain transfer via the liquidity pool-based bridge.
     * NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
     * @param _receiver The address of the receiver.
     * @param _token The address of the token.
     * @param _amount The amount of the transfer.
     * @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.
     */
    function send(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage // slippage * 1M, eg. 0.5% -> 5000
    ) external nonReentrant whenNotPaused {
        bytes32 transferId = _send(_receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage);
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
        emit Send(transferId, msg.sender, _receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage);
    }

    /**
     * @notice Send a cross-chain transfer via the liquidity pool-based bridge using the native token.
     * @param _receiver The address of the receiver.
     * @param _amount The amount of the transfer.
     * @param _dstChainId The destination chain ID.
     * @param _nonce A unique number. 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.
     */
    function sendNative(
        address _receiver,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage
    ) external payable nonReentrant whenNotPaused {
        require(msg.value == _amount, "Amount mismatch");
        require(nativeWrap != address(0), "Native wrap not set");
        bytes32 transferId = _send(_receiver, nativeWrap, _amount, _dstChainId, _nonce, _maxSlippage);
        IWETH(nativeWrap).deposit{value: _amount}();
        emit Send(transferId, msg.sender, _receiver, nativeWrap, _amount, _dstChainId, _nonce, _maxSlippage);
    }

    function _send(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage
    ) private returns (bytes32) {
        require(_amount > minSend[_token], "amount too small");
        require(maxSend[_token] == 0 || _amount <= maxSend[_token], "amount too large");
        require(_maxSlippage > minimalMaxSlippage, "max slippage too small");
        bytes32 transferId = keccak256(
            // uint64(block.chainid) for consistency as entire system uses uint64 for chain id
            // len = 20 + 20 + 20 + 32 + 8 + 8 + 8 = 116
            abi.encodePacked(msg.sender, _receiver, _token, _amount, _dstChainId, _nonce, uint64(block.chainid))
        );
        require(transfers[transferId] == false, "transfer exists");
        transfers[transferId] = true;
        return transferId;
    }

    /**
     * @notice Relay a cross-chain transfer sent from a liquidity pool-based bridge on another chain.
     * @param _relayRequest The serialized Relay 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 relay(
        bytes calldata _relayRequest,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external whenNotPaused {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Relay"));
        verifySigs(abi.encodePacked(domain, _relayRequest), _sigs, _signers, _powers);
        PbBridge.Relay memory request = PbBridge.decRelay(_relayRequest);
        // len = 20 + 20 + 20 + 32 + 8 + 8 + 32 = 140
        bytes32 transferId = keccak256(
            abi.encodePacked(
                request.sender,
                request.receiver,
                request.token,
                request.amount,
                request.srcChainId,
                request.dstChainId,
                request.srcTransferId
            )
        );
        require(transfers[transferId] == false, "transfer exists");
        transfers[transferId] = true;
        _updateVolume(request.token, request.amount);
        uint256 delayThreshold = delayThresholds[request.token];
        if (delayThreshold > 0 && request.amount > delayThreshold) {
            _addDelayedTransfer(transferId, request.receiver, request.token, request.amount);
        } else {
            _sendToken(request.receiver, request.token, request.amount);
        }

        emit Relay(
            transferId,
            request.sender,
            request.receiver,
            request.token,
            request.amount,
            request.srcChainId,
            request.srcTransferId
        );
    }

    function setMinSend(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            minSend[_tokens[i]] = _amounts[i];
            emit MinSendUpdated(_tokens[i], _amounts[i]);
        }
    }

    function setMaxSend(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            maxSend[_tokens[i]] = _amounts[i];
            emit MaxSendUpdated(_tokens[i], _amounts[i]);
        }
    }

    function setMinimalMaxSlippage(uint32 _minimalMaxSlippage) external onlyGovernor {
        minimalMaxSlippage = _minimalMaxSlippage;
    }

    // This is needed to receive ETH when calling `IWETH.withdraw`
    receive() external payable {}
}

File 2 of 75 : IERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, 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 `sender` to `recipient` 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 sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

File 3 of 75 : SafeERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

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

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

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

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

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

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

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

File 4 of 75 : PbBridge.sol
// SPDX-License-Identifier: GPL-3.0-only

// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: bridge.proto
pragma solidity 0.8.9;
import "./Pb.sol";

library PbBridge {
    using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj

    struct Relay {
        address sender; // tag: 1
        address receiver; // tag: 2
        address token; // tag: 3
        uint256 amount; // tag: 4
        uint64 srcChainId; // tag: 5
        uint64 dstChainId; // tag: 6
        bytes32 srcTransferId; // tag: 7
    } // end struct Relay

    function decRelay(bytes memory raw) internal pure returns (Relay memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.sender = Pb._address(buf.decBytes());
            } else if (tag == 2) {
                m.receiver = Pb._address(buf.decBytes());
            } else if (tag == 3) {
                m.token = Pb._address(buf.decBytes());
            } else if (tag == 4) {
                m.amount = Pb._uint256(buf.decBytes());
            } else if (tag == 5) {
                m.srcChainId = uint64(buf.decVarint());
            } else if (tag == 6) {
                m.dstChainId = uint64(buf.decVarint());
            } else if (tag == 7) {
                m.srcTransferId = Pb._bytes32(buf.decBytes());
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder Relay
}

File 5 of 75 : Pool.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./interfaces/IWETH.sol";
import "./libraries/PbPool.sol";
import "./safeguard/Pauser.sol";
import "./safeguard/VolumeControl.sol";
import "./safeguard/DelayedTransfer.sol";
import "./Signers.sol";

// add liquidity and withdraw
// withdraw can be used by user or liquidity provider

contract Pool is Signers, ReentrancyGuard, Pauser, VolumeControl, DelayedTransfer {
    using SafeERC20 for IERC20;

    uint64 public addseq; // ensure unique LiquidityAdded event, start from 1
    mapping(address => uint256) public minAdd; // add _amount must > minAdd

    // map of successful withdraws, if true means already withdrew money or added to delayedTransfers
    mapping(bytes32 => bool) public withdraws;

    // erc20 wrap of gas token of this chain, eg. WETH, when relay ie. pay out,
    // if request.token equals this, will withdraw and send native token to receiver
    // note we don't check whether it's zero address. when this isn't set, and request.token
    // is all 0 address, guarantee fail
    address public nativeWrap;

    // liquidity events
    event LiquidityAdded(
        uint64 seqnum,
        address provider,
        address token,
        uint256 amount // how many tokens were added
    );
    event WithdrawDone(
        bytes32 withdrawId,
        uint64 seqnum,
        address receiver,
        address token,
        uint256 amount,
        bytes32 refid
    );
    event MinAddUpdated(address token, uint256 amount);

    /**
     * @notice Add liquidity to the pool-based bridge.
     * NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
     * NOTE: ONLY call this from an EOA. DO NOT call from a contract address.
     * @param _token The address of the token.
     * @param _amount The amount to add.
     */
    function addLiquidity(address _token, uint256 _amount) external nonReentrant whenNotPaused {
        require(_amount > minAdd[_token], "amount too small");
        addseq += 1;
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
        emit LiquidityAdded(addseq, msg.sender, _token, _amount);
    }

    /**
     * @notice Add native token liquidity to the pool-based bridge.
     * NOTE: ONLY call this from an EOA. DO NOT call from a contract address.
     * @param _amount The amount to add.
     */
    function addNativeLiquidity(uint256 _amount) external payable nonReentrant whenNotPaused {
        require(msg.value == _amount, "Amount mismatch");
        require(nativeWrap != address(0), "Native wrap not set");
        require(_amount > minAdd[nativeWrap], "amount too small");
        addseq += 1;
        IWETH(nativeWrap).deposit{value: _amount}();
        emit LiquidityAdded(addseq, msg.sender, nativeWrap, _amount);
    }

    /**
     * @notice Withdraw funds from the bridge pool.
     * @param _wdmsg The serialized Withdraw protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A withdrawal 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 _wdmsg,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external whenNotPaused {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "WithdrawMsg"));
        verifySigs(abi.encodePacked(domain, _wdmsg), _sigs, _signers, _powers);
        // decode and check wdmsg
        PbPool.WithdrawMsg memory wdmsg = PbPool.decWithdrawMsg(_wdmsg);
        // len = 8 + 8 + 20 + 20 + 32 = 88
        bytes32 wdId = keccak256(
            abi.encodePacked(wdmsg.chainid, wdmsg.seqnum, wdmsg.receiver, wdmsg.token, wdmsg.amount)
        );
        require(withdraws[wdId] == false, "withdraw already succeeded");
        withdraws[wdId] = true;
        _updateVolume(wdmsg.token, wdmsg.amount);
        uint256 delayThreshold = delayThresholds[wdmsg.token];
        if (delayThreshold > 0 && wdmsg.amount > delayThreshold) {
            _addDelayedTransfer(wdId, wdmsg.receiver, wdmsg.token, wdmsg.amount);
        } else {
            _sendToken(wdmsg.receiver, wdmsg.token, wdmsg.amount);
        }
        emit WithdrawDone(wdId, wdmsg.seqnum, wdmsg.receiver, wdmsg.token, wdmsg.amount, wdmsg.refid);
    }

    function executeDelayedTransfer(bytes32 id) external whenNotPaused {
        delayedTransfer memory transfer = _executeDelayedTransfer(id);
        _sendToken(transfer.receiver, transfer.token, transfer.amount);
    }

    function setMinAdd(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            minAdd[_tokens[i]] = _amounts[i];
            emit MinAddUpdated(_tokens[i], _amounts[i]);
        }
    }

    function _sendToken(
        address _receiver,
        address _token,
        uint256 _amount
    ) internal {
        if (_token == nativeWrap) {
            // withdraw then transfer native to receiver
            IWETH(nativeWrap).withdraw(_amount);
            (bool sent, ) = _receiver.call{value: _amount, gas: 50000}("");
            require(sent, "failed to send native token");
        } else {
            IERC20(_token).safeTransfer(_receiver, _amount);
        }
    }

    // set nativeWrap, for relay requests, if token == nativeWrap, will withdraw first then transfer native to receiver
    function setWrap(address _weth) external onlyOwner {
        nativeWrap = _weth;
    }
}

File 6 of 75 : Address.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @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
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        assembly {
            size := extcodesize(account)
        }
        return size > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    function _verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) private pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

File 7 of 75 : Pb.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

// runtime proto sol library
library Pb {
    enum WireType {
        Varint,
        Fixed64,
        LengthDelim,
        StartGroup,
        EndGroup,
        Fixed32
    }

    struct Buffer {
        uint256 idx; // the start index of next read. when idx=b.length, we're done
        bytes b; // hold serialized proto msg, readonly
    }

    // create a new in-memory Buffer object from raw msg bytes
    function fromBytes(bytes memory raw) internal pure returns (Buffer memory buf) {
        buf.b = raw;
        buf.idx = 0;
    }

    // whether there are unread bytes
    function hasMore(Buffer memory buf) internal pure returns (bool) {
        return buf.idx < buf.b.length;
    }

    // decode current field number and wiretype
    function decKey(Buffer memory buf) internal pure returns (uint256 tag, WireType wiretype) {
        uint256 v = decVarint(buf);
        tag = v / 8;
        wiretype = WireType(v & 7);
    }

    // count tag occurrences, return an array due to no memory map support
    // have to create array for (maxtag+1) size. cnts[tag] = occurrences
    // should keep buf.idx unchanged because this is only a count function
    function cntTags(Buffer memory buf, uint256 maxtag) internal pure returns (uint256[] memory cnts) {
        uint256 originalIdx = buf.idx;
        cnts = new uint256[](maxtag + 1); // protobuf's tags are from 1 rather than 0
        uint256 tag;
        WireType wire;
        while (hasMore(buf)) {
            (tag, wire) = decKey(buf);
            cnts[tag] += 1;
            skipValue(buf, wire);
        }
        buf.idx = originalIdx;
    }

    // read varint from current buf idx, move buf.idx to next read, return the int value
    function decVarint(Buffer memory buf) internal pure returns (uint256 v) {
        bytes10 tmp; // proto int is at most 10 bytes (7 bits can be used per byte)
        bytes memory bb = buf.b; // get buf.b mem addr to use in assembly
        v = buf.idx; // use v to save one additional uint variable
        assembly {
            tmp := mload(add(add(bb, 32), v)) // load 10 bytes from buf.b[buf.idx] to tmp
        }
        uint256 b; // store current byte content
        v = 0; // reset to 0 for return value
        for (uint256 i = 0; i < 10; i++) {
            assembly {
                b := byte(i, tmp) // don't use tmp[i] because it does bound check and costs extra
            }
            v |= (b & 0x7F) << (i * 7);
            if (b & 0x80 == 0) {
                buf.idx += i + 1;
                return v;
            }
        }
        revert(); // i=10, invalid varint stream
    }

    // read length delimited field and return bytes
    function decBytes(Buffer memory buf) internal pure returns (bytes memory b) {
        uint256 len = decVarint(buf);
        uint256 end = buf.idx + len;
        require(end <= buf.b.length); // avoid overflow
        b = new bytes(len);
        bytes memory bufB = buf.b; // get buf.b mem addr to use in assembly
        uint256 bStart;
        uint256 bufBStart = buf.idx;
        assembly {
            bStart := add(b, 32)
            bufBStart := add(add(bufB, 32), bufBStart)
        }
        for (uint256 i = 0; i < len; i += 32) {
            assembly {
                mstore(add(bStart, i), mload(add(bufBStart, i)))
            }
        }
        buf.idx = end;
    }

    // return packed ints
    function decPacked(Buffer memory buf) internal pure returns (uint256[] memory t) {
        uint256 len = decVarint(buf);
        uint256 end = buf.idx + len;
        require(end <= buf.b.length); // avoid overflow
        // array in memory must be init w/ known length
        // so we have to create a tmp array w/ max possible len first
        uint256[] memory tmp = new uint256[](len);
        uint256 i = 0; // count how many ints are there
        while (buf.idx < end) {
            tmp[i] = decVarint(buf);
            i++;
        }
        t = new uint256[](i); // init t with correct length
        for (uint256 j = 0; j < i; j++) {
            t[j] = tmp[j];
        }
        return t;
    }

    // move idx pass current value field, to beginning of next tag or msg end
    function skipValue(Buffer memory buf, WireType wire) internal pure {
        if (wire == WireType.Varint) {
            decVarint(buf);
        } else if (wire == WireType.LengthDelim) {
            uint256 len = decVarint(buf);
            buf.idx += len; // skip len bytes value data
            require(buf.idx <= buf.b.length); // avoid overflow
        } else {
            revert();
        } // unsupported wiretype
    }

    // type conversion help utils
    function _bool(uint256 x) internal pure returns (bool v) {
        return x != 0;
    }

    function _uint256(bytes memory b) internal pure returns (uint256 v) {
        require(b.length <= 32); // b's length must be smaller than or equal to 32
        assembly {
            v := mload(add(b, 32))
        } // load all 32bytes to v
        v = v >> (8 * (32 - b.length)); // only first b.length is valid
    }

    function _address(bytes memory b) internal pure returns (address v) {
        v = _addressPayable(b);
    }

    function _addressPayable(bytes memory b) internal pure returns (address payable v) {
        require(b.length == 20);
        //load 32bytes then shift right 12 bytes
        assembly {
            v := div(mload(add(b, 32)), 0x1000000000000000000000000)
        }
    }

    function _bytes32(bytes memory b) internal pure returns (bytes32 v) {
        require(b.length == 32);
        assembly {
            v := mload(add(b, 32))
        }
    }

    // uint[] to uint8[]
    function uint8s(uint256[] memory arr) internal pure returns (uint8[] memory t) {
        t = new uint8[](arr.length);
        for (uint256 i = 0; i < t.length; i++) {
            t[i] = uint8(arr[i]);
        }
    }

    function uint32s(uint256[] memory arr) internal pure returns (uint32[] memory t) {
        t = new uint32[](arr.length);
        for (uint256 i = 0; i < t.length; i++) {
            t[i] = uint32(arr[i]);
        }
    }

    function uint64s(uint256[] memory arr) internal pure returns (uint64[] memory t) {
        t = new uint64[](arr.length);
        for (uint256 i = 0; i < t.length; i++) {
            t[i] = uint64(arr[i]);
        }
    }

    function bools(uint256[] memory arr) internal pure returns (bool[] memory t) {
        t = new bool[](arr.length);
        for (uint256 i = 0; i < t.length; i++) {
            t[i] = arr[i] != 0;
        }
    }
}

File 8 of 75 : ReentrancyGuard.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and make it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

File 9 of 75 : IWETH.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

interface IWETH {
    function deposit() external payable;

    function withdraw(uint256) external;
}

File 10 of 75 : PbPool.sol
// SPDX-License-Identifier: GPL-3.0-only

// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: contracts/libraries/proto/pool.proto
pragma solidity 0.8.9;
import "./Pb.sol";

library PbPool {
    using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj

    struct WithdrawMsg {
        uint64 chainid; // tag: 1
        uint64 seqnum; // tag: 2
        address receiver; // tag: 3
        address token; // tag: 4
        uint256 amount; // tag: 5
        bytes32 refid; // tag: 6
    } // end struct WithdrawMsg

    function decWithdrawMsg(bytes memory raw) internal pure returns (WithdrawMsg memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.chainid = uint64(buf.decVarint());
            } else if (tag == 2) {
                m.seqnum = uint64(buf.decVarint());
            } else if (tag == 3) {
                m.receiver = Pb._address(buf.decBytes());
            } else if (tag == 4) {
                m.token = Pb._address(buf.decBytes());
            } else if (tag == 5) {
                m.amount = Pb._uint256(buf.decBytes());
            } else if (tag == 6) {
                m.refid = Pb._bytes32(buf.decBytes());
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder WithdrawMsg
}

File 11 of 75 : Pauser.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";

abstract contract Pauser is Ownable, Pausable {
    mapping(address => bool) public pausers;

    event PauserAdded(address account);
    event PauserRemoved(address account);

    constructor() {
        _addPauser(msg.sender);
    }

    modifier onlyPauser() {
        require(isPauser(msg.sender), "Caller is not pauser");
        _;
    }

    function pause() public onlyPauser {
        _pause();
    }

    function unpause() public onlyPauser {
        _unpause();
    }

    function isPauser(address account) public view returns (bool) {
        return pausers[account];
    }

    function addPauser(address account) public onlyOwner {
        _addPauser(account);
    }

    function removePauser(address account) public onlyOwner {
        _removePauser(account);
    }

    function renouncePauser() public {
        _removePauser(msg.sender);
    }

    function _addPauser(address account) private {
        require(!isPauser(account), "Account is already pauser");
        pausers[account] = true;
        emit PauserAdded(account);
    }

    function _removePauser(address account) private {
        require(isPauser(account), "Account is not pauser");
        pausers[account] = false;
        emit PauserRemoved(account);
    }
}

File 12 of 75 : VolumeControl.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "./Governor.sol";

abstract contract VolumeControl is Governor {
    uint256 public epochLength; // seconds
    mapping(address => uint256) public epochVolumes; // key is token
    mapping(address => uint256) public epochVolumeCaps; // key is token
    mapping(address => uint256) public lastOpTimestamps; // key is token

    event EpochLengthUpdated(uint256 length);
    event EpochVolumeUpdated(address token, uint256 cap);

    function setEpochLength(uint256 _length) external onlyGovernor {
        epochLength = _length;
        emit EpochLengthUpdated(_length);
    }

    function setEpochVolumeCaps(address[] calldata _tokens, uint256[] calldata _caps) external onlyGovernor {
        require(_tokens.length == _caps.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            epochVolumeCaps[_tokens[i]] = _caps[i];
            emit EpochVolumeUpdated(_tokens[i], _caps[i]);
        }
    }

    function _updateVolume(address _token, uint256 _amount) internal {
        if (epochLength == 0) {
            return;
        }
        uint256 cap = epochVolumeCaps[_token];
        if (cap == 0) {
            return;
        }
        uint256 volume = epochVolumes[_token];
        uint256 timestamp = block.timestamp;
        uint256 epochStartTime = (timestamp / epochLength) * epochLength;
        if (lastOpTimestamps[_token] < epochStartTime) {
            volume = _amount;
        } else {
            volume += _amount;
        }
        require(volume <= cap, "volume exceeds cap");
        epochVolumes[_token] = volume;
        lastOpTimestamps[_token] = timestamp;
    }
}

File 13 of 75 : DelayedTransfer.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "./Governor.sol";

abstract contract DelayedTransfer is Governor {
    struct delayedTransfer {
        address receiver;
        address token;
        uint256 amount;
        uint256 timestamp;
    }
    mapping(bytes32 => delayedTransfer) public delayedTransfers;
    mapping(address => uint256) public delayThresholds;
    uint256 public delayPeriod; // in seconds

    event DelayedTransferAdded(bytes32 id);
    event DelayedTransferExecuted(bytes32 id, address receiver, address token, uint256 amount);

    event DelayPeriodUpdated(uint256 period);
    event DelayThresholdUpdated(address token, uint256 threshold);

    function setDelayThresholds(address[] calldata _tokens, uint256[] calldata _thresholds) external onlyGovernor {
        require(_tokens.length == _thresholds.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            delayThresholds[_tokens[i]] = _thresholds[i];
            emit DelayThresholdUpdated(_tokens[i], _thresholds[i]);
        }
    }

    function setDelayPeriod(uint256 _period) external onlyGovernor {
        delayPeriod = _period;
        emit DelayPeriodUpdated(_period);
    }

    function _addDelayedTransfer(
        bytes32 id,
        address receiver,
        address token,
        uint256 amount
    ) internal {
        require(delayedTransfers[id].timestamp == 0, "delayed transfer already exists");
        delayedTransfers[id] = delayedTransfer({
            receiver: receiver,
            token: token,
            amount: amount,
            timestamp: block.timestamp
        });
        emit DelayedTransferAdded(id);
    }

    // caller needs to do the actual token transfer
    function _executeDelayedTransfer(bytes32 id) internal returns (delayedTransfer memory) {
        delayedTransfer memory transfer = delayedTransfers[id];
        require(transfer.timestamp > 0, "delayed transfer not exist");
        require(block.timestamp > transfer.timestamp + delayPeriod, "delayed transfer still locked");
        delete delayedTransfers[id];
        emit DelayedTransferExecuted(id, transfer.receiver, transfer.token, transfer.amount);
        return transfer;
    }
}

File 14 of 75 : Signers.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./interfaces/ISigsVerifier.sol";

contract Signers is Ownable, ISigsVerifier {
    using ECDSA for bytes32;

    bytes32 public ssHash;
    uint256 public triggerTime; // timestamp when last update was triggered

    // reset can be called by the owner address for emergency recovery
    uint256 public resetTime;
    uint256 public noticePeriod; // advance notice period as seconds for reset
    uint256 constant MAX_INT = 2**256 - 1;

    event SignersUpdated(address[] _signers, uint256[] _powers);

    event ResetNotification(uint256 resetTime);

    /**
     * @notice Verifies that a message is signed by a quorum among the signers
     * The sigs must be sorted by signer addresses in ascending order.
     * @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
    ) public view override {
        bytes32 h = keccak256(abi.encodePacked(_signers, _powers));
        require(ssHash == h, "Mismatch current signers");
        _verifySignedPowers(keccak256(_msg).toEthSignedMessageHash(), _sigs, _signers, _powers);
    }

    /**
     * @notice Update new signers.
     * @param _newSigners sorted list of new signers
     * @param _curPowers powers of new signers
     * @param _sigs list of signatures sorted by signer addresses in ascending order
     * @param _curSigners sorted list of current signers
     * @param _curPowers powers of current signers
     */
    function updateSigners(
        uint256 _triggerTime,
        address[] calldata _newSigners,
        uint256[] calldata _newPowers,
        bytes[] calldata _sigs,
        address[] calldata _curSigners,
        uint256[] calldata _curPowers
    ) external {
        // use trigger time for nonce protection, must be ascending
        require(_triggerTime > triggerTime, "Trigger time is not increasing");
        // make sure triggerTime is not too large, as it cannot be decreased once set
        require(_triggerTime < block.timestamp + 3600, "Trigger time is too large");
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "UpdateSigners"));
        verifySigs(abi.encodePacked(domain, _triggerTime, _newSigners, _newPowers), _sigs, _curSigners, _curPowers);
        _updateSigners(_newSigners, _newPowers);
        triggerTime = _triggerTime;
    }

    /**
     * @notice reset signers, only used for init setup and emergency recovery
     */
    function resetSigners(address[] calldata _signers, uint256[] calldata _powers) external onlyOwner {
        require(block.timestamp > resetTime, "not reach reset time");
        resetTime = MAX_INT;
        _updateSigners(_signers, _powers);
    }

    function notifyResetSigners() external onlyOwner {
        resetTime = block.timestamp + noticePeriod;
        emit ResetNotification(resetTime);
    }

    function increaseNoticePeriod(uint256 period) external onlyOwner {
        require(period > noticePeriod, "notice period can only be increased");
        noticePeriod = period;
    }

    // separate from verifySigs func to avoid "stack too deep" issue
    function _verifySignedPowers(
        bytes32 _hash,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) private pure {
        require(_signers.length == _powers.length, "signers and powers length not match");
        uint256 totalPower; // sum of all signer.power
        for (uint256 i = 0; i < _signers.length; i++) {
            totalPower += _powers[i];
        }
        uint256 quorum = (totalPower * 2) / 3 + 1;

        uint256 signedPower; // sum of signer powers who are in sigs
        address prev = address(0);
        uint256 index = 0;
        for (uint256 i = 0; i < _sigs.length; i++) {
            address signer = _hash.recover(_sigs[i]);
            require(signer > prev, "signers not in ascending order");
            prev = signer;
            // now find match signer add its power
            while (signer > _signers[index]) {
                index += 1;
                require(index < _signers.length, "signer not found");
            }
            if (signer == _signers[index]) {
                signedPower += _powers[index];
            }
            if (signedPower >= quorum) {
                // return early to save gas
                return;
            }
        }
        revert("quorum not reached");
    }

    function _updateSigners(address[] calldata _signers, uint256[] calldata _powers) private {
        require(_signers.length == _powers.length, "signers and powers length not match");
        address prev = address(0);
        for (uint256 i = 0; i < _signers.length; i++) {
            require(_signers[i] > prev, "New signers not in ascending order");
            prev = _signers[i];
        }
        ssHash = keccak256(abi.encodePacked(_signers, _powers));
        emit SignersUpdated(_signers, _powers);
    }
}

File 15 of 75 : Ownable.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

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

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

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _setOwner(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _setOwner(newOwner);
    }

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

File 16 of 75 : Pausable.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        require(!paused(), "Pausable: paused");
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        require(paused(), "Pausable: not paused");
        _;
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

File 17 of 75 : Context.sol
// SPDX-License-Identifier: MIT

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 18 of 75 : Governor.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/access/Ownable.sol";

abstract contract Governor is Ownable {
    mapping(address => bool) public governors;

    event GovernorAdded(address account);
    event GovernorRemoved(address account);

    modifier onlyGovernor() {
        require(isGovernor(msg.sender), "Caller is not governor");
        _;
    }

    constructor() {
        _addGovernor(msg.sender);
    }

    function isGovernor(address _account) public view returns (bool) {
        return governors[_account];
    }

    function addGovernor(address _account) public onlyOwner {
        _addGovernor(_account);
    }

    function removeGovernor(address _account) public onlyOwner {
        _removeGovernor(_account);
    }

    function renounceGovernor() public {
        _removeGovernor(msg.sender);
    }

    function _addGovernor(address _account) private {
        require(!isGovernor(_account), "Account is already governor");
        governors[_account] = true;
        emit GovernorAdded(_account);
    }

    function _removeGovernor(address _account) private {
        require(isGovernor(_account), "Account is not governor");
        governors[_account] = false;
        emit GovernorRemoved(_account);
    }
}

File 19 of 75 : ECDSA.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        // Check the signature length
        // - case 65: r,s,v signature (standard)
        // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return recover(hash, v, r, s);
        } else if (signature.length == 64) {
            bytes32 r;
            bytes32 vs;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly {
                r := mload(add(signature, 0x20))
                vs := mload(add(signature, 0x40))
            }
            return recover(hash, r, vs);
        } else {
            revert("ECDSA: invalid signature length");
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        bytes32 s;
        uint8 v;
        assembly {
            s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
            v := add(shr(255, vs), 27)
        }
        return recover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately.
     */
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        require(
            uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
            "ECDSA: invalid signature 's' value"
        );
        require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        require(signer != address(0), "ECDSA: invalid signature");

        return signer;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}

File 20 of 75 : ISigsVerifier.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

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 21 of 75 : PeggedTokenBridge.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "../interfaces/ISigsVerifier.sol";
import "../interfaces/IPeggedToken.sol";
import "../libraries/PbPegged.sol";
import "../safeguard/Pauser.sol";
import "../safeguard/VolumeControl.sol";
import "../safeguard/DelayedTransfer.sol";

/**
 * @title The bridge contract to mint and burn pegged tokens
 * @dev Work together with OriginalTokenVault deployed at remote chains.
 */
contract PeggedTokenBridge is Pauser, VolumeControl, DelayedTransfer {
    ISigsVerifier public immutable sigsVerifier;

    mapping(bytes32 => bool) public records;

    mapping(address => uint256) public minBurn;
    mapping(address => uint256) public maxBurn;

    event Mint(
        bytes32 mintId,
        address token,
        address account,
        uint256 amount,
        uint64 refChainId,
        bytes32 refId,
        address depositor
    );
    event Burn(bytes32 burnId, address token, address account, uint256 amount, address withdrawAccount);
    event MinBurnUpdated(address token, uint256 amount);
    event MaxBurnUpdated(address token, uint256 amount);

    constructor(ISigsVerifier _sigsVerifier) {
        sigsVerifier = _sigsVerifier;
    }

    /**
     * @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 whenNotPaused {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Mint"));
        sigsVerifier.verifySigs(abi.encodePacked(domain, _request), _sigs, _signers, _powers);
        PbPegged.Mint memory request = PbPegged.decMint(_request);
        bytes32 mintId = keccak256(
            // len = 20 + 20 + 32 + 20 + 8 + 32 = 132
            abi.encodePacked(
                request.account,
                request.token,
                request.amount,
                request.depositor,
                request.refChainId,
                request.refId
            )
        );
        require(records[mintId] == false, "record exists");
        records[mintId] = true;
        _updateVolume(request.token, request.amount);
        uint256 delayThreshold = delayThresholds[request.token];
        if (delayThreshold > 0 && request.amount > delayThreshold) {
            _addDelayedTransfer(mintId, request.account, request.token, request.amount);
        } else {
            IPeggedToken(request.token).mint(request.account, request.amount);
        }
        emit Mint(
            mintId,
            request.token,
            request.account,
            request.amount,
            request.refChainId,
            request.refId,
            request.depositor
        );
    }

    /**
     * @notice Burn pegged tokens to trigger a cross-chain withdrawal of the original tokens at a remote chain's
     * OriginalTokenVault.
     * NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
     * @param _token The pegged token address.
     * @param _amount The amount to burn.
     * @param _withdrawAccount The account to receive the original tokens withdrawn on the remote chain.
     * @param _nonce A number to guarantee unique depositId. Can be timestamp in practice.
     */
    function burn(
        address _token,
        uint256 _amount,
        address _withdrawAccount,
        uint64 _nonce
    ) external whenNotPaused {
        require(_amount > minBurn[_token], "amount too small");
        require(maxBurn[_token] == 0 || _amount <= maxBurn[_token], "amount too large");
        bytes32 burnId = keccak256(
            // len = 20 + 20 + 32 + 20 + 8 + 8 = 108
            abi.encodePacked(msg.sender, _token, _amount, _withdrawAccount, _nonce, uint64(block.chainid))
        );
        require(records[burnId] == false, "record exists");
        records[burnId] = true;
        IPeggedToken(_token).burn(msg.sender, _amount);
        emit Burn(burnId, _token, msg.sender, _amount, _withdrawAccount);
    }

    function executeDelayedTransfer(bytes32 id) external whenNotPaused {
        delayedTransfer memory transfer = _executeDelayedTransfer(id);
        IPeggedToken(transfer.token).mint(transfer.receiver, transfer.amount);
    }

    function setMinBurn(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            minBurn[_tokens[i]] = _amounts[i];
            emit MinBurnUpdated(_tokens[i], _amounts[i]);
        }
    }

    function setMaxBurn(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            maxBurn[_tokens[i]] = _amounts[i];
            emit MaxBurnUpdated(_tokens[i], _amounts[i]);
        }
    }
}

File 22 of 75 : IPeggedToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

interface IPeggedToken {
    function mint(address _to, uint256 _amount) external;

    function burn(address _from, uint256 _amount) external;
}

File 23 of 75 : PbPegged.sol
// SPDX-License-Identifier: GPL-3.0-only

// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: contracts/libraries/proto/pegged.proto
pragma solidity 0.8.9;
import "./Pb.sol";

library PbPegged {
    using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj

    struct Mint {
        address token; // tag: 1
        address account; // tag: 2
        uint256 amount; // tag: 3
        address depositor; // tag: 4
        uint64 refChainId; // tag: 5
        bytes32 refId; // tag: 6
    } // end struct Mint

    function decMint(bytes memory raw) internal pure returns (Mint memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.token = Pb._address(buf.decBytes());
            } else if (tag == 2) {
                m.account = Pb._address(buf.decBytes());
            } else if (tag == 3) {
                m.amount = Pb._uint256(buf.decBytes());
            } else if (tag == 4) {
                m.depositor = Pb._address(buf.decBytes());
            } else if (tag == 5) {
                m.refChainId = uint64(buf.decVarint());
            } else if (tag == 6) {
                m.refId = Pb._bytes32(buf.decBytes());
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder Mint

    struct Withdraw {
        address token; // tag: 1
        address receiver; // tag: 2
        uint256 amount; // tag: 3
        address burnAccount; // tag: 4
        uint64 refChainId; // tag: 5
        bytes32 refId; // tag: 6
    } // end struct Withdraw

    function decWithdraw(bytes memory raw) internal pure returns (Withdraw memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.token = Pb._address(buf.decBytes());
            } else if (tag == 2) {
                m.receiver = Pb._address(buf.decBytes());
            } else if (tag == 3) {
                m.amount = Pb._uint256(buf.decBytes());
            } else if (tag == 4) {
                m.burnAccount = Pb._address(buf.decBytes());
            } else if (tag == 5) {
                m.refChainId = uint64(buf.decVarint());
            } else if (tag == 6) {
                m.refId = Pb._bytes32(buf.decBytes());
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder Withdraw
}

File 24 of 75 : OriginalTokenVault.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/ISigsVerifier.sol";
import "../interfaces/IWETH.sol";
import "../libraries/PbPegged.sol";
import "../safeguard/Pauser.sol";
import "../safeguard/VolumeControl.sol";
import "../safeguard/DelayedTransfer.sol";

/**
 * @title the vault to deposit and withdraw original tokens
 * @dev Work together with PeggedTokenBridge contracts deployed at remote chains
 */
contract OriginalTokenVault is ReentrancyGuard, Pauser, VolumeControl, DelayedTransfer {
    using SafeERC20 for IERC20;

    ISigsVerifier public immutable sigsVerifier;

    mapping(bytes32 => bool) public records;

    mapping(address => uint256) public minDeposit;
    mapping(address => uint256) public maxDeposit;

    address public nativeWrap;

    event Deposited(
        bytes32 depositId,
        address depositor,
        address token,
        uint256 amount,
        uint64 mintChainId,
        address mintAccount
    );
    event Withdrawn(
        bytes32 withdrawId,
        address receiver,
        address token,
        uint256 amount,
        uint64 refChainId,
        bytes32 refId,
        address burnAccount
    );
    event MinDepositUpdated(address token, uint256 amount);
    event MaxDepositUpdated(address token, uint256 amount);

    constructor(ISigsVerifier _sigsVerifier) {
        sigsVerifier = _sigsVerifier;
    }

    /**
     * @notice Lock original tokens to trigger cross-chain mint of pegged tokens at a remote chain's PeggedTokenBridge.
     * NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
     * @param _token The original token address.
     * @param _amount The amount to deposit.
     * @param _mintChainId The destination chain ID to mint tokens.
     * @param _mintAccount The destination account to receive the minted pegged tokens.
     * @param _nonce A number input to guarantee unique depositId. Can be timestamp in practice.
     */
    function deposit(
        address _token,
        uint256 _amount,
        uint64 _mintChainId,
        address _mintAccount,
        uint64 _nonce
    ) external nonReentrant whenNotPaused {
        bytes32 depId = _deposit(_token, _amount, _mintChainId, _mintAccount, _nonce);
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
        emit Deposited(depId, msg.sender, _token, _amount, _mintChainId, _mintAccount);
    }

    /**
     * @notice Lock native token as original token to trigger cross-chain mint of pegged tokens at a remote chain's
     * PeggedTokenBridge.
     * @param _amount The amount to deposit.
     * @param _mintChainId The destination chain ID to mint tokens.
     * @param _mintAccount The destination account to receive the minted pegged tokens.
     * @param _nonce A number input to guarantee unique depositId. Can be timestamp in practice.
     */
    function depositNative(
        uint256 _amount,
        uint64 _mintChainId,
        address _mintAccount,
        uint64 _nonce
    ) external payable nonReentrant whenNotPaused {
        require(msg.value == _amount, "Amount mismatch");
        require(nativeWrap != address(0), "Native wrap not set");
        bytes32 depId = _deposit(nativeWrap, _amount, _mintChainId, _mintAccount, _nonce);
        IWETH(nativeWrap).deposit{value: _amount}();
        emit Deposited(depId, msg.sender, nativeWrap, _amount, _mintChainId, _mintAccount);
    }

    function _deposit(
        address _token,
        uint256 _amount,
        uint64 _mintChainId,
        address _mintAccount,
        uint64 _nonce
    ) private returns (bytes32) {
        require(_amount > minDeposit[_token], "amount too small");
        require(maxDeposit[_token] == 0 || _amount <= maxDeposit[_token], "amount too large");
        bytes32 depId = keccak256(
            // len = 20 + 20 + 32 + 8 + 20 + 8 + 8 = 116
            abi.encodePacked(msg.sender, _token, _amount, _mintChainId, _mintAccount, _nonce, uint64(block.chainid))
        );
        require(records[depId] == false, "record exists");
        records[depId] = true;
        return depId;
    }

    /**
     * @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 whenNotPaused {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Withdraw"));
        sigsVerifier.verifySigs(abi.encodePacked(domain, _request), _sigs, _signers, _powers);
        PbPegged.Withdraw memory request = PbPegged.decWithdraw(_request);
        bytes32 wdId = keccak256(
            // len = 20 + 20 + 32 + 20 + 8 + 32 = 132
            abi.encodePacked(
                request.receiver,
                request.token,
                request.amount,
                request.burnAccount,
                request.refChainId,
                request.refId
            )
        );
        require(records[wdId] == false, "record exists");
        records[wdId] = true;
        _updateVolume(request.token, request.amount);
        uint256 delayThreshold = delayThresholds[request.token];
        if (delayThreshold > 0 && request.amount > delayThreshold) {
            _addDelayedTransfer(wdId, request.receiver, request.token, request.amount);
        } else {
            _sendToken(request.receiver, request.token, request.amount);
        }
        emit Withdrawn(
            wdId,
            request.receiver,
            request.token,
            request.amount,
            request.refChainId,
            request.refId,
            request.burnAccount
        );
    }

    function executeDelayedTransfer(bytes32 id) external whenNotPaused {
        delayedTransfer memory transfer = _executeDelayedTransfer(id);
        _sendToken(transfer.receiver, transfer.token, transfer.amount);
    }

    function setMinDeposit(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            minDeposit[_tokens[i]] = _amounts[i];
            emit MinDepositUpdated(_tokens[i], _amounts[i]);
        }
    }

    function setMaxDeposit(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            maxDeposit[_tokens[i]] = _amounts[i];
            emit MaxDepositUpdated(_tokens[i], _amounts[i]);
        }
    }

    function setWrap(address _weth) external onlyOwner {
        nativeWrap = _weth;
    }

    function _sendToken(
        address _receiver,
        address _token,
        uint256 _amount
    ) private {
        if (_token == nativeWrap) {
            // withdraw then transfer native to receiver
            IWETH(nativeWrap).withdraw(_amount);
            (bool sent, ) = _receiver.call{value: _amount, gas: 50000}("");
            require(sent, "failed to send native token");
        } else {
            IERC20(_token).safeTransfer(_receiver, _amount);
        }
    }

    receive() external payable {}
}

File 25 of 75 : SwapBridgeToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

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

interface ISwapCanoToken {
    function swapBridgeForCanonical(address, uint256) external returns (uint256);

    function swapCanonicalForBridge(address, uint256) external returns (uint256);
}

/**
 * @title Per bridge intermediary token that supports swapping with a canonical token.
 */
contract SwapBridgeToken is ERC20, Ownable {
    using SafeERC20 for IERC20;

    address public bridge;
    address public immutable canonical; // canonical token that support swap

    event BridgeUpdated(address bridge);

    modifier onlyBridge() {
        require(msg.sender == bridge, "caller is not bridge");
        _;
    }

    constructor(
        string memory name_,
        string memory symbol_,
        address bridge_,
        address canonical_
    ) ERC20(name_, symbol_) {
        bridge = bridge_;
        canonical = canonical_;
    }

    function mint(address _to, uint256 _amount) external onlyBridge returns (bool) {
        _mint(address(this), _amount); // add amount to myself so swapBridgeForCanonical can transfer amount
        uint256 got = ISwapCanoToken(canonical).swapBridgeForCanonical(address(this), _amount);
        // now this has canonical token, next step is to transfer to user
        IERC20(canonical).safeTransfer(_to, got);
        return true;
    }

    function burn(address _from, uint256 _amount) external onlyBridge returns (bool) {
        IERC20(canonical).safeTransferFrom(_from, address(this), _amount);
        uint256 got = ISwapCanoToken(canonical).swapCanonicalForBridge(address(this), _amount);
        _burn(address(this), got);
        return true;
    }

    function updateBridge(address _bridge) external onlyOwner {
        bridge = _bridge;
        emit BridgeUpdated(bridge);
    }

    // approve canonical token so swapBridgeForCanonical can work. or we approve before call it in mint w/ added gas
    function approveCanonical() external onlyOwner {
        _approve(address(this), canonical, type(uint256).max);
    }

    function revokeCanonical() external onlyOwner {
        _approve(address(this), canonical, 0);
    }

    // to make compatible with BEP20
    function getOwner() external view returns (address) {
        return owner();
    }

    function decimals() public view virtual override returns (uint8) {
        return ERC20(canonical).decimals();
    }
}

File 26 of 75 : ERC20.sol
// SPDX-License-Identifier: MIT

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.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin guidelines: functions revert instead
 * of 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}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * 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 value {ERC20} uses, unless this function is
     * 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:
     *
     * - `recipient` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(_msgSender(), recipient, 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}.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(_msgSender(), 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}.
     *
     * Requirements:
     *
     * - `sender` and `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     * - the caller must have allowance for ``sender``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);

        uint256 currentAllowance = _allowances[sender][_msgSender()];
        require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
        unchecked {
            _approve(sender, _msgSender(), currentAllowance - 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) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][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) {
        uint256 currentAllowance = _allowances[_msgSender()][spender];
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(_msgSender(), spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `sender` to `recipient`.
     *
     * 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:
     *
     * - `sender` cannot be the zero address.
     * - `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     */
    function _transfer(
        address sender,
        address recipient,
        uint256 amount
    ) internal virtual {
        require(sender != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(sender, recipient, amount);

        uint256 senderBalance = _balances[sender];
        require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[sender] = senderBalance - amount;
        }
        _balances[recipient] += amount;

        emit Transfer(sender, recipient, amount);

        _afterTokenTransfer(sender, recipient, 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;
        _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;
        }
        _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 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 27 of 75 : IERC20Metadata.sol
// SPDX-License-Identifier: MIT

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 28 of 75 : DummySwap.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

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

contract DummySwap {
    using SafeERC20 for IERC20;

    uint256 fakeSlippage; // 100% = 100 * 1e4
    uint256 hundredPercent = 100 * 1e4;

    constructor(uint256 _fakeSlippage) {
        fakeSlippage = _fakeSlippage;
    }

    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts) {
        require(deadline != 0 && deadline > block.timestamp, "deadline exceeded");
        require(path.length > 1, "path must have more than 1 token in it");
        IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn);
        // fake simulate slippage
        uint256 amountAfterSlippage = (amountIn * (hundredPercent - fakeSlippage)) / hundredPercent;
        require(amountAfterSlippage > amountOutMin, "bad slippage");

        IERC20(path[path.length - 1]).safeTransfer(to, amountAfterSlippage);
        uint256[] memory ret = new uint256[](2);
        ret[0] = amountIn;
        ret[1] = amountAfterSlippage;
        return ret;
    }

    function setFakeSlippage(uint256 _fakeSlippage) public {
        fakeSlippage = _fakeSlippage;
    }
}

File 29 of 75 : StakingReward.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {DataTypes as dt} from "./libraries/DataTypes.sol";
import "./safeguard/Pauser.sol";
import "./Staking.sol";

contract StakingReward is Pauser {
    using SafeERC20 for IERC20;

    Staking public immutable staking;

    // recipient => CELR reward amount
    mapping(address => uint256) public claimedRewardAmounts;

    event StakingRewardClaimed(address indexed recipient, uint256 reward);
    event StakingRewardContributed(address indexed contributor, uint256 contribution);

    constructor(Staking _staking) {
        staking = _staking;
    }

    /**
     * @notice Claim reward
     * @dev Here we use cumulative reward to make claim process idempotent
     * @param _rewardRequest reward request bytes coded in protobuf
     * @param _sigs list of validator signatures
     */
    function claimReward(bytes calldata _rewardRequest, bytes[] calldata _sigs) external whenNotPaused {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "StakingReward"));
        staking.verifySignatures(abi.encodePacked(domain, _rewardRequest), _sigs);
        PbStaking.StakingReward memory reward = PbStaking.decStakingReward(_rewardRequest);

        uint256 cumulativeRewardAmount = reward.cumulativeRewardAmount;
        uint256 newReward = cumulativeRewardAmount - claimedRewardAmounts[reward.recipient];
        require(newReward > 0, "No new reward");
        claimedRewardAmounts[reward.recipient] = cumulativeRewardAmount;
        staking.CELER_TOKEN().safeTransfer(reward.recipient, newReward);
        emit StakingRewardClaimed(reward.recipient, newReward);
    }

    /**
     * @notice Contribute CELR tokens to the reward pool
     * @param _amount the amount of CELR token to contribute
     */
    function contributeToRewardPool(uint256 _amount) external whenNotPaused {
        address contributor = msg.sender;
        IERC20(staking.CELER_TOKEN()).safeTransferFrom(contributor, address(this), _amount);

        emit StakingRewardContributed(contributor, _amount);
    }

    /**
     * @notice Owner drains CELR tokens when the contract is paused
     * @dev emergency use only
     * @param _amount drained CELR token amount
     */
    function drainToken(uint256 _amount) external whenPaused onlyOwner {
        IERC20(staking.CELER_TOKEN()).safeTransfer(msg.sender, _amount);
    }
}

File 30 of 75 : DataTypes.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

library DataTypes {
    uint256 constant CELR_DECIMAL = 1e18;
    uint256 constant MAX_INT = 2**256 - 1;
    uint256 constant COMMISSION_RATE_BASE = 10000; // 1 commissionRate means 0.01%
    uint256 constant MAX_UNDELEGATION_ENTRIES = 10;
    uint256 constant SLASH_FACTOR_DECIMAL = 1e6;

    enum ValidatorStatus {
        Null,
        Unbonded,
        Unbonding,
        Bonded
    }

    enum ParamName {
        ProposalDeposit,
        VotingPeriod,
        UnbondingPeriod,
        MaxBondedValidators,
        MinValidatorTokens,
        MinSelfDelegation,
        AdvanceNoticePeriod,
        ValidatorBondInterval,
        MaxSlashFactor
    }

    struct Undelegation {
        uint256 shares;
        uint256 creationBlock;
    }

    struct Undelegations {
        mapping(uint256 => Undelegation) queue;
        uint32 head;
        uint32 tail;
    }

    struct Delegator {
        uint256 shares;
        Undelegations undelegations;
    }

    struct Validator {
        ValidatorStatus status;
        address signer;
        uint256 tokens; // sum of all tokens delegated to this validator
        uint256 shares; // sum of all delegation shares
        uint256 undelegationTokens; // tokens being undelegated
        uint256 undelegationShares; // shares of tokens being undelegated
        mapping(address => Delegator) delegators;
        uint256 minSelfDelegation;
        uint64 bondBlock; // cannot become bonded before this block
        uint64 unbondBlock; // cannot become unbonded before this block
        uint64 commissionRate; // equal to real commission rate * COMMISSION_RATE_BASE
    }

    // used for external view output
    struct ValidatorTokens {
        address valAddr;
        uint256 tokens;
    }

    // used for external view output
    struct ValidatorInfo {
        address valAddr;
        ValidatorStatus status;
        address signer;
        uint256 tokens;
        uint256 shares;
        uint256 minSelfDelegation;
        uint64 commissionRate;
    }

    // used for external view output
    struct DelegatorInfo {
        address valAddr;
        uint256 tokens;
        uint256 shares;
        Undelegation[] undelegations;
        uint256 undelegationTokens;
        uint256 withdrawableUndelegationTokens;
    }
}

File 31 of 75 : Staking.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {DataTypes as dt} from "./libraries/DataTypes.sol";
import "./interfaces/ISigsVerifier.sol";
import "./libraries/PbStaking.sol";
import "./safeguard/Pauser.sol";
import "./safeguard/Whitelist.sol";

/**
 * @title A Staking contract shared by all external sidechains and apps
 */
contract Staking is ISigsVerifier, Pauser, Whitelist {
    using SafeERC20 for IERC20;
    using ECDSA for bytes32;

    IERC20 public immutable CELER_TOKEN;

    uint256 public bondedTokens;
    uint256 public nextBondBlock;
    address[] public valAddrs;
    address[] public bondedValAddrs;
    mapping(address => dt.Validator) public validators; // key is valAddr
    mapping(address => address) public signerVals; // signerAddr -> valAddr
    mapping(uint256 => bool) public slashNonces;

    mapping(dt.ParamName => uint256) public params;
    address public govContract;
    address public rewardContract;
    uint256 public forfeiture;

    /* Events */
    event ValidatorNotice(address indexed valAddr, string key, bytes data, address from);
    event ValidatorStatusUpdate(address indexed valAddr, dt.ValidatorStatus indexed status);
    event DelegationUpdate(
        address indexed valAddr,
        address indexed delAddr,
        uint256 valTokens,
        uint256 delShares,
        int256 tokenDiff
    );
    event Undelegated(address indexed valAddr, address indexed delAddr, uint256 amount);
    event Slash(address indexed valAddr, uint64 nonce, uint256 slashAmt);
    event SlashAmtCollected(address indexed recipient, uint256 amount);

    /**
     * @notice Staking constructor
     * @param _celerTokenAddress address of Celer Token Contract
     * @param _proposalDeposit required deposit amount for a governance proposal
     * @param _votingPeriod voting timeout for a governance proposal
     * @param _unbondingPeriod the locking time for funds locked before withdrawn
     * @param _maxBondedValidators the maximum number of bonded validators
     * @param _minValidatorTokens the global minimum token amount requirement for bonded validator
     * @param _minSelfDelegation minimal amount of self-delegated tokens
     * @param _advanceNoticePeriod the wait time after the announcement and prior to the effective date of an update
     * @param _validatorBondInterval min interval between bondValidator
     * @param _maxSlashFactor maximal slashing factor (1e6 = 100%)
     */
    constructor(
        address _celerTokenAddress,
        uint256 _proposalDeposit,
        uint256 _votingPeriod,
        uint256 _unbondingPeriod,
        uint256 _maxBondedValidators,
        uint256 _minValidatorTokens,
        uint256 _minSelfDelegation,
        uint256 _advanceNoticePeriod,
        uint256 _validatorBondInterval,
        uint256 _maxSlashFactor
    ) {
        CELER_TOKEN = IERC20(_celerTokenAddress);

        params[dt.ParamName.ProposalDeposit] = _proposalDeposit;
        params[dt.ParamName.VotingPeriod] = _votingPeriod;
        params[dt.ParamName.UnbondingPeriod] = _unbondingPeriod;
        params[dt.ParamName.MaxBondedValidators] = _maxBondedValidators;
        params[dt.ParamName.MinValidatorTokens] = _minValidatorTokens;
        params[dt.ParamName.MinSelfDelegation] = _minSelfDelegation;
        params[dt.ParamName.AdvanceNoticePeriod] = _advanceNoticePeriod;
        params[dt.ParamName.ValidatorBondInterval] = _validatorBondInterval;
        params[dt.ParamName.MaxSlashFactor] = _maxSlashFactor;
    }

    receive() external payable {}

    /*********************************
     * External and Public Functions *
     *********************************/

    /**
     * @notice Initialize a validator candidate
     * @param _signer signer address
     * @param _minSelfDelegation minimal amount of tokens staked by the validator itself
     * @param _commissionRate the self-declaimed commission rate
     */
    function initializeValidator(
        address _signer,
        uint256 _minSelfDelegation,
        uint64 _commissionRate
    ) external whenNotPaused onlyWhitelisted {
        address valAddr = msg.sender;
        dt.Validator storage validator = validators[valAddr];
        require(validator.status == dt.ValidatorStatus.Null, "Validator is initialized");
        require(validators[_signer].status == dt.ValidatorStatus.Null, "Signer is other validator");
        require(signerVals[valAddr] == address(0), "Validator is other signer");
        require(signerVals[_signer] == address(0), "Signer already used");
        require(_commissionRate <= dt.COMMISSION_RATE_BASE, "Invalid commission rate");
        require(_minSelfDelegation >= params[dt.ParamName.MinSelfDelegation], "Insufficient min self delegation");
        validator.signer = _signer;
        validator.status = dt.ValidatorStatus.Unbonded;
        validator.minSelfDelegation = _minSelfDelegation;
        validator.commissionRate = _commissionRate;
        valAddrs.push(valAddr);
        signerVals[_signer] = valAddr;

        delegate(valAddr, _minSelfDelegation);
        emit ValidatorNotice(valAddr, "init", abi.encode(_signer, _minSelfDelegation, _commissionRate), address(0));
    }

    /**
     * @notice Update validator signer address
     * @param _signer signer address
     */
    function updateValidatorSigner(address _signer) external {
        address valAddr = msg.sender;
        dt.Validator storage validator = validators[valAddr];
        require(validator.status != dt.ValidatorStatus.Null, "Validator not initialized");
        require(signerVals[_signer] == address(0), "Signer already used");
        if (_signer != valAddr) {
            require(validators[_signer].status == dt.ValidatorStatus.Null, "Signer is other validator");
        }

        delete signerVals[validator.signer];
        validator.signer = _signer;
        signerVals[_signer] = valAddr;

        emit ValidatorNotice(valAddr, "signer", abi.encode(_signer), address(0));
    }

    /**
     * @notice Candidate claims to become a bonded validator
     * @dev caller can be either validator owner or signer
     */
    function bondValidator() external {
        address valAddr = msg.sender;
        if (signerVals[msg.sender] != address(0)) {
            valAddr = signerVals[msg.sender];
        }
        dt.Validator storage validator = validators[valAddr];
        require(
            validator.status == dt.ValidatorStatus.Unbonded || validator.status == dt.ValidatorStatus.Unbonding,
            "Invalid validator status"
        );
        require(block.number >= validator.bondBlock, "Bond block not reached");
        require(block.number >= nextBondBlock, "Too frequent validator bond");
        nextBondBlock = block.number + params[dt.ParamName.ValidatorBondInterval];
        require(hasMinRequiredTokens(valAddr, true), "Not have min tokens");

        uint256 maxBondedValidators = params[dt.ParamName.MaxBondedValidators];
        // if the number of validators has not reached the max_validator_num,
        // add validator directly
        if (bondedValAddrs.length < maxBondedValidators) {
            _bondValidator(valAddr);
            _decentralizationCheck(validator.tokens);
            return;
        }
        // if the number of validators has already reached the max_validator_num,
        // add validator only if its tokens is more than the current least bonded validator tokens
        uint256 minTokens = dt.MAX_INT;
        uint256 minTokensIndex;
        for (uint256 i = 0; i < maxBondedValidators; i++) {
            if (validators[bondedValAddrs[i]].tokens < minTokens) {
                minTokensIndex = i;
                minTokens = validators[bondedValAddrs[i]].tokens;
                if (minTokens == 0) {
                    break;
                }
            }
        }
        require(validator.tokens > minTokens, "Insufficient tokens");
        _replaceBondedValidator(valAddr, minTokensIndex);
        _decentralizationCheck(validator.tokens);
    }

    /**
     * @notice Confirm validator status from Unbonding to Unbonded
     * @param _valAddr the address of the validator
     */
    function confirmUnbondedValidator(address _valAddr) external {
        dt.Validator storage validator = validators[_valAddr];
        require(validator.status == dt.ValidatorStatus.Unbonding, "Validator not unbonding");
        require(block.number >= validator.unbondBlock, "Unbond block not reached");

        validator.status = dt.ValidatorStatus.Unbonded;
        delete validator.unbondBlock;
        emit ValidatorStatusUpdate(_valAddr, dt.ValidatorStatus.Unbonded);
    }

    /**
     * @notice Delegate CELR tokens to a validator
     * @dev Minimal amount per delegate operation is 1 CELR
     * @param _valAddr validator to delegate
     * @param _tokens the amount of delegated CELR tokens
     */
    function delegate(address _valAddr, uint256 _tokens) public whenNotPaused {
        address delAddr = msg.sender;
        require(_tokens >= dt.CELR_DECIMAL, "Minimal amount is 1 CELR");

        dt.Validator storage validator = validators[_valAddr];
        require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
        uint256 shares = _tokenToShare(_tokens, validator.tokens, validator.shares);

        dt.Delegator storage delegator = validator.delegators[delAddr];
        delegator.shares += shares;
        validator.shares += shares;
        validator.tokens += _tokens;
        if (validator.status == dt.ValidatorStatus.Bonded) {
            bondedTokens += _tokens;
            _decentralizationCheck(validator.tokens);
        }
        CELER_TOKEN.safeTransferFrom(delAddr, address(this), _tokens);
        emit DelegationUpdate(_valAddr, delAddr, validator.tokens, delegator.shares, int256(_tokens));
    }

    /**
     * @notice Undelegate shares from a validator
     * @dev Tokens are delegated by the msgSender to the validator
     * @param _valAddr the address of the validator
     * @param _shares undelegate shares
     */
    function undelegateShares(address _valAddr, uint256 _shares) external {
        require(_shares >= dt.CELR_DECIMAL, "Minimal amount is 1 share");
        dt.Validator storage validator = validators[_valAddr];
        require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
        uint256 tokens = _shareToToken(_shares, validator.tokens, validator.shares);
        _undelegate(validator, _valAddr, tokens, _shares);
    }

    /**
     * @notice Undelegate shares from a validator
     * @dev Tokens are delegated by the msgSender to the validator
     * @param _valAddr the address of the validator
     * @param _tokens undelegate tokens
     */
    function undelegateTokens(address _valAddr, uint256 _tokens) external {
        require(_tokens >= dt.CELR_DECIMAL, "Minimal amount is 1 CELR");
        dt.Validator storage validator = validators[_valAddr];
        require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
        uint256 shares = _tokenToShare(_tokens, validator.tokens, validator.shares);
        _undelegate(validator, _valAddr, _tokens, shares);
    }

    /**
     * @notice Complete pending undelegations from a validator
     * @param _valAddr the address of the validator
     */
    function completeUndelegate(address _valAddr) external {
        address delAddr = msg.sender;
        dt.Validator storage validator = validators[_valAddr];
        require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
        dt.Delegator storage delegator = validator.delegators[delAddr];

        uint256 unbondingPeriod = params[dt.ParamName.UnbondingPeriod];
        bool isUnbonded = validator.status == dt.ValidatorStatus.Unbonded;
        // for all pending undelegations
        uint32 i;
        uint256 undelegationShares;
        for (i = delegator.undelegations.head; i < delegator.undelegations.tail; i++) {
            if (isUnbonded || delegator.undelegations.queue[i].creationBlock + unbondingPeriod <= block.number) {
                // complete undelegation when the validator becomes unbonded or
                // the unbondingPeriod for the pending undelegation is up.
                undelegationShares += delegator.undelegations.queue[i].shares;
                delete delegator.undelegations.queue[i];
                continue;
            }
            break;
        }
        delegator.undelegations.head = i;

        require(undelegationShares > 0, "No undelegation ready to be completed");
        uint256 tokens = _shareToToken(undelegationShares, validator.undelegationTokens, validator.undelegationShares);
        validator.undelegationShares -= undelegationShares;
        validator.undelegationTokens -= tokens;
        CELER_TOKEN.safeTransfer(delAddr, tokens);
        emit Undelegated(_valAddr, delAddr, tokens);
    }

    /**
     * @notice Update commission rate
     * @param _newRate new commission rate
     */
    function updateCommissionRate(uint64 _newRate) external {
        address valAddr = msg.sender;
        dt.Validator storage validator = validators[valAddr];
        require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
        require(_newRate <= dt.COMMISSION_RATE_BASE, "Invalid new rate");
        validator.commissionRate = _newRate;
        emit ValidatorNotice(valAddr, "commission", abi.encode(_newRate), address(0));
    }

    /**
     * @notice Update minimal self delegation value
     * @param _minSelfDelegation minimal amount of tokens staked by the validator itself
     */
    function updateMinSelfDelegation(uint256 _minSelfDelegation) external {
        address valAddr = msg.sender;
        dt.Validator storage validator = validators[valAddr];
        require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
        require(_minSelfDelegation >= params[dt.ParamName.MinSelfDelegation], "Insufficient min self delegation");
        if (_minSelfDelegation < validator.minSelfDelegation) {
            require(validator.status != dt.ValidatorStatus.Bonded, "Validator is bonded");
            validator.bondBlock = uint64(block.number + params[dt.ParamName.AdvanceNoticePeriod]);
        }
        validator.minSelfDelegation = _minSelfDelegation;
        emit ValidatorNotice(valAddr, "min-self-delegation", abi.encode(_minSelfDelegation), address(0));
    }

    /**
     * @notice Slash a validator and its delegators
     * @param _slashRequest slash request bytes coded in protobuf
     * @param _sigs list of validator signatures
     */
    function slash(bytes calldata _slashRequest, bytes[] calldata _sigs) external whenNotPaused {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Slash"));
        verifySignatures(abi.encodePacked(domain, _slashRequest), _sigs);

        PbStaking.Slash memory request = PbStaking.decSlash(_slashRequest);
        require(block.timestamp < request.expireTime, "Slash expired");
        require(request.slashFactor <= dt.SLASH_FACTOR_DECIMAL, "Invalid slash factor");
        require(request.slashFactor <= params[dt.ParamName.MaxSlashFactor], "Exceed max slash factor");
        require(!slashNonces[request.nonce], "Used slash nonce");
        slashNonces[request.nonce] = true;

        address valAddr = request.validator;
        dt.Validator storage validator = validators[valAddr];
        require(
            validator.status == dt.ValidatorStatus.Bonded || validator.status == dt.ValidatorStatus.Unbonding,
            "Invalid validator status"
        );

        // slash delegated tokens
        uint256 slashAmt = (validator.tokens * request.slashFactor) / dt.SLASH_FACTOR_DECIMAL;
        validator.tokens -= slashAmt;
        if (validator.status == dt.ValidatorStatus.Bonded) {
            bondedTokens -= slashAmt;
            if (request.jailPeriod > 0 || !hasMinRequiredTokens(valAddr, true)) {
                _unbondValidator(valAddr);
            }
        }
        if (validator.status == dt.ValidatorStatus.Unbonding && request.jailPeriod > 0) {
            validator.bondBlock = uint64(block.number + request.jailPeriod);
        }
        emit DelegationUpdate(valAddr, address(0), validator.tokens, 0, -int256(slashAmt));

        // slash pending undelegations
        uint256 slashUndelegation = (validator.undelegationTokens * request.slashFactor) / dt.SLASH_FACTOR_DECIMAL;
        validator.undelegationTokens -= slashUndelegation;
        slashAmt += slashUndelegation;

        uint256 collectAmt;
        for (uint256 i = 0; i < request.collectors.length; i++) {
            PbStaking.AcctAmtPair memory collector = request.collectors[i];
            if (collectAmt + collector.amount > slashAmt) {
                collector.amount = slashAmt - collectAmt;
            }
            if (collector.amount > 0) {
                collectAmt += collector.amount;
                if (collector.account == address(0)) {
                    CELER_TOKEN.safeTransfer(msg.sender, collector.amount);
                    emit SlashAmtCollected(msg.sender, collector.amount);
                } else {
                    CELER_TOKEN.safeTransfer(collector.account, collector.amount);
                    emit SlashAmtCollected(collector.account, collector.amount);
                }
            }
        }
        forfeiture += slashAmt - collectAmt;
        emit Slash(valAddr, request.nonce, slashAmt);
    }

    function collectForfeiture() external {
        require(forfeiture > 0, "Nothing to collect");
        CELER_TOKEN.safeTransfer(rewardContract, forfeiture);
        forfeiture = 0;
    }

    /**
     * @notice Validator notice event, could be triggered by anyone
     */
    function validatorNotice(
        address _valAddr,
        string calldata _key,
        bytes calldata _data
    ) external {
        dt.Validator storage validator = validators[_valAddr];
        require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
        emit ValidatorNotice(_valAddr, _key, _data, msg.sender);
    }

    function setParamValue(dt.ParamName _name, uint256 _value) external {
        require(msg.sender == govContract, "Caller is not gov contract");
        if (_name == dt.ParamName.MaxBondedValidators) {
            require(bondedValAddrs.length <= _value, "invalid value");
        }
        params[_name] = _value;
    }

    function setGovContract(address _addr) external onlyOwner {
        govContract = _addr;
    }

    function setRewardContract(address _addr) external onlyOwner {
        rewardContract = _addr;
    }

    /**
     * @notice Set max slash factor
     */
    function setMaxSlashFactor(uint256 _maxSlashFactor) external onlyOwner {
        params[dt.ParamName.MaxSlashFactor] = _maxSlashFactor;
    }

    /**
     * @notice Owner drains tokens when the contract is paused
     * @dev emergency use only
     * @param _amount drained token amount
     */
    function drainToken(uint256 _amount) external whenPaused onlyOwner {
        CELER_TOKEN.safeTransfer(msg.sender, _amount);
    }

    /**************************
     *  Public View Functions *
     **************************/

    /**
     * @notice Validate if a message is signed by quorum tokens
     * @param _msg signed message
     * @param _sigs list of validator signatures
     */
    function verifySignatures(bytes memory _msg, bytes[] memory _sigs) public view returns (bool) {
        bytes32 hash = keccak256(_msg).toEthSignedMessageHash();
        uint256 signedTokens;
        address prev = address(0);
        uint256 quorum = getQuorumTokens();
        for (uint256 i = 0; i < _sigs.length; i++) {
            address signer = hash.recover(_sigs[i]);
            require(signer > prev, "Signers not in ascending order");
            prev = signer;
            dt.Validator storage validator = validators[signerVals[signer]];
            if (validator.status != dt.ValidatorStatus.Bonded) {
                continue;
            }
            signedTokens += validator.tokens;
            if (signedTokens >= quorum) {
                return true;
            }
        }
        revert("Quorum not reached");
    }

    /**
     * @notice Verifies that a message is signed by a quorum among the validators.
     * @param _msg signed message
     * @param _sigs the list of signatures
     */
    function verifySigs(
        bytes memory _msg,
        bytes[] calldata _sigs,
        address[] calldata,
        uint256[] calldata
    ) public view override {
        require(verifySignatures(_msg, _sigs), "Failed to verify sigs");
    }

    /**
     * @notice Get quorum amount of tokens
     * @return the quorum amount
     */
    function getQuorumTokens() public view returns (uint256) {
        return (bondedTokens * 2) / 3 + 1;
    }

    /**
     * @notice Get validator info
     * @param _valAddr the address of the validator
     * @return Validator token amount
     */
    function getValidatorTokens(address _valAddr) public view returns (uint256) {
        return validators[_valAddr].tokens;
    }

    /**
     * @notice Get validator info
     * @param _valAddr the address of the validator
     * @return Validator status
     */
    function getValidatorStatus(address _valAddr) public view returns (dt.ValidatorStatus) {
        return validators[_valAddr].status;
    }

    /**
     * @notice Check the given address is a validator or not
     * @param _addr the address to check
     * @return the given address is a validator or not
     */
    function isBondedValidator(address _addr) public view returns (bool) {
        return validators[_addr].status == dt.ValidatorStatus.Bonded;
    }

    /**
     * @notice Get the number of validators
     * @return the number of validators
     */
    function getValidatorNum() public view returns (uint256) {
        return valAddrs.length;
    }

    /**
     * @notice Get the number of bonded validators
     * @return the number of bonded validators
     */
    function getBondedValidatorNum() public view returns (uint256) {
        return bondedValAddrs.length;
    }

    /**
     * @return addresses and token amounts of bonded validators
     */
    function getBondedValidatorsTokens() public view returns (dt.ValidatorTokens[] memory) {
        dt.ValidatorTokens[] memory infos = new dt.ValidatorTokens[](bondedValAddrs.length);
        for (uint256 i = 0; i < bondedValAddrs.length; i++) {
            address valAddr = bondedValAddrs[i];
            infos[i] = dt.ValidatorTokens(valAddr, validators[valAddr].tokens);
        }
        return infos;
    }

    /**
     * @notice Check if min token requirements are met
     * @param _valAddr the address of the validator
     * @param _checkSelfDelegation check self delegation
     */
    function hasMinRequiredTokens(address _valAddr, bool _checkSelfDelegation) public view returns (bool) {
        dt.Validator storage v = validators[_valAddr];
        uint256 valTokens = v.tokens;
        if (valTokens < params[dt.ParamName.MinValidatorTokens]) {
            return false;
        }
        if (_checkSelfDelegation) {
            uint256 selfDelegation = _shareToToken(v.delegators[_valAddr].shares, valTokens, v.shares);
            if (selfDelegation < v.minSelfDelegation) {
                return false;
            }
        }
        return true;
    }

    /**
     * @notice Get the delegator info of a specific validator
     * @param _valAddr the address of the validator
     * @param _delAddr the address of the delegator
     * @return DelegatorInfo from the given validator
     */
    function getDelegatorInfo(address _valAddr, address _delAddr) public view returns (dt.DelegatorInfo memory) {
        dt.Validator storage validator = validators[_valAddr];
        dt.Delegator storage d = validator.delegators[_delAddr];
        uint256 tokens = _shareToToken(d.shares, validator.tokens, validator.shares);

        uint256 undelegationShares;
        uint256 withdrawableUndelegationShares;
        uint256 unbondingPeriod = params[dt.ParamName.UnbondingPeriod];
        bool isUnbonded = validator.status == dt.ValidatorStatus.Unbonded;
        uint256 len = d.undelegations.tail - d.undelegations.head;
        dt.Undelegation[] memory undelegations = new dt.Undelegation[](len);
        for (uint256 i = 0; i < len; i++) {
            undelegations[i] = d.undelegations.queue[i + d.undelegations.head];
            undelegationShares += undelegations[i].shares;
            if (isUnbonded || undelegations[i].creationBlock + unbondingPeriod <= block.number) {
                withdrawableUndelegationShares += undelegations[i].shares;
            }
        }
        uint256 undelegationTokens = _shareToToken(
            undelegationShares,
            validator.undelegationTokens,
            validator.undelegationShares
        );
        uint256 withdrawableUndelegationTokens = _shareToToken(
            withdrawableUndelegationShares,
            validator.undelegationTokens,
            validator.undelegationShares
        );

        return
            dt.DelegatorInfo(
                _valAddr,
                tokens,
                d.shares,
                undelegations,
                undelegationTokens,
                withdrawableUndelegationTokens
            );
    }

    /**
     * @notice Get the value of a specific uint parameter
     * @param _name the key of this parameter
     * @return the value of this parameter
     */
    function getParamValue(dt.ParamName _name) public view returns (uint256) {
        return params[_name];
    }

    /*********************
     * Private Functions *
     *********************/

    function _undelegate(
        dt.Validator storage validator,
        address _valAddr,
        uint256 _tokens,
        uint256 _shares
    ) private {
        address delAddr = msg.sender;
        dt.Delegator storage delegator = validator.delegators[delAddr];
        delegator.shares -= _shares;
        validator.shares -= _shares;
        validator.tokens -= _tokens;
        if (validator.tokens != validator.shares && delegator.shares <= 2) {
            // Remove residual share caused by rounding error when total shares and tokens are not equal
            validator.shares -= delegator.shares;
            delegator.shares = 0;
        }
        require(delegator.shares == 0 || delegator.shares >= dt.CELR_DECIMAL, "not enough remaining shares");

        if (validator.status == dt.ValidatorStatus.Unbonded) {
            CELER_TOKEN.safeTransfer(delAddr, _tokens);
            emit Undelegated(_valAddr, delAddr, _tokens);
            return;
        } else if (validator.status == dt.ValidatorStatus.Bonded) {
            bondedTokens -= _tokens;
            if (!hasMinRequiredTokens(_valAddr, delAddr == _valAddr)) {
                _unbondValidator(_valAddr);
            }
        }
        require(
            delegator.undelegations.tail - delegator.undelegations.head < dt.MAX_UNDELEGATION_ENTRIES,
            "Exceed max undelegation entries"
        );

        uint256 undelegationShares = _tokenToShare(_tokens, validator.undelegationTokens, validator.undelegationShares);
        validator.undelegationShares += undelegationShares;
        validator.undelegationTokens += _tokens;
        dt.Undelegation storage undelegation = delegator.undelegations.queue[delegator.undelegations.tail];
        undelegation.shares = undelegationShares;
        undelegation.creationBlock = block.number;
        delegator.undelegations.tail++;

        emit DelegationUpdate(_valAddr, delAddr, validator.tokens, delegator.shares, -int256(_tokens));
    }

    /**
     * @notice Set validator to bonded
     * @param _valAddr the address of the validator
     */
    function _setBondedValidator(address _valAddr) private {
        dt.Validator storage validator = validators[_valAddr];
        validator.status = dt.ValidatorStatus.Bonded;
        delete validator.unbondBlock;
        bondedTokens += validator.tokens;
        emit ValidatorStatusUpdate(_valAddr, dt.ValidatorStatus.Bonded);
    }

    /**
     * @notice Set validator to unbonding
     * @param _valAddr the address of the validator
     */
    function _setUnbondingValidator(address _valAddr) private {
        dt.Validator storage validator = validators[_valAddr];
        validator.status = dt.ValidatorStatus.Unbonding;
        validator.unbondBlock = uint64(block.number + params[dt.ParamName.UnbondingPeriod]);
        bondedTokens -= validator.tokens;
        emit ValidatorStatusUpdate(_valAddr, dt.ValidatorStatus.Unbonding);
    }

    /**
     * @notice Bond a validator
     * @param _valAddr the address of the validator
     */
    function _bondValidator(address _valAddr) private {
        bondedValAddrs.push(_valAddr);
        _setBondedValidator(_valAddr);
    }

    /**
     * @notice Replace a bonded validator
     * @param _valAddr the address of the new validator
     * @param _index the index of the validator to be replaced
     */
    function _replaceBondedValidator(address _valAddr, uint256 _index) private {
        _setUnbondingValidator(bondedValAddrs[_index]);
        bondedValAddrs[_index] = _valAddr;
        _setBondedValidator(_valAddr);
    }

    /**
     * @notice Unbond a validator
     * @param _valAddr validator to be removed
     */
    function _unbondValidator(address _valAddr) private {
        uint256 lastIndex = bondedValAddrs.length - 1;
        for (uint256 i = 0; i < bondedValAddrs.length; i++) {
            if (bondedValAddrs[i] == _valAddr) {
                if (i < lastIndex) {
                    bondedValAddrs[i] = bondedValAddrs[lastIndex];
                }
                bondedValAddrs.pop();
                _setUnbondingValidator(_valAddr);
                return;
            }
        }
        revert("Not bonded validator");
    }

    /**
     * @notice Check if one validator has too much power
     * @param _valTokens token amounts of the validator
     */
    function _decentralizationCheck(uint256 _valTokens) private view {
        uint256 bondedValNum = bondedValAddrs.length;
        if (bondedValNum == 2 || bondedValNum == 3) {
            require(_valTokens < getQuorumTokens(), "Single validator should not have quorum tokens");
        } else if (bondedValNum > 3) {
            require(_valTokens < bondedTokens / 3, "Single validator should not have 1/3 tokens");
        }
    }

    /**
     * @notice Convert token to share
     */
    function _tokenToShare(
        uint256 tokens,
        uint256 totalTokens,
        uint256 totalShares
    ) private pure returns (uint256) {
        if (totalTokens == 0) {
            return tokens;
        }
        return (tokens * totalShares) / totalTokens;
    }

    /**
     * @notice Convert share to token
     */
    function _shareToToken(
        uint256 shares,
        uint256 totalTokens,
        uint256 totalShares
    ) private pure returns (uint256) {
        if (totalShares == 0) {
            return shares;
        }
        return (shares * totalTokens) / totalShares;
    }
}

File 32 of 75 : PbStaking.sol
// SPDX-License-Identifier: GPL-3.0-only

// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: contracts/libraries/proto/staking.proto
pragma solidity 0.8.9;
import "./Pb.sol";

library PbStaking {
    using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj

    struct StakingReward {
        address recipient; // tag: 1
        uint256 cumulativeRewardAmount; // tag: 2
    } // end struct StakingReward

    function decStakingReward(bytes memory raw) internal pure returns (StakingReward memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.recipient = Pb._address(buf.decBytes());
            } else if (tag == 2) {
                m.cumulativeRewardAmount = Pb._uint256(buf.decBytes());
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder StakingReward

    struct Slash {
        address validator; // tag: 1
        uint64 nonce; // tag: 2
        uint64 slashFactor; // tag: 3
        uint64 expireTime; // tag: 4
        uint64 jailPeriod; // tag: 5
        AcctAmtPair[] collectors; // tag: 6
    } // end struct Slash

    function decSlash(bytes memory raw) internal pure returns (Slash memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256[] memory cnts = buf.cntTags(6);
        m.collectors = new AcctAmtPair[](cnts[6]);
        cnts[6] = 0; // reset counter for later use

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.validator = Pb._address(buf.decBytes());
            } else if (tag == 2) {
                m.nonce = uint64(buf.decVarint());
            } else if (tag == 3) {
                m.slashFactor = uint64(buf.decVarint());
            } else if (tag == 4) {
                m.expireTime = uint64(buf.decVarint());
            } else if (tag == 5) {
                m.jailPeriod = uint64(buf.decVarint());
            } else if (tag == 6) {
                m.collectors[cnts[6]] = decAcctAmtPair(buf.decBytes());
                cnts[6]++;
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder Slash

    struct AcctAmtPair {
        address account; // tag: 1
        uint256 amount; // tag: 2
    } // end struct AcctAmtPair

    function decAcctAmtPair(bytes memory raw) internal pure returns (AcctAmtPair memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.account = Pb._address(buf.decBytes());
            } else if (tag == 2) {
                m.amount = Pb._uint256(buf.decBytes());
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder AcctAmtPair
}

File 33 of 75 : Whitelist.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/access/Ownable.sol";

abstract contract Whitelist is Ownable {
    mapping(address => bool) public whitelist;
    bool public whitelistEnabled;

    event WhitelistedAdded(address account);
    event WhitelistedRemoved(address account);

    modifier onlyWhitelisted() {
        if (whitelistEnabled) {
            require(isWhitelisted(msg.sender), "Caller is not whitelisted");
        }
        _;
    }

    /**
     * @notice Set whitelistEnabled
     */
    function setWhitelistEnabled(bool _whitelistEnabled) external onlyOwner {
        whitelistEnabled = _whitelistEnabled;
    }

    /**
     * @notice Add an account to whitelist
     */
    function addWhitelisted(address account) external onlyOwner {
        require(!isWhitelisted(account), "Already whitelisted");
        whitelist[account] = true;
        emit WhitelistedAdded(account);
    }

    /**
     * @notice Remove an account from whitelist
     */
    function removeWhitelisted(address account) external onlyOwner {
        require(isWhitelisted(account), "Not whitelisted");
        whitelist[account] = false;
        emit WhitelistedRemoved(account);
    }

    /**
     * @return is account whitelisted
     */
    function isWhitelisted(address account) public view returns (bool) {
        return whitelist[account];
    }
}

File 34 of 75 : Viewer.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import {DataTypes as dt} from "./libraries/DataTypes.sol";
import "./Staking.sol";

/**
 * @title Viewer of the staking contract
 * @notice Using a separate viewer contract to reduce staking contract size
 */
contract Viewer {
    Staking public immutable staking;

    constructor(Staking _staking) {
        staking = _staking;
    }

    function getValidatorInfos() public view returns (dt.ValidatorInfo[] memory) {
        uint256 valNum = staking.getValidatorNum();
        dt.ValidatorInfo[] memory infos = new dt.ValidatorInfo[](valNum);
        for (uint32 i = 0; i < valNum; i++) {
            infos[i] = getValidatorInfo(staking.valAddrs(i));
        }
        return infos;
    }

    function getBondedValidatorInfos() public view returns (dt.ValidatorInfo[] memory) {
        uint256 bondedValNum = staking.getBondedValidatorNum();
        dt.ValidatorInfo[] memory infos = new dt.ValidatorInfo[](bondedValNum);
        for (uint32 i = 0; i < bondedValNum; i++) {
            infos[i] = getValidatorInfo(staking.bondedValAddrs(i));
        }
        return infos;
    }

    function getValidatorInfo(address _valAddr) public view returns (dt.ValidatorInfo memory) {
        (
            dt.ValidatorStatus status,
            address signer,
            uint256 tokens,
            uint256 shares,
            ,
            ,
            uint256 minSelfDelegation,
            ,
            ,
            uint64 commissionRate
        ) = staking.validators(_valAddr);
        return
            dt.ValidatorInfo({
                valAddr: _valAddr,
                status: status,
                signer: signer,
                tokens: tokens,
                shares: shares,
                minSelfDelegation: minSelfDelegation,
                commissionRate: commissionRate
            });
    }

    function getDelegatorInfos(address _delAddr) public view returns (dt.DelegatorInfo[] memory) {
        uint256 valNum = staking.getValidatorNum();
        dt.DelegatorInfo[] memory infos = new dt.DelegatorInfo[](valNum);
        uint32 num = 0;
        for (uint32 i = 0; i < valNum; i++) {
            address valAddr = staking.valAddrs(i);
            infos[i] = staking.getDelegatorInfo(valAddr, _delAddr);
            if (infos[i].shares != 0 || infos[i].undelegationTokens != 0) {
                num++;
            }
        }
        dt.DelegatorInfo[] memory res = new dt.DelegatorInfo[](num);
        uint32 j = 0;
        for (uint32 i = 0; i < valNum; i++) {
            if (infos[i].shares != 0 || infos[i].undelegationTokens != 0) {
                res[j] = infos[i];
                j++;
            }
        }
        return res;
    }

    function getDelegatorTokens(address _delAddr) public view returns (uint256, uint256) {
        dt.DelegatorInfo[] memory infos = getDelegatorInfos(_delAddr);
        uint256 tokens;
        uint256 undelegationTokens;
        for (uint32 i = 0; i < infos.length; i++) {
            tokens += infos[i].tokens;
            undelegationTokens += infos[i].undelegationTokens;
        }
        return (tokens, undelegationTokens);
    }

    /**
     * @notice Get the minimum staking pool of all bonded validators
     * @return the minimum staking pool of all bonded validators
     */
    function getMinValidatorTokens() public view returns (uint256) {
        uint256 bondedValNum = staking.getBondedValidatorNum();
        if (bondedValNum < staking.params(dt.ParamName.MaxBondedValidators)) {
            return 0;
        }
        uint256 minTokens = dt.MAX_INT;
        for (uint256 i = 0; i < bondedValNum; i++) {
            uint256 tokens = staking.getValidatorTokens(staking.bondedValAddrs(i));
            if (tokens < minTokens) {
                minTokens = tokens;
                if (minTokens == 0) {
                    return 0;
                }
            }
        }
        return minTokens;
    }

    function shouldBondValidator(address _valAddr) public view returns (bool) {
        (dt.ValidatorStatus status, , uint256 tokens, , , , , uint64 bondBlock, , ) = staking.validators(_valAddr);
        if (status == dt.ValidatorStatus.Null || status == dt.ValidatorStatus.Bonded) {
            return false;
        }
        if (block.number < bondBlock) {
            return false;
        }
        if (!staking.hasMinRequiredTokens(_valAddr, true)) {
            return false;
        }
        if (tokens <= getMinValidatorTokens()) {
            return false;
        }
        uint256 nextBondBlock = staking.nextBondBlock();
        if (block.number < nextBondBlock) {
            return false;
        }
        return true;
    }
}

File 35 of 75 : SGN.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {DataTypes as dt} from "./libraries/DataTypes.sol";
import "./libraries/PbSgn.sol";
import "./safeguard/Pauser.sol";
import "./Staking.sol";

/**
 * @title contract of SGN chain
 */
contract SGN is Pauser {
    using SafeERC20 for IERC20;

    Staking public immutable staking;
    bytes32[] public deposits;
    // account -> (token -> amount)
    mapping(address => mapping(address => uint256)) public withdrawnAmts;
    mapping(address => bytes) public sgnAddrs;

    /* Events */
    event SgnAddrUpdate(address indexed valAddr, bytes oldAddr, bytes newAddr);
    event Deposit(uint256 depositId, address account, address token, uint256 amount);
    event Withdraw(address account, address token, uint256 amount);

    /**
     * @notice SGN constructor
     * @dev Need to deploy Staking contract first before deploying SGN contract
     * @param _staking address of Staking Contract
     */
    constructor(Staking _staking) {
        staking = _staking;
    }

    /**
     * @notice Update sgn address
     * @param _sgnAddr the new address in the layer 2 SGN
     */
    function updateSgnAddr(bytes calldata _sgnAddr) external {
        address valAddr = msg.sender;
        if (staking.signerVals(msg.sender) != address(0)) {
            valAddr = staking.signerVals(msg.sender);
        }

        dt.ValidatorStatus status = staking.getValidatorStatus(valAddr);
        require(status == dt.ValidatorStatus.Unbonded, "Not unbonded validator");

        bytes memory oldAddr = sgnAddrs[valAddr];
        sgnAddrs[valAddr] = _sgnAddr;

        staking.validatorNotice(valAddr, "sgn-addr", _sgnAddr);
        emit SgnAddrUpdate(valAddr, oldAddr, _sgnAddr);
    }

    /**a
     * @notice Deposit to SGN
     * @param _amount subscription fee paid along this function call in CELR tokens
     */
    function deposit(address _token, uint256 _amount) external whenNotPaused {
        address msgSender = msg.sender;
        deposits.push(keccak256(abi.encodePacked(msgSender, _token, _amount)));
        IERC20(_token).safeTransferFrom(msgSender, address(this), _amount);
        uint64 depositId = uint64(deposits.length - 1);
        emit Deposit(depositId, msgSender, _token, _amount);
    }

    /**
     * @notice Withdraw token
     * @dev Here we use cumulative amount to make withdrawal process idempotent
     * @param _withdrawalRequest withdrawal request bytes coded in protobuf
     * @param _sigs list of validator signatures
     */
    function withdraw(bytes calldata _withdrawalRequest, bytes[] calldata _sigs) external whenNotPaused {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Withdrawal"));
        staking.verifySignatures(abi.encodePacked(domain, _withdrawalRequest), _sigs);
        PbSgn.Withdrawal memory withdrawal = PbSgn.decWithdrawal(_withdrawalRequest);

        uint256 amount = withdrawal.cumulativeAmount - withdrawnAmts[withdrawal.account][withdrawal.token];
        require(amount > 0, "No new amount to withdraw");
        withdrawnAmts[withdrawal.account][withdrawal.token] = withdrawal.cumulativeAmount;

        IERC20(withdrawal.token).safeTransfer(withdrawal.account, amount);
        emit Withdraw(withdrawal.account, withdrawal.token, amount);
    }

    /**
     * @notice Owner drains one type of tokens when the contract is paused
     * @dev emergency use only
     * @param _amount drained token amount
     */
    function drainToken(address _token, uint256 _amount) external whenPaused onlyOwner {
        IERC20(_token).safeTransfer(msg.sender, _amount);
    }
}

File 36 of 75 : PbSgn.sol
// SPDX-License-Identifier: GPL-3.0-only

// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: contracts/libraries/proto/sgn.proto
pragma solidity 0.8.9;
import "./Pb.sol";

library PbSgn {
    using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj

    struct Withdrawal {
        address account; // tag: 1
        address token; // tag: 2
        uint256 cumulativeAmount; // tag: 3
    } // end struct Withdrawal

    function decWithdrawal(bytes memory raw) internal pure returns (Withdrawal memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.account = Pb._address(buf.decBytes());
            } else if (tag == 2) {
                m.token = Pb._address(buf.decBytes());
            } else if (tag == 3) {
                m.cumulativeAmount = Pb._uint256(buf.decBytes());
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder Withdrawal
}

File 37 of 75 : FarmingRewards.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {DataTypes as dt} from "./libraries/DataTypes.sol";
import "./interfaces/ISigsVerifier.sol";
import "./libraries/PbFarming.sol";
import "./safeguard/Pauser.sol";

contract FarmingRewards is Pauser {
    using SafeERC20 for IERC20;

    ISigsVerifier public immutable sigsVerifier;

    // recipient => tokenAddress => amount
    mapping(address => mapping(address => uint256)) public claimedRewardAmounts;

    event FarmingRewardClaimed(address indexed recipient, address indexed token, uint256 reward);
    event FarmingRewardContributed(address indexed contributor, address indexed token, uint256 contribution);

    constructor(ISigsVerifier _sigsVerifier) {
        sigsVerifier = _sigsVerifier;
    }

    /**
     * @notice Claim rewards
     * @dev Here we use cumulative reward to make claim process idempotent
     * @param _rewardsRequest rewards request bytes coded in protobuf
     * @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 claimRewards(
        bytes calldata _rewardsRequest,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external whenNotPaused {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "FarmingRewards"));
        sigsVerifier.verifySigs(abi.encodePacked(domain, _rewardsRequest), _sigs, _signers, _powers);
        PbFarming.FarmingRewards memory rewards = PbFarming.decFarmingRewards(_rewardsRequest);
        bool hasNewReward;
        for (uint256 i = 0; i < rewards.tokenAddresses.length; i++) {
            address token = rewards.tokenAddresses[i];
            uint256 cumulativeRewardAmount = rewards.cumulativeRewardAmounts[i];
            uint256 newReward = cumulativeRewardAmount - claimedRewardAmounts[rewards.recipient][token];
            if (newReward > 0) {
                hasNewReward = true;
                claimedRewardAmounts[rewards.recipient][token] = cumulativeRewardAmount;
                IERC20(token).safeTransfer(rewards.recipient, newReward);
                emit FarmingRewardClaimed(rewards.recipient, token, newReward);
            }
        }
        require(hasNewReward, "No new reward");
    }

    /**
     * @notice Contribute reward tokens to the reward pool
     * @param _token the address of the token to contribute
     * @param _amount the amount of the token to contribute
     */
    function contributeToRewardPool(address _token, uint256 _amount) external whenNotPaused {
        address contributor = msg.sender;
        IERC20(_token).safeTransferFrom(contributor, address(this), _amount);

        emit FarmingRewardContributed(contributor, _token, _amount);
    }

    /**
     * @notice Owner drains tokens when the contract is paused
     * @dev emergency use only
     * @param _token the address of the token to drain
     * @param _amount drained token amount
     */
    function drainToken(address _token, uint256 _amount) external whenPaused onlyOwner {
        IERC20(_token).safeTransfer(msg.sender, _amount);
    }
}

File 38 of 75 : PbFarming.sol
// SPDX-License-Identifier: GPL-3.0-only

// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: contracts/libraries/proto/farming.proto
pragma solidity 0.8.9;
import "./Pb.sol";

library PbFarming {
    using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj

    struct FarmingRewards {
        address recipient; // tag: 1
        address[] tokenAddresses; // tag: 2
        uint256[] cumulativeRewardAmounts; // tag: 3
    } // end struct FarmingRewards

    function decFarmingRewards(bytes memory raw) internal pure returns (FarmingRewards memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256[] memory cnts = buf.cntTags(3);
        m.tokenAddresses = new address[](cnts[2]);
        cnts[2] = 0; // reset counter for later use
        m.cumulativeRewardAmounts = new uint256[](cnts[3]);
        cnts[3] = 0; // reset counter for later use

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.recipient = Pb._address(buf.decBytes());
            } else if (tag == 2) {
                m.tokenAddresses[cnts[2]] = Pb._address(buf.decBytes());
                cnts[2]++;
            } else if (tag == 3) {
                m.cumulativeRewardAmounts[cnts[3]] = Pb._uint256(buf.decBytes());
                cnts[3]++;
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder FarmingRewards
}

File 39 of 75 : ERC20Burnable.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../ERC20.sol";
import "../../../utils/Context.sol";

/**
 * @dev Extension of {ERC20} that allows token holders to destroy both their own
 * tokens and those that they have an allowance for, in a way that can be
 * recognized off-chain (via event analysis).
 */
abstract contract ERC20Burnable is Context, ERC20 {
    /**
     * @dev Destroys `amount` tokens from the caller.
     *
     * See {ERC20-_burn}.
     */
    function burn(uint256 amount) public virtual {
        _burn(_msgSender(), amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, deducting from the caller's
     * allowance.
     *
     * See {ERC20-_burn} and {ERC20-allowance}.
     *
     * Requirements:
     *
     * - the caller must have allowance for ``accounts``'s tokens of at least
     * `amount`.
     */
    function burnFrom(address account, uint256 amount) public virtual {
        uint256 currentAllowance = allowance(account, _msgSender());
        require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
        unchecked {
            _approve(account, _msgSender(), currentAllowance - amount);
        }
        _burn(account, amount);
    }
}

File 40 of 75 : WETH.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract WETH is ERC20 {
    constructor() ERC20("WETH", "WETH") {}

    function deposit() external payable {
        _mint(msg.sender, msg.value);
    }

    function withdraw(uint256 _amount) external {
        _burn(msg.sender, _amount);
        (bool sent, ) = msg.sender.call{value: _amount, gas: 50000}("");
        require(sent, "failed to send");
    }

    receive() external payable {}
}

File 41 of 75 : TestERC20.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

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

/**
 * @title A test ERC20 token.
 */
contract TestERC20 is ERC20 {
    uint256 public constant INITIAL_SUPPLY = 1e28;

    /**
     * @dev Constructor that gives msg.sender all of the existing tokens.
     */
    constructor() ERC20("TestERC20", "TERC20") {
        _mint(msg.sender, INITIAL_SUPPLY);
    }
}

File 42 of 75 : SingleBridgeToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

/**
 * @title Example Pegged ERC20 token
 */
contract SingleBridgeToken is ERC20, Ownable {
    address public bridge;

    uint8 private immutable _decimals;

    event BridgeUpdated(address bridge);

    modifier onlyBridge() {
        require(msg.sender == bridge, "caller is not bridge");
        _;
    }

    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_,
        address bridge_
    ) ERC20(name_, symbol_) {
        _decimals = decimals_;
        bridge = bridge_;
    }

    function mint(address _to, uint256 _amount) external onlyBridge returns (bool) {
        _mint(_to, _amount);
        return true;
    }

    function burn(address _from, uint256 _amount) external onlyBridge returns (bool) {
        _burn(_from, _amount);
        return true;
    }

    function decimals() public view virtual override returns (uint8) {
        return _decimals;
    }

    function updateBridge(address _bridge) external onlyOwner {
        bridge = _bridge;
        emit BridgeUpdated(bridge);
    }

    // to make compatible with BEP20
    function getOwner() external view returns (address) {
        return owner();
    }
}

File 43 of 75 : SingleBridgeTokenPermit.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
import "../SingleBridgeToken.sol";

/**
 * @title Example Pegged ERC20Permit token
 */
contract SingleBridgeTokenPermit is ERC20Permit, SingleBridgeToken {
    uint8 private immutable _decimals;

    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_,
        address bridge_
    ) SingleBridgeToken(name_, symbol_, decimals_, bridge_) ERC20Permit(name_) {
        _decimals = decimals_;
    }

    function decimals() public view override(ERC20, SingleBridgeToken) returns (uint8) {
        return _decimals;
    }
}

File 44 of 75 : draft-ERC20Permit.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./draft-IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/draft-EIP712.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/Counters.sol";

/**
 * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * _Available since v3.4._
 */
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
    using Counters for Counters.Counter;

    mapping(address => Counters.Counter) private _nonces;

    // solhint-disable-next-line var-name-mixedcase
    bytes32 private immutable _PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");

    /**
     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
     *
     * It's a good idea to use the same `name` that is defined as the ERC20 token name.
     */
    constructor(string memory name) EIP712(name, "1") {}

    /**
     * @dev See {IERC20Permit-permit}.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual override {
        require(block.timestamp <= deadline, "ERC20Permit: expired deadline");

        bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));

        bytes32 hash = _hashTypedDataV4(structHash);

        address signer = ECDSA.recover(hash, v, r, s);
        require(signer == owner, "ERC20Permit: invalid signature");

        _approve(owner, spender, value);
    }

    /**
     * @dev See {IERC20Permit-nonces}.
     */
    function nonces(address owner) public view virtual override returns (uint256) {
        return _nonces[owner].current();
    }

    /**
     * @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view override returns (bytes32) {
        return _domainSeparatorV4();
    }

    /**
     * @dev "Consume a nonce": return the current value and increment.
     *
     * _Available since v4.1._
     */
    function _useNonce(address owner) internal virtual returns (uint256 current) {
        Counters.Counter storage nonce = _nonces[owner];
        current = nonce.current();
        nonce.increment();
    }
}

File 45 of 75 : draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT

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 46 of 75 : draft-EIP712.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./ECDSA.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * _Available since v3.4._
 */
abstract contract EIP712 {
    /* solhint-disable var-name-mixedcase */
    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
    uint256 private immutable _CACHED_CHAIN_ID;

    bytes32 private immutable _HASHED_NAME;
    bytes32 private immutable _HASHED_VERSION;
    bytes32 private immutable _TYPE_HASH;

    /* solhint-enable var-name-mixedcase */

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        bytes32 hashedName = keccak256(bytes(name));
        bytes32 hashedVersion = keccak256(bytes(version));
        bytes32 typeHash = keccak256(
            "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
        );
        _HASHED_NAME = hashedName;
        _HASHED_VERSION = hashedVersion;
        _CACHED_CHAIN_ID = block.chainid;
        _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
        _TYPE_HASH = typeHash;
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (block.chainid == _CACHED_CHAIN_ID) {
            return _CACHED_DOMAIN_SEPARATOR;
        } else {
            return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
        }
    }

    function _buildDomainSeparator(
        bytes32 typeHash,
        bytes32 nameHash,
        bytes32 versionHash
    ) private view returns (bytes32) {
        return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
    }
}

File 47 of 75 : Counters.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @title Counters
 * @author Matt Condon (@shrugs)
 * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
 * of elements in a mapping, issuing ERC721 ids, or counting request ids.
 *
 * Include with `using Counters for Counters.Counter;`
 */
library Counters {
    struct Counter {
        // This variable should never be directly accessed by users of the library: interactions must be restricted to
        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
        // this feature: see https://github.com/ethereum/solidity/issues/4637
        uint256 _value; // default: 0
    }

    function current(Counter storage counter) internal view returns (uint256) {
        return counter._value;
    }

    function increment(Counter storage counter) internal {
        unchecked {
            counter._value += 1;
        }
    }

    function decrement(Counter storage counter) internal {
        uint256 value = counter._value;
        require(value > 0, "Counter: decrement overflow");
        unchecked {
            counter._value = value - 1;
        }
    }

    function reset(Counter storage counter) internal {
        counter._value = 0;
    }
}

File 48 of 75 : MultiBridgeTokenPermit.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
import "../MultiBridgeToken.sol";

/**
 * @title Example Multi-Bridge Pegged ERC20Permit token
 */
contract MultiBridgeTokenPermit is ERC20Permit, MultiBridgeToken {
    uint8 private immutable _decimals;

    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_
    ) MultiBridgeToken(name_, symbol_, decimals_) ERC20Permit(name_) {
        _decimals = decimals_;
    }

    function decimals() public view override(ERC20, MultiBridgeToken) returns (uint8) {
        return _decimals;
    }
}

File 49 of 75 : MultiBridgeToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../safeguard/Ownable.sol";

/**
 * @title Example Multi-Bridge Pegged ERC20 token
 */
contract MultiBridgeToken is ERC20, Ownable {
    struct Supply {
        uint256 cap;
        uint256 total;
    }
    mapping(address => Supply) public bridges; // bridge address -> supply

    uint8 private immutable _decimals;

    event BridgeSupplyCapUpdated(address bridge, uint256 supplyCap);

    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_
    ) ERC20(name_, symbol_) {
        _decimals = decimals_;
    }

    function mint(address _to, uint256 _amount) external returns (bool) {
        Supply storage b = bridges[msg.sender];
        require(b.cap > 0, "invalid caller");
        b.total += _amount;
        require(b.total <= b.cap, "exceeds bridge supply cap");
        _mint(_to, _amount);
        return true;
    }

    function burn(address _from, uint256 _amount) external returns (bool) {
        Supply storage b = bridges[msg.sender];
        require(b.cap > 0, "invalid caller");
        b.total -= _amount;
        _burn(_from, _amount);
        return true;
    }

    function decimals() public view virtual override returns (uint8) {
        return _decimals;
    }

    function updateBridgeSupplyCap(address _bridge, uint256 _cap) external onlyOwner {
        // cap == 0 means revoking bridge role
        bridges[_bridge].cap = _cap;
        emit BridgeSupplyCapUpdated(_bridge, _cap);
    }

    // to make compatible with BEP20
    function getOwner() external view returns (address) {
        return owner();
    }
}

File 50 of 75 : 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 51 of 75 : MessageBusAddress.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

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

abstract contract MessageBusAddress is Ownable {
    address public messageBus;

    function setMessageBus(address _messageBus) public onlyOwner {
        messageBus = _messageBus;
    }
}

File 52 of 75 : TransferSwap.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../framework/MessageBusAddress.sol";
import "../framework/MessageSenderApp.sol";
import "../framework/MessageReceiverApp.sol";
import "../../interfaces/IWETH.sol";
import "../../interfaces/IUniswapV2.sol";

/**
 * @title Demo application contract that facilitates swapping on a chain, transferring to another chain,
 * and swapping another time on the destination chain before sending the result tokens to a user
 */
contract TransferSwap is MessageSenderApp, MessageReceiverApp {
    using SafeERC20 for IERC20;

    modifier onlyEOA() {
        require(msg.sender == tx.origin, "Not EOA");
        _;
    }

    struct SwapInfo {
        // if this array has only one element, it means no need to swap
        address[] path;
        // the following fields are only needed if path.length > 1
        address dex; // the DEX to use for the swap
        uint256 deadline; // deadline for the swap
        uint256 minRecvAmt; // minimum receive amount for the swap
    }

    struct SwapRequest {
        SwapInfo swap;
        // the receiving party (the user) of the final output token
        address receiver;
        // this field is best to be per-user per-transaction unique so that
        // a nonce that is specified by the calling party (the user),
        uint64 nonce;
        // indicates whether the output token coming out of the swap on destination
        // chain should be unwrapped before sending to the user
        bool nativeOut;
    }

    enum SwapStatus {
        Null,
        Succeeded,
        Failed,
        Fallback
    }

    // emitted when requested dstChainId == srcChainId, no bridging
    event DirectSwap(
        bytes32 id,
        uint64 srcChainId,
        uint256 amountIn,
        address tokenIn,
        uint256 amountOut,
        address tokenOut
    );
    event SwapRequestSent(bytes32 id, uint64 dstChainId, uint256 srcAmount, address srcToken, address dstToken);
    event SwapRequestDone(bytes32 id, uint256 dstAmount, SwapStatus status);

    mapping(address => uint256) public minSwapAmounts;
    mapping(address => bool) supportedDex;

    // erc20 wrap of gas token of this chain, eg. WETH
    address public nativeWrap;

    constructor(
        address _messageBus,
        address _supportedDex,
        address _nativeWrap
    ) {
        messageBus = _messageBus;
        supportedDex[_supportedDex] = true;
        nativeWrap = _nativeWrap;
    }

    function transferWithSwapNative(
        address _receiver,
        uint256 _amountIn,
        uint64 _dstChainId,
        SwapInfo calldata _srcSwap,
        SwapInfo calldata _dstSwap,
        uint32 _maxBridgeSlippage,
        uint64 _nonce,
        bool _nativeOut
    ) external payable onlyEOA {
        require(msg.value >= _amountIn, "Amount insufficient");
        require(_srcSwap.path[0] == nativeWrap, "token mismatch");
        IWETH(nativeWrap).deposit{value: _amountIn}();
        _transferWithSwap(
            _receiver,
            _amountIn,
            _dstChainId,
            _srcSwap,
            _dstSwap,
            _maxBridgeSlippage,
            _nonce,
            _nativeOut,
            msg.value - _amountIn
        );
    }

    function transferWithSwap(
        address _receiver,
        uint256 _amountIn,
        uint64 _dstChainId,
        SwapInfo calldata _srcSwap,
        SwapInfo calldata _dstSwap,
        uint32 _maxBridgeSlippage,
        uint64 _nonce
    ) external payable onlyEOA {
        IERC20(_srcSwap.path[0]).safeTransferFrom(msg.sender, address(this), _amountIn);
        _transferWithSwap(
            _receiver,
            _amountIn,
            _dstChainId,
            _srcSwap,
            _dstSwap,
            _maxBridgeSlippage,
            _nonce,
            false,
            msg.value
        );
    }

    /**
     * @notice Sends a cross-chain transfer via the liquidity pool-based bridge and sends a message specifying a wanted swap action on the
               destination chain via the message bus
     * @param _receiver the app contract that implements the MessageReceiver abstract contract
     *        NOTE not to be confused with the receiver field in SwapInfo which is an EOA address of a user
     * @param _amountIn the input amount that the user wants to swap and/or bridge
     * @param _dstChainId destination chain ID
     * @param _srcSwap a struct containing swap related requirements
     * @param _dstSwap a struct containing swap related requirements
     * @param _maxBridgeSlippage the max acceptable slippage at bridge, 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 _fee the fee to pay to MessageBus.
     */
    function _transferWithSwap(
        address _receiver,
        uint256 _amountIn,
        uint64 _dstChainId,
        SwapInfo memory _srcSwap,
        SwapInfo memory _dstSwap,
        uint32 _maxBridgeSlippage,
        uint64 _nonce,
        bool _nativeOut,
        uint256 _fee
    ) private {
        require(_srcSwap.path.length > 0, "empty src swap path");
        address srcTokenOut = _srcSwap.path[_srcSwap.path.length - 1];

        require(_amountIn > minSwapAmounts[_srcSwap.path[0]], "amount must be greater than min swap amount");
        uint64 chainId = uint64(block.chainid);
        require(_srcSwap.path.length > 1 || _dstChainId != chainId, "noop is not allowed"); // revert early to save gas

        uint256 srcAmtOut = _amountIn;

        // swap source token for intermediate token on the source DEX
        if (_srcSwap.path.length > 1) {
            bool ok = true;
            (ok, srcAmtOut) = _trySwap(_srcSwap, _amountIn);
            if (!ok) revert("src swap failed");
        }

        if (_dstChainId == chainId) {
            _directSend(_receiver, _amountIn, chainId, _srcSwap, _nonce, srcTokenOut, srcAmtOut);
        } else {
            _crossChainTransferWithSwap(
                _receiver,
                _amountIn,
                chainId,
                _dstChainId,
                _srcSwap,
                _dstSwap,
                _maxBridgeSlippage,
                _nonce,
                _nativeOut,
                _fee,
                srcTokenOut,
                srcAmtOut
            );
        }
    }

    function _directSend(
        address _receiver,
        uint256 _amountIn,
        uint64 _chainId,
        SwapInfo memory _srcSwap,
        uint64 _nonce,
        address srcTokenOut,
        uint256 srcAmtOut
    ) private {
        // no need to bridge, directly send the tokens to user
        IERC20(srcTokenOut).safeTransfer(_receiver, srcAmtOut);
        // use uint64 for chainid to be consistent with other components in the system
        bytes32 id = keccak256(abi.encode(msg.sender, _chainId, _receiver, _nonce, _srcSwap));
        emit DirectSwap(id, _chainId, _amountIn, _srcSwap.path[0], srcAmtOut, srcTokenOut);
    }

    function _crossChainTransferWithSwap(
        address _receiver,
        uint256 _amountIn,
        uint64 _chainId,
        uint64 _dstChainId,
        SwapInfo memory _srcSwap,
        SwapInfo memory _dstSwap,
        uint32 _maxBridgeSlippage,
        uint64 _nonce,
        bool _nativeOut,
        uint256 _fee,
        address srcTokenOut,
        uint256 srcAmtOut
    ) private {
        require(_dstSwap.path.length > 0, "empty dst swap path");
        bytes memory message = abi.encode(
            SwapRequest({swap: _dstSwap, receiver: msg.sender, nonce: _nonce, nativeOut: _nativeOut})
        );
        bytes32 id = _computeSwapRequestId(msg.sender, _chainId, _dstChainId, message);
        // bridge the intermediate token to destination chain along with the message
        // NOTE In production, it's better use a per-user per-transaction nonce so that it's less likely transferId collision
        // would happen at Bridge contract. Currently this nonce is a timestamp supplied by frontend
        sendMessageWithTransfer(
            _receiver,
            srcTokenOut,
            srcAmtOut,
            _dstChainId,
            _nonce,
            _maxBridgeSlippage,
            message,
            MessageSenderLib.BridgeType.Liquidity,
            _fee
        );
        emit SwapRequestSent(id, _dstChainId, _amountIn, _srcSwap.path[0], _dstSwap.path[_dstSwap.path.length - 1]);
    }

    /**
     * @notice called by MessageBus when the tokens are checked to be arrived at this contract's address.
               sends the amount received to the receiver. swaps beforehand if swap behavior is defined in message
     * NOTE: if the swap fails, it sends the tokens received directly to the receiver as fallback behavior
     * @param _token the address of the token sent through the bridge
     * @param _amount the amount of tokens received at this contract through the cross-chain bridge
     * @param _srcChainId source chain ID
     * @param _message SwapRequest message that defines the swap behavior on this destination chain
     */
    function executeMessageWithTransfer(
        address, // _sender
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes memory _message
    ) external payable override onlyMessageBus returns (bool) {
        SwapRequest memory m = abi.decode((_message), (SwapRequest));
        require(_token == m.swap.path[0], "bridged token must be the same as the first token in destination swap path");
        bytes32 id = _computeSwapRequestId(m.receiver, _srcChainId, uint64(block.chainid), _message);
        uint256 dstAmount;
        SwapStatus status = SwapStatus.Succeeded;

        if (m.swap.path.length > 1) {
            bool ok = true;
            (ok, dstAmount) = _trySwap(m.swap, _amount);
            if (ok) {
                _sendToken(m.swap.path[m.swap.path.length - 1], dstAmount, m.receiver, m.nativeOut);
                status = SwapStatus.Succeeded;
            } else {
                // handle swap failure, send the received token directly to receiver
                _sendToken(_token, _amount, m.receiver, false);
                dstAmount = _amount;
                status = SwapStatus.Fallback;
            }
        } else {
            // no need to swap, directly send the bridged token to user
            _sendToken(m.swap.path[0], _amount, m.receiver, m.nativeOut);
            dstAmount = _amount;
            status = SwapStatus.Succeeded;
        }
        emit SwapRequestDone(id, dstAmount, status);
        // always return true since swap failure is already handled in-place
        return true;
    }

    /**
     * @notice called by MessageBus when the executeMessageWithTransfer call fails. does nothing but emitting a "fail" event
     * @param _srcChainId source chain ID
     * @param _message SwapRequest message that defines the swap behavior on this destination chain
     */
    function executeMessageWithTransferFallback(
        address, // _sender
        address, // _token
        uint256, // _amount
        uint64 _srcChainId,
        bytes memory _message
    ) external payable override onlyMessageBus returns (bool) {
        SwapRequest memory m = abi.decode((_message), (SwapRequest));
        bytes32 id = _computeSwapRequestId(m.receiver, _srcChainId, uint64(block.chainid), _message);
        emit SwapRequestDone(id, 0, SwapStatus.Failed);
        // always return false to mark this transfer as failed since if this function is called then there nothing more
        // we can do in this app as the swap failures are already handled in executeMessageWithTransfer
        return false;
    }

    function _trySwap(SwapInfo memory _swap, uint256 _amount) private returns (bool ok, uint256 amountOut) {
        uint256 zero;
        if (!supportedDex[_swap.dex]) {
            return (false, zero);
        }
        IERC20(_swap.path[0]).safeIncreaseAllowance(_swap.dex, _amount);
        try
            IUniswapV2(_swap.dex).swapExactTokensForTokens(
                _amount,
                _swap.minRecvAmt,
                _swap.path,
                address(this),
                _swap.deadline
            )
        returns (uint256[] memory amounts) {
            return (true, amounts[amounts.length - 1]);
        } catch {
            return (false, zero);
        }
    }

    function _sendToken(
        address _token,
        uint256 _amount,
        address _receiver,
        bool _nativeOut
    ) private {
        if (_nativeOut) {
            require(_token == nativeWrap, "token mismatch");
            IWETH(nativeWrap).withdraw(_amount);
            (bool sent, ) = _receiver.call{value: _amount, gas: 50000}("");
            require(sent, "failed to send native");
        } else {
            IERC20(_token).safeTransfer(_receiver, _amount);
        }
    }

    function _computeSwapRequestId(
        address _sender,
        uint64 _srcChainId,
        uint64 _dstChainId,
        bytes memory _message
    ) private pure returns (bytes32) {
        return keccak256(abi.encodePacked(_sender, _srcChainId, _dstChainId, _message));
    }

    function setMinSwapAmount(address _token, uint256 _minSwapAmount) external onlyOwner {
        minSwapAmounts[_token] = _minSwapAmount;
    }

    function setSupportedDex(address _dex, bool _enabled) external onlyOwner {
        supportedDex[_dex] = _enabled;
    }

    function setNativeWrap(address _nativeWrap) external onlyOwner {
        nativeWrap = _nativeWrap;
    }

    // This is needed to receive ETH when calling `IWETH.withdraw`
    receive() external payable {}
}

File 53 of 75 : MessageSenderApp.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

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

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

abstract contract MessageSenderApp is MessageBusAddress {
    using SafeERC20 for IERC20;

    // ============== Utility 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 _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);
    }

    /**
     * @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 {BridgeType.Liquidity}.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     * @param _bridgeType One of the {BridgeType} 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,
        MessageSenderLib.BridgeType _bridgeType,
        uint256 _fee
    ) internal returns (bytes32) {
        return
            MessageSenderLib.sendMessageWithTransfer(
                _receiver,
                _token,
                _amount,
                _dstChainId,
                _nonce,
                _maxSlippage,
                _message,
                _bridgeType,
                messageBus,
                _fee
            );
    }

    /**
     * @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 _bridgeType One of the {BridgeType} enum.
     */
    function sendTokenTransfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage,
        MessageSenderLib.BridgeType _bridgeType
    ) internal {
        address bridge;
        if (_bridgeType == MessageSenderLib.BridgeType.Liquidity) {
            bridge = MessageBus(messageBus).liquidityBridge();
        } else if (_bridgeType == MessageSenderLib.BridgeType.PegDeposit) {
            bridge = MessageBus(messageBus).pegVault();
        } else if (_bridgeType == MessageSenderLib.BridgeType.PegBurn) {
            bridge = MessageBus(messageBus).pegBridge();
        } else {
            revert("bridge type not supported");
        }
        MessageSenderLib.sendTokenTransfer(
            _receiver,
            _token,
            _amount,
            _dstChainId,
            _nonce,
            _maxSlippage,
            _bridgeType,
            bridge
        );
    }
}

File 54 of 75 : MessageReceiverApp.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

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

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

    /**
     * @notice Called by MessageBus (MessageBusReceiver) if the process is originated from MessageBus (MessageBusSender)'s
     *         sendMessageWithTransfer it is only called when the tokens are checked to be arrived at this contract's address.
     * @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.
     *        the contract that implements this contract can safely assume that the tokens will arrive before this
     *        function is called.
     * @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
     */
    function executeMessageWithTransfer(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes calldata _message
    ) external payable virtual override onlyMessageBus returns (bool) {}

    /**
     * @notice Only called by MessageBus (MessageBusReceiver) if
     *         1. executeMessageWithTransfer reverts, or
     *         2. executeMessageWithTransfer returns false
     * @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.
     *        the contract that implements this contract can safely assume that the tokens will arrive before this
     *        function is called.
     * @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
     */
    function executeMessageWithTransferFallback(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes calldata _message
    ) external payable virtual override onlyMessageBus returns (bool) {}

    /**
     * @notice Called by MessageBus (MessageBusReceiver) to process refund of the original transfer from this contract
     * @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
     */
    function executeMessageWithTransferRefund(
        address _token,
        uint256 _amount,
        bytes calldata _message
    ) external payable virtual override onlyMessageBus returns (bool) {}

    /**
     * @notice Called by MessageBus (MessageBusReceiver)
     * @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
     */
    function executeMessage(
        address _sender,
        uint64 _srcChainId,
        bytes calldata _message
    ) external payable virtual override onlyMessageBus returns (bool) {}
}

File 55 of 75 : IUniswapV2.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

interface IUniswapV2 {
    function swapTokensForExactTokens(
        uint256 amountOut,
        uint256 amountInMax,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);

    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
}

File 56 of 75 : MessageSenderLib.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

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/IPeggedTokenBridge.sol";
import "../messagebus/MessageBus.sol";

library MessageSenderLib {
    using SafeERC20 for IERC20;

    enum BridgeType {
        Null,
        Liquidity,
        PegDeposit,
        PegBurn
    }

    // ============== 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 {
        MessageBus(_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 {BridgeType.Liquidity}.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     * @param _bridgeType One of the {BridgeType} 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,
        BridgeType _bridgeType,
        address _messageBus,
        uint256 _fee
    ) internal returns (bytes32) {
        if (_bridgeType == BridgeType.Liquidity) {
            return
                sendMessageWithLiquidityBridgeTransfer(
                    _receiver,
                    _token,
                    _amount,
                    _dstChainId,
                    _nonce,
                    _maxSlippage,
                    _message,
                    _messageBus,
                    _fee
                );
        } else if (_bridgeType == BridgeType.PegDeposit) {
            return
                sendMessageWithPegVaultDeposit(
                    _receiver,
                    _token,
                    _amount,
                    _dstChainId,
                    _nonce,
                    _message,
                    _messageBus,
                    _fee
                );
        } else if (_bridgeType == BridgeType.PegBurn) {
            return
                sendMessageWithPegBridgeBurn(
                    _receiver,
                    _token,
                    _amount,
                    _dstChainId,
                    _nonce,
                    _message,
                    _messageBus,
                    _fee
                );
        } else {
            revert("bridge type not supported");
        }
    }

    /**
     * @notice Sends a message to an app on another chain via MessageBus with an associated liquidity bridge 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.
     * @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.
     * @return The transfer ID.
     */
    function sendMessageWithLiquidityBridgeTransfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage,
        bytes memory _message,
        address _messageBus,
        uint256 _fee
    ) internal returns (bytes32) {
        address bridge = MessageBus(_messageBus).liquidityBridge();
        IERC20(_token).safeIncreaseAllowance(bridge, _amount);
        IBridge(bridge).send(_receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage);
        bytes32 transferId = keccak256(
            abi.encodePacked(address(this), _receiver, _token, _amount, _dstChainId, _nonce, uint64(block.chainid))
        );
        MessageBus(_messageBus).sendMessageWithTransfer{value: _fee}(
            _receiver,
            _dstChainId,
            bridge,
            transferId,
            _message
        );
        return transferId;
    }

    /**
     * @notice Sends a message to an app on another chain via MessageBus with an associated OriginalTokenVault deposit.
     * @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 _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.
     * @return The transfer ID.
     */
    function sendMessageWithPegVaultDeposit(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        bytes memory _message,
        address _messageBus,
        uint256 _fee
    ) internal returns (bytes32) {
        address pegVault = MessageBus(_messageBus).pegVault();
        IERC20(_token).safeIncreaseAllowance(pegVault, _amount);
        IOriginalTokenVault(pegVault).deposit(_token, _amount, _dstChainId, _receiver, _nonce);
        bytes32 transferId = keccak256(
            abi.encodePacked(address(this), _token, _amount, _dstChainId, _receiver, _nonce, uint64(block.chainid))
        );
        MessageBus(_messageBus).sendMessageWithTransfer{value: _fee}(
            _receiver,
            _dstChainId,
            pegVault,
            transferId,
            _message
        );
        return transferId;
    }

    /**
     * @notice Sends a message to an app on another chain via MessageBus with an associated PeggedTokenBridge burn.
     * @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 _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.
     * @return The transfer ID.
     */
    function sendMessageWithPegBridgeBurn(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        bytes memory _message,
        address _messageBus,
        uint256 _fee
    ) internal returns (bytes32) {
        address pegBridge = MessageBus(_messageBus).pegBridge();
        IPeggedTokenBridge(pegBridge).burn(_token, _amount, _receiver, _nonce);
        bytes32 transferId = keccak256(
            abi.encodePacked(address(this), _token, _amount, _receiver, _nonce, uint64(block.chainid))
        );
        MessageBus(_messageBus).sendMessageWithTransfer{value: _fee}(
            _receiver,
            _dstChainId,
            pegBridge,
            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 _bridgeType One of the {BridgeType} enum.
     */
    function sendTokenTransfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage,
        BridgeType _bridgeType,
        address _bridge
    ) internal {
        if (_bridgeType == BridgeType.Liquidity) {
            IERC20(_token).safeIncreaseAllowance(_bridge, _amount);
            IBridge(_bridge).send(_receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage);
        } else if (_bridgeType == BridgeType.PegDeposit) {
            IERC20(_token).safeIncreaseAllowance(_bridge, _amount);
            IOriginalTokenVault(_bridge).deposit(_token, _amount, _dstChainId, _receiver, _nonce);
        } else if (_bridgeType == BridgeType.PegBurn) {
            IPeggedTokenBridge(_bridge).burn(_token, _amount, _receiver, _nonce);
        } else {
            revert("bridge type not supported");
        }
    }
}

File 57 of 75 : MessageBus.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

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

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

    // 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
    ) 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);
    }
}

File 58 of 75 : 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 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);

    /**
     * @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 59 of 75 : 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;

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

File 60 of 75 : 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;

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

File 61 of 75 : MessageBusSender.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

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);

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

    constructor(ISigsVerifier _sigsVerifier) {
        sigsVerifier = _sigsVerifier;
    }

    /**
     * @notice Sends a message to an app on another chain via MessageBus without an associated transfer.
     * 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 {
        uint256 minFee = calcFee(_message);
        require(msg.value >= minFee, "Insufficient fee");
        emit Message(msg.sender, _receiver, _dstChainId, _message, msg.value);
    }

    /**
     * @notice Sends a message associated with a transfer to an app on another chain via MessageBus without an associated transfer.
     * 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 {
        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");
        (bool sent, ) = _account.call{value: amount, gas: 50000}("");
        require(sent, "failed to withdraw fee");
    }

    /**
     * @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;
    }

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

File 62 of 75 : MessageBusReceiver.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "../../interfaces/IBridge.sol";
import "../../interfaces/IOriginalTokenVault.sol";
import "../../interfaces/IPeggedTokenBridge.sol";
import "../interfaces/IMessageReceiverApp.sol";
import "../../safeguard/Ownable.sol";

contract MessageBusReceiver is Ownable {
    enum TransferType {
        Null,
        LqSend, // send through liquidity bridge
        LqWithdraw, // withdraw from liquidity bridge
        PegMint, // mint through pegged token bridge
        PegWithdraw // withdraw from original token vault
    }

    struct TransferInfo {
        TransferType t;
        address sender;
        address receiver;
        address token;
        uint256 amount;
        uint64 seqnum; // only needed for LqWithdraw
        uint64 srcChainId;
        bytes32 refId;
    }

    struct RouteInfo {
        address sender;
        address receiver;
        uint64 srcChainId;
    }

    enum TxStatus {
        Null,
        Success,
        Fail,
        Fallback
    }
    mapping(bytes32 => TxStatus) public executedMessages;

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

    enum MsgType {
        MessageWithTransfer,
        MessageOnly
    }
    event Executed(MsgType msgType, bytes32 id, TxStatus status);

    constructor(
        address _liquidityBridge,
        address _pegBridge,
        address _pegVault
    ) {
        liquidityBridge = _liquidityBridge;
        pegBridge = _pegBridge;
        pegVault = _pegVault;
    }

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

    // ============== 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,
        TransferInfo calldata _transfer,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external 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.
        // This also indicates that different transfers can carry the exact same messages.
        bytes32 messageId = verifyTransfer(_transfer);
        require(executedMessages[messageId] == TxStatus.Null, "transfer already executed");

        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "MessageWithTransfer"));
        IBridge(liquidityBridge).verifySigs(abi.encodePacked(domain, messageId, _message), _sigs, _signers, _powers);
        TxStatus status;
        bool success = executeMessageWithTransfer(_transfer, _message);
        if (success) {
            status = TxStatus.Success;
        } else {
            success = executeMessageWithTransferFallback(_transfer, _message);
            if (success) {
                status = TxStatus.Fallback;
            } else {
                status = TxStatus.Fail;
            }
        }
        executedMessages[messageId] = status;
        emit Executed(MsgType.MessageWithTransfer, messageId, status);
    }

    /**
     * @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
        TransferInfo calldata _transfer,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external payable {
        // similar to executeMessageWithTransfer
        bytes32 messageId = verifyTransfer(_transfer);
        require(executedMessages[messageId] == TxStatus.Null, "transfer already executed");

        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "MessageWithTransferRefund"));
        IBridge(liquidityBridge).verifySigs(abi.encodePacked(domain, messageId, _message), _sigs, _signers, _powers);
        TxStatus status;
        bool success = executeMessageWithTransferRefund(_transfer, _message);
        if (success) {
            status = TxStatus.Success;
        } else {
            status = TxStatus.Fail;
        }
        executedMessages[messageId] = status;
        emit Executed(MsgType.MessageWithTransfer, messageId, status);
    }

    /**
     * @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,
        RouteInfo calldata _route,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external payable {
        // 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] == TxStatus.Null, "message already executed");

        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Message"));
        IBridge(liquidityBridge).verifySigs(abi.encodePacked(domain, messageId), _sigs, _signers, _powers);
        TxStatus status;
        bool success = executeMessage(_route, _message);
        if (success) {
            status = TxStatus.Success;
        } else {
            status = TxStatus.Fail;
        }
        executedMessages[messageId] = status;
        emit Executed(MsgType.MessageOnly, messageId, status);
    }

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

    function executeMessageWithTransfer(TransferInfo calldata _transfer, bytes calldata _message)
        private
        returns (bool)
    {
        (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
            )
        );
        if (ok) {
            bool success = abi.decode((res), (bool));
            return success;
        }
        return false;
    }

    function executeMessageWithTransferFallback(TransferInfo calldata _transfer, bytes calldata _message)
        private
        returns (bool)
    {
        (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
            )
        );
        if (ok) {
            bool success = abi.decode((res), (bool));
            return success;
        }
        return false;
    }

    function executeMessageWithTransferRefund(TransferInfo calldata _transfer, bytes calldata _message)
        private
        returns (bool)
    {
        (bool ok, bytes memory res) = address(_transfer.receiver).call{value: msg.value}(
            abi.encodeWithSelector(
                IMessageReceiverApp.executeMessageWithTransferRefund.selector,
                _transfer.token,
                _transfer.amount,
                _message
            )
        );
        if (ok) {
            bool success = abi.decode((res), (bool));
            return success;
        }
        return false;
    }

    function verifyTransfer(TransferInfo calldata _transfer) private view returns (bytes32) {
        bytes32 transferId;
        address bridgeAddr;
        if (_transfer.t == TransferType.LqSend) {
            transferId = keccak256(
                abi.encodePacked(
                    _transfer.sender,
                    _transfer.receiver,
                    _transfer.token,
                    _transfer.amount,
                    _transfer.srcChainId,
                    uint64(block.chainid),
                    _transfer.refId
                )
            );
            bridgeAddr = liquidityBridge;
            require(IBridge(bridgeAddr).transfers(transferId) == true, "bridge relay not exist");
        } else if (_transfer.t == TransferType.LqWithdraw) {
            transferId = keccak256(
                abi.encodePacked(
                    uint64(block.chainid),
                    _transfer.seqnum,
                    _transfer.receiver,
                    _transfer.token,
                    _transfer.amount
                )
            );
            bridgeAddr = liquidityBridge;
            require(IBridge(bridgeAddr).withdraws(transferId) == true, "bridge withdraw not exist");
        } else if (_transfer.t == TransferType.PegMint || _transfer.t == TransferType.PegWithdraw) {
            transferId = keccak256(
                abi.encodePacked(
                    _transfer.receiver,
                    _transfer.token,
                    _transfer.amount,
                    _transfer.sender,
                    _transfer.srcChainId,
                    _transfer.refId
                )
            );
            if (_transfer.t == TransferType.PegMint) {
                bridgeAddr = pegBridge;
                require(IPeggedTokenBridge(bridgeAddr).records(transferId) == true, "mint record not exist");
            } else {
                // _transfer.t == TransferType.PegWithdraw
                bridgeAddr = pegVault;
                require(IOriginalTokenVault(bridgeAddr).records(transferId) == true, "withdraw record not exist");
            }
        }
        return keccak256(abi.encodePacked(MsgType.MessageWithTransfer, bridgeAddr, transferId));
    }

    function computeMessageOnlyId(RouteInfo calldata _route, bytes calldata _message) private pure returns (bytes32) {
        return
            keccak256(
                abi.encodePacked(MsgType.MessageOnly, _route.sender, _route.receiver, _route.srcChainId, _message)
            );
    }

    function executeMessage(RouteInfo calldata _route, bytes calldata _message) private returns (bool) {
        (bool ok, bytes memory res) = address(_route.receiver).call{value: msg.value}(
            abi.encodeWithSelector(
                IMessageReceiverApp.executeMessage.selector,
                _route.sender,
                _route.srcChainId,
                _message
            )
        );
        if (ok) {
            bool success = abi.decode((res), (bool));
            return success;
        }
        return false;
    }

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

    function setLiquidityBridge(address _addr) public onlyOwner {
        liquidityBridge = _addr;
    }

    function setPegBridge(address _addr) public onlyOwner {
        pegBridge = _addr;
    }

    function setPegVault(address _addr) public onlyOwner {
        pegVault = _addr;
    }
}

File 63 of 75 : IMessageReceiverApp.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IMessageReceiverApp {
    /**
     * @notice Called by MessageBus (MessageBusReceiver) if the process is originated from MessageBus (MessageBusSender)'s
     *         sendMessageWithTransfer it is only called when the tokens are checked to be arrived at this contract's address.
     * @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.
     *        the contract that implements this contract can safely assume that the tokens will arrive before this
     *        function is called.
     * @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
     */
    function executeMessageWithTransfer(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes calldata _message
    ) external payable returns (bool);

    /**
     * @notice Only called by MessageBus (MessageBusReceiver) if
     *         1. executeMessageWithTransfer reverts, or
     *         2. executeMessageWithTransfer returns false
     * @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.
     *        the contract that implements this contract can safely assume that the tokens will arrive before this
     *        function is called.
     * @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
     */
    function executeMessageWithTransferFallback(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes calldata _message
    ) external payable returns (bool);

    /**
     * @notice Called by MessageBus (MessageBusReceiver) to process refund of the original transfer from this contract
     * @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
     */
    function executeMessageWithTransferRefund(
        address _token,
        uint256 _amount,
        bytes calldata _message
    ) external payable returns (bool);

    /**
     * @notice Called by MessageBus (MessageBusReceiver)
     * @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
     */
    function executeMessage(
        address _sender,
        uint64 _srcChainId,
        bytes calldata _message
    ) external payable returns (bool);
}

File 64 of 75 : TransferSwapSendBack.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

import "../libraries/MessageSenderLib.sol";
import "../framework/MessageSenderApp.sol";
import "../framework/MessageReceiverApp.sol";

interface ISwapToken {
    // function sellBase(address to) external returns (uint256);
    // uniswap v2
    function swapExactTokensForTokens(
        uint256,
        uint256,
        address[] calldata,
        address,
        uint256
    ) external returns (uint256[] memory);
}

contract CrossChainSwap is MessageSenderApp, MessageReceiverApp {
    using SafeERC20 for IERC20;

    address public dex; // needed on swap chain

    struct SwapInfo {
        address wantToken; // token user want to receive on dest chain
        address user;
        bool sendBack; // if true, send wantToken back to start chain
        uint32 cbrMaxSlippage; // _maxSlippage for cbridge send
    }

    constructor(address dex_) {
        dex = dex_;
    }

    // ========== on start chain ==========

    uint64 nonce; // required by IBridge.send

    // this func could be called by a router contract
    function startCrossChainSwap(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        SwapInfo calldata swapInfo // wantToken on destChain and actual user address as receiver when send back
    ) external payable {
        nonce += 1;
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
        bytes memory message = abi.encode(swapInfo);
        sendMessageWithTransfer(
            _receiver,
            _token,
            _amount,
            _dstChainId,
            nonce,
            swapInfo.cbrMaxSlippage,
            message,
            MessageSenderLib.BridgeType.Liquidity,
            msg.value
        );
    }

    // ========== on swap chain ==========
    // do dex, send received asset to src chain via bridge
    function executeMessageWithTransfer(
        address, // _sender
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes memory _message
    ) external payable override onlyMessageBus returns (bool) {
        SwapInfo memory swapInfo = abi.decode((_message), (SwapInfo));
        IERC20(_token).approve(dex, _amount);
        address[] memory path = new address[](2);
        path[0] = _token;
        path[1] = swapInfo.wantToken;
        if (swapInfo.sendBack) {
            nonce += 1;
            uint256[] memory swapReturn = ISwapToken(dex).swapExactTokensForTokens(
                _amount,
                0,
                path,
                address(this),
                type(uint256).max
            );
            // send received token back to start chain. swapReturn[1] is amount of wantToken
            sendTokenTransfer(
                swapInfo.user,
                swapInfo.wantToken,
                swapReturn[1],
                _srcChainId,
                nonce,
                swapInfo.cbrMaxSlippage,
                MessageSenderLib.BridgeType.Liquidity
            );
        } else {
            // swap to wantToken and send to user
            ISwapToken(dex).swapExactTokensForTokens(_amount, 0, path, swapInfo.user, type(uint256).max);
        }
        // bytes memory notice; // send back to src chain to handleMessage
        // sendMessage(_sender, _srcChainId, notice);
        return true;
    }
}

File 65 of 75 : TransferMsg.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

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

/** @title Application to test message only flow */
contract TransferMessage is MessageSenderApp, MessageReceiverApp {
    constructor(address _messageBus) {
        messageBus = _messageBus;
    }

    function transferMessage(
        address _receiver,
        uint64 _dstChainId,
        bytes memory _message
    ) external payable {
        sendMessage(_receiver, _dstChainId, _message, msg.value);
    }

    function executeMessage(
        address,
        uint64,
        bytes calldata
    ) external payable override onlyMessageBus returns (bool) {
        return true;
    }
}

File 66 of 75 : TestRefund.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

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

/** @title Application to test message with transfer refund flow */
contract TestRefund is MessageSenderApp, MessageReceiverApp {
    using SafeERC20 for IERC20;

    event Refunded(address token, uint256 amount, bytes message);

    constructor(address _messageBus) {
        messageBus = _messageBus;
    }

    function sendWithTransfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage,
        MessageSenderLib.BridgeType _bridgeType
    ) external payable {
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
        bytes memory message = abi.encodePacked(_receiver);
        sendMessageWithTransfer(_receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage, message, _bridgeType, 0);
    }

    function executeMessageWithTransferRefund(
        address _token,
        uint256 _amount,
        bytes calldata _message
    ) external payable virtual override onlyMessageBus returns (bool) {
        emit Refunded(_token, _amount, _message);
        address receiver = abi.decode((_message), (address));
        IERC20(_token).safeTransfer(receiver, _amount);
        return true;
    }

    function executeMessage(
        address,
        uint64,
        bytes calldata
    ) external payable override onlyMessageBus returns (bool) {
        return true;
    }
}

File 67 of 75 : BatchTransfer.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

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

/** @title Sample app to test message passing flow, not for production use */
contract BatchTransfer is MessageSenderApp, MessageReceiverApp {
    using SafeERC20 for IERC20;

    struct TransferRequest {
        uint64 nonce;
        address[] accounts;
        uint256[] amounts;
        address sender;
    }

    enum TransferStatus {
        Null,
        Success,
        Fail
    }

    struct TransferReceipt {
        uint64 nonce;
        TransferStatus status;
    }

    constructor(address _messageBus) {
        messageBus = _messageBus;
    }

    // ============== functions and states on source chain ==============

    uint64 nonce;

    struct BatchTransferStatus {
        bytes32 h; // hash(receiver, dstChainId)
        TransferStatus status;
    }
    mapping(uint64 => BatchTransferStatus) public status; // nonce -> BatchTransferStatus

    modifier onlyEOA() {
        require(msg.sender == tx.origin, "Not EOA");
        _;
    }

    function batchTransfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint32 _maxSlippage,
        MessageSenderLib.BridgeType _bridgeType,
        address[] calldata _accounts,
        uint256[] calldata _amounts
    ) external payable onlyEOA {
        uint256 totalAmt;
        for (uint256 i = 0; i < _amounts.length; i++) {
            totalAmt += _amounts[i];
        }
        // commented out the slippage check below to trigger failure case for handleFailedMessageWithTransfer testing
        // uint256 minRecv = _amount - (_amount * _maxSlippage) / 1e6;
        // require(minRecv > totalAmt, "invalid maxSlippage");
        nonce += 1;
        status[nonce] = BatchTransferStatus({
            h: keccak256(abi.encodePacked(_receiver, _dstChainId)),
            status: TransferStatus.Null
        });
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
        bytes memory message = abi.encode(
            TransferRequest({nonce: nonce, accounts: _accounts, amounts: _amounts, sender: msg.sender})
        );
        // MsgSenderApp util function
        sendMessageWithTransfer(
            _receiver,
            _token,
            _amount,
            _dstChainId,
            nonce,
            _maxSlippage,
            message,
            _bridgeType,
            msg.value
        );
    }

    // handler function required by MsgReceiverApp
    function executeMessage(
        address _sender,
        uint64 _srcChainId,
        bytes memory _message
    ) external payable override onlyMessageBus returns (bool) {
        TransferReceipt memory receipt = abi.decode((_message), (TransferReceipt));
        require(status[receipt.nonce].h == keccak256(abi.encodePacked(_sender, _srcChainId)), "invalid message");
        status[receipt.nonce].status = receipt.status;
        return true;
    }

    // ============== functions on destination chain ==============

    // handler function required by MsgReceiverApp
    function executeMessageWithTransfer(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes memory _message
    ) external payable override onlyMessageBus returns (bool) {
        TransferRequest memory transfer = abi.decode((_message), (TransferRequest));
        uint256 totalAmt;
        for (uint256 i = 0; i < transfer.accounts.length; i++) {
            IERC20(_token).safeTransfer(transfer.accounts[i], transfer.amounts[i]);
            totalAmt += transfer.amounts[i];
        }
        uint256 remainder = _amount - totalAmt;
        if (_amount > totalAmt) {
            IERC20(_token).safeTransfer(transfer.sender, remainder);
        }
        bytes memory message = abi.encode(TransferReceipt({nonce: transfer.nonce, status: TransferStatus.Success}));
        // MsgSenderApp util function
        sendMessage(_sender, _srcChainId, message, msg.value);
        return true;
    }

    // handler function required by MsgReceiverApp
    // called only if handleMessageWithTransfer above was reverted
    function executeMessageWithTransferFallback(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes memory _message
    ) external payable override onlyMessageBus returns (bool) {
        TransferRequest memory transfer = abi.decode((_message), (TransferRequest));
        IERC20(_token).safeTransfer(transfer.sender, _amount);
        bytes memory message = abi.encode(TransferReceipt({nonce: transfer.nonce, status: TransferStatus.Fail}));
        sendMessage(_sender, _srcChainId, message, msg.value);
        return true;
    }
}

File 68 of 75 : MintSwapCanonicalToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

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

/**
 * @title Canonical token that supports multi-bridge minter and multi-token swap
 */
contract MintSwapCanonicalToken is MultiBridgeToken {
    using SafeERC20 for IERC20;

    // bridge token address -> minted amount and cap for each bridge
    mapping(address => Supply) public swapSupplies;

    event TokenSwapCapUpdated(address token, uint256 cap);

    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_
    ) MultiBridgeToken(name_, symbol_, decimals_) {}

    /**
     * @notice msg.sender has bridge token and wants to get canonical token.
     * @param _bridgeToken The intermediary token address for a particular bridge.
     * @param _amount The amount.
     */
    function swapBridgeForCanonical(address _bridgeToken, uint256 _amount) external returns (uint256) {
        Supply storage supply = swapSupplies[_bridgeToken];
        require(supply.cap > 0, "invalid bridge token");
        require(supply.total + _amount < supply.cap, "exceed swap cap");

        supply.total += _amount;
        _mint(msg.sender, _amount);

        // move bridge token from msg.sender to canonical token _amount
        IERC20(_bridgeToken).safeTransferFrom(msg.sender, address(this), _amount);
        return _amount;
    }

    /**
     * @notice msg.sender has canonical token and wants to get bridge token (eg. for cross chain burn).
     * @param _bridgeToken The intermediary token address for a particular bridge.
     * @param _amount The amount.
     */
    function swapCanonicalForBridge(address _bridgeToken, uint256 _amount) external returns (uint256) {
        Supply storage supply = swapSupplies[_bridgeToken];
        require(supply.cap > 0, "invalid bridge token");

        supply.total -= _amount;
        _burn(msg.sender, _amount);

        IERC20(_bridgeToken).safeTransfer(msg.sender, _amount);
        return _amount;
    }

    /**
     * @dev Update existing bridge token swap cap or add a new bridge token with swap cap.
     * Setting cap to 0 will disable the bridge token.
     * @param _bridgeToken The intermediary token address for a particular bridge.
     * @param _swapCap The new swap cap.
     */
    function setBridgeTokenSwapCap(address _bridgeToken, uint256 _swapCap) external onlyOwner {
        swapSupplies[_bridgeToken].cap = _swapCap;
        emit TokenSwapCapUpdated(_bridgeToken, _swapCap);
    }
}

File 69 of 75 : MintSwapCanonicalTokenUpgradable.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

import "./MintSwapCanonicalToken.sol";

/**
 * @title Upgradable canonical token that supports multi-bridge minter and multi-token swap
 */

// First deploy this contract, constructor will set name, symbol and owner in contract state, but these are NOT used.
// decimal isn't saved in state because it's immutable in MultiBridgeToken and will be set in the code binary.
// Then deploy proxy contract with this contract as impl, proxy constructor will delegatecall this.init which sets name, symbol and owner in proxy contract state.
// why we need to shadow name and symbol: ERC20 only allows set them in constructor which isn't available after deploy so proxy state can't be updated.
contract MintSwapCanonicalTokenUpgradable is MintSwapCanonicalToken {
    string private _name;
    string private _symbol;

    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_
    ) MintSwapCanonicalToken(name_, symbol_, decimals_) {
    }

    // only to be called by Proxy via delegatecall and will modify Proxy state
    // this func has no access control because initOwner only allows delegateCall
    function init(
        string memory name_,
        string memory symbol_
    ) external {
        initOwner(); // this will fail if Ownable._owner is already set
        _name = name_;
        _symbol = symbol_;
    }

    // override name, symbol and owner getters
    function name() public view virtual override returns (string memory) {
        return _name;
    }
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }
}

File 70 of 75 : MintSwapCanonicalTokenPermit.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
import "../MintSwapCanonicalToken.sol";

/**
 * @title MintSwapCanonicalToke with ERC20Permit
 */
contract MintSwapCanonicalTokenPermit is ERC20Permit, MintSwapCanonicalToken {
    uint8 private immutable _decimals;

    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_
    ) MintSwapCanonicalToken(name_, symbol_, decimals_) ERC20Permit(name_) {
        _decimals = decimals_;
    }

    function decimals() public view override(ERC20, MultiBridgeToken) returns (uint8) {
        return _decimals;
    }
}

File 71 of 75 : MaiBridgeToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

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

interface IMaiBridgeHub {
    // send bridge token, get asset
    function swapIn(address, uint256) external;

    // send asset, get bridge token back
    function swapOut(address, uint256) external;

    // asset address
    function asset() external view returns (address);
}

/**
 * @title Intermediary bridge token that supports swapping with the Mai hub.
 * NOTE: Mai hub is NOT the canonical token itself. The asset is set in the hub constructor.
 */
contract MaiBridgeToken is ERC20, Ownable {
    using SafeERC20 for IERC20;

    // The PeggedTokenBridge
    address public bridge;
    // Mai hub for swapping
    address public immutable maihub;
    // The canonical Mai token
    address public immutable asset;

    event BridgeUpdated(address bridge);

    modifier onlyBridge() {
        require(msg.sender == bridge, "caller is not bridge");
        _;
    }

    constructor(
        string memory name_,
        string memory symbol_,
        address bridge_,
        address maihub_
    ) ERC20(name_, symbol_) {
        bridge = bridge_;
        maihub = maihub_;
        asset = IMaiBridgeHub(maihub_).asset();
    }

    function mint(address _to, uint256 _amount) external onlyBridge returns (bool) {
        _mint(address(this), _amount); // add amount to myself so swapIn can transfer amount to hub
        _approve(address(this), maihub, _amount);
        IMaiBridgeHub(maihub).swapIn(address(this), _amount);
        // now this has canonical token, next step is to transfer to user
        IERC20(asset).safeTransfer(_to, _amount);
        return true;
    }

    function burn(address _from, uint256 _amount) external onlyBridge returns (bool) {
        IERC20(asset).safeTransferFrom(_from, address(this), _amount);
        IERC20(asset).safeIncreaseAllowance(address(maihub), _amount);
        IMaiBridgeHub(maihub).swapOut(address(this), _amount);
        _burn(address(this), _amount);
        return true;
    }

    function updateBridge(address _bridge) external onlyOwner {
        bridge = _bridge;
        emit BridgeUpdated(bridge);
    }

    function decimals() public view virtual override returns (uint8) {
        return ERC20(asset).decimals();
    }

    // to make compatible with BEP20
    function getOwner() external view returns (address) {
        return owner();
    }
}

File 72 of 75 : FraxBridgeToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

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

interface IFraxCanoToken {
    function exchangeOldForCanonical(address, uint256) external returns (uint256);

    function exchangeCanonicalForOld(address, uint256) external returns (uint256);
}

/**
 * @title Intermediary bridge token that supports swapping with the canonical Frax token.
 */
contract FraxBridgeToken is ERC20, Ownable {
    using SafeERC20 for IERC20;

    // The PeggedTokenBridge
    address public bridge;
    // The canonical Frax token that supports swapping
    address public immutable canonical;

    event BridgeUpdated(address bridge);

    modifier onlyBridge() {
        require(msg.sender == bridge, "caller is not bridge");
        _;
    }

    constructor(
        string memory name_,
        string memory symbol_,
        address bridge_,
        address canonical_
    ) ERC20(name_, symbol_) {
        bridge = bridge_;
        canonical = canonical_;
    }

    function mint(address _to, uint256 _amount) external onlyBridge returns (bool) {
        _mint(address(this), _amount); // add amount to myself so exchangeOldForCanonical can transfer amount
        _approve(address(this), canonical, _amount);
        uint256 got = IFraxCanoToken(canonical).exchangeOldForCanonical(address(this), _amount);
        // now this has canonical token, next step is to transfer to user
        IERC20(canonical).safeTransfer(_to, got);
        return true;
    }

    function burn(address _from, uint256 _amount) external onlyBridge returns (bool) {
        IERC20(canonical).safeTransferFrom(_from, address(this), _amount);
        uint256 got = IFraxCanoToken(canonical).exchangeCanonicalForOld(address(this), _amount);
        _burn(address(this), got);
        return true;
    }

    function updateBridge(address _bridge) external onlyOwner {
        bridge = _bridge;
        emit BridgeUpdated(bridge);
    }

    function decimals() public view virtual override returns (uint8) {
        return ERC20(canonical).decimals();
    }

    // to make compatible with BEP20
    function getOwner() external view returns (address) {
        return owner();
    }
}

File 73 of 75 : MintableERC20.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";

/**
 * @title A mintable {ERC20} token.
 */
contract MintableERC20 is ERC20Burnable, Ownable {
    uint8 private _decimals;

    /**
     * @dev Constructor that gives msg.sender an initial supply of tokens.
     */
    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_,
        uint256 initialSupply_
    ) ERC20(name_, symbol_) {
        _decimals = decimals_;
        _mint(msg.sender, initialSupply_);
    }

    /**
     * @dev Creates `amount` new tokens for `to`.
     */
    function mint(address to, uint256 amount) public onlyOwner {
        _mint(to, amount);
    }

    function decimals() public view override returns (uint8) {
        return _decimals;
    }
}

File 74 of 75 : Govern.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {DataTypes as dt} from "./libraries/DataTypes.sol";
import "./Staking.sol";

/**
 * @title Governance module for Staking contract
 */
contract Govern {
    using SafeERC20 for IERC20;

    Staking public immutable staking;
    IERC20 public immutable celerToken;

    enum ProposalStatus {
        Uninitiated,
        Voting,
        Closed
    }

    enum VoteOption {
        Null,
        Yes,
        Abstain,
        No
    }

    struct ParamProposal {
        address proposer;
        uint256 deposit;
        uint256 voteDeadline;
        dt.ParamName name;
        uint256 newValue;
        ProposalStatus status;
        mapping(address => VoteOption) votes;
    }

    mapping(uint256 => ParamProposal) public paramProposals;
    uint256 public nextParamProposalId;

    uint256 public forfeiture;
    address public immutable collector;

    event CreateParamProposal(
        uint256 proposalId,
        address proposer,
        uint256 deposit,
        uint256 voteDeadline,
        dt.ParamName name,
        uint256 newValue
    );
    event VoteParam(uint256 proposalId, address voter, VoteOption vote);
    event ConfirmParamProposal(uint256 proposalId, bool passed, dt.ParamName name, uint256 newValue);

    constructor(
        Staking _staking,
        address _celerTokenAddress,
        address _collector
    ) {
        staking = _staking;
        celerToken = IERC20(_celerTokenAddress);
        collector = _collector;
    }

    /**
     * @notice Get the vote type of a voter on a parameter proposal
     * @param _proposalId the proposal id
     * @param _voter the voter address
     * @return the vote type of the given voter on the given parameter proposal
     */
    function getParamProposalVote(uint256 _proposalId, address _voter) public view returns (VoteOption) {
        return paramProposals[_proposalId].votes[_voter];
    }

    /**
     * @notice Create a parameter proposal
     * @param _name the key of this parameter
     * @param _value the new proposed value of this parameter
     */
    function createParamProposal(dt.ParamName _name, uint256 _value) external {
        ParamProposal storage p = paramProposals[nextParamProposalId];
        nextParamProposalId = nextParamProposalId + 1;
        address msgSender = msg.sender;
        uint256 deposit = staking.getParamValue(dt.ParamName.ProposalDeposit);

        p.proposer = msgSender;
        p.deposit = deposit;
        p.voteDeadline = block.number + staking.getParamValue(dt.ParamName.VotingPeriod);
        p.name = _name;
        p.newValue = _value;
        p.status = ProposalStatus.Voting;

        celerToken.safeTransferFrom(msgSender, address(this), deposit);

        emit CreateParamProposal(nextParamProposalId - 1, msgSender, deposit, p.voteDeadline, _name, _value);
    }

    /**
     * @notice Vote for a parameter proposal with a specific type of vote
     * @param _proposalId the id of the parameter proposal
     * @param _vote the type of vote
     */
    function voteParam(uint256 _proposalId, VoteOption _vote) external {
        address valAddr = msg.sender;
        require(staking.getValidatorStatus(valAddr) == dt.ValidatorStatus.Bonded, "Voter is not a bonded validator");
        ParamProposal storage p = paramProposals[_proposalId];
        require(p.status == ProposalStatus.Voting, "Invalid proposal status");
        require(block.number < p.voteDeadline, "Vote deadline passed");
        require(p.votes[valAddr] == VoteOption.Null, "Voter has voted");
        require(_vote != VoteOption.Null, "Invalid vote");

        p.votes[valAddr] = _vote;

        emit VoteParam(_proposalId, valAddr, _vote);
    }

    /**
     * @notice Confirm a parameter proposal
     * @param _proposalId the id of the parameter proposal
     */
    function confirmParamProposal(uint256 _proposalId) external {
        uint256 yesVotes;
        uint256 bondedTokens;
        dt.ValidatorTokens[] memory validators = staking.getBondedValidatorsTokens();
        for (uint32 i = 0; i < validators.length; i++) {
            if (getParamProposalVote(_proposalId, validators[i].valAddr) == VoteOption.Yes) {
                yesVotes += validators[i].tokens;
            }
            bondedTokens += validators[i].tokens;
        }
        bool passed = (yesVotes >= (bondedTokens * 2) / 3 + 1);

        ParamProposal storage p = paramProposals[_proposalId];
        require(p.status == ProposalStatus.Voting, "Invalid proposal status");
        require(block.number >= p.voteDeadline, "Vote deadline not reached");

        p.status = ProposalStatus.Closed;
        if (passed) {
            staking.setParamValue(p.name, p.newValue);
            celerToken.safeTransfer(p.proposer, p.deposit);
        } else {
            forfeiture += p.deposit;
        }

        emit ConfirmParamProposal(_proposalId, passed, p.name, p.newValue);
    }

    function collectForfeiture() external {
        require(forfeiture > 0, "Nothing to collect");
        celerToken.safeTransfer(collector, forfeiture);
        forfeiture = 0;
    }
}

File 75 of 75 : Faucet.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

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

contract Faucet is Ownable {
    using SafeERC20 for IERC20;

    uint256 public minDripBlkInterval;
    mapping(address => uint256) public lastDripBlk;

    /**
     * @dev Sends 0.01% of each token to the caller.
     * @param tokens The tokens to drip.
     */
    function drip(address[] calldata tokens) public {
        require(block.number - lastDripBlk[msg.sender] >= minDripBlkInterval, "too frequent");
        for (uint256 i = 0; i < tokens.length; i++) {
            IERC20 token = IERC20(tokens[i]);
            uint256 balance = token.balanceOf(address(this));
            require(balance > 0, "Faucet is empty");
            token.safeTransfer(msg.sender, balance / 10000); // 0.01%
        }
        lastDripBlk[msg.sender] = block.number;
    }

    /**
     * @dev Owner set minDripBlkInterval
     *
     * @param _interval minDripBlkInterval value
     */
    function setMinDripBlkInterval(uint256 _interval) external onlyOwner {
        minDripBlkInterval = _interval;
    }

    /**
     * @dev Owner drains one type of tokens
     *
     * @param _asset drained asset address
     * @param _amount drained asset amount
     */
    function drainToken(address _asset, uint256 _amount) external onlyOwner {
        IERC20(_asset).safeTransfer(msg.sender, _amount);
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 800
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "abi"
      ]
    }
  },
  "metadata": {
    "useLiteralContent": true
  }
}

Contract ABI

[{"inputs":[{"internalType":"contract ISigsVerifier","name":"_sigsVerifier","type":"address"},{"internalType":"address","name":"_liquidityBridge","type":"address"},{"internalType":"address","name":"_pegBridge","type":"address"},{"internalType":"address","name":"_pegVault","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"enum MessageBusReceiver.MsgType","name":"msgType","type":"uint8"},{"indexed":false,"internalType":"bytes32","name":"id","type":"bytes32"},{"indexed":false,"internalType":"enum MessageBusReceiver.TxStatus","name":"status","type":"uint8"}],"name":"Executed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"dstChainId","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"message","type":"bytes"},{"indexed":false,"internalType":"uint256","name":"fee","type":"uint256"}],"name":"Message","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"dstChainId","type":"uint256"},{"indexed":false,"internalType":"address","name":"bridge","type":"address"},{"indexed":false,"internalType":"bytes32","name":"srcTransferId","type":"bytes32"},{"indexed":false,"internalType":"bytes","name":"message","type":"bytes"},{"indexed":false,"internalType":"uint256","name":"fee","type":"uint256"}],"name":"MessageWithTransfer","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"},{"inputs":[{"internalType":"bytes","name":"_message","type":"bytes"}],"name":"calcFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"_message","type":"bytes"},{"components":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint64","name":"srcChainId","type":"uint64"}],"internalType":"struct MessageBusReceiver.RouteInfo","name":"_route","type":"tuple"},{"internalType":"bytes[]","name":"_sigs","type":"bytes[]"},{"internalType":"address[]","name":"_signers","type":"address[]"},{"internalType":"uint256[]","name":"_powers","type":"uint256[]"}],"name":"executeMessage","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes","name":"_message","type":"bytes"},{"components":[{"internalType":"enum MessageBusReceiver.TransferType","name":"t","type":"uint8"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint64","name":"seqnum","type":"uint64"},{"internalType":"uint64","name":"srcChainId","type":"uint64"},{"internalType":"bytes32","name":"refId","type":"bytes32"}],"internalType":"struct MessageBusReceiver.TransferInfo","name":"_transfer","type":"tuple"},{"internalType":"bytes[]","name":"_sigs","type":"bytes[]"},{"internalType":"address[]","name":"_signers","type":"address[]"},{"internalType":"uint256[]","name":"_powers","type":"uint256[]"}],"name":"executeMessageWithTransfer","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes","name":"_message","type":"bytes"},{"components":[{"internalType":"enum MessageBusReceiver.TransferType","name":"t","type":"uint8"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint64","name":"seqnum","type":"uint64"},{"internalType":"uint64","name":"srcChainId","type":"uint64"},{"internalType":"bytes32","name":"refId","type":"bytes32"}],"internalType":"struct MessageBusReceiver.TransferInfo","name":"_transfer","type":"tuple"},{"internalType":"bytes[]","name":"_sigs","type":"bytes[]"},{"internalType":"address[]","name":"_signers","type":"address[]"},{"internalType":"uint256[]","name":"_powers","type":"uint256[]"}],"name":"executeMessageWithTransferRefund","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"executedMessages","outputs":[{"internalType":"enum MessageBusReceiver.TxStatus","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeBase","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feePerByte","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_liquidityBridge","type":"address"},{"internalType":"address","name":"_pegBridge","type":"address"},{"internalType":"address","name":"_pegVault","type":"address"}],"name":"init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"liquidityBridge","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pegBridge","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pegVault","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_receiver","type":"address"},{"internalType":"uint256","name":"_dstChainId","type":"uint256"},{"internalType":"bytes","name":"_message","type":"bytes"}],"name":"sendMessage","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"_receiver","type":"address"},{"internalType":"uint256","name":"_dstChainId","type":"uint256"},{"internalType":"address","name":"_srcBridge","type":"address"},{"internalType":"bytes32","name":"_srcTransferId","type":"bytes32"},{"internalType":"bytes","name":"_message","type":"bytes"}],"name":"sendMessageWithTransfer","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_fee","type":"uint256"}],"name":"setFeeBase","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_fee","type":"uint256"}],"name":"setFeePerByte","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_addr","type":"address"}],"name":"setLiquidityBridge","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_addr","type":"address"}],"name":"setPegBridge","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_addr","type":"address"}],"name":"setPegVault","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sigsVerifier","outputs":[{"internalType":"contract ISigsVerifier","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"},{"internalType":"uint256","name":"_cumulativeFee","type":"uint256"},{"internalType":"bytes[]","name":"_sigs","type":"bytes[]"},{"internalType":"address[]","name":"_signers","type":"address[]"},{"internalType":"uint256[]","name":"_powers","type":"uint256[]"}],"name":"withdrawFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"withdrawnFees","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]

60a06040523480156200001157600080fd5b506040516200279e3803806200279e8339810160408190526200003491620000fa565b82828286620000433362000091565b6001600160a01b03908116608052600580546001600160a01b031990811695831695909517905560068054851693821693909317909255600780549093169116179055506200016292505050565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6001600160a01b0381168114620000f757600080fd5b50565b600080600080608085870312156200011157600080fd5b84516200011e81620000e1565b60208601519094506200013181620000e1565b60408601519093506200014481620000e1565b60608601519092506200015781620000e1565b939692955090935050565b6080516126196200018560003960008181610384015261064401526126196000f3fe6080604052600436106101805760003560e01c80638da5cb5b116100d6578063cd2abd661161007f578063e2c1ed2511610059578063e2c1ed2514610423578063f2fde38b14610443578063f60bbe2a1461046357600080fd5b8063cd2abd66146103a6578063d8257d17146103e3578063dfa2dbaf1461040357600080fd5b80639f3ce55a116100b05780639f3ce55a1461034c578063a22322131461035f578063ccf2683b1461037257600080fd5b80638da5cb5b146102f857806395e911a8146103165780639b05a7751461032c57600080fd5b80635335dca2116101385780635b3e5f50116101125780635b3e5f5014610280578063654317bf146102ad57806382980dc4146102c057600080fd5b80635335dca21461021a578063588be02b1461024d578063588df4161461026d57600080fd5b8063184b955911610169578063184b9559146101c75780632ff4c411146101e75780634289fbb31461020757600080fd5b806303cbfe661461018557806306c28bd6146101a7575b600080fd5b34801561019157600080fd5b506101a56101a0366004611c19565b610479565b005b3480156101b357600080fd5b506101a56101c2366004611c34565b610509565b3480156101d357600080fd5b506101a56101e2366004611c4d565b610577565b3480156101f357600080fd5b506101a5610202366004611cdc565b61058f565b6101a5610215366004611dd2565b6107e5565b34801561022657600080fd5b5061023a610235366004611e4a565b61088c565b6040519081526020015b60405180910390f35b34801561025957600080fd5b506101a5610268366004611c19565b6108b2565b6101a561027b366004611e8c565b61093d565b34801561028c57600080fd5b5061023a61029b366004611c19565b60036020526000908152604090205481565b6101a56102bb366004611f7d565b610b6a565b3480156102cc57600080fd5b506005546102e0906001600160a01b031681565b6040516001600160a01b039091168152602001610244565b34801561030457600080fd5b506000546001600160a01b03166102e0565b34801561032257600080fd5b5061023a60015481565b34801561033857600080fd5b506101a5610347366004611c19565b610d65565b6101a561035a366004612044565b610df0565b6101a561036d366004611e8c565b610e91565b34801561037e57600080fd5b506102e07f000000000000000000000000000000000000000000000000000000000000000081565b3480156103b257600080fd5b506103d66103c1366004611c34565b60046020526000908152604090205460ff1681565b60405161024491906120c8565b3480156103ef57600080fd5b506007546102e0906001600160a01b031681565b34801561040f57600080fd5b506006546102e0906001600160a01b031681565b34801561042f57600080fd5b506101a561043e366004611c34565b61105a565b34801561044f57600080fd5b506101a561045e366004611c19565b6110c8565b34801561046f57600080fd5b5061023a60025481565b3361048c6000546001600160a01b031690565b6001600160a01b0316146104e75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b600680546001600160a01b0319166001600160a01b0392909216919091179055565b3361051c6000546001600160a01b031690565b6001600160a01b0316146105725760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016104de565b600155565b61057f6111b9565b61058a83838361121d565b505050565b600046306040516020016105e592919091825260601b6bffffffffffffffffffffffff191660208201527f77697468647261774665650000000000000000000000000000000000000000006034820152603f0190565b60408051808303601f19018152828252805160209182012090830181905260608c901b6bffffffffffffffffffffffff19168383015260548084018c9052825180850390910181526074840192839052633416de1160e11b90925292507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169163682dbc229161068b918b908b908b908b908b908b906078016121c5565b60006040518083038186803b1580156106a357600080fd5b505afa1580156106b7573d6000803e3d6000fd5b505050506001600160a01b0389166000908152600360205260408120546106de908a6122d5565b9050600081116107305760405162461bcd60e51b815260206004820152601960248201527f4e6f206e657720616d6f756e7420746f2077697468647261770000000000000060448201526064016104de565b60008a6001600160a01b03168261c35090604051600060405180830381858888f193505050503d8060008114610782576040519150601f19603f3d011682016040523d82523d6000602084013e610787565b606091505b50509050806107d85760405162461bcd60e51b815260206004820152601660248201527f6661696c656420746f207769746864726177206665650000000000000000000060448201526064016104de565b5050505050505050505050565b60006107f1838361088c565b9050803410156108365760405162461bcd60e51b815260206004820152601060248201526f496e73756666696369656e742066656560801b60448201526064016104de565b336001600160a01b03167f172762498a59a3bc4fed3f2b63f94f17ea0193cffdc304fe7d3eaf4d342d2f668888888888883460405161087b97969594939291906122ec565b60405180910390a250505050505050565b60025460009061089c9083612339565b6001546108a99190612358565b90505b92915050565b336108c56000546001600160a01b031690565b6001600160a01b03161461091b5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016104de565b600580546001600160a01b0319166001600160a01b0392909216919091179055565b6000610948886112b5565b90506000808281526004602052604090205460ff16600381111561096e5761096e61209e565b146109bb5760405162461bcd60e51b815260206004820152601960248201527f7472616e7366657220616c72656164792065786563757465640000000000000060448201526064016104de565b60004630604051602001610a1192919091825260601b6bffffffffffffffffffffffff191660208201527f4d657373616765576974685472616e73666572526566756e64000000000000006034820152604d0190565b604051602081830303815290604052805190602001209050600560009054906101000a90046001600160a01b03166001600160a01b031663682dbc2282848e8e604051602001610a649493929190612370565b6040516020818303038152906040528a8a8a8a8a8a6040518863ffffffff1660e01b8152600401610a9b97969594939291906121c5565b60006040518083038186803b158015610ab357600080fd5b505afa158015610ac7573d6000803e3d6000fd5b50505050600080610ad98b8e8e61190f565b90508015610aea5760019150610aef565b600291505b6000848152600460205260409020805483919060ff19166001836003811115610b1a57610b1a61209e565b02179055507f29122f2c841ca2c3b2feefc4c23e90755d735d8e5b84f307151532e0f1ad62e760008584604051610b5393929190612391565b60405180910390a150505050505050505050505050565b6000610b77888b8b611a46565b90506000808281526004602052604090205460ff166003811115610b9d57610b9d61209e565b14610bea5760405162461bcd60e51b815260206004820152601860248201527f6d65737361676520616c7265616479206578656375746564000000000000000060448201526064016104de565b60004630604051602001610c4092919091825260601b6bffffffffffffffffffffffff191660208201527f4d657373616765000000000000000000000000000000000000000000000000006034820152603b0190565b60408051601f1981840301815282825280516020918201206005549184018190528383018690528251808503840181526060850193849052633416de1160e11b90935293506001600160a01b03169163682dbc2291610cad918c908c908c908c908c908c906064016121c5565b60006040518083038186803b158015610cc557600080fd5b505afa158015610cd9573d6000803e3d6000fd5b50505050600080610ceb8b8e8e611aad565b90508015610cfc5760019150610d01565b600291505b6000848152600460205260409020805483919060ff19166001836003811115610d2c57610d2c61209e565b02179055507f29122f2c841ca2c3b2feefc4c23e90755d735d8e5b84f307151532e0f1ad62e760018584604051610b5393929190612391565b33610d786000546001600160a01b031690565b6001600160a01b031614610dce5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016104de565b600780546001600160a01b0319166001600160a01b0392909216919091179055565b6000610dfc838361088c565b905080341015610e415760405162461bcd60e51b815260206004820152601060248201526f496e73756666696369656e742066656560801b60448201526064016104de565b336001600160a01b03167fce3972bfffe49d317e1d128047a97a3d86b25c94f6f04409f988ef854d25e0e48686868634604051610e829594939291906123c3565b60405180910390a25050505050565b6000610e9c886112b5565b90506000808281526004602052604090205460ff166003811115610ec257610ec261209e565b14610f0f5760405162461bcd60e51b815260206004820152601960248201527f7472616e7366657220616c72656164792065786563757465640000000000000060448201526064016104de565b60004630604051602001610f6592919091825260601b6bffffffffffffffffffffffff191660208201527f4d657373616765576974685472616e7366657200000000000000000000000000603482015260470190565b604051602081830303815290604052805190602001209050600560009054906101000a90046001600160a01b03166001600160a01b031663682dbc2282848e8e604051602001610fb89493929190612370565b6040516020818303038152906040528a8a8a8a8a8a6040518863ffffffff1660e01b8152600401610fef97969594939291906121c5565b60006040518083038186803b15801561100757600080fd5b505afa15801561101b573d6000803e3d6000fd5b5050505060008061102d8b8e8e611b05565b9050801561103e5760019150610aef565b6110498b8e8e611b77565b90508015610aea5760039150610aef565b3361106d6000546001600160a01b031690565b6001600160a01b0316146110c35760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016104de565b600255565b336110db6000546001600160a01b031690565b6001600160a01b0316146111315760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016104de565b6001600160a01b0381166111ad5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201527f646472657373000000000000000000000000000000000000000000000000000060648201526084016104de565b6111b681611bad565b50565b6000546001600160a01b0316156112125760405162461bcd60e51b815260206004820152601160248201527f6f776e657220616c72656164792073657400000000000000000000000000000060448201526064016104de565b61121b33611bad565b565b6005546001600160a01b0316156112765760405162461bcd60e51b815260206004820152601b60248201527f6c697175696469747942726964676520616c726561647920736574000000000060448201526064016104de565b600580546001600160a01b039485166001600160a01b031991821617909155600680549385169382169390931790925560078054919093169116179055565b6000808060016112c860208601866123fe565b60048111156112d9576112d961209e565b1415611479576112ef6040850160208601611c19565b6112ff6060860160408701611c19565b61130f6080870160608801611c19565b608087013561132460e0890160c08a0161241f565b6040516bffffffffffffffffffffffff19606096871b8116602083015294861b851660348201529290941b9092166048820152605c8101919091526001600160c01b031960c092831b8116607c8301524690921b909116608482015260e0850135608c82015260ac0160408051808303601f19018152908290528051602090910120600554633c64f04b60e01b8352600483018290529093506001600160a01b031691508190633c64f04b9060240160206040518083038186803b1580156113eb57600080fd5b505afa1580156113ff573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114239190612449565b15156001146114745760405162461bcd60e51b815260206004820152601660248201527f6272696467652072656c6179206e6f742065786973740000000000000000000060448201526064016104de565b6118da565b600261148860208601866123fe565b60048111156114995761149961209e565b141561160b57466114b060c0860160a0870161241f565b6114c06060870160408801611c19565b6114d06080880160608901611c19565b6040516001600160c01b031960c095861b811660208301529390941b90921660288401526bffffffffffffffffffffffff19606091821b8116603085015291901b1660448201526080850135605882015260780160408051808303601f19018152908290528051602090910120600554631c13568560e31b8352600483018290529093506001600160a01b03169150819063e09ab4289060240160206040518083038186803b15801561158257600080fd5b505afa158015611596573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115ba9190612449565b15156001146114745760405162461bcd60e51b815260206004820152601960248201527f627269646765207769746864726177206e6f742065786973740000000000000060448201526064016104de565b600361161a60208601866123fe565b600481111561162b5761162b61209e565b14806116545750600461164160208601866123fe565b60048111156116525761165261209e565b145b156118da576116696060850160408601611c19565b6116796080860160608701611c19565b608086013561168e6040880160208901611c19565b61169e60e0890160c08a0161241f565b604051606095861b6bffffffffffffffffffffffff19908116602083015294861b851660348201526048810193909352931b909116606882015260c09190911b6001600160c01b031916607c82015260e0850135608482015260a40160408051601f1981840301815291905280516020909101209150600361172360208601866123fe565b60048111156117345761173461209e565b141561180a57506006546040516301e6472560e01b8152600481018390526001600160a01b039091169081906301e647259060240160206040518083038186803b15801561178157600080fd5b505afa158015611795573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117b99190612449565b15156001146114745760405162461bcd60e51b815260206004820152601560248201527f6d696e74207265636f7264206e6f74206578697374000000000000000000000060448201526064016104de565b506007546040516301e6472560e01b8152600481018390526001600160a01b039091169081906301e647259060240160206040518083038186803b15801561185157600080fd5b505afa158015611865573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118899190612449565b15156001146118da5760405162461bcd60e51b815260206004820152601960248201527f7769746864726177207265636f7264206e6f742065786973740000000000000060448201526064016104de565b600081836040516020016118f093929190612482565b6040516020818303038152906040528051906020012092505050919050565b600080806119236060870160408801611c19565b6001600160a01b03163463105f4af960e11b61194560808a0160608b01611c19565b8960800135898960405160240161195f94939291906124b3565b60408051601f198184030181529181526020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fffffffff000000000000000000000000000000000000000000000000000000009094169390931790925290516119ca91906124e6565b60006040518083038185875af1925050503d8060008114611a07576040519150601f19603f3d011682016040523d82523d6000602084013e611a0c565b606091505b50915091508115611a3857600081806020019051810190611a2d9190612449565b9350611a3f92505050565b6000925050505b9392505050565b60006001611a576020860186611c19565b611a676040870160208801611c19565b611a77606088016040890161241f565b8686604051602001611a8e96959493929190612502565b6040516020818303038152906040528051906020012090509392505050565b60008080611ac16040870160208801611c19565b6001600160a01b031634631599d26560e01b611ae060208a018a611c19565b611af060608b0160408c0161241f565b898960405160240161195f9493929190612561565b60008080611b196060870160408801611c19565b6001600160a01b03163463671aeecd60e11b611b3b60408a0160208b01611c19565b611b4b60808b0160608c01611c19565b60808b0135611b6060e08d0160c08e0161241f565b8b8b60405160240161195f96959493929190612594565b60008080611b8b6060870160408801611c19565b6001600160a01b0316346378079ce760e11b611b3b60408a0160208b01611c19565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b80356001600160a01b0381168114611c1457600080fd5b919050565b600060208284031215611c2b57600080fd5b6108a982611bfd565b600060208284031215611c4657600080fd5b5035919050565b600080600060608486031215611c6257600080fd5b611c6b84611bfd565b9250611c7960208501611bfd565b9150611c8760408501611bfd565b90509250925092565b60008083601f840112611ca257600080fd5b50813567ffffffffffffffff811115611cba57600080fd5b6020830191508360208260051b8501011115611cd557600080fd5b9250929050565b60008060008060008060008060a0898b031215611cf857600080fd5b611d0189611bfd565b975060208901359650604089013567ffffffffffffffff80821115611d2557600080fd5b611d318c838d01611c90565b909850965060608b0135915080821115611d4a57600080fd5b611d568c838d01611c90565b909650945060808b0135915080821115611d6f57600080fd5b50611d7c8b828c01611c90565b999c989b5096995094979396929594505050565b60008083601f840112611da257600080fd5b50813567ffffffffffffffff811115611dba57600080fd5b602083019150836020828501011115611cd557600080fd5b60008060008060008060a08789031215611deb57600080fd5b611df487611bfd565b955060208701359450611e0960408801611bfd565b935060608701359250608087013567ffffffffffffffff811115611e2c57600080fd5b611e3889828a01611d90565b979a9699509497509295939492505050565b60008060208385031215611e5d57600080fd5b823567ffffffffffffffff811115611e7457600080fd5b611e8085828601611d90565b90969095509350505050565b6000806000806000806000806000898b03610180811215611eac57600080fd5b8a3567ffffffffffffffff80821115611ec457600080fd5b611ed08e838f01611d90565b909c509a508a9150610100601f1984011215611eeb57600080fd5b60208d0199506101208d0135925080831115611f0657600080fd5b611f128e848f01611c90565b90995097506101408d0135925088915080831115611f2f57600080fd5b611f3b8e848f01611c90565b90975095506101608d0135925086915080831115611f5857600080fd5b5050611f668c828d01611c90565b915080935050809150509295985092959850929598565b6000806000806000806000806000898b0360e0811215611f9c57600080fd5b8a3567ffffffffffffffff80821115611fb457600080fd5b611fc08e838f01611d90565b909c509a508a91506060601f1984011215611fda57600080fd5b60208d01995060808d0135925080831115611ff457600080fd5b6120008e848f01611c90565b909950975060a08d013592508891508083111561201c57600080fd5b6120288e848f01611c90565b909750955060c08d0135925086915080831115611f5857600080fd5b6000806000806060858703121561205a57600080fd5b61206385611bfd565b935060208501359250604085013567ffffffffffffffff81111561208657600080fd5b61209287828801611d90565b95989497509550505050565b634e487b7160e01b600052602160045260246000fd5b600481106120c4576120c461209e565b9052565b602081016108ac82846120b4565b60005b838110156120f15781810151838201526020016120d9565b83811115612100576000848401525b50505050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b8183526000602080850194508260005b8581101561216b576001600160a01b0361215883611bfd565b168752958201959082019060010161213f565b509495945050505050565b81835260007f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8311156121a857600080fd5b8260051b8083602087013760009401602001938452509192915050565b60808152600088518060808401526121e48160a0850160208d016120d6565b601f01601f1916820182810360a090810160208501528101889052600588901b810160c09081019082018a60005b8b8110156122855784840360bf190183528135368e9003601e1901811261223857600080fd5b8d01803567ffffffffffffffff81111561225157600080fd5b8036038f131561226057600080fd5b61226e868260208501612106565b955050506020928301929190910190600101612212565b505050838103604085015261229b81888a61212f565b91505082810360608401526122b1818587612176565b9a9950505050505050505050565b634e487b7160e01b600052601160045260246000fd5b6000828210156122e7576122e76122bf565b500390565b60006001600160a01b03808a16835288602084015280881660408401525085606083015260c0608083015261232560c083018587612106565b90508260a083015298975050505050505050565b6000816000190483118215151615612353576123536122bf565b500290565b6000821982111561236b5761236b6122bf565b500190565b84815283602082015281836040830137600091016040019081529392505050565b60608101600285106123a5576123a561209e565b8482528360208301526123bb60408301846120b4565b949350505050565b6001600160a01b03861681528460208201526080604082015260006123ec608083018587612106565b90508260608301529695505050505050565b60006020828403121561241057600080fd5b813560058110611a3f57600080fd5b60006020828403121561243157600080fd5b813567ffffffffffffffff81168114611a3f57600080fd5b60006020828403121561245b57600080fd5b81518015158114611a3f57600080fd5b6002811061247b5761247b61209e565b60f81b9052565b61248c818561246b565b60609290921b6bffffffffffffffffffffffff191660018301526015820152603501919050565b6001600160a01b03851681528360208201526060604082015260006124dc606083018486612106565b9695505050505050565b600082516124f88184602087016120d6565b9190910192915050565b61250c818861246b565b60006bffffffffffffffffffffffff19808860601b166001840152808760601b166015840152506001600160c01b03198560c01b16602983015282846031840137506000910160310190815295945050505050565b6001600160a01b038516815267ffffffffffffffff841660208201526060604082015260006124dc606083018486612106565b60006001600160a01b03808916835280881660208401525085604083015267ffffffffffffffff8516606083015260a060808301526125d760a083018486612106565b9897505050505050505056fea264697066735822122039fad004b06bdfacc0b47f21cbb77fd17e32b866bad7645b8df7ce8c048fa90464736f6c634300080900330000000000000000000000009b36f165bab9ebe611d491180418d8de4b8f3a1f0000000000000000000000009b36f165bab9ebe611d491180418d8de4b8f3a1f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

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

0000000000000000000000009b36f165bab9ebe611d491180418d8de4b8f3a1f0000000000000000000000009b36f165bab9ebe611d491180418d8de4b8f3a1f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

-----Decoded View---------------
Arg [0] : _sigsVerifier (address): 0x9b36f165bab9ebe611d491180418d8de4b8f3a1f
Arg [1] : _liquidityBridge (address): 0x9b36f165bab9ebe611d491180418d8de4b8f3a1f
Arg [2] : _pegBridge (address): 0x0000000000000000000000000000000000000000
Arg [3] : _pegVault (address): 0x0000000000000000000000000000000000000000

-----Encoded View---------------
4 Constructor Arguments found :
Arg [0] : 0000000000000000000000009b36f165bab9ebe611d491180418d8de4b8f3a1f
Arg [1] : 0000000000000000000000009b36f165bab9ebe611d491180418d8de4b8f3a1f
Arg [2] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000000


Deployed ByteCode Sourcemap

135:857:49:-:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;12431:88:50;;;;;;;;;;-1:-1:-1;12431:88:50;;;;;:::i;:::-;;:::i;:::-;;4445:84:51;;;;;;;;;;-1:-1:-1;4445:84:51;;;;;:::i;:::-;;:::i;615:375:49:-;;;;;;;;;;-1:-1:-1;615:375:49;;;;;:::i;:::-;;:::i;3284:660:51:-;;;;;;;;;;-1:-1:-1;3284:660:51;;;;;:::i;:::-;;:::i;2072:670::-;;;;;;:::i;:::-;;:::i;4153:134::-;;;;;;;;;;-1:-1:-1;4153:134:51;;;;;:::i;:::-;;:::i;:::-;;;4190:25:75;;;4178:2;4163:18;4153:134:51;;;;;;;;12325:100:50;;;;;;;;;;-1:-1:-1;12325:100:50;;;;;:::i;:::-;;:::i;4495:1082::-;;;;;;:::i;:::-;;:::i;302:48:51:-;;;;;;;;;;-1:-1:-1;302:48:51;;;;;:::i;:::-;;;;;;;;;;;;;;6068:1085:50;;;;;;:::i;:::-;;:::i;1108:30::-;;;;;;;;;;-1:-1:-1;1108:30:50;;;;-1:-1:-1;;;;;1108:30:50;;;;;;-1:-1:-1;;;;;7544:55:75;;;7526:74;;7514:2;7499:18;1108:30:50;7380:226:75;1480:85:68;;;;;;;;;;-1:-1:-1;1526:7:68;1552:6;-1:-1:-1;;;;;1552:6:68;1480:85;;243:22:51;;;;;;;;;;;;;;;;12525:86:50;;;;;;;;;;-1:-1:-1;12525:86:50;;;;;:::i;:::-;;:::i;1167:321:51:-;;;;;;:::i;:::-;;:::i;2566:1401:50:-;;;;;;:::i;:::-;;:::i;193:43:51:-;;;;;;;;;;;;;;;1049:52:50;;;;;;;;;;-1:-1:-1;1049:52:50;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;:::i;1224:23::-;;;;;;;;;;-1:-1:-1;1224:23:50;;;;-1:-1:-1;;;;;1224:23:50;;;1172:24;;;;;;;;;;-1:-1:-1;1172:24:50;;;;-1:-1:-1;;;;;1172:24:50;;;4349:90:51;;;;;;;;;;-1:-1:-1;4349:90:51;;;;;:::i;:::-;;:::i;1917:189:68:-;;;;;;;;;;-1:-1:-1;1917:189:68;;;;;:::i;:::-;;:::i;271:25:51:-;;;;;;;;;;;;;;;;12431:88:50;1703:10:68;1692:7;1526;1552:6;-1:-1:-1;;;;;1552:6:68;;1480:85;1692:7;-1:-1:-1;;;;;1692:21:68;;1684:66;;;;-1:-1:-1;;;1684:66:68;;9295:2:75;1684:66:68;;;9277:21:75;;;9314:18;;;9307:30;9373:34;9353:18;;;9346:62;9425:18;;1684:66:68;;;;;;;;;12495:9:50::1;:17:::0;;-1:-1:-1;;;;;;12495:17:50::1;-1:-1:-1::0;;;;;12495:17:50;;;::::1;::::0;;;::::1;::::0;;12431:88::o;4445:84:51:-;1703:10:68;1692:7;1526;1552:6;-1:-1:-1;;;;;1552:6:68;;1480:85;1692:7;-1:-1:-1;;;;;1692:21:68;;1684:66;;;;-1:-1:-1;;;1684:66:68;;9295:2:75;1684:66:68;;;9277:21:75;;;9314:18;;;9307:30;9373:34;9353:18;;;9346:62;9425:18;;1684:66:68;9093:356:75;1684:66:68;4508:7:51::1;:14:::0;4445:84::o;615:375:49:-;810:11;:9;:11::i;:::-;930:53;943:16;961:10;973:9;930:12;:53::i;:::-;615:375;;;:::o;3284:660:51:-;3493:14;3537:13;3560:4;3520:61;;;;;;;;9712:19:75;;;9769:2;9765:15;-1:-1:-1;;9761:53:75;9756:2;9747:12;;9740:75;9845:13;9840:2;9831:12;;9824:35;9884:2;9875:12;;9454:439;3520:61:51;;;;;;;-1:-1:-1;;3520:61:51;;;;;;3510:72;;3520:61;3510:72;;;;3616:50;;;10083:19:75;;;10140:2;10136:15;;;-1:-1:-1;;10132:53:75;10118:12;;;10111:75;10202:12;;;;10195:28;;;3616:50:51;;;;;;;;;;10239:12:75;;;3616:50:51;;;;-1:-1:-1;;;3592:101:51;;;3510:72;-1:-1:-1;3592:12:51;-1:-1:-1;;;;;3592:23:51;;;;:101;;3668:5;;;;3675:8;;;;3685:7;;;;3592:101;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;;;;;;;;;3737:23:51;;3703:14;3737:23;;;:13;:23;;;;;;3720:40;;:14;:40;:::i;:::-;3703:57;;3787:1;3778:6;:10;3770:48;;;;-1:-1:-1;;;3770:48:51;;14065:2:75;3770:48:51;;;14047:21:75;14104:2;14084:18;;;14077:30;14143:27;14123:18;;;14116:55;14188:18;;3770:48:51;13863:349:75;3770:48:51;3829:9;3844:8;-1:-1:-1;;;;;3844:13:51;3865:6;3878:5;3844:44;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;3828:60;;;3906:4;3898:39;;;;-1:-1:-1;;;3898:39:51;;14629:2:75;3898:39:51;;;14611:21:75;14668:2;14648:18;;;14641:30;14707:24;14687:18;;;14680:52;14749:18;;3898:39:51;14427:346:75;3898:39:51;3483:461;;;3284:660;;;;;;;;:::o;2072:670::-;2287:14;2304:17;2312:8;;2304:7;:17::i;:::-;2287:34;;2352:6;2339:9;:19;;2331:48;;;;-1:-1:-1;;;2331:48:51;;14980:2:75;2331:48:51;;;14962:21:75;15019:2;14999:18;;;14992:30;-1:-1:-1;;;15038:18:75;;;15031:46;15094:18;;2331:48:51;14778:340:75;2331:48:51;2651:10;-1:-1:-1;;;;;2631:104:51;;2663:9;2674:11;2687:10;2699:14;2715:8;;2725:9;2631:104;;;;;;;;;;;;:::i;:::-;;;;;;;;2277:465;2072:670;;;;;;:::o;4153:134::-;4270:10;;4216:7;;4252:28;;:8;:28;:::i;:::-;4242:7;;:38;;;;:::i;:::-;4235:45;;4153:134;;;;;:::o;12325:100:50:-;1703:10:68;1692:7;1526;1552:6;-1:-1:-1;;;;;1552:6:68;;1480:85;1692:7;-1:-1:-1;;;;;1692:21:68;;1684:66;;;;-1:-1:-1;;;1684:66:68;;9295:2:75;1684:66:68;;;9277:21:75;;;9314:18;;;9307:30;9373:34;9353:18;;;9346:62;9425:18;;1684:66:68;9093:356:75;1684:66:68;12395:15:50::1;:23:::0;;-1:-1:-1;;;;;;12395:23:50::1;-1:-1:-1::0;;;;;12395:23:50;;;::::1;::::0;;;::::1;::::0;;12325:100::o;4495:1082::-;4856:17;4876:25;4891:9;4876:14;:25::i;:::-;4856:45;-1:-1:-1;4950:13:50;4919:27;;;;:16;:27;;;;;;;;:44;;;;;;;;:::i;:::-;;4911:82;;;;-1:-1:-1;;;4911:82:50;;16318:2:75;4911:82:50;;;16300:21:75;16357:2;16337:18;;;16330:30;16396:27;16376:18;;;16369:55;16441:18;;4911:82:50;16116:349:75;4911:82:50;5004:14;5048:13;5071:4;5031:75;;;;;;;;16728:19:75;;;16785:2;16781:15;-1:-1:-1;;16777:53:75;16772:2;16763:12;;16756:75;16861:27;16856:2;16847:12;;16840:49;16914:2;16905:12;;16470:453;5031:75:50;;;;;;;;;;;;;5021:86;;;;;;5004:103;;5125:15;;;;;;;;;-1:-1:-1;;;;;5125:15:50;-1:-1:-1;;;;;5117:35:50;;5170:6;5178:9;5189:8;;5153:45;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;5200:5;;5207:8;;5217:7;;5117:108;;;;;;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;5235:15;5260:12;5275:53;5308:9;5319:8;;5275:32;:53::i;:::-;5260:68;;5342:7;5338:116;;;5374:16;5365:25;;5338:116;;;5430:13;5421:22;;5338:116;5463:27;;;;:16;:27;;;;;:36;;5493:6;;5463:27;-1:-1:-1;;5463:36:50;;5493:6;5463:36;;;;;;;;:::i;:::-;;;;;;5514:56;5523:27;5552:9;5563:6;5514:56;;;;;;;;:::i;:::-;;;;;;;;4797:780;;;;4495:1082;;;;;;;;;:::o;6068:1085::-;6477:17;6497:38;6518:6;6526:8;;6497:20;:38::i;:::-;6477:58;-1:-1:-1;6584:13:50;6553:27;;;;:16;:27;;;;;;;;:44;;;;;;;;:::i;:::-;;6545:81;;;;-1:-1:-1;;;6545:81:50;;17966:2:75;6545:81:50;;;17948:21:75;18005:2;17985:18;;;17978:30;18044:26;18024:18;;;18017:54;18088:18;;6545:81:50;17764:348:75;6545:81:50;6637:14;6681:13;6704:4;6664:57;;;;;;;;18375:19:75;;;18432:2;18428:15;-1:-1:-1;;18424:53:75;18419:2;18410:12;;18403:75;18508:9;18503:2;18494:12;;18487:31;18543:2;18534:12;;18117:435;6664:57:50;;;;-1:-1:-1;;6664:57:50;;;;;;;;;6654:68;;6664:57;6654:68;;;;6740:15;;6768:35;;;18714:19:75;;;18749:12;;;18742:28;;;6768:35:50;;;;;;;;;18786:12:75;;;6768:35:50;;;;-1:-1:-1;;;6732:98:50;;;6654:68;-1:-1:-1;;;;;;6740:15:50;;6732:35;;:98;;6805:5;;;;6812:8;;;;6822:7;;;;6732:98;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6840:15;6865:12;6880:32;6895:6;6903:8;;6880:14;:32::i;:::-;6865:47;;6926:7;6922:116;;;6958:16;6949:25;;6922:116;;;7014:13;7005:22;;6922:116;7047:27;;;;:16;:27;;;;;:36;;7077:6;;7047:27;-1:-1:-1;;7047:36:50;;7077:6;7047:36;;;;;;;;:::i;:::-;;;;;;7098:48;7107:19;7128:9;7139:6;7098:48;;;;;;;;:::i;12525:86::-;1703:10:68;1692:7;1526;1552:6;-1:-1:-1;;;;;1552:6:68;;1480:85;1692:7;-1:-1:-1;;;;;1692:21:68;;1684:66;;;;-1:-1:-1;;;1684:66:68;;9295:2:75;1684:66:68;;;9277:21:75;;;9314:18;;;9307:30;9373:34;9353:18;;;9346:62;9425:18;;1684:66:68;9093:356:75;1684:66:68;12588:8:50::1;:16:::0;;-1:-1:-1;;;;;;12588:16:50::1;-1:-1:-1::0;;;;;12588:16:50;;;::::1;::::0;;;::::1;::::0;;12525:86::o;1167:321:51:-;1310:14;1327:17;1335:8;;1327:7;:17::i;:::-;1310:34;;1375:6;1362:9;:19;;1354:48;;;;-1:-1:-1;;;1354:48:51;;14980:2:75;1354:48:51;;;14962:21:75;15019:2;14999:18;;;14992:30;-1:-1:-1;;;15038:18:75;;;15031:46;15094:18;;1354:48:51;14778:340:75;1354:48:51;1425:10;-1:-1:-1;;;;;1417:64:51;;1437:9;1448:11;1461:8;;1471:9;1417:64;;;;;;;;;;:::i;:::-;;;;;;;;1300:188;1167:321;;;;:::o;2566:1401:50:-;3069:17;3089:25;3104:9;3089:14;:25::i;:::-;3069:45;-1:-1:-1;3163:13:50;3132:27;;;;:16;:27;;;;;;;;:44;;;;;;;;:::i;:::-;;3124:82;;;;-1:-1:-1;;;3124:82:50;;16318:2:75;3124:82:50;;;16300:21:75;16357:2;16337:18;;;16330:30;16396:27;16376:18;;;16369:55;16441:18;;3124:82:50;16116:349:75;3124:82:50;3217:14;3261:13;3284:4;3244:69;;;;;;;;19580:19:75;;;19637:2;19633:15;-1:-1:-1;;19629:53:75;19624:2;19615:12;;19608:75;19713:21;19708:2;19699:12;;19692:43;19760:2;19751:12;;19322:447;3244:69:50;;;;;;;;;;;;;3234:80;;;;;;3217:97;;3332:15;;;;;;;;;-1:-1:-1;;;;;3332:15:50;-1:-1:-1;;;;;3324:35:50;;3377:6;3385:9;3396:8;;3360:45;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;3407:5;;3414:8;;3424:7;;3324:108;;;;;;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;3442:15;3467:12;3482:47;3509:9;3520:8;;3482:26;:47::i;:::-;3467:62;;3543:7;3539:305;;;3575:16;3566:25;;3539:305;;;3632:55;3667:9;3678:8;;3632:34;:55::i;:::-;3622:65;;3705:7;3701:133;;;3741:17;3732:26;;3701:133;;4349:90:51;1703:10:68;1692:7;1526;1552:6;-1:-1:-1;;;;;1552:6:68;;1480:85;1692:7;-1:-1:-1;;;;;1692:21:68;;1684:66;;;;-1:-1:-1;;;1684:66:68;;9295:2:75;1684:66:68;;;9277:21:75;;;9314:18;;;9307:30;9373:34;9353:18;;;9346:62;9425:18;;1684:66:68;9093:356:75;1684:66:68;4415:10:51::1;:17:::0;4349:90::o;1917:189:68:-;1703:10;1692:7;1526;1552:6;-1:-1:-1;;;;;1552:6:68;;1480:85;1692:7;-1:-1:-1;;;;;1692:21:68;;1684:66;;;;-1:-1:-1;;;1684:66:68;;9295:2:75;1684:66:68;;;9277:21:75;;;9314:18;;;9307:30;9373:34;9353:18;;;9346:62;9425:18;;1684:66:68;9093:356:75;1684:66:68;-1:-1:-1;;;;;2005:22:68;::::1;1997:73;;;::::0;-1:-1:-1;;;1997:73:68;;19976:2:75;1997:73:68::1;::::0;::::1;19958:21:75::0;20015:2;19995:18;;;19988:30;20054:34;20034:18;;;20027:62;20125:8;20105:18;;;20098:36;20151:19;;1997:73:68::1;19774:402:75::0;1997:73:68::1;2080:19;2090:8;2080:9;:19::i;:::-;1917:189:::0;:::o;1276:128::-;1342:1;1324:6;-1:-1:-1;;;;;1324:6:68;:20;1316:50;;;;-1:-1:-1;;;1316:50:68;;20383:2:75;1316:50:68;;;20365:21:75;20422:2;20402:18;;;20395:30;20461:19;20441:18;;;20434:47;20498:18;;1316:50:68;20181:341:75;1316:50:68;1376:21;1386:10;1376:9;:21::i;:::-;1276:128::o;1651:318:50:-;1795:15;;-1:-1:-1;;;;;1795:15:50;:29;1787:69;;;;-1:-1:-1;;;1787:69:50;;20729:2:75;1787:69:50;;;20711:21:75;20768:2;20748:18;;;20741:30;20807:29;20787:18;;;20780:57;20854:18;;1787:69:50;20527:351:75;1787:69:50;1866:15;:34;;-1:-1:-1;;;;;1866:34:50;;;-1:-1:-1;;;;;;1866:34:50;;;;;;;1910:9;:22;;;;;;;;;;;;;;;1942:8;:20;;;;;;;;;;;1651:318::o;9201:2215::-;9280:7;;;9374:19;9359:11;;;;:9;:11;:::i;:::-;:34;;;;;;;;:::i;:::-;;9355:1958;;;9487:16;;;;;;;;:::i;:::-;9525:18;;;;;;;;:::i;:::-;9565:15;;;;;;;;:::i;:::-;9602:16;;;;9640:20;;;;;;;;:::i;:::-;9449:309;;-1:-1:-1;;21814:2:75;21810:15;;;21806:24;;9449:309:50;;;21794:37:75;21865:15;;;21861:24;;21847:12;;;21840:46;21920:15;;;;21916:24;;;21902:12;;;21895:46;21957:12;;;21950:28;;;;-1:-1:-1;;;;;;22101:3:75;22097:16;;;22093:25;;22079:12;;;22072:47;9689:13:50;22154:16:75;;;22150:25;;;22135:13;;;22128:48;9725:15:50;;;;22192:13:75;;;22185:29;22230:13;;9449:309:50;;;;;;-1:-1:-1;;9449:309:50;;;;;;;9422:350;;9449:309;9422:350;;;;9799:15;;-1:-1:-1;;;9836:41:50;;;;;4190:25:75;;;9422:350:50;;-1:-1:-1;;;;;;9799:15:50;;-1:-1:-1;9799:15:50;;9836:29;;4163:18:75;;9836:41:50;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;:49;;9881:4;9836:49;9828:84;;;;-1:-1:-1;;;9828:84:50;;22920:2:75;9828:84:50;;;22902:21:75;22959:2;22939:18;;;22932:30;22998:24;22978:18;;;22971:52;23040:18;;9828:84:50;22718:346:75;9828:84:50;9355:1958;;;9948:23;9933:11;;;;:9;:11;:::i;:::-;:38;;;;;;;;:::i;:::-;;9929:1384;;;10072:13;10108:16;;;;;;;;:::i;:::-;10146:18;;;;;;;;:::i;:::-;10186:15;;;;;;;;:::i;:::-;10027:230;;-1:-1:-1;;;;;;23411:3:75;23407:16;;;23403:25;;10027:230:50;;;23391:38:75;23462:16;;;;23458:25;;;23445:11;;;23438:46;-1:-1:-1;;23572:2:75;23568:15;;;23564:24;;23550:12;;;23543:46;23623:15;;;23619:24;23605:12;;;23598:46;10223:16:50;;;;23660:12:75;;;23653:28;23697:12;;10027:230:50;;;;;;-1:-1:-1;;10027:230:50;;;;;;;10000:271;;10027:230;10000:271;;;;10298:15;;-1:-1:-1;;;10335:41:50;;;;;4190:25:75;;;10000:271:50;;-1:-1:-1;;;;;;10298:15:50;;-1:-1:-1;10298:15:50;;10335:29;;4163:18:75;;10335:41:50;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;:49;;10380:4;10335:49;10327:87;;;;-1:-1:-1;;;10327:87:50;;23922:2:75;10327:87:50;;;23904:21:75;23961:2;23941:18;;;23934:30;24000:27;23980:18;;;23973:55;24045:18;;10327:87:50;23720:349:75;9929:1384:50;10450:20;10435:11;;;;:9;:11;:::i;:::-;:35;;;;;;;;:::i;:::-;;:78;;;-1:-1:-1;10489:24:50;10474:11;;;;:9;:11;:::i;:::-;:39;;;;;;;;:::i;:::-;;10435:78;10431:882;;;10607:18;;;;;;;;:::i;:::-;10647:15;;;;;;;;:::i;:::-;10684:16;;;;10722;;;;;;;;:::i;:::-;10760:20;;;;;;;;:::i;:::-;10569:266;;24411:2:75;24407:15;;;-1:-1:-1;;24403:24:75;;;10569:266:50;;;24391:37:75;24462:15;;;24458:24;;24444:12;;;24437:46;24499:12;;;24492:28;;;;24554:15;;24550:24;;;24536:12;;;24529:46;24613:3;24609:16;;;;-1:-1:-1;;;;;;24605:89:75;24591:12;;;24584:111;10802:15:50;;;;24711:13:75;;;24704:29;24749:13;;10569:266:50;;;-1:-1:-1;;10569:266:50;;;;;;;;;10542:307;;10569:266;10542:307;;;;;-1:-1:-1;10882:20:50;10867:11;;;;:9;:11;:::i;:::-;:35;;;;;;;;:::i;:::-;;10863:440;;;-1:-1:-1;10935:9:50;;10970:50;;-1:-1:-1;;;10970:50:50;;;;;4190:25:75;;;-1:-1:-1;;;;;10935:9:50;;;;;;10970:38;;4163:18:75;;10970:50:50;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;:58;;11024:4;10970:58;10962:92;;;;-1:-1:-1;;;10962:92:50;;24975:2:75;10962:92:50;;;24957:21:75;25014:2;24994:18;;;24987:30;25053:23;25033:18;;;25026:51;25094:18;;10962:92:50;24773:345:75;10863:440:50;-1:-1:-1;11165:8:50;;11199:51;;-1:-1:-1;;;11199:51:50;;;;;4190:25:75;;;-1:-1:-1;;;;;11165:8:50;;;;;;11199:39;;4163:18:75;;11199:51:50;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;:59;;11254:4;11199:59;11191:97;;;;-1:-1:-1;;;11191:97:50;;25325:2:75;11191:97:50;;;25307:21:75;25364:2;25344:18;;;25337:30;25403:27;25383:18;;;25376:55;25448:18;;11191:97:50;25123:349:75;11191:97:50;11356:27;11385:10;11397;11339:69;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;11329:80;;;;;;11322:87;;;;9201:2215;;;:::o;8591:604::-;8724:4;;;8782:18;;;;;;;;:::i;:::-;-1:-1:-1;;;;;8774:32:50;8814:9;-1:-1:-1;;;8957:15:50;;;;;;;;:::i;:::-;8990:9;:16;;;9024:8;;8838:208;;;;;;;;;;;:::i;:::-;;;;-1:-1:-1;;8838:208:50;;;;;;;;;;;;;;;;;;;;;;;;;;;8774:282;;;;8838:208;8774:282;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;8744:312;;;;9070:2;9066:101;;;9088:12;9115:3;9103:25;;;;;;;;;;;;:::i;:::-;9088:40;-1:-1:-1;9142:14:50;;-1:-1:-1;;;9142:14:50;9066:101;9183:5;9176:12;;;;8591:604;;;;;;:::o;11422:288::-;11526:7;11608:19;11629:13;;;;:6;:13;:::i;:::-;11644:15;;;;;;;;:::i;:::-;11661:17;;;;;;;;:::i;:::-;11680:8;;11591:98;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;11564:139;;;;;;11545:158;;11422:288;;;;;:::o;11716:538::-;11809:4;;;11863:15;;;;;;;;:::i;:::-;-1:-1:-1;;;;;11855:29:50;11892:9;-1:-1:-1;;;12017:13:50;;;;:6;:13;:::i;:::-;12048:17;;;;;;;;:::i;:::-;12083:8;;11916:189;;;;;;;;;;;:::i;7235:664::-;7362:4;;;7420:18;;;;;;;;:::i;:::-;-1:-1:-1;;;;;7412:32:50;7452:9;-1:-1:-1;;;7589:16:50;;;;;;;;:::i;:::-;7623:15;;;;;;;;:::i;:::-;7656:16;;;;7690:20;;;;;;;;:::i;:::-;7728:8;;7476:274;;;;;;;;;;;;;:::i;7905:680::-;8040:4;;;8098:18;;;;;;;;:::i;:::-;-1:-1:-1;;;;;8090:32:50;8130:9;-1:-1:-1;;;8275:16:50;;;;;;;;:::i;2112:169:68:-;2167:16;2186:6;;-1:-1:-1;;;;;2202:17:68;;;-1:-1:-1;;;;;;2202:17:68;;;;;;2234:40;;2186:6;;;;;;;2234:40;;2167:16;2234:40;2157:124;2112:169;:::o;14:196:75:-;82:20;;-1:-1:-1;;;;;131:54:75;;121:65;;111:93;;200:1;197;190:12;111:93;14:196;;;:::o;215:186::-;274:6;327:2;315:9;306:7;302:23;298:32;295:52;;;343:1;340;333:12;295:52;366:29;385:9;366:29;:::i;406:180::-;465:6;518:2;506:9;497:7;493:23;489:32;486:52;;;534:1;531;524:12;486:52;-1:-1:-1;557:23:75;;406:180;-1:-1:-1;406:180:75:o;591:334::-;668:6;676;684;737:2;725:9;716:7;712:23;708:32;705:52;;;753:1;750;743:12;705:52;776:29;795:9;776:29;:::i;:::-;766:39;;824:38;858:2;847:9;843:18;824:38;:::i;:::-;814:48;;881:38;915:2;904:9;900:18;881:38;:::i;:::-;871:48;;591:334;;;;;:::o;930:374::-;1000:8;1010:6;1064:3;1057:4;1049:6;1045:17;1041:27;1031:55;;1082:1;1079;1072:12;1031:55;-1:-1:-1;1105:20:75;;1148:18;1137:30;;1134:50;;;1180:1;1177;1170:12;1134:50;1217:4;1209:6;1205:17;1193:29;;1277:3;1270:4;1260:6;1257:1;1253:14;1245:6;1241:27;1237:38;1234:47;1231:67;;;1294:1;1291;1284:12;1231:67;930:374;;;;;:::o;1309:1264::-;1496:6;1504;1512;1520;1528;1536;1544;1552;1605:3;1593:9;1584:7;1580:23;1576:33;1573:53;;;1622:1;1619;1612:12;1573:53;1645:29;1664:9;1645:29;:::i;:::-;1635:39;;1721:2;1710:9;1706:18;1693:32;1683:42;;1776:2;1765:9;1761:18;1748:32;1799:18;1840:2;1832:6;1829:14;1826:34;;;1856:1;1853;1846:12;1826:34;1895:77;1964:7;1955:6;1944:9;1940:22;1895:77;:::i;:::-;1991:8;;-1:-1:-1;1869:103:75;-1:-1:-1;2079:2:75;2064:18;;2051:32;;-1:-1:-1;2095:16:75;;;2092:36;;;2124:1;2121;2114:12;2092:36;2163:79;2234:7;2223:8;2212:9;2208:24;2163:79;:::i;:::-;2261:8;;-1:-1:-1;2137:105:75;-1:-1:-1;2349:3:75;2334:19;;2321:33;;-1:-1:-1;2366:16:75;;;2363:36;;;2395:1;2392;2385:12;2363:36;;2434:79;2505:7;2494:8;2483:9;2479:24;2434:79;:::i;:::-;1309:1264;;;;-1:-1:-1;1309:1264:75;;-1:-1:-1;1309:1264:75;;;;;;2532:8;-1:-1:-1;;;1309:1264:75:o;2578:347::-;2629:8;2639:6;2693:3;2686:4;2678:6;2674:17;2670:27;2660:55;;2711:1;2708;2701:12;2660:55;-1:-1:-1;2734:20:75;;2777:18;2766:30;;2763:50;;;2809:1;2806;2799:12;2763:50;2846:4;2838:6;2834:17;2822:29;;2898:3;2891:4;2882:6;2874;2870:19;2866:30;2863:39;2860:59;;;2915:1;2912;2905:12;2930:695;3036:6;3044;3052;3060;3068;3076;3129:3;3117:9;3108:7;3104:23;3100:33;3097:53;;;3146:1;3143;3136:12;3097:53;3169:29;3188:9;3169:29;:::i;:::-;3159:39;;3245:2;3234:9;3230:18;3217:32;3207:42;;3268:38;3302:2;3291:9;3287:18;3268:38;:::i;:::-;3258:48;;3353:2;3342:9;3338:18;3325:32;3315:42;;3408:3;3397:9;3393:19;3380:33;3436:18;3428:6;3425:30;3422:50;;;3468:1;3465;3458:12;3422:50;3507:58;3557:7;3548:6;3537:9;3533:22;3507:58;:::i;:::-;2930:695;;;;-1:-1:-1;2930:695:75;;-1:-1:-1;2930:695:75;;3584:8;;2930:695;-1:-1:-1;;;2930:695:75:o;3630:409::-;3700:6;3708;3761:2;3749:9;3740:7;3736:23;3732:32;3729:52;;;3777:1;3774;3767:12;3729:52;3817:9;3804:23;3850:18;3842:6;3839:30;3836:50;;;3882:1;3879;3872:12;3836:50;3921:58;3971:7;3962:6;3951:9;3947:22;3921:58;:::i;:::-;3998:8;;3895:84;;-1:-1:-1;3630:409:75;-1:-1:-1;;;;3630:409:75:o;4226:1574::-;4457:6;4465;4473;4481;4489;4497;4505;4513;4521;4565:9;4556:7;4552:23;4595:3;4591:2;4587:12;4584:32;;;4612:1;4609;4602:12;4584:32;4652:9;4639:23;4681:18;4722:2;4714:6;4711:14;4708:34;;;4738:1;4735;4728:12;4708:34;4777:58;4827:7;4818:6;4807:9;4803:22;4777:58;:::i;:::-;4854:8;;-1:-1:-1;4751:84:75;-1:-1:-1;4751:84:75;;-1:-1:-1;4923:3:75;-1:-1:-1;;4905:16:75;;4901:26;4898:46;;;4940:1;4937;4930:12;4898:46;4978:2;4967:9;4963:18;4953:28;;5034:3;5023:9;5019:19;5006:33;4990:49;;5064:2;5054:8;5051:16;5048:36;;;5080:1;5077;5070:12;5048:36;5119:79;5190:7;5179:8;5168:9;5164:24;5119:79;:::i;:::-;5093:105;;-1:-1:-1;5093:105:75;-1:-1:-1;5305:3:75;5290:19;;5277:33;;-1:-1:-1;5093:105:75;;-1:-1:-1;5322:16:75;;;5319:36;;;5351:1;5348;5341:12;5319:36;5390:79;5461:7;5450:8;5439:9;5435:24;5390:79;:::i;:::-;5364:105;;-1:-1:-1;5364:105:75;-1:-1:-1;5576:3:75;5561:19;;5548:33;;-1:-1:-1;5364:105:75;;-1:-1:-1;5593:16:75;;;5590:36;;;5622:1;5619;5612:12;5590:36;;;5661:79;5732:7;5721:8;5710:9;5706:24;5661:79;:::i;:::-;5635:105;;5759:8;5749:18;;;5786:8;5776:18;;;4226:1574;;;;;;;;;;;:::o;5805:1570::-;6033:6;6041;6049;6057;6065;6073;6081;6089;6097;6141:9;6132:7;6128:23;6171:3;6167:2;6163:12;6160:32;;;6188:1;6185;6178:12;6160:32;6228:9;6215:23;6257:18;6298:2;6290:6;6287:14;6284:34;;;6314:1;6311;6304:12;6284:34;6353:58;6403:7;6394:6;6383:9;6379:22;6353:58;:::i;:::-;6430:8;;-1:-1:-1;6327:84:75;-1:-1:-1;6327:84:75;;-1:-1:-1;6499:2:75;-1:-1:-1;;6481:16:75;;6477:25;6474:45;;;6515:1;6512;6505:12;6474:45;6553:2;6542:9;6538:18;6528:28;;6609:3;6598:9;6594:19;6581:33;6565:49;;6639:2;6629:8;6626:16;6623:36;;;6655:1;6652;6645:12;6623:36;6694:79;6765:7;6754:8;6743:9;6739:24;6694:79;:::i;:::-;6668:105;;-1:-1:-1;6668:105:75;-1:-1:-1;6880:3:75;6865:19;;6852:33;;-1:-1:-1;6668:105:75;;-1:-1:-1;6897:16:75;;;6894:36;;;6926:1;6923;6916:12;6894:36;6965:79;7036:7;7025:8;7014:9;7010:24;6965:79;:::i;:::-;6939:105;;-1:-1:-1;6939:105:75;-1:-1:-1;7151:3:75;7136:19;;7123:33;;-1:-1:-1;6939:105:75;;-1:-1:-1;7168:16:75;;;7165:36;;;7197:1;7194;7187:12;7611:551;7699:6;7707;7715;7723;7776:2;7764:9;7755:7;7751:23;7747:32;7744:52;;;7792:1;7789;7782:12;7744:52;7815:29;7834:9;7815:29;:::i;:::-;7805:39;;7891:2;7880:9;7876:18;7863:32;7853:42;;7946:2;7935:9;7931:18;7918:32;7973:18;7965:6;7962:30;7959:50;;;8005:1;8002;7995:12;7959:50;8044:58;8094:7;8085:6;8074:9;8070:22;8044:58;:::i;:::-;7611:551;;;;-1:-1:-1;8121:8:75;-1:-1:-1;;;;7611:551:75:o;8605:127::-;8666:10;8661:3;8657:20;8654:1;8647:31;8697:4;8694:1;8687:15;8721:4;8718:1;8711:15;8737:139;8817:1;8810:5;8807:12;8797:46;;8823:18;;:::i;:::-;8852;;8737:139::o;8881:207::-;9027:2;9012:18;;9039:43;9016:9;9064:6;9039:43;:::i;10262:258::-;10334:1;10344:113;10358:6;10355:1;10352:13;10344:113;;;10434:11;;;10428:18;10415:11;;;10408:39;10380:2;10373:10;10344:113;;;10475:6;10472:1;10469:13;10466:48;;;10510:1;10501:6;10496:3;10492:16;10485:27;10466:48;;10262:258;;;:::o;10525:266::-;10613:6;10608:3;10601:19;10665:6;10658:5;10651:4;10646:3;10642:14;10629:43;-1:-1:-1;10717:1:75;10692:16;;;10710:4;10688:27;;;10681:38;;;;10773:2;10752:15;;;-1:-1:-1;;10748:29:75;10739:39;;;10735:50;;10525:266::o;10796:470::-;10896:6;10891:3;10884:19;10866:3;10922:4;10951:2;10946:3;10942:12;10935:19;;10977:5;11000:1;11010:231;11024:6;11021:1;11018:13;11010:231;;;-1:-1:-1;;;;;11089:26:75;11108:6;11089:26;:::i;:::-;11085:75;11073:88;;11181:12;;;;11216:15;;;;11046:1;11039:9;11010:231;;;-1:-1:-1;11257:3:75;;10796:470;-1:-1:-1;;;;;10796:470:75:o;11271:401::-;11371:6;11366:3;11359:19;11341:3;11401:66;11393:6;11390:78;11387:98;;;11481:1;11478;11471:12;11387:98;11517:6;11514:1;11510:14;11569:8;11562:5;11555:4;11550:3;11546:14;11533:45;11646:1;11601:18;;11621:4;11597:29;11635:13;;;-1:-1:-1;11597:29:75;;11271:401;-1:-1:-1;;11271:401:75:o;11677:1919::-;12108:3;12097:9;12090:22;12071:4;12141:6;12135:13;12185:6;12179:3;12168:9;12164:19;12157:35;12201:69;12263:6;12257:3;12246:9;12242:19;12235:4;12227:6;12223:17;12201:69;:::i;:::-;12329:2;12308:15;-1:-1:-1;;12304:29:75;12289:45;;12408:18;;;12362:3;12404:28;;;12397:4;12382:20;;12375:58;12354:12;;12465:19;;;12551:1;12547:14;;;12539:23;;12508:3;12535:33;;;;12500:12;;12591:6;12615:1;12625:685;12639:6;12636:1;12633:13;12625:685;;;12704:15;;;-1:-1:-1;;12700:30:75;12688:43;;12770:20;;12845:14;12841:27;;;-1:-1:-1;;12837:41:75;12813:66;;12803:94;;12893:1;12890;12883:12;12803:94;12923:31;;12983:19;;13031:18;13018:32;;13015:52;;;13063:1;13060;13053:12;13015:52;13115:8;13099:14;13095:29;13087:6;13083:42;13080:62;;;13138:1;13135;13128:12;13080:62;13165:61;13219:6;13209:8;13202:4;13195:5;13191:16;13165:61;:::i;:::-;13155:71;-1:-1:-1;;;13261:4:75;13286:14;;;;13249:17;;;;;12661:1;12654:9;12625:685;;;12629:3;;;13358:9;13350:6;13346:22;13341:2;13330:9;13326:18;13319:50;13392:61;13446:6;13438;13430;13392:61;:::i;:::-;13378:75;;;13501:9;13493:6;13489:22;13484:2;13473:9;13469:18;13462:50;13529:61;13583:6;13575;13567;13529:61;:::i;:::-;13521:69;11677:1919;-1:-1:-1;;;;;;;;;;11677:1919:75:o;13601:127::-;13662:10;13657:3;13653:20;13650:1;13643:31;13693:4;13690:1;13683:15;13717:4;13714:1;13707:15;13733:125;13773:4;13801:1;13798;13795:8;13792:34;;;13806:18;;:::i;:::-;-1:-1:-1;13843:9:75;;13733:125::o;15123:682::-;15383:4;-1:-1:-1;;;;;15493:2:75;15485:6;15481:15;15470:9;15463:34;15533:6;15528:2;15517:9;15513:18;15506:34;15588:2;15580:6;15576:15;15571:2;15560:9;15556:18;15549:43;;15628:6;15623:2;15612:9;15608:18;15601:34;15672:3;15666;15655:9;15651:19;15644:32;15693:62;15750:3;15739:9;15735:19;15727:6;15719;15693:62;:::i;:::-;15685:70;;15792:6;15786:3;15775:9;15771:19;15764:35;15123:682;;;;;;;;;;:::o;15810:168::-;15850:7;15916:1;15912;15908:6;15904:14;15901:1;15898:21;15893:1;15886:9;15879:17;15875:45;15872:71;;;15923:18;;:::i;:::-;-1:-1:-1;15963:9:75;;15810:168::o;15983:128::-;16023:3;16054:1;16050:6;16047:1;16044:13;16041:39;;;16060:18;;:::i;:::-;-1:-1:-1;16096:9:75;;15983:128::o;16928:410::-;17153:6;17148:3;17141:19;17190:6;17185:2;17180:3;17176:12;17169:28;17241:6;17233;17228:2;17223:3;17219:12;17206:42;17123:3;17271:16;;17289:2;17267:25;17301:13;;;17267:25;16928:410;-1:-1:-1;;;16928:410:75:o;17343:416::-;17556:2;17541:18;;17589:1;17578:13;;17568:47;;17595:18;;:::i;:::-;17642:6;17631:9;17624:25;17685:6;17680:2;17669:9;17665:18;17658:34;17701:52;17749:2;17738:9;17734:18;17726:6;17701:52;:::i;:::-;17343:416;;;;;;:::o;18809:508::-;-1:-1:-1;;;;;19054:6:75;19050:55;19039:9;19032:74;19142:6;19137:2;19126:9;19122:18;19115:34;19185:3;19180:2;19169:9;19165:18;19158:31;19013:4;19206:62;19263:3;19252:9;19248:19;19240:6;19232;19206:62;:::i;:::-;19198:70;;19304:6;19299:2;19288:9;19284:18;19277:34;18809:508;;;;;;;;:::o;20883:274::-;20960:6;21013:2;21001:9;20992:7;20988:23;20984:32;20981:52;;;21029:1;21026;21019:12;20981:52;21068:9;21055:23;21107:1;21100:5;21097:12;21087:40;;21123:1;21120;21113:12;21162:284;21220:6;21273:2;21261:9;21252:7;21248:23;21244:32;21241:52;;;21289:1;21286;21279:12;21241:52;21328:9;21315:23;21378:18;21371:5;21367:30;21360:5;21357:41;21347:69;;21412:1;21409;21402:12;22436:277;22503:6;22556:2;22544:9;22535:7;22531:23;22527:32;22524:52;;;22572:1;22569;22562:12;22524:52;22604:9;22598:16;22657:5;22650:13;22643:21;22636:5;22633:32;22623:60;;22679:1;22676;22669:12;25477:148;25556:1;25549:5;25546:12;25536:46;;25562:18;;:::i;:::-;25607:3;25603:15;25591:28;;25477:148::o;25630:386::-;25826:36;25858:3;25850:6;25826:36;:::i;:::-;25899:2;25895:15;;;;-1:-1:-1;;25891:53:75;25887:1;25878:11;;25871:74;25970:2;25961:12;;25954:28;26007:2;25998:12;;25630:386;-1:-1:-1;25630:386:75:o;26021:435::-;-1:-1:-1;;;;;26238:6:75;26234:55;26223:9;26216:74;26326:6;26321:2;26310:9;26306:18;26299:34;26369:2;26364;26353:9;26349:18;26342:30;26197:4;26389:61;26446:2;26435:9;26431:18;26423:6;26415;26389:61;:::i;:::-;26381:69;26021:435;-1:-1:-1;;;;;;26021:435:75:o;26461:274::-;26590:3;26628:6;26622:13;26644:53;26690:6;26685:3;26678:4;26670:6;26666:17;26644:53;:::i;:::-;26713:16;;;;;26461:274;-1:-1:-1;;26461:274:75:o;26740:734::-;27018:36;27050:3;27042:6;27018:36;:::i;:::-;27000:3;27077:26;27073:31;27154:2;27145:6;27141:2;27137:15;27133:24;27129:1;27124:3;27120:11;27113:45;27209:2;27200:6;27196:2;27192:15;27188:24;27183:2;27178:3;27174:12;27167:46;;-1:-1:-1;;;;;;27256:6:75;27251:3;27247:16;27243:89;27238:2;27233:3;27229:12;27222:111;27377:6;27369;27364:2;27359:3;27355:12;27342:42;-1:-1:-1;27448:1:75;27407:16;;27425:2;27403:25;27437:13;;;27403:25;26740:734;-1:-1:-1;;;;;26740:734:75:o;27479:458::-;-1:-1:-1;;;;;27694:6:75;27690:55;27679:9;27672:74;27794:18;27786:6;27782:31;27777:2;27766:9;27762:18;27755:59;27850:2;27845;27834:9;27830:18;27823:30;27653:4;27870:61;27927:2;27916:9;27912:18;27904:6;27896;27870:61;:::i;27942:633::-;28172:4;-1:-1:-1;;;;;28282:2:75;28274:6;28270:15;28259:9;28252:34;28334:2;28326:6;28322:15;28317:2;28306:9;28302:18;28295:43;;28374:6;28369:2;28358:9;28354:18;28347:34;28429:18;28421:6;28417:31;28412:2;28401:9;28397:18;28390:59;28486:3;28480;28469:9;28465:19;28458:32;28507:62;28564:3;28553:9;28549:19;28541:6;28533;28507:62;:::i;:::-;28499:70;27942:633;-1:-1:-1;;;;;;;;27942:633:75:o

Swarm Source

ipfs://39fad004b06bdfacc0b47f21cbb77fd17e32b866bad7645b8df7ce8c048fa904
Block Transaction Gas Used Reward
Age Block Fee Address BC Fee Address Voting Power Jailed Incoming
Block Uncle Number Difficulty Gas Used Reward
Loading