// 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/Address.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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 functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

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

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

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

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

// File: @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: contracts/access/PermitControl.sol



// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.19;

import {
	Ownable
} from "@openzeppelin/contracts/access/Ownable.sol";
import {
	Address
} from "@openzeppelin/contracts/utils/Address.sol";

error RightNotSpecified();
error CallerHasNoAccess();
error ManagedRightNotSpecified();

/**
	@custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
	@title An advanced permission-management contract.
	@author Tim Clancy <@_Enoch>

	This contract allows for a contract owner to delegate specific rights to
	external addresses. Additionally, these rights can be gated behind certain
	sets of circumstances and granted expiration times. This is useful for some
	more finely-grained access control in contracts.

	The owner of this contract is always a fully-permissioned super-administrator.

	@custom:date August 23rd, 2021.
*/
abstract contract PermitControl is Ownable {
	using Address for address;

	/// A special reserved constant for representing no rights.
	bytes32 internal constant _ZERO_RIGHT = hex"00000000000000000000000000000000";

	/// A special constant specifying the unique, universal-rights circumstance.
	bytes32 internal constant _UNIVERSAL = hex"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";

	/**
		A special constant specifying the unique manager right. This right allows an
		address to freely-manipulate the `managedRight` mapping.
	*/
	bytes32 internal constant _MANAGER = hex"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";

	/**
		A mapping of per-address permissions to the circumstances, represented as
		an additional layer of generic bytes32 data, under which the addresses have
		various permits. A permit in this sense is represented by a per-circumstance
		mapping which couples some right, represented as a generic bytes32, to an
		expiration time wherein the right may no longer be exercised. An expiration
		time of 0 indicates that there is in fact no permit for the specified
		address to exercise the specified right under the specified circumstance.

		@dev Universal rights MUST be stored under the 0xFFFFFFFFFFFFFFFFFFFFFFFF...
		max-integer circumstance. Perpetual rights may be given an expiry time of
		max-integer.
	*/
	mapping ( address => mapping( bytes32 => mapping( bytes32 => uint256 ))) 
		internal _permissions;

	/**
		An additional mapping of managed rights to manager rights. This mapping
		represents the administrator relationship that various rights have with one
		another. An address with a manager right may freely set permits for that
		manager right's managed rights. Each right may be managed by only one other
		right.
	*/
	mapping ( bytes32 => bytes32 ) internal _managerRights;

	/**
		An event emitted when an address has a permit updated. This event captures,
		through its various parameter combinations, the cases of granting a permit,
		updating the expiration time of a permit, or revoking a permit.

		@param updater The address which has updated the permit.
		@param updatee The address whose permit was updated.
		@param circumstance The circumstance wherein the permit was updated.
		@param role The role which was updated.
		@param expirationTime The time when the permit expires.
	*/
	event PermitUpdated (
		address indexed updater,
		address indexed updatee,
		bytes32 circumstance,
		bytes32 indexed role,
		uint256 expirationTime
	);

	/**
		An event emitted when a management relationship in `managerRight` is
		updated. This event captures adding and revoking management permissions via
		observing the update history of the `managerRight` value.

		@param manager The address of the manager performing this update.
		@param managedRight The right which had its manager updated.
		@param managerRight The new manager right which was updated to.
	*/
	event ManagementUpdated (
		address indexed manager,
		bytes32 indexed managedRight,
		bytes32 indexed managerRight
	);

	/**
		A modifier which allows only the super-administrative owner or addresses
		with a specified valid right to perform a call.

		@param _circumstance The circumstance under which to check for the validity
			of the specified `right`.
		@param _right The right to validate for the calling address. It must be
			non-expired and exist within the specified `_circumstance`.
	*/
	modifier hasValidPermit (
		bytes32 _circumstance,
		bytes32 _right
	) {
		if (
			msg.sender != owner() &&
				!_hasRight(msg.sender, _circumstance, _right)
		) {
			revert CallerHasNoAccess();
		}
		_;
	}

	/**
		Determine whether or not an address has some rights under the given
		circumstance,

		@param _address The address to check for the specified `_right`.
		@param _circumstance The circumstance to check the specified `_right` for.
		@param _right The right to check for validity.

		@return true or false, whether user has rights and time is valid.
	*/
	function _hasRight (
		address _address,
		bytes32 _circumstance,
		bytes32 _right
	) internal view returns (bool) {
		return _permissions[_address][_circumstance][_right] > block.timestamp;
	}
	/**
		Set the `_managerRight` whose `UNIVERSAL` holders may freely manage the
		specified `_managedRight`.

		@param _managedRight The right which is to have its manager set to
			`_managerRight`.
		@param _managerRight The right whose `UNIVERSAL` holders may manage
			`_managedRight`.
	*/

	function setManagerRight (
		bytes32 _managedRight,
		bytes32 _managerRight
	) external virtual hasValidPermit(_UNIVERSAL, _MANAGER) {
		if (_managedRight == _ZERO_RIGHT) {
			revert ManagedRightNotSpecified();
		}
		_managerRights[_managedRight] = _managerRight;
		emit ManagementUpdated(msg.sender, _managedRight, _managerRight);
	}

	/**
		Set the permit to a specific address under some circumstances. A permit may
		only be set by the super-administrative contract owner or an address holding
		some delegated management permit.

		@param _address The address to assign the specified `_right` to.
		@param _circumstance The circumstance in which the `_right` is valid.
		@param _right The specific right to assign.
		@param _expirationTime The time when the `_right` expires for the provided
			`_circumstance`.
	*/
	function setPermit (
		address _address,
		bytes32 _circumstance,
		bytes32 _right,
		uint256 _expirationTime
	) public virtual hasValidPermit(_UNIVERSAL, _managerRights[_right]) {
		if(_right == _ZERO_RIGHT) {
			revert RightNotSpecified();
		}
		_permissions[_address][_circumstance][_right] = _expirationTime;
		emit PermitUpdated(
			msg.sender,
			_address,
			_circumstance,
			_right,
			_expirationTime
		);
	}

	/**
		Determine whether or not an address has some rights under the given
		circumstance, and if they do have the right, until when.

		@param _address The address to check for the specified `_right`.
		@param _circumstance The circumstance to check the specified `_right` for.
		@param _right The right to check for validity.

		@return The timestamp in seconds when the `_right` expires. If the timestamp
			is zero, we can assume that the user never had the right.
	*/
	function hasRightUntil (
		address _address,
		bytes32 _circumstance,
		bytes32 _right
	) public view returns (uint256) {
		return _permissions[_address][_circumstance][_right];
	}
}

