QubeBridge

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "@openzeppelin/contracts/security/Pausable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)

pragma solidity ^0.8.0;

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

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

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

    bool private _paused;

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

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

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

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

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

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}
"
    },
    "@openzeppelin/contracts/security/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

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

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

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

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

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}
"
    },
    "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

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

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

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);

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

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}
"
    },
    "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}
"
    },
    "@openzeppelin/contracts/utils/Address.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}
"
    },
    "@openzeppelin/contracts/utils/Context.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}
"
    },
    "@openzeppelin/contracts/utils/cryptography/ECDSA.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../Strings.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        } else if (error == RecoverError.InvalidSignatureV) {
            revert("ECDSA: invalid signature 'v' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        // 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 tryRecover(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 tryRecover(hash, r, vs);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

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

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

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

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

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

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

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

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _HEX_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }
}
"
    },
    "contracts/interfaces/ISigsVerifier.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\r
\r
pragma solidity >=0.8.0;\r
\r
interface ISigsVerifier {\r
    /**\r
     * @notice Verifies that a message is signed by a quorum among the signers.\r
     * @param _msg signed message\r
     * @param _sigs list of signatures sorted by signer addresses in ascending order\r
     * @param _signers sorted list of current signers\r
     * @param _powers powers of current signers\r
     */\r
    function verifySigs(\r
        bytes memory _msg,\r
        bytes[] calldata _sigs,\r
        address[] calldata _signers,\r
        uint256[] calldata _powers\r
    ) external view;\r
}\r
"
    },
    "contracts/interfaces/IWETH.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\r
\r
pragma solidity >=0.8.0;\r
\r
interface IWETH {\r
    function deposit() external payable;\r
\r
    function withdraw(uint256) external;\r
}\r
"
    },
    "contracts/libraries/Pb.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\r
