Contract Name:
CoverProducts
Contract Source Code:
// 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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/draft-IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
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));
}
}
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// 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);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.18;
import "../interfaces/ISAFURAMaster.sol";
import "../interfaces/IMasterAwareV2.sol";
import "../interfaces/IMemberRoles.sol";
abstract contract MasterAwareV2 is IMasterAwareV2 {
ISAFURAMaster public master;
mapping(uint => address payable) public internalContracts;
modifier onlyMember {
require(
IMemberRoles(internalContracts[uint(ID.MR)]).checkRole(
msg.sender,
uint(IMemberRoles.Role.Member)
),
"Caller is not a member"
);
_;
}
modifier onlyAdvisoryBoard {
require(
IMemberRoles(internalContracts[uint(ID.MR)]).checkRole(
msg.sender,
uint(IMemberRoles.Role.AdvisoryBoard)
),
"Caller is not an advisory board member"
);
_;
}
modifier onlyInternal {
require(master.isInternal(msg.sender), "Caller is not an internal contract");
_;
}
modifier onlyMaster {
if (address(master) != address(0)) {
require(address(master) == msg.sender, "Not master");
}
_;
}
modifier onlyGovernance {
require(
master.checkIsAuthToGoverned(msg.sender),
"Caller is not authorized to govern"
);
_;
}
modifier onlyEmergencyAdmin {
require(
msg.sender == master.emergencyAdmin(),
"Caller is not emergency admin"
);
_;
}
modifier whenPaused {
require(master.isPause(), "System is not paused");
_;
}
modifier whenNotPaused {
require(!master.isPause(), "System is paused");
_;
}
function getInternalContractAddress(ID id) internal view returns (address payable) {
return internalContracts[uint(id)];
}
function changeMasterAddress(address masterAddress) public onlyMaster {
master = ISAFURAMaster(masterAddress);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.18;
abstract contract Multicall {
error RevertedWithoutReason(uint index);
// WARNING: Do not set this function as payable
function multicall(bytes[] calldata data) external returns (bytes[] memory results) {
uint callCount = data.length;
results = new bytes[](callCount);
for (uint i = 0; i < callCount; i++) {
(bool ok, bytes memory result) = address(this).delegatecall(data[i]);
if (!ok) {
uint length = result.length;
// 0 length returned from empty revert() / require(false)
if (length == 0) {
revert RevertedWithoutReason(i);
}
assembly {
revert(add(result, 0x20), length)
}
}
results[i] = result;
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
import "./IStakingPoolFactory.sol";
/**
* @dev IStakingPoolFactory is missing the changeOperator() and operator() functions.
* @dev Any change to the original interface will affect staking pool addresses
* @dev This interface is created to add the missing functions so it can be used in other contracts.
*/
interface ICompleteStakingPoolFactory is IStakingPoolFactory {
function operator() external view returns (address);
function changeOperator(address newOperator) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
import "./ICoverNFT.sol";
import "./IStakingNFT.sol";
import "./IStakingPool.sol";
import "./ICompleteStakingPoolFactory.sol";
/* io structs */
enum ClaimMethod {
IndividualClaims,
YieldTokenIncidents
}
struct PoolAllocationRequest {
uint40 poolId;
bool skip;
uint coverAmountInAsset;
}
struct BuyCoverParams {
uint coverId;
address owner;
uint24 productId;
uint8 coverAsset;
uint96 amount;
uint32 period;
uint maxPremiumInAsset;
uint8 paymentAsset;
uint16 commissionRatio;
address commissionDestination;
string ipfsData;
}
/* storage structs */
struct PoolAllocation {
uint40 poolId;
uint96 coverAmountInNXM;
uint96 premiumInNXM;
uint24 allocationId;
}
struct CoverData {
uint24 productId;
uint8 coverAsset;
uint96 amountPaidOut;
}
struct CoverSegment {
uint96 amount;
uint32 start;
uint32 period; // seconds
uint32 gracePeriod; // seconds
uint24 globalRewardsRatio;
uint24 globalCapacityRatio;
}
interface ICover {
/* ========== DATA STRUCTURES ========== */
/* internal structs */
struct RequestAllocationVariables {
uint previousPoolAllocationsLength;
uint previousPremiumInNXM;
uint refund;
uint coverAmountInNXM;
}
/* storage structs */
struct ActiveCover {
// Global active cover amount per asset.
uint192 totalActiveCoverInAsset;
// The last time activeCoverExpirationBuckets was updated
uint64 lastBucketUpdateId;
}
/* ========== VIEWS ========== */
function coverData(uint coverId) external view returns (CoverData memory);
function coverDataCount() external view returns (uint);
function coverSegmentsCount(uint coverId) external view returns (uint);
function coverSegments(uint coverId) external view returns (CoverSegment[] memory);
function coverSegmentWithRemainingAmount(
uint coverId,
uint segmentId
) external view returns (CoverSegment memory);
function recalculateActiveCoverInAsset(uint coverAsset) external;
function totalActiveCoverInAsset(uint coverAsset) external view returns (uint);
function getGlobalCapacityRatio() external view returns (uint);
function getGlobalRewardsRatio() external view returns (uint);
function getGlobalMinPriceRatio() external pure returns (uint);
function getGlobalCapacityAndPriceRatios() external view returns (
uint _globalCapacityRatio,
uint _globalMinPriceRatio
);
function GLOBAL_MIN_PRICE_RATIO() external view returns (uint);
/* === MUTATIVE FUNCTIONS ==== */
function buyCover(
BuyCoverParams calldata params,
PoolAllocationRequest[] calldata coverChunkRequests
) external payable returns (uint coverId);
function burnStake(
uint coverId,
uint segmentId,
uint amount
) external returns (address coverOwner);
function changeStakingPoolFactoryOperator() external;
function coverNFT() external returns (ICoverNFT);
function stakingNFT() external returns (IStakingNFT);
function stakingPoolFactory() external returns (ICompleteStakingPoolFactory);
/* ========== EVENTS ========== */
event CoverEdited(uint indexed coverId, uint indexed productId, uint indexed segmentId, address buyer, string ipfsMetadata);
// Auth
error OnlyOwnerOrApproved();
// Cover details
error CoverPeriodTooShort();
error CoverPeriodTooLong();
error CoverOutsideOfTheGracePeriod();
error CoverAmountIsZero();
// Products
error ProductNotFound();
error ProductDeprecated();
error UnexpectedProductId();
// Cover and payment assets
error CoverAssetNotSupported();
error InvalidPaymentAsset();
error UnexpectedCoverAsset();
error UnexpectedEthSent();
error EditNotSupported();
// Price & Commission
error PriceExceedsMaxPremiumInAsset();
error CommissionRateTooHigh();
// ETH transfers
error InsufficientEthSent();
error SendingEthToPoolFailed();
error SendingEthToCommissionDestinationFailed();
error ReturningEthRemainderToSenderFailed();
// Misc
error ExpiredCoversCannotBeEdited();
error CoverNotYetExpired(uint coverId);
error InsufficientCoverAmountAllocated();
error UnexpectedPoolId();
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
import "@openzeppelin/contracts-v4/token/ERC721/IERC721.sol";
interface ICoverNFT is IERC721 {
function isApprovedOrOwner(address spender, uint tokenId) external returns (bool);
function mint(address to) external returns (uint tokenId);
function changeOperator(address newOperator) external;
function changeNFTDescriptor(address newNFTDescriptor) external;
function totalSupply() external view returns (uint);
function name() external view returns (string memory);
error NotOperator();
error NotMinted();
error WrongFrom();
error InvalidRecipient();
error InvalidNewOperatorAddress();
error InvalidNewNFTDescriptorAddress();
error NotAuthorized();
error UnsafeRecipient();
error AlreadyMinted();
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
import "./ICover.sol";
/* io structs */
struct ProductInitializationParams {
uint productId;
uint8 weight;
uint96 initialPrice;
uint96 targetPrice;
}
/* storage structs */
struct Product {
uint16 productType;
address yieldTokenAddress;
// cover assets bitmap. each bit represents whether the asset with
// the index of that bit is enabled as a cover asset for this product
uint32 coverAssets;
uint16 initialPriceRatio;
uint16 capacityReductionRatio;
bool isDeprecated;
bool useFixedPrice;
}
struct ProductType {
uint8 claimMethod;
uint32 gracePeriod;
}
interface ICoverProducts {
/* storage structs */
struct Metadata {
string ipfsHash;
uint timestamp;
}
/* io structs */
struct ProductParam {
string productName;
uint productId;
string ipfsMetadata;
Product product;
uint[] allowedPools;
}
struct ProductTypeParam {
string productTypeName;
uint productTypeId;
string ipfsMetadata;
ProductType productType;
}
/* ========== VIEWS ========== */
function getProductType(uint productTypeId) external view returns (ProductType memory);
function getProductTypeName(uint productTypeId) external view returns (string memory);
function getProductTypeCount() external view returns (uint);
function getProductTypes() external view returns (ProductType[] memory);
function getProduct(uint productId) external view returns (Product memory);
function getProductName(uint productTypeId) external view returns (string memory);
function getProductCount() external view returns (uint);
function getProducts() external view returns (Product[] memory);
// add grace period function?
function getProductWithType(uint productId) external view returns (Product memory, ProductType memory);
function getLatestProductMetadata(uint productId) external view returns (Metadata memory);
function getLatestProductTypeMetadata(uint productTypeId) external view returns (Metadata memory);
function getProductMetadata(uint productId) external view returns (Metadata[] memory);
function getProductTypeMetadata(uint productTypeId) external view returns (Metadata[] memory);
function getAllowedPools(uint productId) external view returns (uint[] memory _allowedPools);
function getAllowedPoolsCount(uint productId) external view returns (uint);
function isPoolAllowed(uint productId, uint poolId) external view returns (bool);
function requirePoolIsAllowed(uint[] calldata productIds, uint poolId) external view;
function getCapacityReductionRatios(uint[] calldata productIds) external view returns (uint[] memory);
function getInitialPrices(uint[] calldata productIds) external view returns (uint[] memory);
function prepareStakingProductsParams(
ProductInitializationParams[] calldata params
) external returns (
ProductInitializationParams[] memory validatedParams
);
/* === MUTATIVE FUNCTIONS ==== */
function setProductTypes(ProductTypeParam[] calldata productTypes) external;
function setProducts(ProductParam[] calldata params) external;
/* ========== EVENTS ========== */
event ProductSet(uint id);
event ProductTypeSet(uint id);
// Products and product types
error ProductNotFound();
error ProductTypeNotFound();
error ProductDeprecated();
error PoolNotAllowedForThisProduct(uint productId);
error StakingPoolDoesNotExist();
error MismatchedArrayLengths();
error MetadataRequired();
// Misc
error UnsupportedCoverAssets();
error InitialPriceRatioBelowGlobalMinPriceRatio();
error InitialPriceRatioAbove100Percent();
error CapacityReductionRatioAbove100Percent();
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
import "./ICoverProducts.sol";
interface ILegacyCover {
function stakingPoolFactory() external view returns (address);
function getProducts() external view returns (Product[] memory);
function productTypesCount() external view returns (uint);
function productNames(uint productId) external view returns (string memory);
function allowedPools(uint productId, uint index) external view returns (uint);
function productTypes(uint id) external view returns (ProductType memory);
function productTypeNames(uint id) external view returns (string memory);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
interface IMasterAwareV2 {
// TODO: if you update this enum, update lib/constants.js as well
enum ID {
TC, // TokenController.sol
P1, // Pool.sol
MR, // MemberRoles.sol
MC, // MCR.sol
CO, // Cover.sol
SP, // StakingProducts.sol
PS, // LegacyPooledStaking.sol
GV, // Governance.sol
GW, // LegacyGateway.sol - removed
CL, // CoverMigrator.sol - removed
AS, // Assessment.sol
CI, // IndividualClaims.sol - Claims for Individuals
CG, // YieldTokenIncidents.sol - Claims for Groups
RA, // Ramm.sol
ST, // SafeTracker.sol
CP // CoverProducts.sol
}
function changeMasterAddress(address masterAddress) external;
function changeDependentContractAddress() external;
function internalContracts(uint) external view returns (address payable);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
interface IMemberRoles {
enum Role {Unassigned, AdvisoryBoard, Member, Owner, Auditor}
function join(address _userAddress, uint nonce, bytes calldata signature) external payable;
function switchMembership(address _newAddress) external;
function switchMembershipAndAssets(
address newAddress,
uint[] calldata coverIds,
uint[] calldata stakingTokenIds
) external;
function switchMembershipOf(address member, address _newAddress) external;
function totalRoles() external view returns (uint256);
function changeAuthorized(uint _roleId, address _newAuthorized) external;
function setKycAuthAddress(address _add) external;
function members(uint _memberRoleId) external view returns (uint, address[] memory memberArray);
function numberOfMembers(uint _memberRoleId) external view returns (uint);
function authorized(uint _memberRoleId) external view returns (address);
function roles(address _memberAddress) external view returns (uint[] memory);
function checkRole(address _memberAddress, uint _roleId) external view returns (bool);
function getMemberLengthForAllRoles() external view returns (uint[] memory totalMembers);
function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool);
function membersLength(uint _memberRoleId) external view returns (uint);
event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription);
event MemberJoined(address indexed newMember, uint indexed nonce);
event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp);
event MembershipWithdrawn(address indexed member, uint timestamp);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
import "./IPriceFeedOracle.sol";
struct SwapDetails {
uint104 minAmount;
uint104 maxAmount;
uint32 lastSwapTime;
// 2 decimals of precision. 0.01% -> 0.0001 -> 1e14
uint16 maxSlippageRatio;
}
struct Asset {
address assetAddress;
bool isCoverAsset;
bool isAbandoned;
}
interface IPool {
function swapOperator() external view returns (address);
function getAsset(uint assetId) external view returns (Asset memory);
function getAssets() external view returns (Asset[] memory);
function transferAssetToSwapOperator(address asset, uint amount) external;
function setSwapDetailsLastSwapTime(address asset, uint32 lastSwapTime) external;
function getAssetSwapDetails(address assetAddress) external view returns (SwapDetails memory);
function sendPayout(uint assetIndex, address payable payoutAddress, uint amount, uint ethDepositAmount) external;
function sendEth(address payoutAddress, uint amount) external;
function upgradeCapitalPool(address payable newPoolAddress) external;
function priceFeedOracle() external view returns (IPriceFeedOracle);
function getPoolValueInEth() external view returns (uint);
function calculateMCRRatio(uint totalAssetValue, uint mcrEth) external pure returns (uint);
function getInternalTokenPriceInAsset(uint assetId) external view returns (uint tokenPrice);
function getInternalTokenPriceInAssetAndUpdateTwap(uint assetId) external returns (uint tokenPrice);
function getTokenPrice() external view returns (uint tokenPrice);
function getMCRRatio() external view returns (uint);
function setSwapValue(uint value) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
interface Aggregator {
function decimals() external view returns (uint8);
function latestAnswer() external view returns (int);
}
interface IPriceFeedOracle {
struct OracleAsset {
Aggregator aggregator;
uint8 decimals;
}
function ETH() external view returns (address);
function assets(address) external view returns (Aggregator, uint8);
function getAssetToEthRate(address asset) external view returns (uint);
function getAssetForEth(address asset, uint ethIn) external view returns (uint);
function getEthForAsset(address asset, uint amount) external view returns (uint);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
interface ISAFURAMaster {
function tokenAddress() external view returns (address);
function owner() external view returns (address);
function emergencyAdmin() external view returns (address);
function masterInitialized() external view returns (bool);
function isInternal(address _add) external view returns (bool);
function isPause() external view returns (bool check);
function isMember(address _add) external view returns (bool);
function checkIsAuthToGoverned(address _add) external view returns (bool);
function getLatestAddress(bytes2 _contractName) external view returns (address payable contractAddress);
function contractAddresses(bytes2 code) external view returns (address payable);
function upgradeMultipleContracts(
bytes2[] calldata _contractCodes,
address payable[] calldata newAddresses
) external;
function removeContracts(bytes2[] calldata contractCodesToRemove) external;
function addNewInternalContracts(
bytes2[] calldata _contractCodes,
address payable[] calldata newAddresses,
uint[] calldata _types
) external;
function updateOwnerParameters(bytes8 code, address payable val) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
import "@openzeppelin/contracts-v4/token/ERC721/IERC721.sol";
interface IStakingNFT is IERC721 {
function isApprovedOrOwner(address spender, uint tokenId) external returns (bool);
function mint(uint poolId, address to) external returns (uint tokenId);
function changeOperator(address newOperator) external;
function changeNFTDescriptor(address newNFTDescriptor) external;
function totalSupply() external returns (uint);
function tokenInfo(uint tokenId) external view returns (uint poolId, address owner);
function stakingPoolOf(uint tokenId) external view returns (uint poolId);
function stakingPoolFactory() external view returns (address);
function name() external view returns (string memory);
error NotOperator();
error NotMinted();
error WrongFrom();
error InvalidRecipient();
error InvalidNewOperatorAddress();
error InvalidNewNFTDescriptorAddress();
error NotAuthorized();
error UnsafeRecipient();
error AlreadyMinted();
error NotStakingPool();
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
/* structs for io */
struct AllocationRequest {
uint productId;
uint coverId;
uint allocationId;
uint period;
uint gracePeriod;
bool useFixedPrice;
uint previousStart;
uint previousExpiration;
uint previousRewardsRatio;
uint globalCapacityRatio;
uint capacityReductionRatio;
uint rewardRatio;
uint globalMinPrice;
}
struct BurnStakeParams {
uint allocationId;
uint productId;
uint start;
uint period;
uint deallocationAmount;
}
interface IStakingPool {
/* structs for storage */
// stakers are grouped in tranches based on the timelock expiration
// tranche index is calculated based on the expiration date
// the initial proposal is to have 4 tranches per year (1 tranche per quarter)
struct Tranche {
uint128 stakeShares;
uint128 rewardsShares;
}
struct ExpiredTranche {
uint96 accNxmPerRewardShareAtExpiry;
uint96 stakeAmountAtExpiry; // nxm total supply is 6.7e24 and uint96.max is 7.9e28
uint128 stakeSharesSupplyAtExpiry;
}
struct Deposit {
uint96 lastAccNxmPerRewardShare;
uint96 pendingRewards;
uint128 stakeShares;
uint128 rewardsShares;
}
function initialize(
bool isPrivatePool,
uint initialPoolFee,
uint maxPoolFee,
uint _poolId,
string memory ipfsDescriptionHash
) external;
function processExpirations(bool updateUntilCurrentTimestamp) external;
function requestAllocation(
uint amount,
uint previousPremium,
AllocationRequest calldata request
) external returns (uint premium, uint allocationId);
function burnStake(uint amount, BurnStakeParams calldata params) external;
function depositTo(
uint amount,
uint trancheId,
uint requestTokenId,
address destination
) external returns (uint tokenId);
function withdraw(
uint tokenId,
bool withdrawStake,
bool withdrawRewards,
uint[] memory trancheIds
) external returns (uint withdrawnStake, uint withdrawnRewards);
function isPrivatePool() external view returns (bool);
function isHalted() external view returns (bool);
function manager() external view returns (address);
function getPoolId() external view returns (uint);
function getPoolFee() external view returns (uint);
function getMaxPoolFee() external view returns (uint);
function getActiveStake() external view returns (uint);
function getStakeSharesSupply() external view returns (uint);
function getRewardsSharesSupply() external view returns (uint);
function getRewardPerSecond() external view returns (uint);
function getAccNxmPerRewardsShare() external view returns (uint);
function getLastAccNxmUpdate() external view returns (uint);
function getFirstActiveTrancheId() external view returns (uint);
function getFirstActiveBucketId() external view returns (uint);
function getNextAllocationId() external view returns (uint);
function getDeposit(uint tokenId, uint trancheId) external view returns (
uint lastAccNxmPerRewardShare,
uint pendingRewards,
uint stakeShares,
uint rewardsShares
);
function getTranche(uint trancheId) external view returns (
uint stakeShares,
uint rewardsShares
);
function getExpiredTranche(uint trancheId) external view returns (
uint accNxmPerRewardShareAtExpiry,
uint stakeAmountAtExpiry,
uint stakeShareSupplyAtExpiry
);
function setPoolFee(uint newFee) external;
function setPoolPrivacy(bool isPrivatePool) external;
function getActiveAllocations(
uint productId
) external view returns (uint[] memory trancheAllocations);
function getTrancheCapacities(
uint productId,
uint firstTrancheId,
uint trancheCount,
uint capacityRatio,
uint reductionRatio
) external view returns (uint[] memory trancheCapacities);
/* ========== EVENTS ========== */
event StakeDeposited(address indexed user, uint256 amount, uint256 trancheId, uint256 tokenId);
event DepositExtended(address indexed user, uint256 tokenId, uint256 initialTrancheId, uint256 newTrancheId, uint256 topUpAmount);
event PoolPrivacyChanged(address indexed manager, bool isPrivate);
event PoolFeeChanged(address indexed manager, uint newFee);
event PoolDescriptionSet(string ipfsDescriptionHash);
event Withdraw(address indexed user, uint indexed tokenId, uint tranche, uint amountStakeWithdrawn, uint amountRewardsWithdrawn);
event StakeBurned(uint amount);
event Deallocated(uint productId);
event BucketExpired(uint bucketId);
event TrancheExpired(uint trancheId);
// Auth
error OnlyCoverContract();
error OnlyStakingProductsContract();
error OnlyManager();
error PrivatePool();
error SystemPaused();
error PoolHalted();
// Fees
error PoolFeeExceedsMax();
error MaxPoolFeeAbove100();
// Voting
error NxmIsLockedForGovernanceVote();
error ManagerNxmIsLockedForGovernanceVote();
// Deposit
error InsufficientDepositAmount();
error RewardRatioTooHigh();
// Staking NFTs
error InvalidTokenId();
error NotTokenOwnerOrApproved();
error InvalidStakingPoolForToken();
// Tranche & capacity
error NewTrancheEndsBeforeInitialTranche();
error RequestedTrancheIsNotYetActive();
error RequestedTrancheIsExpired();
error InsufficientCapacity();
// Allocation
error AlreadyDeallocated(uint allocationId);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
interface IStakingPoolFactory {
function stakingPoolCount() external view returns (uint);
function beacon() external view returns (address);
function create(address beacon) external returns (uint poolId, address stakingPoolAddress);
event StakingPoolCreated(uint indexed poolId, address indexed stakingPoolAddress);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
import "./ICoverProducts.sol";
import "./IStakingPool.sol";
interface IStakingProducts {
struct StakedProductParam {
uint productId;
bool recalculateEffectiveWeight;
bool setTargetWeight;
uint8 targetWeight;
bool setTargetPrice;
uint96 targetPrice;
}
struct Weights {
uint32 totalEffectiveWeight;
uint32 totalTargetWeight;
}
struct StakedProduct {
uint16 lastEffectiveWeight;
uint8 targetWeight;
uint96 targetPrice;
uint96 bumpedPrice;
uint32 bumpedPriceUpdateTime;
}
/* ============= PRODUCT FUNCTIONS ============= */
function setProducts(uint poolId, StakedProductParam[] memory params) external;
function getProductTargetWeight(uint poolId, uint productId) external view returns (uint);
function getTotalTargetWeight(uint poolId) external view returns (uint);
function getTotalEffectiveWeight(uint poolId) external view returns (uint);
function getProduct(uint poolId, uint productId) external view returns (
uint lastEffectiveWeight,
uint targetWeight,
uint targetPrice,
uint bumpedPrice,
uint bumpedPriceUpdateTime
);
/* ============= PRICING FUNCTIONS ============= */
function getPremium(
uint poolId,
uint productId,
uint period,
uint coverAmount,
uint initialCapacityUsed,
uint totalCapacity,
uint globalMinPrice,
bool useFixedPrice,
uint nxmPerAllocationUnit,
uint allocationUnitsPerNxm
) external returns (uint premium);
function calculateFixedPricePremium(
uint coverAmount,
uint period,
uint fixedPrice,
uint nxmPerAllocationUnit,
uint targetPriceDenominator
) external pure returns (uint);
function calculatePremium(
StakedProduct memory product,
uint period,
uint coverAmount,
uint initialCapacityUsed,
uint totalCapacity,
uint targetPrice,
uint currentBlockTimestamp,
uint nxmPerAllocationUnit,
uint allocationUnitsPerNxm,
uint targetPriceDenominator
) external pure returns (uint premium, StakedProduct memory);
function calculatePremiumPerYear(
uint basePrice,
uint coverAmount,
uint initialCapacityUsed,
uint totalCapacity,
uint nxmPerAllocationUnit,
uint allocationUnitsPerNxm,
uint targetPriceDenominator
) external pure returns (uint);
// Calculates the premium for a given cover amount starting with the surge point
function calculateSurgePremium(
uint amountOnSurge,
uint totalCapacity,
uint allocationUnitsPerNxm
) external pure returns (uint);
/* ========== STAKING POOL CREATION ========== */
function stakingPool(uint poolId) external view returns (IStakingPool);
function getStakingPoolCount() external view returns (uint);
function createStakingPool(
bool isPrivatePool,
uint initialPoolFee,
uint maxPoolFee,
ProductInitializationParams[] calldata productInitParams,
string calldata ipfsDescriptionHash
) external returns (uint poolId, address stakingPoolAddress);
function changeStakingPoolFactoryOperator(address newOperator) external;
/* ============= EVENTS ============= */
event ProductUpdated(uint productId, uint8 targetWeight, uint96 targetPrice);
/* ============= ERRORS ============= */
// Auth
error OnlyStakingPool();
error OnlyCoverContract();
error OnlyManager();
// Products & weights
error MustSetPriceForNewProducts();
error MustSetWeightForNewProducts();
error TargetPriceTooHigh();
error TargetPriceBelowMin();
error TargetWeightTooHigh();
error MustRecalculateEffectiveWeight();
error TotalTargetWeightExceeded();
error TotalEffectiveWeightExceeded();
// Staking Pool creation
error ProductDoesntExistOrIsDeprecated();
error InvalidProductType();
error TargetPriceBelowGlobalMinPriceRatio();
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.18;
import "@openzeppelin/contracts-v4/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts-v4/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-v4/token/ERC20/utils/SafeERC20.sol";
import "../../abstract/MasterAwareV2.sol";
import "../../abstract/Multicall.sol";
import "../../interfaces/ICover.sol";
import "../../interfaces/ICoverProducts.sol";
import "../../interfaces/ILegacyCover.sol";
import "../../interfaces/IPool.sol";
import "../../interfaces/IStakingProducts.sol";
contract CoverProducts is ICoverProducts, MasterAwareV2, Multicall {
/* ========== STATE VARIABLES ========== */
Product[] internal _products;
ProductType[] internal _productTypes;
// productId => product name
mapping(uint => string) internal productNames;
// productTypeId => productType name
mapping(uint => string) internal productTypeNames;
// product id => allowed pool ids
mapping(uint => uint[]) internal allowedPools;
mapping(uint => Metadata[]) internal productMetadata;
mapping(uint => Metadata[]) internal productTypeMetadata;
/* ========== CONSTANTS ========== */
uint private constant PRICE_DENOMINATOR = 10000;
uint private constant CAPACITY_REDUCTION_DENOMINATOR = 10000;
/* ========== VIEWS ========== */
function getProductType(uint productTypeId) external view returns (ProductType memory) {
return _productTypes[productTypeId];
}
function getProductTypeName(uint productTypeId) external view returns (string memory) {
return productTypeNames[productTypeId];
}
function getProductTypeCount() external view returns (uint) {
return _productTypes.length;
}
function getProductTypes() external view returns (ProductType[] memory) {
return _productTypes;
}
function getProduct(uint productId) external view returns (Product memory) {
return _products[productId];
}
function getProductName(uint productId) external view returns (string memory) {
return productNames[productId];
}
function getProductCount() public view returns (uint) {
return _products.length;
}
function getProducts() external view returns (Product[] memory) {
return _products;
}
function getProductWithType(uint productId) external override view returns (
Product memory product,
ProductType memory productType
) {
product = _products[productId];
productType = _productTypes[product.productType];
}
function getLatestProductMetadata(uint productId) external view returns (Metadata memory) {
uint metadataLength = productMetadata[productId].length;
return metadataLength > 0
? productMetadata[productId][metadataLength - 1]
: Metadata("", 0);
}
function getLatestProductTypeMetadata(uint productTypeId) external view returns (Metadata memory) {
uint metadataLength = productTypeMetadata[productTypeId].length;
return metadataLength > 0
? productTypeMetadata[productTypeId][metadataLength - 1]
: Metadata("", 0);
}
function getProductMetadata(uint productId) external view returns (Metadata[] memory) {
return productMetadata[productId];
}
function getProductTypeMetadata(uint productTypeId) external view returns (Metadata[] memory) {
return productTypeMetadata[productTypeId];
}
function getAllowedPools(uint productId) external view returns (uint[] memory _allowedPools) {
uint allowedPoolCount = allowedPools[productId].length;
_allowedPools = new uint[](allowedPoolCount);
for (uint i = 0; i < allowedPoolCount; i++) {
_allowedPools[i] = allowedPools[productId][i];
}
}
function getAllowedPoolsCount(uint productId) external view returns (uint) {
return allowedPools[productId].length;
}
function getInitialPrices(
uint[] calldata productIds
) external view returns (uint[] memory initialPrices) {
uint productCount = _products.length;
initialPrices = new uint[](productIds.length);
for (uint i = 0; i < productIds.length; i++) {
uint productId = productIds[i];
if (productId >= productCount) {
revert ProductNotFound();
}
initialPrices[i] = _products[productId].initialPriceRatio;
}
}
function getCapacityReductionRatios(
uint[] calldata productIds
) external view returns (uint[] memory capacityReductionRatios) {
uint productCount = _products.length;
capacityReductionRatios = new uint[](productIds.length);
for (uint i = 0; i < productIds.length; i++) {
uint productId = productIds[i];
if (productId >= productCount) {
revert ProductNotFound();
}
capacityReductionRatios[i] = _products[productId].capacityReductionRatio;
}
}
function prepareStakingProductsParams(
ProductInitializationParams[] calldata params
) external view returns (
ProductInitializationParams[] memory validatedParams
) {
uint productCount = _products.length;
uint inputLength = params.length;
validatedParams = new ProductInitializationParams[](inputLength);
// override with initial price and check if pool is allowed
for (uint i = 0; i < inputLength; i++) {
uint productId = params[i].productId;
if (productId >= productCount) {
revert ProductNotFound();
}
// if there is a list of allowed pools for this product - the new pool didn't exist yet
// so the product can't be in it
if (allowedPools[productId].length > 0) {
revert PoolNotAllowedForThisProduct(productId);
}
Product memory product = _products[productId];
if (product.isDeprecated) {
revert ProductDeprecated();
}
validatedParams[i] = params[i];
validatedParams[i].initialPrice = product.initialPriceRatio;
}
}
/* ========== PRODUCT CONFIGURATION ========== */
function setProducts(ProductParam[] calldata productParams) external override onlyAdvisoryBoard {
uint unsupportedCoverAssetsBitmap = type(uint).max;
uint globalMinPriceRatio = cover().getGlobalMinPriceRatio();
uint poolCount = stakingProducts().getStakingPoolCount();
Asset[] memory assets = pool().getAssets();
uint assetsLength = assets.length;
for (uint i = 0; i < assetsLength; i++) {
if (assets[i].isCoverAsset && !assets[i].isAbandoned) {
// clear the bit at index i
unsupportedCoverAssetsBitmap ^= 1 << i;
}
}
for (uint i = 0; i < productParams.length; i++) {
ProductParam calldata param = productParams[i];
Product calldata product = param.product;
if (product.productType >= _productTypes.length) {
revert ProductTypeNotFound();
}
if (unsupportedCoverAssetsBitmap & product.coverAssets != 0) {
revert UnsupportedCoverAssets();
}
if (product.initialPriceRatio < globalMinPriceRatio) {
revert InitialPriceRatioBelowGlobalMinPriceRatio();
}
if (product.initialPriceRatio > PRICE_DENOMINATOR) {
revert InitialPriceRatioAbove100Percent();
}
if (product.capacityReductionRatio > CAPACITY_REDUCTION_DENOMINATOR) {
revert CapacityReductionRatioAbove100Percent();
}
if (param.allowedPools.length > 0) {
for (uint j = 0; j < param.allowedPools.length; j++) {
if (param.allowedPools[j] > poolCount || param.allowedPools[j] == 0) {
revert StakingPoolDoesNotExist();
}
}
}
// New product has id == uint256.max
if (param.productId == type(uint256).max) {
uint productId = _products.length;
// the metadata is optional, do not push if empty
if (bytes(param.ipfsMetadata).length > 0) {
productMetadata[productId].push(Metadata(param.ipfsMetadata, block.timestamp));
}
productNames[productId] = param.productName;
allowedPools[productId] = param.allowedPools;
_products.push(product);
emit ProductSet(productId);
continue;
}
// Existing product
if (param.productId >= _products.length) {
revert ProductNotFound();
}
Product storage newProductValue = _products[param.productId];
newProductValue.isDeprecated = product.isDeprecated;
newProductValue.coverAssets = product.coverAssets;
newProductValue.initialPriceRatio = product.initialPriceRatio;
newProductValue.capacityReductionRatio = product.capacityReductionRatio;
allowedPools[param.productId] = param.allowedPools;
if (bytes(param.productName).length > 0) {
productNames[param.productId] = param.productName;
}
if (bytes(param.ipfsMetadata).length > 0) {
productMetadata[param.productId].push(Metadata(param.ipfsMetadata, block.timestamp));
}
emit ProductSet(param.productId);
}
}
function setProductTypes(ProductTypeParam[] calldata productTypeParams) external onlyAdvisoryBoard {
for (uint i = 0; i < productTypeParams.length; i++) {
ProductTypeParam calldata param = productTypeParams[i];
// New product has id == uint256.max
if (param.productTypeId == type(uint256).max) {
uint productTypeId = _productTypes.length;
// the product type metadata is mandatory
if (bytes(param.ipfsMetadata).length == 0) {
revert MetadataRequired();
}
productTypeMetadata[productTypeId].push(Metadata(param.ipfsMetadata, block.timestamp));
productTypeNames[productTypeId] = param.productTypeName;
_productTypes.push(param.productType);
emit ProductTypeSet(productTypeId);
continue;
}
if (param.productTypeId >= _productTypes.length) {
revert ProductTypeNotFound();
}
_productTypes[param.productTypeId].gracePeriod = param.productType.gracePeriod;
if (bytes(param.productTypeName).length > 0) {
productTypeNames[param.productTypeId] = param.productTypeName;
}
if (bytes(param.ipfsMetadata).length > 0) {
productTypeMetadata[param.productTypeId].push(Metadata(param.ipfsMetadata, block.timestamp));
}
emit ProductTypeSet(param.productTypeId);
}
}
function setProductsMetadata(
uint[] calldata productIds,
string[] calldata ipfsMetadata
) external onlyAdvisoryBoard {
if (productIds.length != ipfsMetadata.length) {
revert MismatchedArrayLengths();
}
uint productCount = _products.length;
for (uint i = 0; i < productIds.length; i++) {
uint productId = productIds[i];
if (productId >= productCount) {
revert ProductNotFound();
}
productMetadata[productId].push(Metadata(ipfsMetadata[i], block.timestamp));
}
}
function setProductTypesMetadata(
uint[] calldata productTypeIds,
string[] calldata ipfsMetadata
) external onlyAdvisoryBoard {
if (productTypeIds.length != ipfsMetadata.length) {
revert MismatchedArrayLengths();
}
uint productTypeCount = _productTypes.length;
for (uint i = 0; i < productTypeIds.length; i++) {
uint productTypeId = productTypeIds[i];
if (productTypeId >= productTypeCount) {
revert ProductTypeNotFound();
}
if (bytes(ipfsMetadata[i]).length == 0) {
revert MetadataRequired();
}
productTypeMetadata[productTypeId].push(Metadata(ipfsMetadata[i], block.timestamp));
}
}
/* ========== COVER ASSETS HELPERS ========== */
// Returns true if the product exists and the pool is authorized to have the product
function isPoolAllowed(uint productId, uint poolId) public view returns (bool) {
uint poolCount = allowedPools[productId].length;
// If no pools are specified, every pool is allowed
if (poolCount == 0) {
return true;
}
for (uint i = 0; i < poolCount; i++) {
if (allowedPools[productId][i] == poolId) {
return true;
}
}
// Product has allow list and pool is not in it
return false;
}
function requirePoolIsAllowed(uint[] calldata productIds, uint poolId) external view {
for (uint i = 0; i < productIds.length; i++) {
if (!isPoolAllowed(productIds[i], poolId) ) {
revert PoolNotAllowedForThisProduct(productIds[i]);
}
}
}
/* ========== DEPENDENCIES ========== */
function migrateCoverProducts() external {
require(_products.length == 0, "CoverProducts: _products already migrated");
require(_productTypes.length == 0, "CoverProducts: _productTypes already migrated");
ILegacyCover _cover = ILegacyCover(address(cover()));
IStakingPoolFactory _stakingPoolFactory = IStakingPoolFactory(_cover.stakingPoolFactory());
Product[] memory _productsToMigrate = _cover.getProducts();
uint _productTypeCount = _cover.productTypesCount();
uint stakingPoolCount = _stakingPoolFactory.stakingPoolCount();
for (uint i = 0; i < _productsToMigrate.length; i++) {
_products.push(_productsToMigrate[i]);
productNames[i] = _cover.productNames(i);
uint[] storage _allowedPools = allowedPools[i];
if (!_productsToMigrate[i].useFixedPrice || _productsToMigrate[i].isDeprecated) {
continue;
}
for (uint j = 0; j < stakingPoolCount; j++) {
try _cover.allowedPools(i, j) returns (uint poolId) {
_allowedPools.push(poolId);
} catch {
break;
}
}
}
for (uint i = 0; i < _productTypeCount; i++) {
ProductType memory _productTypeToMigrate = _cover.productTypes(i);
_productTypes.push(_productTypeToMigrate);
productTypeNames[i] = _cover.productTypeNames(i);
}
}
/* ========== DEPENDENCIES ========== */
function pool() internal view returns (IPool) {
return IPool(internalContracts[uint(ID.P1)]);
}
function cover() internal view returns (ICover) {
return ICover(internalContracts[uint(ID.CO)]);
}
function stakingProducts() internal view returns (IStakingProducts) {
return IStakingProducts(internalContracts[uint(ID.SP)]);
}
function changeDependentContractAddress() public {
internalContracts[uint(ID.P1)] = master.getLatestAddress("P1");
internalContracts[uint(ID.CO)] = master.getLatestAddress("CO");
internalContracts[uint(ID.MR)] = master.getLatestAddress("MR");
internalContracts[uint(ID.SP)] = master.getLatestAddress("SP");
}
}