// File: contracts/AlphaRegistry.sol



// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.19;

import {
	IAlphaRegistry,
	IPaymentHandler,
	PriceHigherThanCeiling,
	CallerIsNotPaymentHandler,
	ProtocolFeeRecipientCannotBeZero
} from "./interfaces/IAlphaRegistry.sol";
import {
	PermitControl
} from "./access/PermitControl.sol";

/**
	@custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
	@title Alpha Registry
	@author Rostislav Khlebnikov <@catpic5buck>

	The AlphaRegistry stores information about alpha board subscripions.

	@custom:version 1.0
	@custom:date April 7th, 2023.
*/
contract AlphaRegistry is IAlphaRegistry, PermitControl {

	/// The PermitControl access constant for managing fee configuration.
	bytes32 private constant _FEE_CONFIG = keccak256("FEE_CONFIG");

	/// The PermitControl access constant for setting the payment handler.
	bytes32 private constant _SET_HANDLER = keccak256("SET_HANDLER");

	/// The PermitControl access constant for setting subscription price ceilings.
	bytes32 private constant _PRICE_CEILING_MANAGER = keccak256(
		"PRICE_CEILING_MANAGER"
	);

	/// A divisor constant for calculating fees.
	uint256 private constant _PRECISION = 10_000;

	/// The price ceiling for current alpha board subscriptions.
	uint256 public priceCeiling;

	/**
		A storage slot which contains 160 bits of the fee recipient Address on the 
		left and 96 bits of the fee percent on the right.
	*/
	uint256 private _feeConfig;

	/// The adress of the Payment Handler contract.
	IPaymentHandler public handler;
	
	/// A mapping from each alpha caller to the price of their subscription.
	mapping ( address => uint256 ) public prices;

	/// A mappint from each alpha caller to the status of their subscription.
	mapping ( address => bool ) public created;

	/**
		A mapping of each subscriber and alpha caller to the subscription 
		expiration timestamp.
	*/
	mapping ( address => mapping ( address => uint256 )) public timestamps;

	/**
		Construct new instance of the AlphaRegistry with initial price ceiling and 
		fee details.

		@param _priceCeiling The initial subscription fee ceiling.
		@param _feeRecipient The fee recipient address.
		@param _feePercent The fee percent.
	*/
	constructor (
		uint256 _priceCeiling,
		address _feeRecipient,
		uint96 _feePercent
	) {
		priceCeiling = _priceCeiling;

		/*
			Pack 160 bits of feeRecipient address and 96 bits of feePercent
			and store in the _feeConfig slot.
		*/
		_feeConfig = (uint256(uint160(_feeRecipient)) << 96) +
			uint256(_feePercent);
	}

	/**
		Reads the expiration time of the subscription in question.
		Calls PaymentHandler to check if subscription is recurrent.

		@param _alphaCaller Alpha caller address.
		@param _subscriber Subscriber address.

		@return _ Flag of subscription being active.
	*/
	function _isSubscriptionActive (
		address _alphaCaller,
		address _subscriber
	) private view returns (bool) {

		// If subscription has expired, see if it is recurrent.
		if (block.timestamp > timestamps[_subscriber][_alphaCaller]) {
			return handler.isSubscriptionRecurrent(
				_alphaCaller,
				_subscriber
			);
		}
		return true;
	}

	/**
		Reads subscription information by its caller and subscriber
		addresses and returns:
			1. Subscription status - active/expired.
			2. Fee recipient address.
			3. Amount of fees to pay.
			4. Price of the subscription. 
		
		@param _alphaCaller Address of the alpha caller.
		@param _subscriber Address of the subscriber

		@return exists Subscription existence flag.
		@return active Flag of subscription being active.
		@return feeRecipient Fee recipient address.
		@return feeAmount Amount of fees to pay.
		@return price Subscription price.
	*/
	function subscriptionInfo (
		address _alphaCaller,
		address _subscriber
	) external view returns (
		bool exists,
		bool active,
		address feeRecipient,
		uint256 feeAmount,
		uint256 price
	) {

		// Read subscription status.
		exists = created[_alphaCaller];

		// Check if the subscription is active.
		active = _isSubscriptionActive(
			_alphaCaller,
			_subscriber
		);
		// Read the subscription price.
		price = prices[_alphaCaller];

		// Read fee recipient and percent.
		uint256 feePercent;
		(feeRecipient, feePercent) = currentFee();
		// Calculate amount of fees to pay.
		feeAmount = (price * feePercent) / _PRECISION;
	}

	/**
		Unpacks and returns the fee recipient address and fee percent.

		@return _ A tuple consisting of the (fee recipient address, fee percent).
	*/
	function currentFee () public view returns (address, uint256) {
		uint256 fee = _feeConfig;
		return (address(uint160(fee >> 96)), uint256(uint96(fee)));
	}

	/**
		Updates subscription price for the msg.sender.

		@param _newPrice New price value.

		@custom:throws PriceHigherThanCeiling.
		@custom:emits PriceUpdated event.
	*/
	function updatePrice (
		uint256 _newPrice
	) external {
		// Check new price against the ceiling.
		if (_newPrice > priceCeiling) {
			revert PriceHigherThanCeiling();
		}

		// Put old price on the stack.
		uint256 old = prices[msg.sender];

		// Update status of the subscription if needed.
		if (!created[msg.sender]) {
			created[msg.sender] = true;
		}
		
		// Update the caller's subscription price..
		prices[msg.sender] = _newPrice;

		emit PriceUpdated(msg.sender, old, _newPrice);
	}

	/**
		Stores subscription info. Only PaymentHandler contract
		can call this function.

		@param _alphaCaller Address of the alpha caller.
		@param _subscriber Address of the subscriber.
		@param _end Timestamp when subscription ends.
		
		@custom:throws CallerIsNotPaymentHandler.
		@custom:emits Subscribed event.
	*/
	function subscribe (
		address _alphaCaller,
		address _subscriber,
		uint256 _end
	) external {
		// Check if caller is the PaymentHandler contract.
		if (msg.sender != address(handler)) {
			revert CallerIsNotPaymentHandler();
		}

		// Update expiration time of the subscription.
		timestamps[_subscriber][_alphaCaller] = _end;
		
		emit Subscribed(
			_subscriber,
			_alphaCaller,
			block.timestamp,
			_end
		);
	}

	/**
		Sets new PaymentHandler contract address.
		Only admin can call this function.

		@param _handler New PaymentHandler address.
	*/
	function setPaymentHandler (
		IPaymentHandler _handler
	) external hasValidPermit(_UNIVERSAL, _SET_HANDLER) {
		handler = _handler;
	}

	/**
		Updates fee recipient address and fee percent.
		Only admin can call this function.

		@param _newRecipient New fee recipient address.
		@param _newPercent New fee percent value.

		@custom:throws ProtocolFeeRecipientCannotBeZero.
		@custom:emits FeeUpdated event.
	*/
	function updateFee (
		address _newRecipient,
		uint256 _newPercent
	) external hasValidPermit(_UNIVERSAL, _FEE_CONFIG) {
		if (_newRecipient == address(0)) {
			revert ProtocolFeeRecipientCannotBeZero();
		}

		// Update the fee.
		uint256 oldFeeConfig =_feeConfig;
		unchecked {
			_feeConfig =
				(uint256(uint160(_newRecipient)) << 96) +
				uint256(_newPercent);
		}

		// Emit an event notifying about the update.
		emit FeeUpdated(
			address(uint160(oldFeeConfig >> 96)),
			uint256(uint96(oldFeeConfig)),
			_newRecipient,
			_newPercent
		);
	}

	/**
		Updates subscriptions price ceiling. Only Admin can call this function.

		@param _newPriceCeiling New subscriptions price ceiling value;

		@custom:emits PriceCeilingUpdated.
	*/
	function updatePriceCeiling (
		uint256 _newPriceCeiling
	) external hasValidPermit(_UNIVERSAL, _PRICE_CEILING_MANAGER) {
		// Put old ceiling value on the stack.
		uint256 oldPriceCeiling =  priceCeiling;
		// Set new ceiling value.
		priceCeiling = _newPriceCeiling;

		emit PriceCelingUpdated(oldPriceCeiling, _newPriceCeiling);
	}
}