\r
pragma solidity 0.8.17;\r
\r
// runtime proto sol library\r
library Pb {\r
    enum WireType {\r
        Varint,\r
        Fixed64,\r
        LengthDelim,\r
        StartGroup,\r
        EndGroup,\r
        Fixed32\r
    }\r
\r
    struct Buffer {\r
        uint256 idx; // the start index of next read. when idx=b.length, we're done\r
        bytes b; // hold serialized proto msg, readonly\r
    }\r
\r
    // create a new in-memory Buffer object from raw msg bytes\r
    function fromBytes(bytes memory raw) internal pure returns (Buffer memory buf) {\r
        buf.b = raw;\r
        buf.idx = 0;\r
    }\r
\r
    // whether there are unread bytes\r
    function hasMore(Buffer memory buf) internal pure returns (bool) {\r
        return buf.idx < buf.b.length;\r
    }\r
\r
    // decode current field number and wiretype\r
    function decKey(Buffer memory buf) internal pure returns (uint256 tag, WireType wiretype) {\r
        uint256 v = decVarint(buf);\r
        tag = v / 8;\r
        wiretype = WireType(v & 7);\r
    }\r
\r
    // count tag occurrences, return an array due to no memory map support\r
    // have to create array for (maxtag+1) size. cnts[tag] = occurrences\r
    // should keep buf.idx unchanged because this is only a count function\r
    function cntTags(Buffer memory buf, uint256 maxtag) internal pure returns (uint256[] memory cnts) {\r
        uint256 originalIdx = buf.idx;\r
        cnts = new uint256[](maxtag + 1); // protobuf's tags are from 1 rather than 0\r
        uint256 tag;\r
        WireType wire;\r
        while (hasMore(buf)) {\r
            (tag, wire) = decKey(buf);\r
            cnts[tag] += 1;\r
            skipValue(buf, wire);\r
        }\r
        buf.idx = originalIdx;\r
    }\r
\r
    // read varint from current buf idx, move buf.idx to next read, return the int value\r
    function decVarint(Buffer memory buf) internal pure returns (uint256 v) {\r
        bytes10 tmp; // proto int is at most 10 bytes (7 bits can be used per byte)\r
        bytes memory bb = buf.b; // get buf.b mem addr to use in assembly\r
        v = buf.idx; // use v to save one additional uint variable\r
        assembly {\r
            tmp := mload(add(add(bb, 32), v)) // load 10 bytes from buf.b[buf.idx] to tmp\r
        }\r
        uint256 b; // store current byte content\r
        v = 0; // reset to 0 for return value\r
        for (uint256 i = 0; i < 10; i++) {\r
            assembly {\r
                b := byte(i, tmp) // don't use tmp[i] because it does bound check and costs extra\r
            }\r
            v |= (b & 0x7F) << (i * 7);\r
            if (b & 0x80 == 0) {\r
                buf.idx += i + 1;\r
                return v;\r
            }\r
        }\r
        revert(); // i=10, invalid varint stream\r
    }\r
\r
    // read length delimited field and return bytes\r
    function decBytes(Buffer memory buf) internal pure returns (bytes memory b) {\r
        uint256 len = decVarint(buf);\r
        uint256 end = buf.idx + len;\r
        require(end <= buf.b.length); // avoid overflow\r
        b = new bytes(len);\r
        bytes memory bufB = buf.b; // get buf.b mem addr to use in assembly\r
        uint256 bStart;\r
        uint256 bufBStart = buf.idx;\r
        assembly {\r
            bStart := add(b, 32)\r
            bufBStart := add(add(bufB, 32), bufBStart)\r
        }\r
        for (uint256 i = 0; i < len; i += 32) {\r
            assembly {\r
                mstore(add(bStart, i), mload(add(bufBStart, i)))\r
            }\r
        }\r
        buf.idx = end;\r
    }\r
\r
    // return packed ints\r
    function decPacked(Buffer memory buf) internal pure returns (uint256[] memory t) {\r
        uint256 len = decVarint(buf);\r
        uint256 end = buf.idx + len;\r
        require(end <= buf.b.length); // avoid overflow\r
        // array in memory must be init w/ known length\r
        // so we have to create a tmp array w/ max possible len first\r
        uint256[] memory tmp = new uint256[](len);\r
        uint256 i = 0; // count how many ints are there\r
        while (buf.idx < end) {\r
            tmp[i] = decVarint(buf);\r
            i++;\r
        }\r
        t = new uint256[](i); // init t with correct length\r
        for (uint256 j = 0; j < i; j++) {\r
            t[j] = tmp[j];\r
        }\r
        return t;\r
    }\r
\r
    // move idx pass current value field, to beginning of next tag or msg end\r
    function skipValue(Buffer memory buf, WireType wire) internal pure {\r
        if (wire == WireType.Varint) {\r
            decVarint(buf);\r
        } else if (wire == WireType.LengthDelim) {\r
            uint256 len = decVarint(buf);\r
            buf.idx += len; // skip len bytes value data\r
            require(buf.idx <= buf.b.length); // avoid overflow\r
        } else {\r
            revert();\r
        } // unsupported wiretype\r
    }\r
\r
    // type conversion help utils\r
    function _bool(uint256 x) internal pure returns (bool v) {\r
        return x != 0;\r
    }\r
\r
    function _uint256(bytes memory b) internal pure returns (uint256 v) {\r
        require(b.length <= 32); // b's length must be smaller than or equal to 32\r
        assembly {\r
            v := mload(add(b, 32))\r
        } // load all 32bytes to v\r
        v = v >> (8 * (32 - b.length)); // only first b.length is valid\r
    }\r
\r
    function _address(bytes memory b) internal pure returns (address v) {\r
        v = _addressPayable(b);\r
    }\r
\r
    function _addressPayable(bytes memory b) internal pure returns (address payable v) {\r
        require(b.length == 20);\r
        //load 32bytes then shift right 12 bytes\r
        assembly {\r
            v := div(mload(add(b, 32)), 0x1000000000000000000000000)\r
        }\r
    }\r
\r
    function _bytes32(bytes memory b) internal pure returns (bytes32 v) {\r
        require(b.length == 32);\r
        assembly {\r
            v := mload(add(b, 32))\r
        }\r
    }\r
\r
    // uint[] to uint8[]\r
    function uint8s(uint256[] memory arr) internal pure returns (uint8[] memory t) {\r
        t = new uint8[](arr.length);\r
        for (uint256 i = 0; i < t.length; i++) {\r
            t[i] = uint8(arr[i]);\r
        }\r
    }\r
\r
    function uint32s(uint256[] memory arr) internal pure returns (uint32[] memory t) {\r
        t = new uint32[](arr.length);\r
        for (uint256 i = 0; i < t.length; i++) {\r
            t[i] = uint32(arr[i]);\r
        }\r
    }\r
\r
    function uint64s(uint256[] memory arr) internal pure returns (uint64[] memory t) {\r
        t = new uint64[](arr.length);\r
        for (uint256 i = 0; i < t.length; i++) {\r
            t[i] = uint64(arr[i]);\r
        }\r
    }\r
\r
    function bools(uint256[] memory arr) internal pure returns (bool[] memory t) {\r
        t = new bool[](arr.length);\r
        for (uint256 i = 0; i < t.length; i++) {\r
            t[i] = arr[i] != 0;\r
        }\r
    }\r
}\r
"
    },
    "contracts/libraries/PbBridge.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\r
