{ "language": "Solidity", "sources": { "@openzeppelin/contracts-v4/token/ERC721/IERC721.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n" }, "@openzeppelin/contracts-v4/utils/Base64.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n" }, "@openzeppelin/contracts-v4/utils/introspection/IERC165.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" }, "@openzeppelin/contracts-v4/utils/Strings.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n" }, "contracts/interfaces/IStakingNFT.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\nimport \"@openzeppelin/contracts-v4/token/ERC721/IERC721.sol\";\n\ninterface IStakingNFT is IERC721 {\n\n function isApprovedOrOwner(address spender, uint tokenId) external returns (bool);\n\n function mint(uint poolId, address to) external returns (uint tokenId);\n\n function changeOperator(address newOperator) external;\n\n function totalSupply() external returns (uint);\n\n function tokenInfo(uint tokenId) external view returns (uint poolId, address owner);\n\n function stakingPoolOf(uint tokenId) external view returns (uint poolId);\n\n function stakingPoolFactory() external view returns (address);\n\n function name() external view returns (string memory);\n\n error NotOperator();\n error NotMinted();\n error WrongFrom();\n error InvalidRecipient();\n error InvalidNewOperatorAddress();\n error InvalidNewNFTDescriptorAddress();\n error NotAuthorized();\n error UnsafeRecipient();\n error AlreadyMinted();\n error NotStakingPool();\n\n}\n" }, "contracts/interfaces/IStakingNFTDescriptor.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\ninterface IStakingNFTDescriptor {\n\n function tokenURI(uint tokenId) external view returns (string memory);\n\n}\n" }, "contracts/interfaces/IStakingPool.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\n/* structs for io */\n\nstruct AllocationRequest {\n uint productId;\n uint coverId;\n uint allocationId;\n uint period;\n uint gracePeriod;\n bool useFixedPrice;\n uint previousStart;\n uint previousExpiration;\n uint previousRewardsRatio;\n uint globalCapacityRatio;\n uint capacityReductionRatio;\n uint rewardRatio;\n uint globalMinPrice;\n}\n\nstruct StakedProductParam {\n uint productId;\n bool recalculateEffectiveWeight;\n bool setTargetWeight;\n uint8 targetWeight;\n bool setTargetPrice;\n uint96 targetPrice;\n}\n\n struct BurnStakeParams {\n uint allocationId;\n uint productId;\n uint start;\n uint period;\n uint deallocationAmount;\n }\n\ninterface IStakingPool {\n\n /* structs for storage */\n\n // stakers are grouped in tranches based on the timelock expiration\n // tranche index is calculated based on the expiration date\n // the initial proposal is to have 4 tranches per year (1 tranche per quarter)\n struct Tranche {\n uint128 stakeShares;\n uint128 rewardsShares;\n }\n\n struct ExpiredTranche {\n uint96 accNxmPerRewardShareAtExpiry;\n uint96 stakeAmountAtExpiry; // nxm total supply is 6.7e24 and uint96.max is 7.9e28\n uint128 stakeSharesSupplyAtExpiry;\n }\n\n struct Deposit {\n uint96 lastAccNxmPerRewardShare;\n uint96 pendingRewards;\n uint128 stakeShares;\n uint128 rewardsShares;\n }\n\n function initialize(\n bool isPrivatePool,\n uint initialPoolFee,\n uint maxPoolFee,\n uint _poolId,\n string memory ipfsDescriptionHash\n ) external;\n\n function processExpirations(bool updateUntilCurrentTimestamp) external;\n\n function requestAllocation(\n uint amount,\n uint previousPremium,\n AllocationRequest calldata request\n ) external returns (uint premium, uint allocationId);\n\n function burnStake(uint amount, BurnStakeParams calldata params) external;\n\n function depositTo(\n uint amount,\n uint trancheId,\n uint requestTokenId,\n address destination\n ) external returns (uint tokenId);\n\n function withdraw(\n uint tokenId,\n bool withdrawStake,\n bool withdrawRewards,\n uint[] memory trancheIds\n ) external returns (uint withdrawnStake, uint withdrawnRewards);\n\n function isPrivatePool() external view returns (bool);\n\n function isHalted() external view returns (bool);\n\n function manager() external view returns (address);\n\n function getPoolId() external view returns (uint);\n\n function getPoolFee() external view returns (uint);\n\n function getMaxPoolFee() external view returns (uint);\n\n function getActiveStake() external view returns (uint);\n\n function getStakeSharesSupply() external view returns (uint);\n\n function getRewardsSharesSupply() external view returns (uint);\n\n function getRewardPerSecond() external view returns (uint);\n\n function getAccNxmPerRewardsShare() external view returns (uint);\n\n function getLastAccNxmUpdate() external view returns (uint);\n\n function getFirstActiveTrancheId() external view returns (uint);\n\n function getFirstActiveBucketId() external view returns (uint);\n\n function getNextAllocationId() external view returns (uint);\n\n function getDeposit(uint tokenId, uint trancheId) external view returns (\n uint lastAccNxmPerRewardShare,\n uint pendingRewards,\n uint stakeShares,\n uint rewardsShares\n );\n\n function getTranche(uint trancheId) external view returns (\n uint stakeShares,\n uint rewardsShares\n );\n\n function getExpiredTranche(uint trancheId) external view returns (\n uint accNxmPerRewardShareAtExpiry,\n uint stakeAmountAtExpiry,\n uint stakeShareSupplyAtExpiry\n );\n\n function setPoolFee(uint newFee) external;\n\n function setPoolPrivacy(bool isPrivatePool) external;\n\n function getActiveAllocations(\n uint productId\n ) external view returns (uint[] memory trancheAllocations);\n\n function getTrancheCapacities(\n uint productId,\n uint firstTrancheId,\n uint trancheCount,\n uint capacityRatio,\n uint reductionRatio\n ) external view returns (uint[] memory trancheCapacities);\n\n /* ========== EVENTS ========== */\n\n event StakeDeposited(address indexed user, uint256 amount, uint256 trancheId, uint256 tokenId);\n\n event DepositExtended(address indexed user, uint256 tokenId, uint256 initialTrancheId, uint256 newTrancheId, uint256 topUpAmount);\n\n event PoolPrivacyChanged(address indexed manager, bool isPrivate);\n\n event PoolFeeChanged(address indexed manager, uint newFee);\n\n event PoolDescriptionSet(string ipfsDescriptionHash);\n\n event Withdraw(address indexed user, uint indexed tokenId, uint tranche, uint amountStakeWithdrawn, uint amountRewardsWithdrawn);\n\n event StakeBurned(uint amount);\n\n // Auth\n error OnlyCoverContract();\n error OnlyManager();\n error PrivatePool();\n error SystemPaused();\n error PoolHalted();\n\n // Fees\n error PoolFeeExceedsMax();\n error MaxPoolFeeAbove100();\n\n // Voting\n error NxmIsLockedForGovernanceVote();\n error ManagerNxmIsLockedForGovernanceVote();\n\n // Deposit\n error InsufficientDepositAmount();\n error RewardRatioTooHigh();\n\n // Staking NFTs\n error InvalidTokenId();\n error NotTokenOwnerOrApproved();\n error InvalidStakingPoolForToken();\n\n // Tranche & capacity\n error NewTrancheEndsBeforeInitialTranche();\n error RequestedTrancheIsNotYetActive();\n error RequestedTrancheIsExpired();\n error InsufficientCapacity();\n\n}\n" }, "contracts/interfaces/IStakingPoolFactory.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\ninterface IStakingPoolFactory {\n\n function stakingPoolCount() external view returns (uint);\n\n function beacon() external view returns (address);\n\n function create(address beacon) external returns (uint poolId, address stakingPoolAddress);\n\n event StakingPoolCreated(uint indexed poolId, address indexed stakingPoolAddress);\n}\n" }, "contracts/libraries/DateTime.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Modified from: https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary/blob/master/contracts/BokkyPooBahsDateTimeLibrary.sol\nlibrary DateTime {\n uint constant SECONDS_PER_MINUTE = 60;\n uint constant SECONDS_PER_HOUR = SECONDS_PER_MINUTE * SECONDS_PER_MINUTE;\n uint constant SECONDS_PER_DAY = 24 * SECONDS_PER_HOUR;\n int constant OFFSET19700101 = 2440588;\n\n\n function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {\n int __days = int(_days);\n\n int L = __days + 68569 + OFFSET19700101;\n int N = 4 * L / 146097;\n L = L - (146097 * N + 3) / 4;\n int _year = 4000 * (L + 1) / 1461001;\n L = L - 1461 * _year / 4 + 31;\n int _month = 80 * L / 2447;\n int _day = L - 2447 * _month / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint(_year);\n month = uint(_month);\n day = uint(_day);\n }\n\n function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) {\n (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);\n }\n\n function getMonthString(uint month) internal pure returns (string memory) {\n if (month == 1) { return \"Jan\"; }\n if (month == 2) { return \"Feb\"; }\n if (month == 3) { return \"Mar\"; }\n if (month == 4) { return \"Apr\"; }\n if (month == 5) { return \"May\"; }\n if (month == 6) { return \"Jun\"; }\n if (month == 7) { return \"Jul\"; }\n if (month == 8) { return \"Aug\"; }\n if (month == 9) { return \"Sep\"; }\n if (month == 10) { return \"Oct\"; }\n if (month == 11) { return \"Nov\"; }\n if (month == 12) { return \"Dec\"; }\n revert(\"Invalid month\");\n }\n}\n" }, "contracts/libraries/FloatingPoint.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts-v4/utils/Strings.sol\";\n\nlibrary FloatingPoint {\n using Strings for uint;\n\n // Convert a number to a float string with 2 decimals\n function toFloat(\n uint number,\n uint decimals\n ) internal pure returns (string memory float) {\n if (decimals == 0) {\n return string(abi.encodePacked(number.toString(), \".00\"));\n }\n\n uint decimalBase = 10 ** decimals;\n\n // Get the integer part\n uint integerVal = number / (decimalBase);\n float = string(abi.encodePacked(integerVal.toString(), \".\"));\n\n // Get the remainder\n uint remainder = number % (decimalBase);\n string memory remainderStr = remainder.toString();\n bytes memory remainderBytes = bytes(remainderStr);\n\n // The number of digits should be greater than decimals - 1\n if (remainderBytes.length + 1 < decimals) {\n return string(abi.encodePacked(float, \"00\"));\n }\n\n // If the remainder is less than 10, add a leading zero before digit and return\n if (remainder < decimalBase / 10) {\n remainderStr = string(abi.encodePacked(\"0\", remainderBytes[0]));\n return string(abi.encodePacked(float, remainderStr));\n }\n\n // If the remainder is a single digit, add a trailing zero and return\n if (remainderBytes.length == 1) {\n remainderStr = string(abi.encodePacked(remainderBytes[0], \"0\"));\n return string(abi.encodePacked(float, remainderStr));\n }\n\n // Otherwise encode first two digits of remainder\n remainderStr = string(\n abi.encodePacked(remainderBytes[0], remainderBytes[1])\n );\n float = string(abi.encodePacked(float, remainderStr));\n }\n}\n" }, "contracts/libraries/StakingPoolLibrary.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity ^0.8.18;\n\n/**\n * @dev Simple library to derive the staking pool address from the pool id without external calls\n */\nlibrary StakingPoolLibrary {\n\n function getAddress(address factory, uint poolId) internal pure returns (address) {\n\n bytes32 hash = keccak256(\n abi.encodePacked(\n hex'ff',\n factory,\n poolId, // salt\n // init code hash of the MinimalBeaconProxy\n // updated using patch-staking-pool-library.js script\n hex'1eb804b66941a2e8465fa0951be9c8b855b7794ee05b0789ab22a02ee1298ebe' // init code hash\n )\n );\n\n // cast last 20 bytes of hash to address\n return address(uint160(uint(hash)));\n }\n\n}\n" }, "contracts/modules/staking/StakingNFTDescriptor.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts-v4/utils/Strings.sol\";\nimport \"@openzeppelin/contracts-v4/utils/Base64.sol\";\nimport \"../../interfaces/IStakingNFT.sol\";\nimport \"../../interfaces/IStakingNFTDescriptor.sol\";\nimport \"../../interfaces/IStakingPool.sol\";\nimport \"../../interfaces/IStakingPoolFactory.sol\";\nimport \"../../libraries/DateTime.sol\";\nimport \"../../libraries/FloatingPoint.sol\";\nimport \"../../libraries/StakingPoolLibrary.sol\";\n\nstruct StakeData {\n uint poolId;\n uint stakeAmount;\n uint tokenId;\n}\n\ncontract StakingNFTDescriptor is IStakingNFTDescriptor {\n using Strings for uint;\n using DateTime for uint;\n\n uint public constant TRANCHE_DURATION = 91 days;\n uint public constant MAX_ACTIVE_TRANCHES = 8;\n uint public constant ONE_NXM = 1 ether;\n uint public constant NXM_DECIMALS = 18;\n\n function tokenURI(uint tokenId) public view returns (string memory) {\n (string memory description, StakeData memory stakeData) = buildDescription(tokenId);\n string memory image = Base64.encode(bytes(generateSVGImage(stakeData)));\n\n return string(\n abi.encodePacked(\n \"data:application/json;base64,\",\n Base64.encode(\n bytes(\n abi.encodePacked(\n '{\"name\":\"', IStakingNFT(msg.sender).name(), '\",',\n '\"description\":\"', description, '\",',\n '\"image\": \"', \"data:image/svg+xml;base64,\", image,\n '\"}'\n )\n )\n )\n )\n );\n }\n\n function buildDescription(uint tokenId) public view returns (string memory description, StakeData memory stakeData) {\n uint poolId = IStakingNFT(msg.sender).stakingPoolOf(tokenId);\n address stakingPoolFactory = IStakingNFT(msg.sender).stakingPoolFactory();\n address stakingPool = StakingPoolLibrary.getAddress(stakingPoolFactory, poolId);\n\n // Check if token exists\n (string memory depositInfo, uint totalStake, uint pendingRewards) = getActiveDeposits(\n tokenId,\n IStakingPool(stakingPool)\n );\n\n // Add pool info\n description = append(\n \"This NFT represents a deposit into staking pool: \",\n uint(uint160(stakingPool)).toHexString()\n );\n description = appendWithNewline(description, \"Pool ID: \", poolId.toString());\n\n // No active deposits, assume it has expired\n if (totalStake == 0) {\n description = appendWithNewline(description, \"Deposit has expired!\");\n return (description, StakeData(poolId, 0, tokenId));\n }\n\n // Add deposit info\n description = appendWithNewline(description, \"Staked amount: \", FloatingPoint.toFloat(totalStake, NXM_DECIMALS), \" NXM\");\n description = appendWithNewline(description, \"Pending rewards: \", FloatingPoint.toFloat(pendingRewards, NXM_DECIMALS), \" NXM\");\n description = appendWithNewline(description, \"Active deposits: \", depositInfo);\n\n return (description, StakeData(poolId, totalStake, tokenId));\n }\n\n function getActiveDeposits(\n uint tokenId,\n IStakingPool stakingPool\n ) public view returns (\n string memory depositInfo,\n uint totalStake,\n uint pendingRewards\n ) {\n\n uint activeStake = stakingPool.getActiveStake();\n uint stakeSharesSupply = stakingPool.getStakeSharesSupply();\n\n // Get total stake from each active tranche\n for (uint i = 0; i < MAX_ACTIVE_TRANCHES; i++) {\n // get deposit\n (uint lastAccNxmPerRewardShare, uint _pendingRewards, uint _stakeShares, uint _rewardsShares) =\n stakingPool.getDeposit(tokenId, (block.timestamp / TRANCHE_DURATION) + i);\n\n // no active stake, skip this tranche\n if (_rewardsShares == 0) {\n continue;\n }\n\n string memory dateString;\n {\n // calculate days left until stake expires\n uint secondsLeftInTranche = (TRANCHE_DURATION - (block.timestamp % TRANCHE_DURATION));\n (uint year, uint month, uint day) = (block.timestamp + (secondsLeftInTranche + (i * TRANCHE_DURATION))).timestampToDate();\n dateString = string(abi.encodePacked(month.getMonthString(), \" \", addZeroPrefix(day), \" \", year.toString()));\n }\n\n uint stake = (activeStake * _stakeShares) / stakeSharesSupply;\n\n depositInfo = appendWithNewline(\n depositInfo,\n \" -\",\n append(FloatingPoint.toFloat(stake, NXM_DECIMALS), \" NXM will expire at tranche: \", uint((block.timestamp / TRANCHE_DURATION) + i).toString()),\n append(\" (\", dateString, \")\")\n );\n\n // update pending rewards\n uint newRewardPerShare = stakingPool.getAccNxmPerRewardsShare() - lastAccNxmPerRewardShare;\n pendingRewards += _pendingRewards + (newRewardPerShare * _rewardsShares) / ONE_NXM;\n\n // update total stake\n totalStake += stake;\n }\n return (depositInfo, totalStake, pendingRewards);\n }\n\n\n function generateSVGImage(StakeData memory stakeDescription) public pure returns (bytes memory) {\n return abi.encodePacked(\n string(\n abi.encodePacked(\n ' Staking Info Pool ID: Stake: NFT ID:',\n '', stakeDescription.poolId.toString(), '',\n '', FloatingPoint.toFloat(stakeDescription.stakeAmount, NXM_DECIMALS), ' NXM',\n '', stakeDescription.tokenId.toString(), ''\n )\n )\n );\n }\n\n // If value is single digit, add a zero prefix\n function addZeroPrefix(uint256 value) public pure returns (string memory) {\n if (value < 10) {\n return string(abi.encodePacked(\"0\", value.toString()));\n }\n return value.toString();\n }\n\n function append(string memory a, string memory b) internal pure returns (string memory) {\n return string(abi.encodePacked(a, b));\n }\n\n function append(string memory a, string memory b, string memory c) internal pure returns (string memory) {\n return string(abi.encodePacked(a, b, c));\n }\n\n function appendWithNewline(string memory a, string memory b) internal pure returns (string memory) {\n return string(abi.encodePacked(a, \"\\\\n\", b));\n }\n\n function appendWithNewline(string memory a, string memory b, string memory c) internal pure returns (string memory) {\n return string(abi.encodePacked(a, \"\\\\n\", b, c));\n }\n\n function appendWithNewline(string memory a, string memory b, string memory c, string memory d) internal pure returns (string memory) {\n return string(abi.encodePacked(a, \"\\\\n\", b, c, d));\n }\n\n function toFloat(uint number, uint decimals) public pure returns (string memory) {\n return FloatingPoint.toFloat(number, decimals);\n }\n}\n" } }, "settings": { "optimizer": { "enabled": true, "runs": 200 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} } }