// File: contracts/interfaces/IAlphaRegistry.sol



// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.19;

import {
	IPaymentHandler
} from "./IPaymentHandler.sol";

/// Thrown if the `subscribe` function is called by account other than handler.
error CallerIsNotPaymentHandler ();

/// Thrown if attempting to set address(0) as a new fee recipient.
error ProtocolFeeRecipientCannotBeZero ();

/// Thrown if attempting to set subscription price higher than price ceiling.
error PriceHigherThanCeiling ();

/**
	@custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
	@title Alpha Registry Interface
	@author Rostislav Khlebnikov <@catpic5buck>

	An interface for the AlphaRegistry contract.

	@custom:version 1.0
	@custom:date April 7th, 2023.
*/
interface IAlphaRegistry {

	/**
		Emitted when caller updated their price.

		@param alphaCaller Address of the caller.
		@param oldPrice Old price value.
		@param newPrice New price value.
	*/
	event PriceUpdated(
		address indexed alphaCaller,
		uint256 oldPrice,
		uint256 newPrice
	);

	/**
		Emitted when someone sibscribes.

		@param subscriber Address of the subscriber.
		@param alphaCaller Address of the caller.
		@param start Timestamp, when subsription started.
		@param end Timestamp, when subscription ends.
	*/
	event Subscribed(
		address indexed subscriber,
		address  indexed alphaCaller,
		uint256 start,
		uint256 end
	);