\r
// Code generated by protoc-gen-sol. DO NOT EDIT.\r
// source: bridge.proto\r
pragma solidity 0.8.17;\r
import "./Pb.sol";\r
\r
library PbBridge {\r
    using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj\r
\r
    struct Relay {\r
        address sender; // tag: 1\r
        address receiver; // tag: 2\r
        address token; // tag: 3\r
        uint256 amount; // tag: 4\r
        uint64 srcChainId; // tag: 5\r
        uint64 dstChainId; // tag: 6\r
        bytes32 srcTransferId; // tag: 7\r
    } // end struct Relay\r
\r
    function decRelay(bytes memory raw) internal pure returns (Relay memory m) {\r
        Pb.Buffer memory buf = Pb.fromBytes(raw);\r
\r
        uint256 tag;\r
        Pb.WireType wire;\r
        while (buf.hasMore()) {\r
            (tag, wire) = buf.decKey();\r
            if (false) {}\r
            // solidity has no switch/case\r
            else if (tag == 1) {\r
                m.sender = Pb._address(buf.decBytes());\r
            } else if (tag == 2) {\r
                m.receiver = Pb._address(buf.decBytes());\r
            } else if (tag == 3) {\r
                m.token = Pb._address(buf.decBytes());\r
            } else if (tag == 4) {\r
                m.amount = Pb._uint256(buf.decBytes());\r
            } else if (tag == 5) {\r
                m.srcChainId = uint64(buf.decVarint());\r
            } else if (tag == 6) {\r
                m.dstChainId = uint64(buf.decVarint());\r
            } else if (tag == 7) {\r
                m.srcTransferId = Pb._bytes32(buf.decBytes());\r
            } else {\r
                buf.skipValue(wire);\r
            } // skip value of unknown tag\r
        }\r
    } // end decoder Relay\r
}\r
"
    },
    "contracts/libraries/PbPool.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\r
