// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

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

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

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

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

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

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

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

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

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

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

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

// File: @openzeppelin/contracts/utils/introspection/ERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

// File: @openzeppelin/contracts/utils/introspection/IERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// File: contracts/interfaces/IRelayerManager.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

interface IRelayerManager {
    event RelayerAdded(address indexed addr);
    event RelayerRemoved(address indexed addr);
    struct Pool {
        address addr;
        uint256 index;
        uint256 joinTimestamp;
        uint256 amount;
    }

    function addRelayer(address relayerAddr) external;

    function addRelayerBatch(address[] calldata relayerAddr) external;

    function removeRelayer(address relayerAddr) external;

    function removeRelayerBatch(address[] calldata relayerAddr) external;

    function appId() external view returns (bytes32);

    function getRelayer(uint256 index) external view returns (address);

    function getRelayers() external view returns (address[] memory);

    function pickRelayer(bytes32 seed) external view returns (address);
}

// File: contracts/libraries/Errors.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/**
 * @title Errors library
 * @author Exoswap
 * @notice Defines the error messages emitted by the different contracts of bridge exoswap protocol
 * @dev Error messages prefix glossary:
 *  - B = Base errors
 *  - R = Relayer errors
 *  - M = Manager errors
 *  - BR = Router errors
 */
library Errors {
    //common errors
    string public constant B_ENTITY_EXIST = "1";
    string public constant B_ENTITY_NOT_EXIST = "2";
    string public constant B_LENGTH_MISMATCH = "3";
    string public constant B_INSUFFICIENT_BALANCE = "4";
    string public constant B_SEND_REVERT = "5";
    string public constant B_NOT_LISTED = "6";
    string public constant B_ZERO_ADDRESS = "7";
    string public constant B_EMPTY_BATCH = "8";
    string public constant B_ZERO_AMOUNT = "9";
    string public constant B_INVALID_EVENT = "10";
    string public constant B_EXPIRED = "11";
    string public constant B_AMOUNT_TOO_LOW = "12";
    string public constant B_GAS_OVERFLOW = "13";
    string public constant B_LOCKED = "14";
    string public constant B_PROTECTED_ADDRESS = "15";
    //relayer
    string public constant R_RESERVED_ENTITY = "R1";
    string public constant R_RESERVED_OWNER = "R2";
    string public constant R_NOT_APP_OWNER = "R3";
    string public constant R_ACQUIRE_FAILED = "R4";
    //manager
    string public constant M_ONLY_EXTERNAL = "M1";
    string public constant M_MAX_SIZE = "M2";
    string public constant M_SAME_CHAIN = "M3";
    string public constant M_SOURCE_EXIST = "M4";
    string public constant M_TARGET_EXIST = "M5";
    //router
    string public constant BR_WRONG_SOURCE_CHAIN = "BR1";
    string public constant BR_WRONG_TARGET_CHAIN = "BR2";
    string public constant BR_COMMITMENT_KNOWN = "BR3";
    string public constant BR_INVALID_SIGNATURES = "BR4";
    string public constant BR_AMOUNT_OVERFLOW = "BR5";
    string public constant BR_FEE_OVERFLOW = "BR6";
    string public constant BR_LIMIT_OVERFLOW = "BR7";
    string public constant BR_WRONG_EXECUTOR = "BR8";
    string public constant BR_FEE_TOO_LOW = "BR9";
    string public constant BR_EXECUTION_FAILED = "BR10";
}

// File: contracts/managers/RelayerManager.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

import "../libraries/Errors.sol";
import "../interfaces/IRelayerManager.sol";

contract RelayerManager is ERC165, Ownable, IRelayerManager {
    mapping(address => Pool) private _rpoolsAddrs;
    address[] private _rpools;

    bytes32 public immutable override appId; // app id for fee processing
    uint256 public immutable blockDelta; // blocks delta

    constructor(bytes32 _appId, uint256 _blockDelta) {
        appId = _appId;
        blockDelta = _blockDelta;
    }

    function addRelayer(address relAddr) public override onlyOwner {
        require(relAddr != address(0), Errors.B_ZERO_ADDRESS);
        require(
            _rpoolsAddrs[relAddr].addr == address(0),
            Errors.B_ENTITY_EXIST
        );

        _rpools.push(relAddr);
        _rpoolsAddrs[relAddr] = Pool(
            relAddr,
            _rpools.length - 1,
            block.timestamp,
            0
        );
        emit RelayerAdded(relAddr);
    }

    function addRelayerBatch(
        address[] calldata relAddrs
    ) public override onlyOwner {
        for (uint256 i = 0; i < relAddrs.length; i++) {
            addRelayer(relAddrs[i]);
        }
    }

    function removeRelayer(address relAddr) public override onlyOwner {
        require(relAddr != address(0), Errors.B_ZERO_ADDRESS);
        Pool memory pool = _rpoolsAddrs[relAddr];
        require(pool.addr != address(0), Errors.B_ENTITY_NOT_EXIST);

        if (_rpools.length > 1) {
            // move last to rm slot
            _rpools[pool.index] = _rpools[_rpools.length - 1];
            _rpools.pop();

            // change indexing
            address poolAddrLast = _rpools[pool.index];
            _rpoolsAddrs[poolAddrLast].index = pool.index;
        } else {
            // just remove it as 1 left
            _rpools.pop();
        }

        delete _rpoolsAddrs[pool.addr];

        emit RelayerRemoved(relAddr);
    }

    function removeRelayerBatch(
        address[] calldata relAddrs
    ) public override onlyOwner {
        for (uint256 i = 0; i < relAddrs.length; i++) {
            removeRelayer(relAddrs[i]);
        }
    }

    function getRelayer(uint256 index) public view override returns (address) {
        return _rpools[index];
    }

    function getRelayers() public view override returns (address[] memory) {
        return _rpools;
    }

    function pickRelayer(bytes32 seed) public view override returns (address) {
        uint256 index = _getRandomIndex(
            uint256(seed),
            block.number,
            blockDelta,
            _rpools.length
        );
        return _rpools[index];
    }

    function getRandomIndex(
        uint256 rk,
        uint256 height,
        uint256 delta,
        uint256 length
    ) public pure returns (uint256) {
        return _getRandomIndex(rk, height, delta, length);
    }

    function _getRandomIndex(
        uint256 rk,
        uint256 height,
        uint256 delta,
        uint256 length
    ) private pure returns (uint256) {
        rk = _deltaRoundDown(rk, delta);
        uint256 pseudoHeight;
        unchecked {
            pseudoHeight = rk - height - 1;
        }
        pseudoHeight = _deltaRoundDown(pseudoHeight, delta);

        uint256 random = uint256(keccak256(abi.encodePacked(pseudoHeight)));
        return random % length;
    }

    function _deltaRoundDown(
        uint256 n,
        uint256 delta
    ) private pure returns (uint256) {
        if (n < delta) {
            return 0;
        }
        uint256 dev = n % delta;
        if (dev != 0) {
            n = n - dev;
        }
        return n;
    }
}