	/**
		Emitted when Admin updates fees.

		@param oldRecipient Old recipient address.
		@param oldPercent Old fee percent.
		@param newRecipient New recipient address.
		@param newPercent New fee percent.
	*/
	event FeeUpdated(
		address oldRecipient,
		uint256 oldPercent,
		address newRecipient,
		uint256 newPercent
	);

	/**
		Emitted when Adming updates subscriptions price ceiling.

		@param oldPriceCeiling Previous price ceiling value.
		@param newPriceCeiling New price ceiling value.
	*/
	event PriceCelingUpdated(
		uint256 oldPriceCeiling,
		uint256 newPriceCeiling
	);

	/**
		Updates subscription price for the msg.sender.

		@param _newPrice New price value.

		@custom:emits PriceUpdated event.
	*/
	function updatePrice (uint256 _newPrice) external;

	/**
		Stores subscription info. Only PaymentHandler contract
		can call this function.

		@param _alphaCaller Address of the alpha caller.
		@param _subscriber Address of the subscriber.
		@param _end Timestamp when subscription ends.
		
		@custom:throws CallerIsNotPaymentHandler.
		@custom:emits Subscribed event.
	*/
	function subscribe(
		address _alphaCaller,
		address _subscriber,
		uint256 _end
	) external;

	/**
		Updates fee recipient address and fee percent.
		Only admin can call this function.

		@param _newRecipient New fee recipient address.
		@param _newPercent New fee percent value.

		@custom:throws ProtocolFeeRecipientCannotBeZero.
		@custom:emits FeeUpdated event.
	*/
	function updateFee(
		address _newRecipient,
		uint256 _newPercent
	) external;