\r
// Code generated by protoc-gen-sol. DO NOT EDIT.\r
// source: contracts/libraries/proto/pool.proto\r
pragma solidity 0.8.17;\r
import "./Pb.sol";\r
\r
library PbPool {\r
    using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj\r
\r
    struct WithdrawMsg {\r
        uint64 chainid; // tag: 1\r
        uint64 seqnum; // tag: 2\r
        address receiver; // tag: 3\r
        address token; // tag: 4\r
        uint256 amount; // tag: 5\r
        bytes32 refid; // tag: 6\r
    } // end struct WithdrawMsg\r
\r
    function decWithdrawMsg(bytes memory raw) internal pure returns (WithdrawMsg memory m) {\r
        Pb.Buffer memory buf = Pb.fromBytes(raw);\r
\r
        uint256 tag;\r
        Pb.WireType wire;\r
        while (buf.hasMore()) {\r
            (tag, wire) = buf.decKey();\r
            if (false) {}\r
            // solidity has no switch/case\r
            else if (tag == 1) {\r
                m.chainid = uint64(buf.decVarint());\r
            } else if (tag == 2) {\r
                m.seqnum = uint64(buf.decVarint());\r
            } else if (tag == 3) {\r
                m.receiver = Pb._address(buf.decBytes());\r
            } else if (tag == 4) {\r
                m.token = Pb._address(buf.decBytes());\r
            } else if (tag == 5) {\r
                m.amount = Pb._uint256(buf.decBytes());\r
            } else if (tag == 6) {\r
                m.refid = Pb._bytes32(buf.decBytes());\r
            } else {\r
                buf.skipValue(wire);\r
            } // skip value of unknown tag\r
        }\r
    } // end decoder WithdrawMsg\r
}\r
"
    },
    "contracts/liquidity-bridge/Bridge.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\r
\r
pragma solidity 0.8.17;\r
\r
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";\r
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";\r
import "../libraries/PbBridge.sol";\r
import "./Pool.sol";\r
\r
/**\r
 * @title The liquidity-pool based bridge.\r
 */\r
contract QubeBridge is Pool {\r
    using SafeERC20 for IERC20;\r
\r
    // liquidity events\r
    event Send(\r
        bytes32 transferId,\r
        address sender,\r
        address receiver,\r
        address token,\r
        uint256 amount,\r
        uint64 dstChainId,\r
        uint64 nonce,\r
        uint32 maxSlippage\r
    );\r
    event Relay(\r
        bytes32 transferId,\r
        address sender,\r
        address receiver,\r
        address token,\r
        uint256 amount,\r
        uint64 srcChainId,\r
        bytes32 srcTransferId\r
    );\r
    // gov events\r
    event MinSendUpdated(address token, uint256 amount);\r
    event MaxSendUpdated(address token, uint256 amount);\r
\r
    mapping(bytes32 => bool) public transfers;\r
    mapping(address => uint256) public minSend; // send _amount must > minSend\r
    mapping(address => uint256) public maxSend;\r
\r
    // min allowed max slippage uint32 value is slippage * 1M, eg. 0.5% -> 5000\r
    uint32 public minimalMaxSlippage;\r
\r
    /**\r
     * @notice Send a cross-chain transfer via the liquidity pool-based bridge.\r
     * NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.\r
     * @param _receiver The address of the receiver.\r
     * @param _token The address of the token.\r
     * @param _amount The amount of the transfer.\r
     * @param _dstChainId The destination chain ID.\r
     * @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.\r
     * @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.\r
     * Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least (100% - max slippage percentage) * amount or the\r
     * transfer can be refunded.\r
     */\r
    function send(\r
        address _receiver,\r
        address _token,\r
        uint256 _amount,\r
        uint64 _dstChainId,\r
        uint64 _nonce,\r
        uint32 _maxSlippage // slippage * 1M, eg. 0.5% -> 5000\r
    ) external nonReentrant whenNotPaused {\r
        bytes32 transferId = _send(_receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage);\r
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);\r
        emit Send(transferId, msg.sender, _receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage);\r
    }\r
\r
    /**\r
     * @notice Send a cross-chain transfer via the liquidity pool-based bridge using the native token.\r
     * @param _receiver The address of the receiver.\r
     * @param _amount The amount of the transfer.\r
     * @param _dstChainId The destination chain ID.\r
     * @param _nonce A unique number. Can be timestamp in practice.\r
     * @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.\r
     * Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least (100% - max slippage percentage) * amount or the\r
     * transfer can be refunded.\r
     */\r
    function sendNative(\r
        address _receiver,\r
        uint256 _amount,\r
        uint64 _dstChainId,\r
        uint64 _nonce,\r
        uint32 _maxSlippage\r
    ) external payable nonReentrant whenNotPaused {\r
        require(msg.value == _amount, "Amount mismatch");\r
        require(nativeWrap != address(0), "Native wrap not set");\r
        bytes32 transferId = _send(_receiver, nativeWrap, _amount, _dstChainId, _nonce, _maxSlippage);\r
        IWETH(nativeWrap).deposit{value: _amount}();\r
        emit Send(transferId, msg.sender, _receiver, nativeWrap, _amount, _dstChainId, _nonce, _maxSlippage);\r
    }\r
\r
    function _send(\r
        address _receiver,\r
        address _token,\r
        uint256 _amount,\r
        uint64 _dstChainId,\r
        uint64 _nonce,\r
        uint32 _maxSlippage\r
    ) private returns (bytes32) {\r
        require(_amount > minSend[_token], "amount too small");\r
        require(maxSend[_token] == 0 || _amount <= maxSend[_token], "amount too large");\r
        require(_maxSlippage > minimalMaxSlippage, "max slippage too small");\r
        bytes32 transferId = keccak256(\r
            // uint64(block.chainid) for consistency as entire system uses uint64 for chain id\r
            // len = 20 + 20 + 20 + 32 + 8 + 8 + 8 = 116\r
            abi.encodePacked(msg.sender, _receiver, _token, _amount, _dstChainId, _nonce, uint64(block.chainid))\r
        );\r
        require(transfers[transferId] == false, "transfer exists");\r
        transfers[transferId] = true;\r
        return transferId;\r
    }\r
\r
    /**\r
     * @notice Relay a cross-chain transfer sent from a liquidity pool-based bridge on another chain.\r
     * @param _relayRequest The serialized Relay protobuf.\r
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by\r
     * +2/3 of the bridge's current signing power to be delivered.\r
     * @param _signers The sorted list of signers.\r
     * @param _powers The signing powers of the signers.\r
     */\r
    function relay(\r
        bytes calldata _relayRequest,\r
        bytes[] calldata _sigs,\r
        address[] calldata _signers,\r
        uint256[] calldata _powers\r
    ) external whenNotPaused {\r
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Relay"));\r
        verifySigs(abi.encodePacked(domain, _relayRequest), _sigs, _signers, _powers);\r
        PbBridge.Relay memory request = PbBridge.decRelay(_relayRequest);\r
        // len = 20 + 20 + 20 + 32 + 8 + 8 + 32 = 140\r
        bytes32 transferId = keccak256(\r
            abi.encodePacked(\r
                request.sender,\r
                request.receiver,\r
                request.token,\r
                request.amount,\r
                request.srcChainId,\r
                request.dstChainId,\r
                request.srcTransferId\r
            )\r
        );\r
        require(transfers[transferId] == false, "transfer exists");\r
        transfers[transferId] = true;\r
        _updateVolume(request.token, request.amount);\r
        uint256 delayThreshold = delayThresholds[request.token];\r
        if (delayThreshold > 0 && request.amount > delayThreshold) {\r
            _addDelayedTransfer(transferId, request.receiver, request.token, request.amount);\r
        } else {\r
            _sendToken(request.receiver, request.token, request.amount);\r
        }\r
\r
        emit Relay(\r
            transferId,\r
            request.sender,\r
            request.receiver,\r
            request.token,\r
            request.amount,\r
            request.srcChainId,\r
            request.srcTransferId\r
        );\r
    }\r
\r
    function setMinSend(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {\r
        require(_tokens.length == _amounts.length, "length mismatch");\r
        for (uint256 i = 0; i < _tokens.length; i++) {\r
            minSend[_tokens[i]] = _amounts[i];\r
            emit MinSendUpdated(_tokens[i], _amounts[i]);\r
        }\r
    }\r
\r
    function setMaxSend(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {\r
        require(_tokens.length == _amounts.length, "length mismatch");\r
        for (uint256 i = 0; i < _tokens.length; i++) {\r
            maxSend[_tokens[i]] = _amounts[i];\r
            emit MaxSendUpdated(_tokens[i], _amounts[i]);\r
        }\r
    }\r
\r
    function setMinimalMaxSlippage(uint32 _minimalMaxSlippage) external onlyGovernor {\r
        minimalMaxSlippage = _minimalMaxSlippage;\r
    }\r
\r
    // This is needed to receive ETH when calling `IWETH.withdraw`\r
    receive() external payable {}\r
}\r
"
    },
    "contracts/liquidity-bridge/Pool.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\r