	/**
		Sets new PaymentHandler contract address.
		Only admin can call this function.

		@param _handler New PaymentHandler address.
	*/
	function setPaymentHandler (
		IPaymentHandler _handler
	) external;

	/**
		Updates subscriptions price ceiling. Only Admin can call this function.

		@param _newPriceCeiling New subscriptions price ceiling value;

		@custom:emits PriceCeilingUpdated.
	*/
	function updatePriceCeiling (
		uint256 _newPriceCeiling
	) external;

	/**
		Returns current fee recipient and fee percent.

		@return _  The fee recipient address.
		@return _ The fee percent.
	*/
	function currentFee() external view returns (address, uint256);

	/** 
		Returns current address of the PaymentHandler.

		@return _ PaymentHandler address.
	*/
	function handler() external view returns (IPaymentHandler);

	/**
		Returns current subscription price for the alpha caller.

		@param _caller Address of the alpha caller.

		@return _ Subscription price amount.
	*/
	function prices (
		address _caller
	) external view returns (uint256);

	/**
		Returns current subscription price ceiling.

		@return _ Subscription price ceiling.
	*/
	function priceCeiling () external view returns (uint256);

	/**
		Returns current subscription status for the alpha caller.

		@param _caller Address of the alpha caller.

		@return _ Subscription status flag.
	*/
	function created (
		address _caller
	) external view returns (bool);

	/**
		Returns a subscription's expiration timestamp.

		@param _subscriber Address of the subscriber.
		@param _alphaCaller Address of the alpha caller.

		@return _ A subscription's expiration timestamp.
	*/
	function timestamps (
		address _subscriber,
		address _alphaCaller
	) external view returns (uint256);

	/**
		Reads subscription information by its caller and subscriber
		addresses and returns:
			1. Subscription status - active/expired.
			2. Fee recipient address.
			3. Amount of fees to pay.
			4. Price of the subscription. 
		
		@param _alphaCaller Address of the alpha caller.
		@param _subscriber Address of the subscriber

		@return exists Subscription existence flag.
		@return active Flag of subscription being active.
		@return feeRecipient Fee recipient address.
		@return feeAmount Amount of fees to pay.
		@return price Subscription price.
	*/
	function subscriptionInfo (
		address _alphaCaller,
		address _subscriber
	) external view returns (
		bool exists,
		bool active,
		address feeRecipient,
		uint256 feeAmount,
		uint256 price
	);
}

// File: contracts/interfaces/IPaymentHandler.sol



// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.19;

import {
	IAlphaRegistry
} from "./IAlphaRegistry.sol";

/// An error thrown if Ether transfer fails.
error TransferFailed ();

/// An error thrown if trying to resubscribe when subscription is still active.
error SubscriptionStillActive ();

/**
	An error thrown if a subscriber does not supply exactly the correct amount of 
	Ether to pay for a subscription.
*/
error SubscriptionPriceNotMatched ();

/// Thrown if attempting to buy an inactive subscription.
error SubscriptionDoesNotExist ();

/**
	@custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
	@title Payment Handler Interface
	@author Rostislav Khlebnikov <@catpic5buck>

	The interface for the `PaymentHandler` contract.

	@custom:version 1.0
	@custom:date April 7th, 2023.
*/
interface IPaymentHandler {

	/**
		Return the duration of each subscription.

		@return _ The subscription duration.
	*/
	function SUBSCRIPTION_DURATION () external view returns (uint256);

	/**
		Return the `AlphaRegistry` contract address.

		@return _ The address of the `AlphaRegistry`.
	*/
	function REGISTRY () external view returns (IAlphaRegistry);

	/**
		Checks if a particular subcription is recurrent.

		@param _alphaCaller The address of the alpha caller.
		@param _subscriber The address of the subscriber.

		@return _ Whether or not the subscription is recurrent.
	*/
	function isSubscriptionRecurrent (
		address _alphaCaller,
		address _subscriber
	) external view returns (bool);

	/**
		Update caller status of the subscription and transfers fees and payments.

		@param _alphaCaller Address of the alpha caller.

		@custom:throws SubscriptionStillActive.
		@custom:throws SubscriptionPriceNotMatched.
		@custom:throws TransferFailed.
	*/
	function subscribe (
		address _alphaCaller
	) external payable;
}