\r
pragma solidity 0.8.17;\r
\r
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";\r
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";\r
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";\r
import "../interfaces/IWETH.sol";\r
import "../libraries/PbPool.sol";\r
import "../safeguard/Pauser.sol";\r
import "../safeguard/VolumeControl.sol";\r
import "../safeguard/DelayedTransfer.sol";\r
import "./Signers.sol";\r
\r
/**\r
 * @title Liquidity pool functions for {Bridge}.\r
 */\r
contract Pool is Signers, ReentrancyGuard, Pauser, VolumeControl, DelayedTransfer {\r
    using SafeERC20 for IERC20;\r
\r
    uint64 public addseq; // ensure unique LiquidityAdded event, start from 1\r
    mapping(address => uint256) public minAdd; // add _amount must > minAdd\r
\r
    // map of successful withdraws, if true means already withdrew money or added to delayedTransfers\r
    mapping(bytes32 => bool) public withdraws;\r
\r
    // erc20 wrap of gas token of this chain, eg. WETH, when relay ie. pay out,\r
    // if request.token equals this, will withdraw and send native token to receiver\r
    // note we don't check whether it's zero address. when this isn't set, and request.token\r
    // is all 0 address, guarantee fail\r
    address public nativeWrap;\r
\r
    // when transfer native token after wrap, use this gas used config.\r
    uint256 public nativeTokenTransferGas = 50000;\r
\r
    // liquidity events\r
    event LiquidityAdded(\r
        uint64 seqnum,\r
        address provider,\r
        address token,\r
        uint256 amount // how many tokens were added\r
    );\r
    event WithdrawDone(\r
        bytes32 withdrawId,\r
        uint64 seqnum,\r
        address receiver,\r
        address token,\r
        uint256 amount,\r
        bytes32 refid\r
    );\r
    event MinAddUpdated(address token, uint256 amount);\r
\r
    /**\r
     * @notice Add liquidity to the pool-based bridge.\r
     * NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.\r
     * @param _token The address of the token.\r
     * @param _amount The amount to add.\r
     */\r
    function addLiquidity(address _token, uint256 _amount) external nonReentrant whenNotPaused {\r
        require(_amount > minAdd[_token], "amount too small");\r
        addseq += 1;\r
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);\r
        emit LiquidityAdded(addseq, msg.sender, _token, _amount);\r
    }\r
\r
    /**\r
     * @notice Add native token liquidity to the pool-based bridge.\r
     * @param _amount The amount to add.\r
     */\r
    function addNativeLiquidity(uint256 _amount) external payable nonReentrant whenNotPaused {\r
        require(msg.value == _amount, "Amount mismatch");\r
        require(nativeWrap != address(0), "Native wrap not set");\r
        require(_amount > minAdd[nativeWrap], "amount too small");\r
        addseq += 1;\r
        IWETH(nativeWrap).deposit{value: _amount}();\r
        emit LiquidityAdded(addseq, msg.sender, nativeWrap, _amount);\r
    }\r
\r
    /**\r
     * @notice Withdraw funds from the bridge pool.\r
     * @param _wdmsg The serialized Withdraw protobuf.\r
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A withdrawal must be\r
     * signed-off by +2/3 of the bridge's current signing power to be delivered.\r
     * @param _signers The sorted list of signers.\r
     * @param _powers The signing powers of the signers.\r
     */\r
    function withdraw(\r
        bytes calldata _wdmsg,\r
        bytes[] calldata _sigs,\r
        address[] calldata _signers,\r
        uint256[] calldata _powers\r
    ) external whenNotPaused {\r
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "WithdrawMsg"));\r
        verifySigs(abi.encodePacked(domain, _wdmsg), _sigs, _signers, _powers);\r
        // decode and check wdmsg\r
        PbPool.WithdrawMsg memory wdmsg = PbPool.decWithdrawMsg(_wdmsg);\r
        // len = 8 + 8 + 20 + 20 + 32 = 88\r
        bytes32 wdId = keccak256(\r
            abi.encodePacked(wdmsg.chainid, wdmsg.seqnum, wdmsg.receiver, wdmsg.token, wdmsg.amount)\r
        );\r
        require(withdraws[wdId] == false, "withdraw already succeeded");\r
        withdraws[wdId] = true;\r
        _updateVolume(wdmsg.token, wdmsg.amount);\r
        uint256 delayThreshold = delayThresholds[wdmsg.token];\r
        if (delayThreshold > 0 && wdmsg.amount > delayThreshold) {\r
            _addDelayedTransfer(wdId, wdmsg.receiver, wdmsg.token, wdmsg.amount);\r
        } else {\r
            _sendToken(wdmsg.receiver, wdmsg.token, wdmsg.amount);\r
        }\r
        emit WithdrawDone(wdId, wdmsg.seqnum, wdmsg.receiver, wdmsg.token, wdmsg.amount, wdmsg.refid);\r
    }\r
\r
    function executeDelayedTransfer(bytes32 id) external whenNotPaused {\r
        delayedTransfer memory transfer = _executeDelayedTransfer(id);\r
        _sendToken(transfer.receiver, transfer.token, transfer.amount);\r
    }\r
\r
    function setMinAdd(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {\r
        require(_tokens.length == _amounts.length, "length mismatch");\r
        for (uint256 i = 0; i < _tokens.length; i++) {\r
            minAdd[_tokens[i]] = _amounts[i];\r
            emit MinAddUpdated(_tokens[i], _amounts[i]);\r
        }\r
    }\r
\r
    function _sendToken(\r
        address _receiver,\r
        address _token,\r
        uint256 _amount\r
    ) internal {\r
        if (_token == nativeWrap) {\r
            // withdraw then transfer native to receiver\r
            IWETH(nativeWrap).withdraw(_amount);\r
            (bool sent, ) = _receiver.call{value: _amount, gas: nativeTokenTransferGas}("");\r
            require(sent, "failed to send native token");\r
        } else {\r
            IERC20(_token).safeTransfer(_receiver, _amount);\r
        }\r
    }\r
\r
    // set nativeWrap, for relay requests, if token == nativeWrap, will withdraw first then transfer native to receiver\r
    function setWrap(address _weth) external onlyOwner {\r
        nativeWrap = _weth;\r
    }\r
\r
    // setNativeTransferGasUsed, native transfer will use this config.\r
    function setNativeTokenTransferGas(uint256 _gasUsed) external onlyGovernor {\r
        nativeTokenTransferGas = _gasUsed;\r
    }\r
}\r
"
    },
    "contracts/liquidity-bridge/Signers.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\r
\r
pragma solidity 0.8.17;\r
\r
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";\r
import "../safeguard/Ownable.sol";\r
import "../interfaces/ISigsVerifier.sol";\r
\r
/**\r
 * @title Multi-sig verification and management functions for {Bridge}.\r
 */\r
contract Signers is Ownable, ISigsVerifier {\r
    using ECDSA for bytes32;\r
\r
    bytes32 public ssHash;\r
    uint256 public triggerTime; // timestamp when last update was triggered\r
\r
    // reset can be called by the owner address for emergency recovery\r
    uint256 public resetTime;\r
    uint256 public noticePeriod; // advance notice period as seconds for reset\r
    uint256 constant MAX_INT = 2 ** 256 - 1;\r
\r
    event SignersUpdated(address[] _signers, uint256[] _powers);\r
\r
    event ResetNotification(uint256 resetTime);\r
\r
    /**\r
     * @notice Verifies that a message is signed by a quorum among the signers\r
     * The sigs must be sorted by signer addresses in ascending order.\r
     * @param _msg signed message\r
     * @param _sigs list of signatures sorted by signer addresses in ascending order\r
     * @param _signers sorted list of current signers\r
     * @param _powers powers of current signers\r
     */\r
    function verifySigs(\r
        bytes memory _msg,\r
        bytes[] calldata _sigs,\r
        address[] calldata _signers,\r
        uint256[] calldata _powers\r
    ) public view override {\r
        bytes32 h = keccak256(abi.encodePacked(_signers, _powers));\r
        require(ssHash == h, "Mismatch current signers");\r
        _verifySignedPowers(keccak256(_msg).toEthSignedMessageHash(), _sigs, _signers, _powers);\r
    }\r
\r
    /**\r
     * @notice Update new signers.\r
     * @param _newSigners sorted list of new signers\r
     * @param _curPowers powers of new signers\r
     * @param _sigs list of signatures sorted by signer addresses in ascending order\r
     * @param _curSigners sorted list of current signers\r
     * @param _curPowers powers of current signers\r
     */\r
    function updateSigners(\r
        uint256 _triggerTime,\r
        address[] calldata _newSigners,\r
        uint256[] calldata _newPowers,\r
        bytes[] calldata _sigs,\r
        address[] calldata _curSigners,\r
        uint256[] calldata _curPowers\r
    ) external {\r
        // use trigger time for nonce protection, must be ascending\r
        require(_triggerTime > triggerTime, "Trigger time is not increasing");\r
        // make sure triggerTime is not too large, as it cannot be decreased once set\r
        require(_triggerTime < block.timestamp + 3600, "Trigger time is too large");\r
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "UpdateSigners"));\r
        verifySigs(abi.encodePacked(domain, _triggerTime, _newSigners, _newPowers), _sigs, _curSigners, _curPowers);\r
        _updateSigners(_newSigners, _newPowers);\r
        triggerTime = _triggerTime;\r
    }\r
\r
    /**\r
     * @notice reset signers, only used for init setup and emergency recovery\r
     */\r
    function resetSigners(address[] calldata _signers, uint256[] calldata _powers) external onlyOwner {\r
        require(block.timestamp > resetTime, "not reach reset time");\r
        resetTime = MAX_INT;\r
        _updateSigners(_signers, _powers);\r
    }\r
\r
    function notifyResetSigners() external onlyOwner {\r
        resetTime = block.timestamp + noticePeriod;\r
        emit ResetNotification(resetTime);\r
    }\r
\r
    function increaseNoticePeriod(uint256 period) external onlyOwner {\r
        require(period > noticePeriod, "notice period can only be increased");\r
        noticePeriod = period;\r
    }\r
\r
    // separate from verifySigs func to avoid "stack too deep" issue\r
    function _verifySignedPowers(\r
        bytes32 _hash,\r
        bytes[] calldata _sigs,\r
        address[] calldata _signers,\r
        uint256[] calldata _powers\r
    ) private pure {\r
        require(_signers.length == _powers.length, "signers and powers length not match");\r
        uint256 totalPower; // sum of all signer.power\r
        for (uint256 i = 0; i < _signers.length; i++) {\r
            totalPower += _powers[i];\r
        }\r
        uint256 quorum = (totalPower * 2) / 3 + 1;\r
\r
        uint256 signedPower; // sum of signer powers who are in sigs\r
        address prev = address(0);\r
        uint256 index = 0;\r
        for (uint256 i = 0; i < _sigs.length; i++) {\r
            address signer = _hash.recover(_sigs[i]);\r
            require(signer > prev, "signers not in ascending order");\r
            prev = signer;\r
            // now find match signer add its power\r
            while (signer > _signers[index]) {\r
                index += 

Tags:
ERC20, Multisig, Pausable, Liquidity, Voting, Upgradeable, Multi-Signature, Factory|addr:0x022b8945882fc9326cb151ad2deeeba8518f1593|verified:true|block:23706014|tx:0x712545c3a66f616bd3141d6e31457c3e6385e67ad02bf31318fed4828f5834a3|first_check:1762019212

Submitted on: 2025-11-01 18:46:52

Comments

Log in to comment.

No comments yet.