zellic-audit
Initial commit
f998fcd
raw
history blame
116 kB
{
"language": "Solidity",
"sources": {
"src/diamonds/nayms/AppStorage.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/// @notice storage for nayms v3 decentralized insurance platform\n\nimport \"./interfaces/FreeStructs.sol\";\n\nstruct AppStorage {\n // Has this diamond been initialized?\n bool diamondInitialized;\n //// EIP712 domain separator ////\n uint256 initialChainId;\n bytes32 initialDomainSeparator;\n //// Reentrancy guard ////\n uint256 reentrancyStatus;\n //// NAYMS ERC20 TOKEN ////\n string name;\n mapping(address => mapping(address => uint256)) allowance;\n uint256 totalSupply;\n mapping(bytes32 => bool) internalToken;\n mapping(address => uint256) balances;\n //// Object ////\n mapping(bytes32 => bool) existingObjects; // objectId => is an object?\n mapping(bytes32 => bytes32) objectParent; // objectId => parentId\n mapping(bytes32 => bytes32) objectDataHashes;\n mapping(bytes32 => string) objectTokenSymbol;\n mapping(bytes32 => string) objectTokenName;\n mapping(bytes32 => address) objectTokenWrapper;\n mapping(bytes32 => bool) existingEntities; // entityId => is an entity?\n mapping(bytes32 => bool) existingSimplePolicies; // simplePolicyId => is a simple policy?\n //// ENTITY ////\n mapping(bytes32 => Entity) entities; // objectId => Entity struct\n //// SIMPLE POLICY ////\n mapping(bytes32 => SimplePolicy) simplePolicies; // objectId => SimplePolicy struct\n //// External Tokens ////\n mapping(address => bool) externalTokenSupported;\n address[] supportedExternalTokens;\n //// TokenizedObject ////\n mapping(bytes32 => mapping(bytes32 => uint256)) tokenBalances; // tokenId => (ownerId => balance)\n mapping(bytes32 => uint256) tokenSupply; // tokenId => Total Token Supply\n //// Dividends ////\n uint8 maxDividendDenominations;\n mapping(bytes32 => bytes32[]) dividendDenominations; // object => tokenId of the dividend it allows\n mapping(bytes32 => mapping(bytes32 => uint8)) dividendDenominationIndex; // entity ID => (token ID => index of dividend denomination)\n mapping(bytes32 => mapping(uint8 => bytes32)) dividendDenominationAtIndex; // entity ID => (index of dividend denomination => token id)\n mapping(bytes32 => mapping(bytes32 => uint256)) totalDividends; // token ID => (denomination ID => total dividend)\n mapping(bytes32 => mapping(bytes32 => mapping(bytes32 => uint256))) withdrawnDividendPerOwner; // entity => (tokenId => (owner => total withdrawn dividend)) NOT per share!!! this is TOTAL\n //// ACL Configuration////\n mapping(bytes32 => mapping(bytes32 => bool)) groups; //role => (group => isRoleInGroup)\n mapping(bytes32 => bytes32) canAssign; //role => Group that can assign/unassign that role\n //// User Data ////\n mapping(bytes32 => mapping(bytes32 => bytes32)) roles; // userId => (contextId => role)\n //// MARKET ////\n uint256 lastOfferId;\n mapping(uint256 => MarketInfo) offers; // offer Id => MarketInfo struct\n mapping(bytes32 => mapping(bytes32 => uint256)) bestOfferId; // sell token => buy token => best offer Id\n mapping(bytes32 => mapping(bytes32 => uint256)) span; // sell token => buy token => span\n address naymsToken; // represents the address key for this NAYMS token in AppStorage\n bytes32 naymsTokenId; // represents the bytes32 key for this NAYMS token in AppStorage\n /// Trading Commissions (all in basis points) ///\n uint16 tradingCommissionTotalBP; // the total amount that is deducted for trading commissions (BP)\n // The total commission above is further divided as follows:\n uint16 tradingCommissionNaymsLtdBP;\n uint16 tradingCommissionNDFBP;\n uint16 tradingCommissionSTMBP;\n uint16 tradingCommissionMakerBP;\n // Premium Commissions\n uint16 premiumCommissionNaymsLtdBP;\n uint16 premiumCommissionNDFBP;\n uint16 premiumCommissionSTMBP;\n // A policy can pay out additional commissions on premiums to entities having a variety of roles on the policy\n mapping(bytes32 => mapping(bytes32 => uint256)) lockedBalances; // keep track of token balance that is locked, ownerId => tokenId => lockedAmount\n /// Simple two phase upgrade scheme\n mapping(bytes32 => uint256) upgradeScheduled; // id of the upgrade => the time that the upgrade is valid until.\n uint256 upgradeExpiration; // the period of time that an upgrade is valid until.\n uint256 sysAdmins; // counter for the number of sys admin accounts currently assigned\n}\n\nlibrary LibAppStorage {\n bytes32 internal constant NAYMS_DIAMOND_STORAGE_POSITION = keccak256(\"diamond.standard.nayms.storage\");\n\n function diamondStorage() internal pure returns (AppStorage storage ds) {\n bytes32 position = NAYMS_DIAMOND_STORAGE_POSITION;\n assembly {\n ds.slot := position\n }\n }\n}\n"
},
"src/diamonds/nayms/INayms.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n// solhint-disable no-empty-blocks\n\nimport { IDiamondCut } from \"../shared/interfaces/IDiamondCut.sol\";\nimport { IDiamondLoupe } from \"../shared/interfaces/IDiamondLoupe.sol\";\nimport { IERC165 } from \"../shared/interfaces/IERC165.sol\";\nimport { IERC173 } from \"../shared/interfaces/IERC173.sol\";\n\nimport { IACLFacet } from \"./interfaces/IACLFacet.sol\";\nimport { IUserFacet } from \"./interfaces/IUserFacet.sol\";\nimport { IAdminFacet } from \"./interfaces/IAdminFacet.sol\";\nimport { ISystemFacet } from \"./interfaces/ISystemFacet.sol\";\nimport { INaymsTokenFacet } from \"./interfaces/INaymsTokenFacet.sol\";\nimport { ITokenizedVaultFacet } from \"./interfaces/ITokenizedVaultFacet.sol\";\nimport { ITokenizedVaultIOFacet } from \"./interfaces/ITokenizedVaultIOFacet.sol\";\nimport { IMarketFacet } from \"./interfaces/IMarketFacet.sol\";\nimport { IEntityFacet } from \"./interfaces/IEntityFacet.sol\";\nimport { ISimplePolicyFacet } from \"./interfaces/ISimplePolicyFacet.sol\";\nimport { IGovernanceFacet } from \"./interfaces/IGovernanceFacet.sol\";\n\n/**\n * @title Nayms Diamond\n * @notice Everything is a part of one big diamond.\n * @dev Every facet should be cut into this diamond.\n */\ninterface INayms is\n IDiamondCut,\n IDiamondLoupe,\n IERC165,\n IERC173,\n IACLFacet,\n IAdminFacet,\n IUserFacet,\n ISystemFacet,\n INaymsTokenFacet,\n ITokenizedVaultFacet,\n ITokenizedVaultIOFacet,\n IMarketFacet,\n IEntityFacet,\n ISimplePolicyFacet,\n IGovernanceFacet\n{\n\n}\n"
},
"src/diamonds/nayms/Modifiers.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/// @notice modifiers\n\nimport { LibMeta } from \"../shared/libs/LibMeta.sol\";\nimport { LibAdmin } from \"./libs/LibAdmin.sol\";\nimport { LibConstants } from \"./libs/LibConstants.sol\";\nimport { LibHelpers } from \"./libs/LibHelpers.sol\";\nimport { LibObject } from \"./libs/LibObject.sol\";\nimport { LibACL } from \"./libs/LibACL.sol\";\n\n/**\n * @title Modifiers\n * @notice Function modifiers to control access\n * @dev Function modifiers to control access\n */\ncontract Modifiers {\n modifier assertSysAdmin() {\n require(\n LibACL._isInGroup(LibHelpers._getIdForAddress(LibMeta.msgSender()), LibAdmin._getSystemId(), LibHelpers._stringToBytes32(LibConstants.GROUP_SYSTEM_ADMINS)),\n \"not a system admin\"\n );\n _;\n }\n\n modifier assertSysMgr() {\n require(\n LibACL._isInGroup(LibHelpers._getIdForAddress(LibMeta.msgSender()), LibAdmin._getSystemId(), LibHelpers._stringToBytes32(LibConstants.GROUP_SYSTEM_MANAGERS)),\n \"not a system manager\"\n );\n _;\n }\n\n modifier assertEntityAdmin(bytes32 _context) {\n require(\n LibACL._isInGroup(LibHelpers._getIdForAddress(LibMeta.msgSender()), _context, LibHelpers._stringToBytes32(LibConstants.GROUP_ENTITY_ADMINS)),\n \"not the entity's admin\"\n );\n _;\n }\n\n modifier assertPolicyHandler(bytes32 _context) {\n require(\n LibACL._isInGroup(LibObject._getParentFromAddress(LibMeta.msgSender()), _context, LibHelpers._stringToBytes32(LibConstants.GROUP_POLICY_HANDLERS)),\n \"not a policy handler\"\n );\n _;\n }\n\n modifier assertIsInGroup(\n bytes32 _objectId,\n bytes32 _contextId,\n bytes32 _group\n ) {\n require(LibACL._isInGroup(_objectId, _contextId, _group), \"not in group\");\n _;\n }\n\n modifier assertERC20Wrapper(bytes32 _tokenId) {\n (, , , , address erc20Wrapper) = LibObject._getObjectMeta(_tokenId);\n require(msg.sender == erc20Wrapper, \"only wrapper calls allowed\");\n _;\n }\n}\n"
},
"src/diamonds/nayms/Nayms.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/******************************************************************************\\\n* Author: Nick Mudge <nick@perfectabstractions.com> (https://twitter.com/mudgen)\n* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535\n*\n* Implementation of a diamond.\n/******************************************************************************/\nimport { LibDiamond } from \"../shared/libs/LibDiamond.sol\";\nimport { DiamondCutFacet } from \"../shared/facets/DiamondCutFacet.sol\";\nimport { DiamondLoupeFacet } from \"../shared/facets/DiamondLoupeFacet.sol\";\nimport { NaymsOwnershipFacet } from \"src/diamonds/shared/facets/NaymsOwnershipFacet.sol\";\n\ncontract Nayms {\n constructor(address _contractOwner) payable {\n LibDiamond.setContractOwner(_contractOwner);\n LibDiamond.addDiamondFunctions(address(new DiamondCutFacet()), address(new DiamondLoupeFacet()), address(new NaymsOwnershipFacet()));\n }\n\n // Find facet for function that is called and execute the\n // function if a facet is found and return any value.\n // solhint-disable no-complex-fallback\n fallback() external payable {\n LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();\n\n // get facet from function selector\n address facet = address(bytes20(ds.facets[msg.sig]));\n // require(facet != address(0), \"Diamond: Function does not exist\"); - don't need to do this since we check for code below\n LibDiamond.enforceHasContractCode(facet, \"Diamond: Facet has no code\");\n // Execute external function from facet using delegatecall and return any value.\n assembly {\n // copy function selector and any arguments\n calldatacopy(0, 0, calldatasize())\n // execute function call using the facet\n let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0)\n // get any return value\n returndatacopy(0, 0, returndatasize())\n // return any return value or error back to the caller\n switch result\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n // solhint-disable no-empty-blocks\n receive() external payable {}\n}\n"
},
"src/diamonds/nayms/interfaces/CustomErrors.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/// @dev Passing in a missing role when trying to assign a role.\nerror RoleIsMissing();\n\n/// @dev Passing in a missing group when trying to assign a role to a group.\nerror AssignerGroupIsMissing();\n\n/// @dev Passing in a missing address when trying to add a token address to the supported external token list.\nerror CannotAddNullSupportedExternalToken();\n\n/// @dev Cannot add a ERC20 token to the supported external token list that has more than 18 decimal places.\nerror CannotSupportExternalTokenWithMoreThan18Decimals();\n\n/// @dev Passing in a missing address when trying to assign a new token address as the new discount token.\nerror CannotAddNullDiscountToken();\n\n/// @dev The entity does not exist when it should.\nerror EntityDoesNotExist(bytes32 objectId);\n/// @dev Cannot create an entity that already exists.\nerror CreatingEntityThatAlreadyExists(bytes32 entityId);\n\n/// @dev (non specific) the object is not enabled to be tokenized.\nerror ObjectCannotBeTokenized(bytes32 objectId);\n\n/// @dev Passing in a missing symbol when trying to enable an object to be tokenized.\nerror MissingSymbolWhenEnablingTokenization(bytes32 objectId);\n\n/// @dev Passing in 0 amount for deposits is not allowed.\nerror ExternalDepositAmountCannotBeZero();\n\n/// @dev Passing in 0 amount for withdraws is not allowed.\nerror ExternalWithdrawAmountCannotBeZero();\n\n/// @dev Cannot create a simple policy with policyId of 0\nerror PolicyIdCannotBeZero();\n\n/// @dev Policy commissions among commission receivers cannot sum to be greater than 10_000 basis points.\nerror PolicyCommissionsBasisPointsCannotBeGreaterThan10000(uint256 calculatedTotalBp);\n\n/// @dev When validating an entity, the utilized capacity cannot be greater than the max capacity.\nerror UtilizedCapacityGreaterThanMaxCapacity(uint256 utilizedCapacity, uint256 maxCapacity);\n\n/// @dev Policy stakeholder signature validation failed\nerror SimplePolicyStakeholderSignatureInvalid(bytes32 signingHash, bytes signature, bytes32 signerId, bytes32 signersParent, bytes32 entityId);\n\n/// @dev When creating a simple policy, the total claims paid should start at 0.\nerror SimplePolicyClaimsPaidShouldStartAtZero();\n\n/// @dev When creating a simple policy, the total premiums paid should start at 0.\nerror SimplePolicyPremiumsPaidShouldStartAtZero();\n\n/// @dev The cancel bool should not be set to true when creating a new simple policy.\nerror CancelCannotBeTrueWhenCreatingSimplePolicy();\n\n/// @dev (non specific) The policyId must exist.\nerror PolicyDoesNotExist(bytes32 policyId);\n\n/// @dev There is a duplicate address in the list of signers (the previous signer in the list is not < the next signer in the list).\nerror DuplicateSignerCreatingSimplePolicy(address previousSigner, address nextSigner);\n"
},
"src/diamonds/nayms/interfaces/FreeStructs.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nstruct MarketInfo {\n bytes32 creator; // entity ID\n bytes32 sellToken;\n uint256 sellAmount;\n uint256 sellAmountInitial;\n bytes32 buyToken;\n uint256 buyAmount;\n uint256 buyAmountInitial;\n uint256 feeSchedule;\n uint256 state;\n uint256 rankNext;\n uint256 rankPrev;\n}\n\nstruct TokenAmount {\n bytes32 token;\n uint256 amount;\n}\n\n/**\n * @param maxCapacity Maxmimum allowable amount of capacity that an entity is given. Denominated by assetId.\n * @param utilizedCapacity The utilized capacity of the entity. Denominated by assetId.\n */\nstruct Entity {\n bytes32 assetId;\n uint256 collateralRatio;\n uint256 maxCapacity;\n uint256 utilizedCapacity;\n bool simplePolicyEnabled;\n}\n\nstruct SimplePolicy {\n uint256 startDate;\n uint256 maturationDate;\n bytes32 asset;\n uint256 limit;\n bool fundsLocked;\n bool cancelled;\n uint256 claimsPaid;\n uint256 premiumsPaid;\n bytes32[] commissionReceivers;\n uint256[] commissionBasisPoints;\n}\n\nstruct SimplePolicyInfo {\n uint256 startDate;\n uint256 maturationDate;\n bytes32 asset;\n uint256 limit;\n bool fundsLocked;\n bool cancelled;\n uint256 claimsPaid;\n uint256 premiumsPaid;\n}\n\nstruct PolicyCommissionsBasisPoints {\n uint16 premiumCommissionNaymsLtdBP;\n uint16 premiumCommissionNDFBP;\n uint16 premiumCommissionSTMBP;\n}\n\nstruct Stakeholders {\n bytes32[] roles;\n bytes32[] entityIds;\n bytes[] signatures;\n}\n\n// Used in StakingFacet\nstruct LockedBalance {\n uint256 amount;\n uint256 endTime;\n}\n\nstruct StakingCheckpoint {\n int128 bias;\n int128 slope; // - dweight / dt\n uint256 ts; // timestamp\n uint256 blk; // block number\n}\n\nstruct FeeRatio {\n uint256 brokerShareRatio;\n uint256 naymsLtdShareRatio;\n uint256 ndfShareRatio;\n}\n\nstruct TradingCommissions {\n uint256 roughCommissionPaid;\n uint256 commissionNaymsLtd;\n uint256 commissionNDF;\n uint256 commissionSTM;\n uint256 commissionMaker;\n uint256 totalCommissions;\n}\n\nstruct TradingCommissionsBasisPoints {\n uint16 tradingCommissionTotalBP;\n uint16 tradingCommissionNaymsLtdBP;\n uint16 tradingCommissionNDFBP;\n uint16 tradingCommissionSTMBP;\n uint16 tradingCommissionMakerBP;\n}\n"
},
"src/diamonds/nayms/interfaces/IACLFacet.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/**\n * @title Access Control List\n * @notice Use it to authorize various actions on the contracts\n * @dev Use it to (un)assign or check role membership\n */\ninterface IACLFacet {\n /**\n * @notice Assign a `_roleId` to the object in given context\n * @dev Any object ID can be a context, system is a special context with highest priority\n * @param _objectId ID of an object that is being assigned a role\n * @param _contextId ID of the context in which a role is being assigned\n * @param _role Name of the role being assigned\n */\n function assignRole(\n bytes32 _objectId,\n bytes32 _contextId,\n string memory _role\n ) external;\n\n /**\n * @notice Unassign object from a role in given context\n * @dev Any object ID can be a context, system is a special context with highest priority\n * @param _objectId ID of an object that is being unassigned from a role\n * @param _contextId ID of the context in which a role membership is being revoked\n */\n function unassignRole(bytes32 _objectId, bytes32 _contextId) external;\n\n /**\n * @notice Checks if an object belongs to `_group` group in given context\n * @dev Assigning a role to the object makes it a member of a corresponding role group\n * @param _objectId ID of an object that is being checked for role group membership\n * @param _contextId Context in which membership should be checked\n * @param _group name of the role group\n * @return true if object with given ID is a member, false otherwise\n */\n function isInGroup(\n bytes32 _objectId,\n bytes32 _contextId,\n string memory _group\n ) external view returns (bool);\n\n /**\n * @notice Check whether a parent object belongs to the `_group` group in given context\n * @dev Objects can have a parent object, i.e. entity is a parent of a user\n * @param _objectId ID of an object whose parent is being checked for role group membership\n * @param _contextId Context in which the role group membership is being checked\n * @param _group name of the role group\n * @return true if object's parent is a member of this role group, false otherwise\n */\n function isParentInGroup(\n bytes32 _objectId,\n bytes32 _contextId,\n string memory _group\n ) external view returns (bool);\n\n /**\n * @notice Check whether a user can assign specific object to the `_role` role in given context\n * @dev Check permission to assign to a role\n * @param _assignerId The object ID of the user who is assigning a role to another object.\n * @param _objectId ID of an object that is being checked for assigning rights\n * @param _contextId ID of the context in which permission is checked\n * @param _role name of the role to check\n * @return true if user the right to assign, false otherwise\n */\n function canAssign(\n bytes32 _assignerId,\n bytes32 _objectId,\n bytes32 _contextId,\n string memory _role\n ) external view returns (bool);\n\n /**\n * @notice Get a user's (an objectId's) assigned role in a specific context\n * @param objectId ID of an object that is being checked for its assigned role in a specific context\n * @param contextId ID of the context in which the objectId's role is being checked\n * @return roleId objectId's role in the contextId\n */\n function getRoleInContext(bytes32 objectId, bytes32 contextId) external view returns (bytes32);\n\n /**\n * @notice Get whether role is in group.\n * @dev Get whether role is in group.\n * @param role the role.\n * @param group the group.\n * @return true if role is in group, false otherwise.\n */\n function isRoleInGroup(string memory role, string memory group) external view returns (bool);\n\n /**\n * @notice Get whether given group can assign given role.\n * @dev Get whether given group can assign given role.\n * @param role the role.\n * @param group the group.\n * @return true if role can be assigned by group, false otherwise.\n */\n function canGroupAssignRole(string memory role, string memory group) external view returns (bool);\n\n /**\n * @notice Update who can assign `_role` role\n * @dev Update who has permission to assign this role\n * @param _role name of the role\n * @param _assignerGroup Group who can assign members to this role\n */\n function updateRoleAssigner(string memory _role, string memory _assignerGroup) external;\n\n /**\n * @notice Update role group memebership for `_role` role and `_group` group\n * @dev Update role group memebership\n * @param _role name of the role\n * @param _group name of the group\n * @param _roleInGroup is member of\n */\n function updateRoleGroup(\n string memory _role,\n string memory _group,\n bool _roleInGroup\n ) external;\n}\n"
},
"src/diamonds/nayms/interfaces/IAdminFacet.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { PolicyCommissionsBasisPoints, TradingCommissionsBasisPoints } from \"./FreeStructs.sol\";\n\n/**\n * @title Administration\n * @notice Exposes methods that require administrative priviledges\n * @dev Use it to configure various core parameters\n */\ninterface IAdminFacet {\n /**\n * @notice Set `_newMax` as the max dividend denominations value.\n * @param _newMax new value to be used.\n */\n function setMaxDividendDenominations(uint8 _newMax) external;\n\n /**\n * @notice Update policy commission basis points configuration.\n * @param _policyCommissions policy commissions configuration to set\n */\n function setPolicyCommissionsBasisPoints(PolicyCommissionsBasisPoints calldata _policyCommissions) external;\n\n /**\n * @notice Update trading commission basis points configuration.\n * @param _tradingCommissions trading commissions configuration to set\n */\n function setTradingCommissionsBasisPoints(TradingCommissionsBasisPoints calldata _tradingCommissions) external;\n\n /**\n * @notice Get the max dividend denominations value\n * @return max dividend denominations\n */\n function getMaxDividendDenominations() external view returns (uint8);\n\n /**\n * @notice Is the specified tokenId an external ERC20 that is supported by the Nayms platform?\n * @param _tokenId token address converted to bytes32\n * @return whether token issupported or not\n */\n function isSupportedExternalToken(bytes32 _tokenId) external view returns (bool);\n\n /**\n * @notice Add another token to the supported tokens list\n * @param _tokenAddress address of the token to support\n */\n function addSupportedExternalToken(address _tokenAddress) external;\n\n /**\n * @notice Get the supported tokens list as an array\n * @return array containing address of all supported tokens\n */\n function getSupportedExternalTokens() external view returns (address[] memory);\n\n /**\n * @notice Gets the System context ID.\n * @return System Identifier\n */\n function getSystemId() external pure returns (bytes32);\n\n /**\n * @notice Check if object can be tokenized\n * @param _objectId ID of the object\n */\n function isObjectTokenizable(bytes32 _objectId) external returns (bool);\n}\n"
},
"src/diamonds/nayms/interfaces/IEntityFacet.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { SimplePolicy, Entity, Stakeholders } from \"./FreeStructs.sol\";\n\n/**\n * @title Entities\n * @notice Used to handle policies and token sales\n * @dev Mainly used for token sale and policies\n */\ninterface IEntityFacet {\n /**\n * @dev Returns the domain separator for the current chain.\n */\n function domainSeparatorV4() external view returns (bytes32);\n\n /**\n * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n * function returns the hash of the fully encoded EIP712 message for this domain.\n *\n * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n *\n * ```solidity\n * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n * keccak256(\"Mail(address to,string contents)\"),\n * mailTo,\n * keccak256(bytes(mailContents))\n * )));\n * address signer = ECDSA.recover(digest, signature);\n * ```\n */\n function hashTypedDataV4(bytes32 structHash) external view returns (bytes32);\n\n /**\n * @notice Create a Simple Policy\n * @param _policyId id of the policy\n * @param _entityId id of the entity\n * @param _stakeholders Struct of roles, entity IDs and signatures for the policy\n * @param _simplePolicy policy to create\n * @param _dataHash hash of the offchain data\n */\n function createSimplePolicy(\n bytes32 _policyId,\n bytes32 _entityId,\n Stakeholders calldata _stakeholders,\n SimplePolicy calldata _simplePolicy,\n bytes32 _dataHash\n ) external;\n\n /**\n * @notice Enable an entity to be tokenized\n * @param _entityId ID of the entity\n * @param _symbol The symbol assigned to the entity token\n * @param _name The name assigned to the entity token\n */\n function enableEntityTokenization(\n bytes32 _entityId,\n string memory _symbol,\n string memory _name\n ) external;\n\n /**\n * @notice Start token sale of `_amount` tokens for total price of `_totalPrice`\n * @dev Entity tokens are minted when the sale is started\n * @param _entityId ID of the entity\n * @param _amount amount of entity tokens to put on sale\n * @param _totalPrice total price of the tokens\n */\n function startTokenSale(\n bytes32 _entityId,\n uint256 _amount,\n uint256 _totalPrice\n ) external;\n\n /**\n * @notice Check if an entity token is wrapped as ERC20\n * @param _entityId ID of the entity\n */\n function isTokenWrapped(bytes32 _entityId) external view returns (bool);\n\n /**\n * @notice Update entity metadata\n * @param _entityId ID of the entity\n * @param _entity metadata of the entity\n */\n function updateEntity(bytes32 _entityId, Entity calldata _entity) external;\n\n /**\n * @notice Get the the data for entity with ID: `_entityId`\n * @dev Get the Entity data for a given entityId\n * @param _entityId ID of the entity\n * @return Entity struct with metadata of the entity\n */\n function getEntityInfo(bytes32 _entityId) external view returns (Entity memory);\n}\n"
},
"src/diamonds/nayms/interfaces/IGovernanceFacet.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\ninterface IGovernanceFacet {\n /**\n * @notice Approve the following upgrade hash: `id`\n * @dev The diamondCut() has been modified to check if the upgrade has been scheduled. This method needs to be called in order\n * for an upgrade to be executed.\n * @param id This is the keccak256(abi.encode(cut)), where cut is the array of FacetCut struct, IDiamondCut.FacetCut[].\n */\n function createUpgrade(bytes32 id) external;\n\n /**\n * @notice Update the diamond cut upgrade expiration period.\n * @dev When createUpgrade() is called, it allows a diamondCut() upgrade to be executed. This upgrade must be executed before the\n * upgrade expires. The upgrade expires based on when the upgrade was scheduled (when createUpgrade() was called) + AppStorage.upgradeExpiration.\n * @param duration The duration until the upgrade expires.\n */\n function updateUpgradeExpiration(uint256 duration) external;\n\n /**\n * @notice Cancel the following upgrade hash: `id`\n * @dev This will set the mapping AppStorage.upgradeScheduled back to 0.\n * @param id This is the keccak256(abi.encode(cut)), where cut is the array of FacetCut struct, IDiamondCut.FacetCut[].\n */\n function cancelUpgrade(bytes32 id) external;\n\n /**\n * @notice Get the expiry date for provided upgrade hash.\n * @dev This will get the value from AppStorage.upgradeScheduled mapping.\n * @param id This is the keccak256(abi.encode(cut)), where cut is the array of FacetCut struct, IDiamondCut.FacetCut[].\n */\n function getUpgrade(bytes32 id) external view returns (uint256 expiry);\n}\n"
},
"src/diamonds/nayms/interfaces/IMarketFacet.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { MarketInfo, TradingCommissions, TradingCommissionsBasisPoints } from \"./FreeStructs.sol\";\n\n/**\n * @title Matching Market (inspired by MakerOTC: https://github.com/nayms/maker-otc/blob/master/contracts/matching_market.sol)\n * @notice Trade entity tokens\n * @dev This should only be called through an entity, never directly by an EOA\n */\ninterface IMarketFacet {\n /**\n * @notice Execute a limit offer.\n *\n * @param _sellToken Token to sell.\n * @param _sellAmount Amount to sell.\n * @param _buyToken Token to buy.\n * @param _buyAmount Amount to buy.\n * @return offerId_ returns >0 if a limit offer was created on the market because the offer couldn't be totally fulfilled immediately. In this case the return value is the created offer's id.\n * @return buyTokenCommissionsPaid_ The amount of the buy token paid as commissions on this particular order.\n * @return sellTokenCommissionsPaid_ The amount of the sell token paid as commissions on this particular order.\n */\n function executeLimitOffer(\n bytes32 _sellToken,\n uint256 _sellAmount,\n bytes32 _buyToken,\n uint256 _buyAmount\n )\n external\n returns (\n uint256 offerId_,\n uint256 buyTokenCommissionsPaid_,\n uint256 sellTokenCommissionsPaid_\n );\n\n /**\n * @notice Cancel offer #`_offerId`. This will cancel the offer so that it's no longer active.\n *\n * @dev This function can be frontrun: In the scenario where a user wants to cancel an unfavorable market offer, an attacker can potentially monitor and identify\n * that the user has called this method, determine that filling this market offer is profitable, and as a result call executeLimitOffer with a higher gas price to have\n * their transaction filled before the user can have cancelOffer filled. The most ideal situation for the user is to not have placed the unfavorable market offer\n * in the first place since an attacker can always monitor our marketplace and potentially identify profitable market offers. Our UI will aide users in not placing\n * market offers that are obviously unfavorable to the user and/or seem like mistake orders. In the event that a user needs to cancel an offer, it is recommended to\n * use Flashbots in order to privately send your transaction so an attack cannot be triggered from monitoring the mempool for calls to cancelOffer. A user is recommended\n * to change their RPC endpoint to point to https://rpc.flashbots.net when calling cancelOffer. We will add additional documentation to aide our users in this process.\n * More information on using Flashbots: https://docs.flashbots.net/flashbots-protect/rpc/quick-start/\n *\n * @param _offerId offer ID\n */\n function cancelOffer(uint256 _offerId) external;\n\n /**\n * @notice Get current best offer for given token pair.\n *\n * @dev This means finding the highest sellToken-per-buyToken price, i.e. price = sellToken / buyToken\n *\n * @return offerId, or 0 if no current best is available.\n */\n function getBestOfferId(bytes32 _sellToken, bytes32 _buyToken) external view returns (uint256);\n\n /**\n * @dev Get last created offer.\n *\n * @return offer id.\n */\n function getLastOfferId() external view returns (uint256);\n\n /**\n * @dev Get the details of the offer #`_offerId`\n * @param _offerId ID of a particular offer\n * @return _offerState details of the offer\n */\n function getOffer(uint256 _offerId) external view returns (MarketInfo memory _offerState);\n\n /**\n * @dev Check if the offer #`_offerId` is active or not.\n * @param _offerId ID of a particular offer\n * @return active or not\n */\n function isActiveOffer(uint256 _offerId) external view returns (bool);\n\n /**\n * @dev Calculate the trading commissions based on a buy amount.\n * @param buyAmount The amount that the commissions payments are calculated from.\n * @return tc TradingCommissions struct with metadata regarding the trade commission payment amounts.\n */\n function calculateTradingCommissions(uint256 buyAmount) external view returns (TradingCommissions memory tc);\n\n /**\n * @notice Get the marketplace's trading commissions basis points.\n * @return bp - TradingCommissionsBasisPoints struct containing the individual basis points set for each marketplace commission receiver.\n */\n function getTradingCommissionsBasisPoints() external view returns (TradingCommissionsBasisPoints memory bp);\n}\n"
},
"src/diamonds/nayms/interfaces/INaymsTokenFacet.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/**\n * @title Nayms token facet.\n * @dev Use it to access and manipulate Nayms token.\n */\ninterface INaymsTokenFacet {\n /**\n * @dev Get total supply of token.\n * @return total supply.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Get token balance of given wallet.\n * @param addr wallet whose balance to get.\n * @return balance of wallet.\n */\n function balanceOf(address addr) external view returns (uint256);\n}\n"
},
"src/diamonds/nayms/interfaces/ISimplePolicyFacet.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { SimplePolicy, SimplePolicyInfo, PolicyCommissionsBasisPoints } from \"./FreeStructs.sol\";\n\n/**\n * @title Simple Policies\n * @notice Facet for working with Simple Policies\n * @dev Simple Policy facet\n */\ninterface ISimplePolicyFacet {\n /**\n * @dev Generate a simple policy hash for singing by the stakeholders\n * @param _startDate Date when policy becomes active\n * @param _maturationDate Date after which policy becomes matured\n * @param _asset ID of the underlying asset, used as collateral and to pay out claims\n * @param _limit Policy coverage limit\n * @param _offchainDataHash Hash of all the important policy data stored offchain\n * @return signingHash_ hash for signing\n */\n function getSigningHash(\n uint256 _startDate,\n uint256 _maturationDate,\n bytes32 _asset,\n uint256 _limit,\n bytes32 _offchainDataHash\n ) external view returns (bytes32 signingHash_);\n\n /**\n * @dev Pay a premium of `_amount` on simple policy\n * @param _policyId Id of the simple policy\n * @param _amount Amount of the premium\n */\n function paySimplePremium(bytes32 _policyId, uint256 _amount) external;\n\n /**\n * @dev Pay a claim of `_amount` for simple policy\n * @param _claimId Id of the simple policy claim\n * @param _policyId Id of the simple policy\n * @param _insuredId Id of the insured party\n * @param _amount Amount of the claim\n */\n function paySimpleClaim(\n bytes32 _claimId,\n bytes32 _policyId,\n bytes32 _insuredId,\n uint256 _amount\n ) external;\n\n /**\n * @dev Get simple policy info\n * @param _id Id of the simple policy\n * @return Simple policy metadata\n */\n function getSimplePolicyInfo(bytes32 _id) external view returns (SimplePolicyInfo memory);\n\n /**\n * @notice Get the policy premium commissions basis points.\n * @return PolicyCommissionsBasisPoints struct containing the individual basis points set for each policy commission receiver.\n */\n function getPremiumCommissionBasisPoints() external view returns (PolicyCommissionsBasisPoints memory);\n\n /**\n * @dev Check and update simple policy state\n * @param _id Id of the simple policy\n */\n function checkAndUpdateSimplePolicyState(bytes32 _id) external;\n\n /**\n * @dev Cancel a simple policy\n * @param _policyId Id of the simple policy\n */\n function cancelSimplePolicy(bytes32 _policyId) external;\n}\n"
},
"src/diamonds/nayms/interfaces/ISystemFacet.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { Entity } from \"./FreeStructs.sol\";\n\n/**\n * @title System\n * @notice Use it to perform system level operations\n * @dev Use it to perform system level operations\n */\ninterface ISystemFacet {\n /**\n * @notice Create an entity\n * @dev An entity can be created with a zero max capacity! This is in the event where an entity cannot write any policies.\n * @param _entityId Unique ID for the entity\n * @param _entityAdmin Unique ID of the entity administrator\n * @param _entityData remaining entity metadata\n * @param _dataHash hash of the offchain data\n */\n function createEntity(\n bytes32 _entityId,\n bytes32 _entityAdmin,\n Entity memory _entityData,\n bytes32 _dataHash\n ) external;\n\n /**\n * @notice Convert a string type to a bytes32 type\n * @param _strIn a string\n */\n function stringToBytes32(string memory _strIn) external pure returns (bytes32 result);\n\n /**\n * @dev Get whether given id is an object in the system.\n * @param _id object id.\n * @return true if it is an object, false otherwise\n */\n function isObject(bytes32 _id) external view returns (bool);\n\n /**\n * @dev Get meta of given object.\n * @param _id object id.\n * @return parent object parent\n * @return dataHash object data hash\n * @return tokenSymbol object token symbol\n * @return tokenName object token name\n * @return tokenWrapper object token ERC20 wrapper address\n */\n function getObjectMeta(bytes32 _id)\n external\n view\n returns (\n bytes32 parent,\n bytes32 dataHash,\n string memory tokenSymbol,\n string memory tokenName,\n address tokenWrapper\n );\n\n /**\n * @notice Wrap an object token as ERC20\n * @param _objectId ID of the tokenized object\n */\n function wrapToken(bytes32 _objectId) external;\n}\n"
},
"src/diamonds/nayms/interfaces/ITokenizedVaultFacet.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\ninterface ITokenizedVaultFacet {\n /**\n * @notice Gets balance of an account within platform\n * @dev Internal balance for given account\n * @param tokenId Internal ID of the asset\n * @return current balance\n */\n function internalBalanceOf(bytes32 accountId, bytes32 tokenId) external view returns (uint256);\n\n /**\n * @notice Current supply for the asset\n * @dev Total supply of platform asset\n * @param tokenId Internal ID of the asset\n * @return current balance\n */\n function internalTokenSupply(bytes32 tokenId) external view returns (uint256);\n\n /**\n * @notice Internal transfer of `amount` tokens\n * @dev Transfer tokens internally\n * @param to token receiver\n * @param tokenId Internal ID of the token\n */\n function internalTransferFromEntity(\n bytes32 to,\n bytes32 tokenId,\n uint256 amount\n ) external;\n\n /**\n * @notice Internal transfer of `amount` tokens `from` -> `to`\n * @dev Transfer tokens internally between two IDs\n * @param from token sender\n * @param to token receiver\n * @param tokenId Internal ID of the token\n */\n function wrapperInternalTransferFrom(\n bytes32 from,\n bytes32 to,\n bytes32 tokenId,\n uint256 amount\n ) external;\n\n function internalBurn(\n bytes32 from,\n bytes32 tokenId,\n uint256 amount\n ) external;\n\n /**\n * @notice Get withdrawable dividend amount\n * @dev Divident available for an entity to withdraw\n * @param _entityId Unique ID of the entity\n * @param _tokenId Unique ID of token\n * @param _dividendTokenId Unique ID of dividend token\n * @return _entityPayout accumulated dividend\n */\n function getWithdrawableDividend(\n bytes32 _entityId,\n bytes32 _tokenId,\n bytes32 _dividendTokenId\n ) external view returns (uint256 _entityPayout);\n\n /**\n * @notice Withdraw available dividend\n * @dev Transfer dividends to the entity\n * @param ownerId Unique ID of the dividend receiver\n * @param tokenId Unique ID of token\n * @param dividendTokenId Unique ID of dividend token\n */\n function withdrawDividend(\n bytes32 ownerId,\n bytes32 tokenId,\n bytes32 dividendTokenId\n ) external;\n\n /**\n * @notice Withdraws a user's available dividends.\n * @dev Dividends can be available in more than one dividend denomination. This method will withdraw all available dividends in the different dividend denominations.\n * @param ownerId Unique ID of the dividend receiver\n * @param tokenId Unique ID of token\n */\n function withdrawAllDividends(bytes32 ownerId, bytes32 tokenId) external;\n\n /**\n * @notice Pay `amount` of dividends\n * @dev Transfer dividends to the entity\n * @param guid Globally unique identifier of a dividend distribution.\n * @param amount the mamount of the dividend token to be distributed to NAYMS token holders.\n */\n function payDividendFromEntity(bytes32 guid, uint256 amount) external;\n\n /**\n * @notice Get the amount of tokens that an entity has for sale in the marketplace.\n * @param _entityId Unique platform ID of the entity.\n * @param _tokenId The ID assigned to an external token.\n * @return amount of tokens that the entity has for sale in the marketplace.\n */\n function getLockedBalance(bytes32 _entityId, bytes32 _tokenId) external view returns (uint256 amount);\n}\n"
},
"src/diamonds/nayms/interfaces/ITokenizedVaultIOFacet.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/**\n * @title Token Vault IO\n * @notice External interface to the Token Vault\n * @dev Used for external transfers. Adaptation of ERC-1155 that uses AppStorage and aligns with Nayms ACL implementation.\n * https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC1155\n */\ninterface ITokenizedVaultIOFacet {\n /**\n * @notice Deposit funds into msg.sender's Nayms platform entity\n * @dev Deposit from msg.sender to their associated entity\n * @param _externalTokenAddress Token address\n * @param _amount deposit amount\n */\n function externalDeposit(address _externalTokenAddress, uint256 _amount) external;\n\n /**\n * @notice Withdraw funds out of Nayms platform\n * @dev Withdraw from entity to an external account\n * @param _entityId Internal ID of the entity the user is withdrawing from\n * @param _receiverId Internal ID of the account receiving the funds\n * @param _externalTokenAddress Token address\n * @param _amount amount to withdraw\n */\n function externalWithdrawFromEntity(\n bytes32 _entityId,\n address _receiverId,\n address _externalTokenAddress,\n uint256 _amount\n ) external;\n}\n"
},
"src/diamonds/nayms/interfaces/IUserFacet.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/**\n * @title Users\n * @notice Manage user entity\n * @dev Use manage user entity\n */\ninterface IUserFacet {\n /**\n * @notice Get the platform ID of `addr` account\n * @dev Convert address to platform ID\n * @param addr Account address\n * @return userId Unique platform ID\n */\n function getUserIdFromAddress(address addr) external pure returns (bytes32 userId);\n\n /**\n * @notice Get the token address from ID of the external token\n * @dev Convert the bytes32 external token ID to its respective ERC20 contract address\n * @param _externalTokenId The ID assigned to an external token\n * @return tokenAddress Contract address\n */\n function getAddressFromExternalTokenId(bytes32 _externalTokenId) external pure returns (address tokenAddress);\n\n /**\n * @notice Set the entity for the user\n * @dev Assign the user an entity. The entity must exist in order to associate it with a user.\n * @param _userId Unique platform ID of the user account\n * @param _entityId Unique platform ID of the entity\n */\n function setEntity(bytes32 _userId, bytes32 _entityId) external;\n\n /**\n * @notice Get the entity for the user\n * @dev Gets the entity related to the user\n * @param _userId Unique platform ID of the user account\n * @return entityId Unique platform ID of the entity\n */\n function getEntity(bytes32 _userId) external view returns (bytes32 entityId);\n}\n"
},
"src/diamonds/nayms/libs/LibACL.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { AppStorage, LibAppStorage } from \"../AppStorage.sol\";\nimport { LibHelpers } from \"./LibHelpers.sol\";\nimport { LibAdmin } from \"./LibAdmin.sol\";\nimport { LibObject } from \"./LibObject.sol\";\nimport { LibConstants } from \"./LibConstants.sol\";\nimport { RoleIsMissing, AssignerGroupIsMissing } from \"src/diamonds/nayms/interfaces/CustomErrors.sol\";\n\nlibrary LibACL {\n /**\n * @dev Emitted when a role gets updated. Empty roleId is assigned upon role removal\n * @param objectId The user or object that was assigned the role.\n * @param contextId The context where the role was assigned to.\n * @param assignedRoleId The ID of the role which got (un)assigned. (empty ID when unassigned)\n * @param functionName The function performing the action\n */\n event RoleUpdate(bytes32 indexed objectId, bytes32 contextId, bytes32 assignedRoleId, string functionName);\n /**\n * @dev Emitted when a role group gets updated.\n * @param role The role name.\n * @param group the group name.\n * @param roleInGroup whether the role is now in the group or not.\n */\n event RoleGroupUpdated(string role, string group, bool roleInGroup);\n /**\n * @dev Emitted when a role assigners gets updated.\n * @param role The role name.\n * @param group the name of the group that can now assign this role.\n */\n event RoleCanAssignUpdated(string role, string group);\n\n function _assignRole(\n bytes32 _objectId,\n bytes32 _contextId,\n bytes32 _roleId\n ) internal {\n AppStorage storage s = LibAppStorage.diamondStorage();\n require(_objectId != \"\", \"invalid object ID\");\n require(_contextId != \"\", \"invalid context ID\");\n require(_roleId != \"\", \"invalid role ID\");\n\n s.roles[_objectId][_contextId] = _roleId;\n\n if (_contextId == LibAdmin._getSystemId() && _roleId == LibHelpers._stringToBytes32(LibConstants.ROLE_SYSTEM_ADMIN)) {\n unchecked {\n s.sysAdmins += 1;\n }\n }\n\n emit RoleUpdate(_objectId, _contextId, _roleId, \"_assignRole\");\n }\n\n function _unassignRole(bytes32 _objectId, bytes32 _contextId) internal {\n AppStorage storage s = LibAppStorage.diamondStorage();\n\n bytes32 roleId = s.roles[_objectId][_contextId];\n if (_contextId == LibAdmin._getSystemId() && roleId == LibHelpers._stringToBytes32(LibConstants.ROLE_SYSTEM_ADMIN)) {\n require(s.sysAdmins > 1, \"must have at least one system admin\");\n unchecked {\n s.sysAdmins -= 1;\n }\n }\n\n emit RoleUpdate(_objectId, _contextId, s.roles[_objectId][_contextId], \"_unassignRole\");\n delete s.roles[_objectId][_contextId];\n }\n\n function _isInGroup(\n bytes32 _objectId,\n bytes32 _contextId,\n bytes32 _groupId\n ) internal view returns (bool ret) {\n AppStorage storage s = LibAppStorage.diamondStorage();\n\n // Check for the role in the context\n bytes32 objectRoleInContext = s.roles[_objectId][_contextId];\n\n if (objectRoleInContext != 0 && s.groups[objectRoleInContext][_groupId]) {\n ret = true;\n } else {\n // A role in the context of the system covers all objects\n bytes32 objectRoleInSystem = s.roles[_objectId][LibAdmin._getSystemId()];\n\n if (objectRoleInSystem != 0 && s.groups[objectRoleInSystem][_groupId]) {\n ret = true;\n }\n }\n }\n\n function _isParentInGroup(\n bytes32 _objectId,\n bytes32 _contextId,\n bytes32 _groupId\n ) internal view returns (bool) {\n bytes32 parentId = LibObject._getParent(_objectId);\n return _isInGroup(parentId, _contextId, _groupId);\n }\n\n /**\n * @notice Checks if assigner has the authority to assign object to a role in given context\n * @dev Any object ID can be a context, system is a special context with highest priority\n * @param _assignerId ID of an account wanting to assign a role to an object\n * @param _objectId ID of an object that is being assigned a role\n * @param _contextId ID of the context in which a role is being assigned\n * @param _roleId ID of a role being assigned\n */\n function _canAssign(\n bytes32 _assignerId,\n bytes32 _objectId,\n bytes32 _contextId,\n bytes32 _roleId\n ) internal view returns (bool) {\n // we might impose additional restrictions on _objectId in the future\n require(_objectId != \"\", \"invalid object ID\");\n\n bool ret = false;\n AppStorage storage s = LibAppStorage.diamondStorage();\n\n bytes32 assignerGroup = s.canAssign[_roleId];\n\n // assigners group undefined\n if (assignerGroup == 0) {\n ret = false;\n }\n // Check for assigner's group membership in given context\n else if (_isInGroup(_assignerId, _contextId, assignerGroup)) {\n ret = true;\n }\n // Otherwise, check his parent's membership in system context\n // if account itself does not have the membership in given context, then having his parent\n // in the system context grants him the privilege needed\n else if (_isParentInGroup(_assignerId, LibAdmin._getSystemId(), assignerGroup)) {\n ret = true;\n }\n\n return ret;\n }\n\n function _getRoleInContext(bytes32 _objectId, bytes32 _contextId) internal view returns (bytes32) {\n AppStorage storage s = LibAppStorage.diamondStorage();\n return s.roles[_objectId][_contextId];\n }\n\n function _isRoleInGroup(string memory role, string memory group) internal view returns (bool) {\n AppStorage storage s = LibAppStorage.diamondStorage();\n return s.groups[LibHelpers._stringToBytes32(role)][LibHelpers._stringToBytes32(group)];\n }\n\n function _canGroupAssignRole(string memory role, string memory group) internal view returns (bool) {\n AppStorage storage s = LibAppStorage.diamondStorage();\n return s.canAssign[LibHelpers._stringToBytes32(role)] == LibHelpers._stringToBytes32(group);\n }\n\n function _updateRoleAssigner(string memory _role, string memory _assignerGroup) internal {\n if (bytes32(bytes(_role)) == \"\") {\n revert RoleIsMissing();\n }\n if (bytes32(bytes(_assignerGroup)) == \"\") {\n revert AssignerGroupIsMissing();\n }\n AppStorage storage s = LibAppStorage.diamondStorage();\n s.canAssign[LibHelpers._stringToBytes32(_role)] = LibHelpers._stringToBytes32(_assignerGroup);\n emit RoleCanAssignUpdated(_role, _assignerGroup);\n }\n\n function _updateRoleGroup(\n string memory _role,\n string memory _group,\n bool _roleInGroup\n ) internal {\n AppStorage storage s = LibAppStorage.diamondStorage();\n if (bytes32(bytes(_role)) == \"\") {\n revert RoleIsMissing();\n }\n if (bytes32(bytes(_group)) == \"\") {\n revert AssignerGroupIsMissing();\n }\n\n s.groups[LibHelpers._stringToBytes32(_role)][LibHelpers._stringToBytes32(_group)] = _roleInGroup;\n emit RoleGroupUpdated(_role, _group, _roleInGroup);\n }\n}\n"
},
"src/diamonds/nayms/libs/LibAdmin.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { AppStorage, LibAppStorage } from \"../AppStorage.sol\";\nimport { LibConstants } from \"./LibConstants.sol\";\nimport { LibHelpers } from \"./LibHelpers.sol\";\nimport { LibObject } from \"./LibObject.sol\";\nimport { LibERC20 } from \"src/erc20/LibERC20.sol\";\n\nimport { CannotAddNullDiscountToken, CannotAddNullSupportedExternalToken, CannotSupportExternalTokenWithMoreThan18Decimals } from \"src/diamonds/nayms/interfaces/CustomErrors.sol\";\n\nlibrary LibAdmin {\n event MaxDividendDenominationsUpdated(uint8 oldMax, uint8 newMax);\n event SupportedTokenAdded(address tokenAddress);\n\n function _getSystemId() internal pure returns (bytes32) {\n return LibHelpers._stringToBytes32(LibConstants.SYSTEM_IDENTIFIER);\n }\n\n function _getEmptyId() internal pure returns (bytes32) {\n return LibHelpers._stringToBytes32(LibConstants.EMPTY_IDENTIFIER);\n }\n\n function _updateMaxDividendDenominations(uint8 _newMaxDividendDenominations) internal {\n AppStorage storage s = LibAppStorage.diamondStorage();\n require(_newMaxDividendDenominations > s.maxDividendDenominations, \"_updateMaxDividendDenominations: cannot reduce\");\n uint8 old = s.maxDividendDenominations;\n s.maxDividendDenominations = _newMaxDividendDenominations;\n\n emit MaxDividendDenominationsUpdated(old, _newMaxDividendDenominations);\n }\n\n function _getMaxDividendDenominations() internal view returns (uint8) {\n AppStorage storage s = LibAppStorage.diamondStorage();\n return s.maxDividendDenominations;\n }\n\n function _isSupportedExternalTokenAddress(address _tokenId) internal view returns (bool) {\n AppStorage storage s = LibAppStorage.diamondStorage();\n return s.externalTokenSupported[_tokenId];\n }\n\n function _isSupportedExternalToken(bytes32 _tokenId) internal view returns (bool) {\n AppStorage storage s = LibAppStorage.diamondStorage();\n return s.externalTokenSupported[LibHelpers._getAddressFromId(_tokenId)];\n }\n\n function _addSupportedExternalToken(address _tokenAddress) internal {\n if (LibERC20.decimals(_tokenAddress) > 18) {\n revert CannotSupportExternalTokenWithMoreThan18Decimals();\n }\n AppStorage storage s = LibAppStorage.diamondStorage();\n\n bool alreadyAdded = s.externalTokenSupported[_tokenAddress];\n if (!alreadyAdded) {\n s.externalTokenSupported[_tokenAddress] = true;\n LibObject._createObject(LibHelpers._getIdForAddress(_tokenAddress));\n s.supportedExternalTokens.push(_tokenAddress);\n emit SupportedTokenAdded(_tokenAddress);\n }\n }\n\n function _getSupportedExternalTokens() internal view returns (address[] memory) {\n AppStorage storage s = LibAppStorage.diamondStorage();\n\n // Supported tokens cannot be removed because they may exist in the system!\n return s.supportedExternalTokens;\n }\n}\n"
},
"src/diamonds/nayms/libs/LibConstants.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/**\n * @dev Settings keys.\n */\nlibrary LibConstants {\n //Reserved IDs\n string internal constant EMPTY_IDENTIFIER = \"\";\n string internal constant SYSTEM_IDENTIFIER = \"System\";\n string internal constant NDF_IDENTIFIER = \"NDF\";\n string internal constant STM_IDENTIFIER = \"Staking Mechanism\";\n string internal constant SSF_IDENTIFIER = \"SSF\";\n string internal constant NAYM_TOKEN_IDENTIFIER = \"NAYM\"; //This is the ID in the system as well as the token ID\n string internal constant DIVIDEND_BANK_IDENTIFIER = \"Dividend Bank\"; //This will hold all the dividends\n string internal constant NAYMS_LTD_IDENTIFIER = \"Nayms Ltd\";\n\n //Roles\n string internal constant ROLE_SYSTEM_ADMIN = \"System Admin\";\n string internal constant ROLE_SYSTEM_MANAGER = \"System Manager\";\n string internal constant ROLE_ENTITY_ADMIN = \"Entity Admin\";\n string internal constant ROLE_ENTITY_MANAGER = \"Entity Manager\";\n string internal constant ROLE_BROKER = \"Broker\";\n string internal constant ROLE_INSURED_PARTY = \"Insured\";\n string internal constant ROLE_UNDERWRITER = \"Underwriter\";\n string internal constant ROLE_CAPITAL_PROVIDER = \"Capital Provider\";\n string internal constant ROLE_CLAIMS_ADMIN = \"Claims Admin\";\n string internal constant ROLE_TRADER = \"Trader\";\n string internal constant ROLE_SEGREGATED_ACCOUNT = \"Segregated Account\";\n string internal constant ROLE_SERVICE_PROVIDER = \"Service Provider\";\n\n //Groups\n string internal constant GROUP_SYSTEM_ADMINS = \"System Admins\";\n string internal constant GROUP_SYSTEM_MANAGERS = \"System Managers\";\n string internal constant GROUP_ENTITY_ADMINS = \"Entity Admins\";\n string internal constant GROUP_ENTITY_MANAGERS = \"Entity Managers\";\n string internal constant GROUP_APPROVED_USERS = \"Approved Users\";\n string internal constant GROUP_BROKERS = \"Brokers\";\n string internal constant GROUP_INSURED_PARTIES = \"Insured Parties\";\n string internal constant GROUP_UNDERWRITERS = \"Underwriters\";\n string internal constant GROUP_CAPITAL_PROVIDERS = \"Capital Providers\";\n string internal constant GROUP_CLAIMS_ADMINS = \"Claims Admins\";\n string internal constant GROUP_TRADERS = \"Traders\";\n string internal constant GROUP_SEGREGATED_ACCOUNTS = \"Segregated Accounts\";\n string internal constant GROUP_SERVICE_PROVIDERS = \"Service Providers\";\n string internal constant GROUP_POLICY_HANDLERS = \"Policy Handlers\";\n\n /*///////////////////////////////////////////////////////////////////////////\n Market Fee Schedules\n ///////////////////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Standard fee is charged.\n */\n uint256 internal constant FEE_SCHEDULE_STANDARD = 1;\n /**\n * @dev Platform-initiated trade, e.g. token sale or buyback.\n */\n uint256 internal constant FEE_SCHEDULE_PLATFORM_ACTION = 2;\n\n /*///////////////////////////////////////////////////////////////////////////\n MARKET OFFER STATES\n ///////////////////////////////////////////////////////////////////////////*/\n\n uint256 internal constant OFFER_STATE_ACTIVE = 1;\n uint256 internal constant OFFER_STATE_CANCELLED = 2;\n uint256 internal constant OFFER_STATE_FULFILLED = 3;\n\n uint256 internal constant DUST = 1;\n uint256 internal constant BP_FACTOR = 10000;\n\n /*///////////////////////////////////////////////////////////////////////////\n SIMPLE POLICY STATES\n ///////////////////////////////////////////////////////////////////////////*/\n\n uint256 internal constant SIMPLE_POLICY_STATE_CREATED = 0;\n uint256 internal constant SIMPLE_POLICY_STATE_APPROVED = 1;\n uint256 internal constant SIMPLE_POLICY_STATE_ACTIVE = 2;\n uint256 internal constant SIMPLE_POLICY_STATE_MATURED = 3;\n uint256 internal constant SIMPLE_POLICY_STATE_CANCELLED = 4;\n uint256 internal constant STAKING_WEEK = 7 days;\n uint256 internal constant STAKING_MINTIME = 60 days; // 60 days min lock\n uint256 internal constant STAKING_MAXTIME = 4 * 365 days; // 4 years max lock\n uint256 internal constant SCALE = 1e18; //10 ^ 18\n\n /// _depositFor Types for events\n int128 internal constant STAKING_DEPOSIT_FOR_TYPE = 0;\n int128 internal constant STAKING_CREATE_LOCK_TYPE = 1;\n int128 internal constant STAKING_INCREASE_LOCK_AMOUNT = 2;\n int128 internal constant STAKING_INCREASE_UNLOCK_TIME = 3;\n\n string internal constant VE_NAYM_NAME = \"veNAYM\";\n string internal constant VE_NAYM_SYMBOL = \"veNAYM\";\n uint8 internal constant VE_NAYM_DECIMALS = 18;\n uint8 internal constant INTERNAL_TOKEN_DECIMALS = 18;\n address internal constant DAI_CONSTANT = 0x6B175474E89094C44Da98b954EedeAC495271d0F;\n}\n"
},
"src/diamonds/nayms/libs/LibHelpers.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/// @notice Pure functions\nlibrary LibHelpers {\n function _getIdForObjectAtIndex(uint256 _index) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(_index));\n }\n\n function _getIdForAddress(address _addr) internal pure returns (bytes32) {\n return bytes32(bytes20(_addr));\n }\n\n function _getSenderId() internal view returns (bytes32) {\n return _getIdForAddress(msg.sender);\n }\n\n function _getAddressFromId(bytes32 _id) internal pure returns (address) {\n return address(bytes20(_id));\n }\n\n // Conversion Utilities\n\n function _addressToBytes32(address addr) internal pure returns (bytes32) {\n return _bytesToBytes32(abi.encode(addr));\n }\n\n function _stringToBytes32(string memory strIn) internal pure returns (bytes32) {\n return _bytesToBytes32(bytes(strIn));\n }\n\n function _bytes32ToString(bytes32 bytesIn) internal pure returns (string memory) {\n return string(_bytes32ToBytes(bytesIn));\n }\n\n function _bytesToBytes32(bytes memory source) internal pure returns (bytes32 result) {\n if (source.length == 0) {\n return 0x0;\n }\n assembly {\n result := mload(add(source, 32))\n }\n }\n\n function _bytes32ToBytes(bytes32 input) internal pure returns (bytes memory) {\n bytes memory b = new bytes(32);\n assembly {\n mstore(add(b, 32), input)\n }\n return b;\n }\n}\n"
},
"src/diamonds/nayms/libs/LibObject.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { AppStorage, LibAppStorage } from \"../AppStorage.sol\";\nimport { LibHelpers } from \"./LibHelpers.sol\";\nimport { LibAdmin } from \"./LibAdmin.sol\";\nimport { EntityDoesNotExist, MissingSymbolWhenEnablingTokenization } from \"src/diamonds/nayms/interfaces/CustomErrors.sol\";\n\nimport { ERC20Wrapper } from \"../../../erc20/ERC20Wrapper.sol\";\n\n/// @notice Contains internal methods for core Nayms system functionality\nlibrary LibObject {\n event TokenWrapped(bytes32 indexed entityId, address tokenWrapper);\n\n function _createObject(\n bytes32 _objectId,\n bytes32 _parentId,\n bytes32 _dataHash\n ) internal {\n AppStorage storage s = LibAppStorage.diamondStorage();\n\n // Check if the objectId is already being used by another object\n require(!s.existingObjects[_objectId], \"objectId is already being used by another object\");\n\n s.existingObjects[_objectId] = true;\n s.objectParent[_objectId] = _parentId;\n s.objectDataHashes[_objectId] = _dataHash;\n }\n\n function _createObject(bytes32 _objectId, bytes32 _dataHash) internal {\n AppStorage storage s = LibAppStorage.diamondStorage();\n\n require(!s.existingObjects[_objectId], \"objectId is already being used by another object\");\n\n s.existingObjects[_objectId] = true;\n s.objectDataHashes[_objectId] = _dataHash;\n }\n\n function _createObject(bytes32 _objectId) internal {\n AppStorage storage s = LibAppStorage.diamondStorage();\n\n require(!s.existingObjects[_objectId], \"objectId is already being used by another object\");\n\n s.existingObjects[_objectId] = true;\n }\n\n function _setDataHash(bytes32 _objectId, bytes32 _dataHash) internal {\n AppStorage storage s = LibAppStorage.diamondStorage();\n\n require(s.existingObjects[_objectId], \"setDataHash: object doesn't exist\");\n s.objectDataHashes[_objectId] = _dataHash;\n }\n\n function _getDataHash(bytes32 _objectId) internal view returns (bytes32 objectDataHash) {\n AppStorage storage s = LibAppStorage.diamondStorage();\n return s.objectDataHashes[_objectId];\n }\n\n function _getParent(bytes32 _objectId) internal view returns (bytes32) {\n AppStorage storage s = LibAppStorage.diamondStorage();\n return s.objectParent[_objectId];\n }\n\n function _getParentFromAddress(address addr) internal view returns (bytes32) {\n AppStorage storage s = LibAppStorage.diamondStorage();\n bytes32 objectId = LibHelpers._getIdForAddress(addr);\n return s.objectParent[objectId];\n }\n\n function _setParent(bytes32 _objectId, bytes32 _parentId) internal {\n AppStorage storage s = LibAppStorage.diamondStorage();\n s.objectParent[_objectId] = _parentId;\n }\n\n function _isObjectTokenizable(bytes32 _objectId) internal view returns (bool) {\n AppStorage storage s = LibAppStorage.diamondStorage();\n return (bytes(s.objectTokenSymbol[_objectId]).length != 0);\n }\n\n function _enableObjectTokenization(\n bytes32 _objectId,\n string memory _symbol,\n string memory _name\n ) internal {\n AppStorage storage s = LibAppStorage.diamondStorage();\n if (bytes(_symbol).length == 0) {\n revert MissingSymbolWhenEnablingTokenization(_objectId);\n }\n\n // Ensure the entity exists before tokenizing the entity, otherwise revert.\n if (!s.existingEntities[_objectId]) {\n revert EntityDoesNotExist(_objectId);\n }\n\n require(!_isObjectTokenizable(_objectId), \"object already tokenized\");\n require(bytes(_symbol).length < 16, \"symbol must be less than 16 characters\");\n\n s.objectTokenSymbol[_objectId] = _symbol;\n s.objectTokenName[_objectId] = _name;\n }\n\n function _isObjectTokenWrapped(bytes32 _objectId) internal view returns (bool) {\n AppStorage storage s = LibAppStorage.diamondStorage();\n return (s.objectTokenWrapper[_objectId] != address(0));\n }\n\n function _wrapToken(bytes32 _entityId) internal {\n AppStorage storage s = LibAppStorage.diamondStorage();\n\n require(_isObjectTokenizable(_entityId), \"must be tokenizable\");\n require(!_isObjectTokenWrapped(_entityId), \"must not be wrapped already\");\n\n ERC20Wrapper tokenWrapper = new ERC20Wrapper(_entityId);\n address wrapperAddress = address(tokenWrapper);\n\n s.objectTokenWrapper[_entityId] = wrapperAddress;\n\n emit TokenWrapped(_entityId, wrapperAddress);\n }\n\n function _isObject(bytes32 _id) internal view returns (bool) {\n AppStorage storage s = LibAppStorage.diamondStorage();\n return s.existingObjects[_id];\n }\n\n function _getObjectMeta(bytes32 _id)\n internal\n view\n returns (\n bytes32 parent,\n bytes32 dataHash,\n string memory tokenSymbol,\n string memory tokenName,\n address tokenWrapper\n )\n {\n AppStorage storage s = LibAppStorage.diamondStorage();\n parent = s.objectParent[_id];\n dataHash = s.objectDataHashes[_id];\n tokenSymbol = s.objectTokenSymbol[_id];\n tokenName = s.objectTokenName[_id];\n tokenWrapper = s.objectTokenWrapper[_id];\n }\n}\n"
},
"src/diamonds/shared/facets/DiamondCutFacet.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/******************************************************************************\\\n* Author: Nick Mudge <nick@perfectabstractions.com> (https://twitter.com/mudgen)\n* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535\n/******************************************************************************/\n\nimport { IDiamondCut } from \"../interfaces/IDiamondCut.sol\";\nimport { LibDiamond } from \"../libs/LibDiamond.sol\";\n\ncontract DiamondCutFacet is IDiamondCut {\n /// @notice Add/replace/remove any number of functions and optionally execute\n /// a function with delegatecall\n /// @param _diamondCut Contains the facet addresses and function selectors\n /// @param _init The address of the contract or facet to execute _calldata\n /// @param _calldata A function call, including function selector and arguments\n /// _calldata is executed with delegatecall on _init\n function diamondCut(\n FacetCut[] calldata _diamondCut,\n address _init,\n bytes calldata _calldata\n ) external override {\n LibDiamond.enforceIsContractOwner();\n LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();\n uint256 originalSelectorCount = ds.selectorCount;\n uint256 selectorCount = originalSelectorCount;\n bytes32 selectorSlot;\n // Check if last selector slot is not full\n // \"selectorCount & 7\" is a gas efficient modulo by eight \"selectorCount % 8\"\n if (selectorCount & 7 > 0) {\n // get last selectorSlot\n // \"selectorCount >> 3\" is a gas efficient division by 8 \"selectorCount / 8\"\n selectorSlot = ds.selectorSlots[selectorCount >> 3];\n }\n // loop through diamond cut\n for (uint256 facetIndex = 0; facetIndex < _diamondCut.length; facetIndex++) {\n (selectorCount, selectorSlot) = LibDiamond.addReplaceRemoveFacetSelectors(\n selectorCount,\n selectorSlot,\n _diamondCut[facetIndex].facetAddress,\n _diamondCut[facetIndex].action,\n _diamondCut[facetIndex].functionSelectors\n );\n }\n if (selectorCount != originalSelectorCount) {\n ds.selectorCount = uint16(selectorCount);\n }\n // If last selector slot is not full\n // \"selectorCount & 7\" is a gas efficient modulo by eight \"selectorCount % 8\"\n if (selectorCount & 7 > 0) {\n // \"selectorCount >> 3\" is a gas efficient division by 8 \"selectorCount / 8\"\n ds.selectorSlots[selectorCount >> 3] = selectorSlot;\n }\n emit DiamondCut(_diamondCut, _init, _calldata);\n LibDiamond.initializeDiamondCut(_init, _calldata);\n }\n}\n"
},
"src/diamonds/shared/facets/DiamondLoupeFacet.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/******************************************************************************\\\n* Author: Nick Mudge <nick@perfectabstractions.com> (https://twitter.com/mudgen)\n* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535\n/******************************************************************************/\n\nimport { LibDiamond } from \"../libs/LibDiamond.sol\";\nimport { IDiamondLoupe } from \"../interfaces/IDiamondLoupe.sol\";\nimport { IERC165 } from \"../interfaces/IERC165.sol\";\n\ncontract DiamondLoupeFacet is IDiamondLoupe, IERC165 {\n // Diamond Loupe Functions\n ////////////////////////////////////////////////////////////////////\n /// These functions are expected to be called frequently by tools.\n //\n // struct Facet {\n // address facetAddress;\n // bytes4[] functionSelectors;\n // }\n /// @notice Gets all facets and their selectors.\n /// @return facets_ Facet\n function facets() external view override returns (Facet[] memory facets_) {\n LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();\n facets_ = new Facet[](ds.selectorCount);\n uint8[] memory numFacetSelectors = new uint8[](ds.selectorCount);\n uint256 numFacets;\n uint256 selectorIndex;\n // loop through function selectors\n for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {\n bytes32 slot = ds.selectorSlots[slotIndex];\n for (uint256 selectorSlotIndex; selectorSlotIndex < 8; selectorSlotIndex++) {\n selectorIndex++;\n if (selectorIndex > ds.selectorCount) {\n break;\n }\n bytes4 selector = bytes4(slot << (selectorSlotIndex << 5));\n address facetAddress_ = address(bytes20(ds.facets[selector]));\n bool continueLoop;\n for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {\n if (facets_[facetIndex].facetAddress == facetAddress_) {\n facets_[facetIndex].functionSelectors[numFacetSelectors[facetIndex]] = selector;\n // probably will never have more than 256 functions from one facet contract\n require(numFacetSelectors[facetIndex] < 255);\n numFacetSelectors[facetIndex]++;\n continueLoop = true;\n break;\n }\n }\n if (continueLoop) {\n continue;\n }\n facets_[numFacets].facetAddress = facetAddress_;\n facets_[numFacets].functionSelectors = new bytes4[](ds.selectorCount);\n facets_[numFacets].functionSelectors[0] = selector;\n numFacetSelectors[numFacets] = 1;\n numFacets++;\n }\n }\n for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {\n uint256 numSelectors = numFacetSelectors[facetIndex];\n bytes4[] memory selectors = facets_[facetIndex].functionSelectors;\n // setting the number of selectors\n assembly {\n mstore(selectors, numSelectors)\n }\n }\n // setting the number of facets\n assembly {\n mstore(facets_, numFacets)\n }\n }\n\n /// @notice Gets all the function selectors supported by a specific facet.\n /// @param _facet The facet address.\n /// @return facetFunctionSelectors_ The selectors associated with a facet address.\n function facetFunctionSelectors(address _facet) external view override returns (bytes4[] memory facetFunctionSelectors_) {\n LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();\n uint256 numSelectors;\n facetFunctionSelectors_ = new bytes4[](ds.selectorCount);\n uint256 selectorIndex;\n // loop through function selectors\n for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {\n bytes32 slot = ds.selectorSlots[slotIndex];\n for (uint256 selectorSlotIndex; selectorSlotIndex < 8; selectorSlotIndex++) {\n selectorIndex++;\n if (selectorIndex > ds.selectorCount) {\n break;\n }\n bytes4 selector = bytes4(slot << (selectorSlotIndex << 5));\n address facet = address(bytes20(ds.facets[selector]));\n if (_facet == facet) {\n facetFunctionSelectors_[numSelectors] = selector;\n numSelectors++;\n }\n }\n }\n // Set the number of selectors in the array\n assembly {\n mstore(facetFunctionSelectors_, numSelectors)\n }\n }\n\n /// @notice Get all the facet addresses used by a diamond.\n /// @return facetAddresses_\n function facetAddresses() external view override returns (address[] memory facetAddresses_) {\n LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();\n facetAddresses_ = new address[](ds.selectorCount);\n uint256 numFacets;\n uint256 selectorIndex;\n // loop through function selectors\n for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {\n bytes32 slot = ds.selectorSlots[slotIndex];\n for (uint256 selectorSlotIndex; selectorSlotIndex < 8; selectorSlotIndex++) {\n selectorIndex++;\n if (selectorIndex > ds.selectorCount) {\n break;\n }\n bytes4 selector = bytes4(slot << (selectorSlotIndex << 5));\n address facetAddress_ = address(bytes20(ds.facets[selector]));\n bool continueLoop;\n for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {\n if (facetAddress_ == facetAddresses_[facetIndex]) {\n continueLoop = true;\n break;\n }\n }\n if (continueLoop) {\n continue;\n }\n facetAddresses_[numFacets] = facetAddress_;\n numFacets++;\n }\n }\n // Set the number of facet addresses in the array\n assembly {\n mstore(facetAddresses_, numFacets)\n }\n }\n\n /// @notice Gets the facet that supports the given selector.\n /// @dev If facet is not found return address(0).\n /// @param _functionSelector The function selector.\n /// @return facetAddress_ The facet address.\n function facetAddress(bytes4 _functionSelector) external view override returns (address facetAddress_) {\n LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();\n facetAddress_ = address(bytes20(ds.facets[_functionSelector]));\n }\n\n // This implements ERC-165.\n function supportsInterface(bytes4 _interfaceId) external view override returns (bool) {\n LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();\n return ds.supportedInterfaces[_interfaceId];\n }\n}\n"
},
"src/diamonds/shared/facets/NaymsOwnershipFacet.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { LibACL } from \"src/diamonds/nayms/libs/LibACL.sol\";\nimport { LibHelpers } from \"src/diamonds/nayms/libs/LibHelpers.sol\";\nimport { LibConstants } from \"src/diamonds/nayms/libs/LibConstants.sol\";\nimport { LibDiamond } from \"src/diamonds/shared/libs/LibDiamond.sol\";\nimport { OwnershipFacet } from \"src/diamonds/shared/facets/OwnershipFacet.sol\";\nimport { Modifiers } from \"src/diamonds/nayms/Modifiers.sol\";\n\ncontract NaymsOwnershipFacet is OwnershipFacet, Modifiers {\n function transferOwnership(address _newOwner) public override assertSysAdmin {\n bytes32 systemID = LibHelpers._stringToBytes32(LibConstants.SYSTEM_IDENTIFIER);\n bytes32 newAcc1Id = LibHelpers._getIdForAddress(_newOwner);\n\n require(!LibACL._isInGroup(newAcc1Id, systemID, LibHelpers._stringToBytes32(LibConstants.GROUP_SYSTEM_ADMINS)), \"NEW owner MUST NOT be sys admin\");\n require(!LibACL._isInGroup(newAcc1Id, systemID, LibHelpers._stringToBytes32(LibConstants.GROUP_SYSTEM_MANAGERS)), \"NEW owner MUST NOT be sys manager\");\n\n super.transferOwnership(_newOwner);\n }\n}\n"
},
"src/diamonds/shared/facets/OwnershipFacet.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { LibDiamond } from \"../libs/LibDiamond.sol\";\nimport { IERC173 } from \"../interfaces/IERC173.sol\";\n\ncontract OwnershipFacet is IERC173 {\n function transferOwnership(address _newOwner) public virtual override {\n LibDiamond.setContractOwner(_newOwner);\n }\n\n function owner() external view override returns (address owner_) {\n owner_ = LibDiamond.contractOwner();\n }\n}\n"
},
"src/diamonds/shared/interfaces/IDiamondCut.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/******************************************************************************\\\n* Author: Nick Mudge <nick@perfectabstractions.com> (https://twitter.com/mudgen)\n* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535\n/******************************************************************************/\n\ninterface IDiamondCut {\n enum FacetCutAction {\n Add,\n Replace,\n Remove\n }\n // Add=0, Replace=1, Remove=2\n\n struct FacetCut {\n address facetAddress;\n FacetCutAction action;\n bytes4[] functionSelectors;\n }\n\n /// @notice Add/replace/remove any number of functions and optionally execute\n /// a function with delegatecall\n /// @param _diamondCut Contains the facet addresses and function selectors\n /// @param _init The address of the contract or facet to execute _calldata\n /// @param _calldata A function call, including function selector and arguments\n /// _calldata is executed with delegatecall on _init\n function diamondCut(\n FacetCut[] calldata _diamondCut,\n address _init,\n bytes calldata _calldata\n ) external;\n\n event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);\n}\n"
},
"src/diamonds/shared/interfaces/IDiamondLoupe.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/******************************************************************************\\\n* Author: Nick Mudge <nick@perfectabstractions.com> (https://twitter.com/mudgen)\n* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535\n/******************************************************************************/\n\n// A loupe is a small magnifying glass used to look at diamonds.\n// These functions look at diamonds\ninterface IDiamondLoupe {\n /// These functions are expected to be called frequently\n /// by tools.\n\n struct Facet {\n address facetAddress;\n bytes4[] functionSelectors;\n }\n\n /// @notice Gets all facet addresses and their four byte function selectors.\n /// @return facets_ Facet\n function facets() external view returns (Facet[] memory facets_);\n\n /// @notice Gets all the function selectors supported by a specific facet.\n /// @param _facet The facet address.\n /// @return facetFunctionSelectors_\n function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_);\n\n /// @notice Get all the facet addresses used by a diamond.\n /// @return facetAddresses_\n function facetAddresses() external view returns (address[] memory facetAddresses_);\n\n /// @notice Gets the facet that supports the given selector.\n /// @dev If facet is not found return address(0).\n /// @param _functionSelector The function selector.\n /// @return facetAddress_ The facet address.\n function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_);\n}\n"
},
"src/diamonds/shared/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\ninterface IERC165 {\n /// @notice Query if a contract implements an interface\n /// @param interfaceId The interface identifier, as specified in ERC-165\n /// @dev Interface identification is specified in ERC-165. This function\n /// uses less than 30,000 gas.\n /// @return `true` if the contract implements `interfaceID` and\n /// `interfaceID` is not 0xffffffff, `false` otherwise\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"src/diamonds/shared/interfaces/IERC173.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/// @title ERC-173 Contract Ownership Standard\n/// Note: the ERC-165 identifier for this interface is 0x7f5828d0 is ERC165\ninterface IERC173 {\n /// @dev This emits when ownership of a contract changes.\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /// @notice Get the address of the owner\n /// @return owner_ The address of the owner.\n function owner() external view returns (address owner_);\n\n /// @notice Set the address of the new owner of the contract\n /// @dev Set _newOwner to address(0) to renounce any ownership.\n /// @param _newOwner The address of the new owner of the contract\n function transferOwnership(address _newOwner) external;\n}\n"
},
"src/diamonds/shared/libs/LibDiamond.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/******************************************************************************\\\n* Author: Nick Mudge <nick@perfectabstractions.com> (https://twitter.com/mudgen)\n* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535\n/******************************************************************************/\nimport { IDiamondCut } from \"../interfaces/IDiamondCut.sol\";\nimport { IDiamondLoupe } from \"../interfaces/IDiamondLoupe.sol\";\nimport { IERC165 } from \"../interfaces/IERC165.sol\";\nimport { IERC173 } from \"../interfaces/IERC173.sol\";\n\nlibrary LibDiamond {\n bytes32 internal constant DIAMOND_STORAGE_POSITION = keccak256(\"diamond.standard.diamond.storage\");\n\n struct DiamondStorage {\n // maps function selectors to the facets that execute the functions.\n // and maps the selectors to their position in the selectorSlots array.\n // func selector => address facet, selector position\n mapping(bytes4 => bytes32) facets;\n // array of slots of function selectors.\n // each slot holds 8 function selectors.\n mapping(uint256 => bytes32) selectorSlots;\n // The number of function selectors in selectorSlots\n uint16 selectorCount;\n // Used to query if a contract implements an interface.\n // Used to implement ERC-165.\n mapping(bytes4 => bool) supportedInterfaces;\n // owner of the contract\n address contractOwner;\n }\n\n function diamondStorage() internal pure returns (DiamondStorage storage ds) {\n bytes32 position = DIAMOND_STORAGE_POSITION;\n assembly {\n ds.slot := position\n }\n }\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n function setContractOwner(address _newOwner) internal {\n DiamondStorage storage ds = diamondStorage();\n address previousOwner = ds.contractOwner;\n ds.contractOwner = _newOwner;\n emit OwnershipTransferred(previousOwner, _newOwner);\n }\n\n function contractOwner() internal view returns (address contractOwner_) {\n contractOwner_ = diamondStorage().contractOwner;\n }\n\n function enforceIsContractOwner() internal view {\n require(msg.sender == diamondStorage().contractOwner, \"LibDiamond: Must be contract owner\");\n }\n\n function addDiamondFunctions(\n address _diamondCutFacet,\n address _diamondLoupeFacet,\n address _ownershipFacet\n ) internal {\n IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](3);\n bytes4[] memory functionSelectors = new bytes4[](1);\n functionSelectors[0] = IDiamondCut.diamondCut.selector;\n cut[0] = IDiamondCut.FacetCut({ facetAddress: _diamondCutFacet, action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors });\n functionSelectors = new bytes4[](5);\n functionSelectors[0] = IDiamondLoupe.facets.selector;\n functionSelectors[1] = IDiamondLoupe.facetFunctionSelectors.selector;\n functionSelectors[2] = IDiamondLoupe.facetAddresses.selector;\n functionSelectors[3] = IDiamondLoupe.facetAddress.selector;\n functionSelectors[4] = IERC165.supportsInterface.selector;\n cut[1] = IDiamondCut.FacetCut({ facetAddress: _diamondLoupeFacet, action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors });\n functionSelectors = new bytes4[](2);\n functionSelectors[0] = IERC173.transferOwnership.selector;\n functionSelectors[1] = IERC173.owner.selector;\n cut[2] = IDiamondCut.FacetCut({ facetAddress: _ownershipFacet, action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors });\n diamondCut(cut, address(0), \"\");\n }\n\n event DiamondCut(IDiamondCut.FacetCut[] diamondCut, address init, bytes _calldata);\n\n bytes32 internal constant CLEAR_ADDRESS_MASK = bytes32(uint256(0xffffffffffffffffffffffff));\n bytes32 internal constant CLEAR_SELECTOR_MASK = bytes32(uint256(0xffffffff << 224));\n\n // Internal function version of diamondCut\n // This code is almost the same as the external diamondCut,\n // except it is using 'Facet[] memory _diamondCut' instead of\n // 'Facet[] calldata _diamondCut'.\n // The code is duplicated to prevent copying calldata to memory which\n // causes an error for a two dimensional array.\n function diamondCut(\n IDiamondCut.FacetCut[] memory _diamondCut,\n address _init,\n bytes memory _calldata\n ) internal {\n DiamondStorage storage ds = diamondStorage();\n uint256 originalSelectorCount = ds.selectorCount;\n uint256 selectorCount = originalSelectorCount;\n bytes32 selectorSlot;\n // Check if last selector slot is not full\n // \"selectorCount & 7\" is a gas efficient modulo by eight \"selectorCount % 8\"\n if (selectorCount & 7 > 0) {\n // get last selectorSlot\n // \"selectorSlot >> 3\" is a gas efficient division by 8 \"selectorSlot / 8\"\n selectorSlot = ds.selectorSlots[selectorCount >> 3];\n }\n // loop through diamond cut\n for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {\n (selectorCount, selectorSlot) = addReplaceRemoveFacetSelectors(\n selectorCount,\n selectorSlot,\n _diamondCut[facetIndex].facetAddress,\n _diamondCut[facetIndex].action,\n _diamondCut[facetIndex].functionSelectors\n );\n }\n if (selectorCount != originalSelectorCount) {\n ds.selectorCount = uint16(selectorCount);\n }\n // If last selector slot is not full\n // \"selectorCount & 7\" is a gas efficient modulo by eight \"selectorCount % 8\"\n if (selectorCount & 7 > 0) {\n // \"selectorSlot >> 3\" is a gas efficient division by 8 \"selectorSlot / 8\"\n ds.selectorSlots[selectorCount >> 3] = selectorSlot;\n }\n emit DiamondCut(_diamondCut, _init, _calldata);\n initializeDiamondCut(_init, _calldata);\n }\n\n function addReplaceRemoveFacetSelectors(\n uint256 _selectorCount,\n bytes32 _selectorSlot,\n address _newFacetAddress,\n IDiamondCut.FacetCutAction _action,\n bytes4[] memory _selectors\n ) internal returns (uint256, bytes32) {\n DiamondStorage storage ds = diamondStorage();\n require(_selectors.length > 0, \"LibDiamondCut: No selectors in facet to cut\");\n if (_action == IDiamondCut.FacetCutAction.Add) {\n enforceHasContractCode(_newFacetAddress, \"LibDiamondCut: Add facet has no code\");\n for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {\n bytes4 selector = _selectors[selectorIndex];\n bytes32 oldFacet = ds.facets[selector];\n require(address(bytes20(oldFacet)) == address(0), \"LibDiamondCut: Can't add function that already exists\");\n // add facet for selector\n ds.facets[selector] = bytes20(_newFacetAddress) | bytes32(_selectorCount);\n // \"_selectorCount & 7\" is a gas efficient modulo by eight \"_selectorCount % 8\"\n uint256 selectorInSlotPosition = (_selectorCount & 7) << 5;\n // clear selector position in slot and add selector\n _selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorInSlotPosition)) | (bytes32(selector) >> selectorInSlotPosition);\n // if slot is full then write it to storage\n if (selectorInSlotPosition == 224) {\n // \"_selectorSlot >> 3\" is a gas efficient division by 8 \"_selectorSlot / 8\"\n ds.selectorSlots[_selectorCount >> 3] = _selectorSlot;\n _selectorSlot = 0;\n }\n _selectorCount++;\n }\n } else if (_action == IDiamondCut.FacetCutAction.Replace) {\n enforceHasContractCode(_newFacetAddress, \"LibDiamondCut: Replace facet has no code\");\n for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {\n bytes4 selector = _selectors[selectorIndex];\n bytes32 oldFacet = ds.facets[selector];\n address oldFacetAddress = address(bytes20(oldFacet));\n // only useful if immutable functions exist\n require(oldFacetAddress != address(this), \"LibDiamondCut: Can't replace immutable function\");\n require(oldFacetAddress != _newFacetAddress, \"LibDiamondCut: Can't replace function with same function\");\n require(oldFacetAddress != address(0), \"LibDiamondCut: Can't replace function that doesn't exist\");\n // replace old facet address\n ds.facets[selector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(_newFacetAddress);\n }\n } else if (_action == IDiamondCut.FacetCutAction.Remove) {\n require(_newFacetAddress == address(0), \"LibDiamondCut: Remove facet address must be address(0)\");\n // \"_selectorCount >> 3\" is a gas efficient division by 8 \"_selectorCount / 8\"\n uint256 selectorSlotCount = _selectorCount >> 3;\n // \"_selectorCount & 7\" is a gas efficient modulo by eight \"_selectorCount % 8\"\n uint256 selectorInSlotIndex = _selectorCount & 7;\n for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {\n if (_selectorSlot == 0) {\n // get last selectorSlot\n selectorSlotCount--;\n _selectorSlot = ds.selectorSlots[selectorSlotCount];\n selectorInSlotIndex = 7;\n } else {\n selectorInSlotIndex--;\n }\n bytes4 lastSelector;\n uint256 oldSelectorsSlotCount;\n uint256 oldSelectorInSlotPosition;\n // adding a block here prevents stack too deep error\n {\n bytes4 selector = _selectors[selectorIndex];\n bytes32 oldFacet = ds.facets[selector];\n require(address(bytes20(oldFacet)) != address(0), \"LibDiamondCut: Can't remove function that doesn't exist\");\n // only useful if immutable functions exist\n require(address(bytes20(oldFacet)) != address(this), \"LibDiamondCut: Can't remove immutable function\");\n // replace selector with last selector in ds.facets\n // gets the last selector\n lastSelector = bytes4(_selectorSlot << (selectorInSlotIndex << 5));\n if (lastSelector != selector) {\n // update last selector slot position info\n ds.facets[lastSelector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(ds.facets[lastSelector]);\n }\n delete ds.facets[selector];\n uint256 oldSelectorCount = uint16(uint256(oldFacet));\n // \"oldSelectorCount >> 3\" is a gas efficient division by 8 \"oldSelectorCount / 8\"\n oldSelectorsSlotCount = oldSelectorCount >> 3;\n // \"oldSelectorCount & 7\" is a gas efficient modulo by eight \"oldSelectorCount % 8\"\n oldSelectorInSlotPosition = (oldSelectorCount & 7) << 5;\n }\n if (oldSelectorsSlotCount != selectorSlotCount) {\n bytes32 oldSelectorSlot = ds.selectorSlots[oldSelectorsSlotCount];\n // clears the selector we are deleting and puts the last selector in its place.\n oldSelectorSlot = (oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) | (bytes32(lastSelector) >> oldSelectorInSlotPosition);\n // update storage with the modified slot\n ds.selectorSlots[oldSelectorsSlotCount] = oldSelectorSlot;\n } else {\n // clears the selector we are deleting and puts the last selector in its place.\n _selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) | (bytes32(lastSelector) >> oldSelectorInSlotPosition);\n }\n if (selectorInSlotIndex == 0) {\n delete ds.selectorSlots[selectorSlotCount];\n _selectorSlot = 0;\n }\n }\n _selectorCount = selectorSlotCount * 8 + selectorInSlotIndex;\n } else {\n revert(\"LibDiamondCut: Incorrect FacetCutAction\");\n }\n return (_selectorCount, _selectorSlot);\n }\n\n function initializeDiamondCut(address _init, bytes memory _calldata) internal {\n if (_init == address(0)) {\n require(_calldata.length == 0, \"LibDiamondCut: _init is address(0) but_calldata is not empty\");\n } else {\n require(_calldata.length > 0, \"LibDiamondCut: _calldata is empty but _init is not address(0)\");\n if (_init != address(this)) {\n enforceHasContractCode(_init, \"LibDiamondCut: _init address has no code\");\n }\n (bool success, bytes memory error) = _init.delegatecall(_calldata);\n if (!success) {\n if (error.length > 0) {\n // bubble up the error\n revert(string(error));\n } else {\n revert(\"LibDiamondCut: _init function reverted\");\n }\n }\n }\n }\n\n function enforceHasContractCode(address _contract, string memory _errorMessage) internal view {\n uint256 contractSize;\n assembly {\n contractSize := extcodesize(_contract)\n }\n require(contractSize > 0, _errorMessage);\n }\n}\n"
},
"src/diamonds/shared/libs/LibMeta.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nlibrary LibMeta {\n function msgSender() internal view returns (address sender_) {\n if (msg.sender == address(this)) {\n bytes memory array = msg.data;\n uint256 index = msg.data.length;\n assembly {\n // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.\n sender_ := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)\n }\n } else {\n sender_ = msg.sender;\n }\n }\n}\n"
},
"src/erc20/ERC20Wrapper.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n// solhint-disable func-name-mixedcase\n\nimport { IERC20 } from \"./IERC20.sol\";\nimport { INayms } from \"../diamonds/nayms/INayms.sol\";\nimport { LibHelpers } from \"../diamonds/nayms/libs/LibHelpers.sol\";\nimport { LibConstants } from \"../diamonds/nayms/libs/LibConstants.sol\";\nimport { ReentrancyGuard } from \"../utils/ReentrancyGuard.sol\";\n\ncontract ERC20Wrapper is IERC20, ReentrancyGuard {\n /*//////////////////////////////////////////////////////////////\n ERC20 STORAGE\n //////////////////////////////////////////////////////////////*/\n bytes32 internal immutable tokenId;\n INayms internal immutable nayms;\n mapping(address => mapping(address => uint256)) public allowances;\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 STORAGE\n //////////////////////////////////////////////////////////////*/\n uint256 internal immutable INITIAL_CHAIN_ID;\n bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n mapping(address => uint256) public nonces;\n\n constructor(bytes32 _tokenId) {\n // ensure only diamond can instantiate this\n nayms = INayms(msg.sender);\n\n require(nayms.isObjectTokenizable(_tokenId), \"must be tokenizable\");\n require(!nayms.isTokenWrapped(_tokenId), \"must not be wrapped already\");\n\n tokenId = _tokenId;\n\n INITIAL_CHAIN_ID = block.chainid;\n INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n }\n\n function name() external view returns (string memory) {\n (, , , string memory tokenName, ) = nayms.getObjectMeta(tokenId);\n return tokenName;\n }\n\n function symbol() external view returns (string memory) {\n (, , string memory tokenSymbol, , ) = nayms.getObjectMeta(tokenId);\n return tokenSymbol;\n }\n\n function decimals() external pure returns (uint8) {\n return 18;\n }\n\n function totalSupply() external view returns (uint256) {\n return nayms.internalTokenSupply(tokenId);\n }\n\n function balanceOf(address who) external view returns (uint256) {\n return nayms.internalBalanceOf(LibHelpers._getIdForAddress(who), tokenId);\n }\n\n function allowance(address owner, address spender) external view returns (uint256) {\n return allowances[owner][spender];\n }\n\n function transfer(address to, uint256 value) external nonReentrant returns (bool) {\n bytes32 fromId = LibHelpers._getIdForAddress(msg.sender);\n bytes32 toId = LibHelpers._getIdForAddress(to);\n\n emit Transfer(msg.sender, to, value);\n\n nayms.wrapperInternalTransferFrom(fromId, toId, tokenId, value);\n\n return true;\n }\n\n function approve(address spender, uint256 value) external returns (bool) {\n allowances[msg.sender][spender] = value;\n return true;\n }\n\n function transferFrom(\n address from,\n address to,\n uint256 value\n ) external nonReentrant returns (bool) {\n if (value == 0) {\n revert();\n }\n uint256 allowed = allowances[from][msg.sender]; // Saves gas for limited approvals.\n require(allowed >= value, \"not enough allowance\");\n\n if (allowed != type(uint256).max) allowances[from][msg.sender] = allowed - value;\n\n bytes32 fromId = LibHelpers._getIdForAddress(from);\n bytes32 toId = LibHelpers._getIdForAddress(to);\n\n emit Transfer(from, to, value);\n\n nayms.wrapperInternalTransferFrom(fromId, toId, tokenId, value);\n\n return true;\n }\n\n // refer to https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol#L116\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external {\n require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n // Unchecked because the only math done is incrementing\n // the owner's nonce which cannot realistically overflow.\n unchecked {\n address recoveredAddress = ecrecover(\n keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR(),\n keccak256(\n abi.encode(\n keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"),\n owner,\n spender,\n value,\n nonces[owner]++,\n deadline\n )\n )\n )\n ),\n v,\n r,\n s\n );\n\n require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n allowances[recoveredAddress][spender] = value;\n }\n\n emit Approval(owner, spender, value);\n }\n\n function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n }\n\n function computeDomainSeparator() internal view virtual returns (bytes32) {\n return\n keccak256(\n abi.encode(\n keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n keccak256(LibHelpers._bytes32ToBytes(tokenId)),\n keccak256(\"1\"),\n block.chainid,\n address(this)\n )\n );\n }\n}\n"
},
"src/erc20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/**\n * See https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC20\n */\ninterface IERC20 {\n function name() external view returns (string memory);\n\n function symbol() external view returns (string memory);\n\n function decimals() external view returns (uint8);\n\n function totalSupply() external view returns (uint256);\n\n function balanceOf(address who) external view returns (uint256);\n\n function allowance(address owner, address spender) external view returns (uint256);\n\n function transfer(address to, uint256 value) external returns (bool);\n\n function approve(address spender, uint256 value) external returns (bool);\n\n function transferFrom(\n address from,\n address to,\n uint256 value\n ) external returns (bool);\n\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
},
"src/erc20/LibERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/******************************************************************************\\\n* Author: Nick Mudge\n*\n/******************************************************************************/\n\nimport { IERC20 } from \"./IERC20.sol\";\n\nlibrary LibERC20 {\n function decimals(address _token) internal returns (uint8) {\n uint256 size;\n assembly {\n size := extcodesize(_token)\n }\n require(size > 0, \"LibERC20: ERC20 token address has no code\");\n (bool success, bytes memory result) = _token.call(abi.encodeWithSelector(IERC20.decimals.selector));\n if (success) {\n return abi.decode(result, (uint8));\n } else {\n revert(\"LibERC20: call to decimals() failed\");\n }\n }\n\n function balanceOf(address _token, address _who) internal returns (uint256) {\n uint256 size;\n assembly {\n size := extcodesize(_token)\n }\n require(size > 0, \"LibERC20: ERC20 token address has no code\");\n (bool success, bytes memory result) = _token.call(abi.encodeWithSelector(IERC20.balanceOf.selector, _who));\n if (success) {\n return abi.decode(result, (uint256));\n } else {\n revert(\"LibERC20: call to balanceOf() failed\");\n }\n }\n\n function transferFrom(\n address _token,\n address _from,\n address _to,\n uint256 _value\n ) internal {\n uint256 size;\n assembly {\n size := extcodesize(_token)\n }\n require(size > 0, \"LibERC20: ERC20 token address has no code\");\n (bool success, bytes memory result) = _token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, _from, _to, _value));\n handleReturn(success, result);\n }\n\n function transfer(\n address _token,\n address _to,\n uint256 _value\n ) internal {\n uint256 size;\n assembly {\n size := extcodesize(_token)\n }\n require(size > 0, \"LibERC20: ERC20 token address has no code\");\n (bool success, bytes memory result) = _token.call(abi.encodeWithSelector(IERC20.transfer.selector, _to, _value));\n handleReturn(success, result);\n }\n\n function handleReturn(bool _success, bytes memory _result) internal pure {\n if (_success) {\n if (_result.length > 0) {\n require(abi.decode(_result, (bool)), \"LibERC20: transfer or transferFrom returned false\");\n }\n } else {\n if (_result.length > 0) {\n // bubble up any reason for revert\n // see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/c239e1af8d1a1296577108dd6989a17b57434f8e/contracts/utils/Address.sol#L201\n assembly {\n revert(add(32, _result), mload(_result))\n }\n } else {\n revert(\"LibERC20: transfer or transferFrom reverted\");\n }\n }\n }\n}\n"
},
"src/utils/ReentrancyGuard.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { LibAppStorage } from \"src/diamonds/nayms/AppStorage.sol\";\n\n// From OpenZeppellin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and make it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n // On the first call to nonReentrant, _notEntered will be true\n require(LibAppStorage.diamondStorage().reentrancyStatus != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n LibAppStorage.diamondStorage().reentrancyStatus = _ENTERED;\n\n _;\n\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n LibAppStorage.diamondStorage().reentrancyStatus = _NOT_ENTERED;\n }\n}\n"
}
},
"settings": {
"remappings": [
"@openzeppelin/=lib/ozv4/",
"@uniswap/lib/=lib/solidity-lib/",
"@uniswap/v2-core/=lib/v2-core/",
"@uniswap/v3-core/=lib/v3-core/",
"@uniswap/v3-periphery/=lib/v3-periphery/",
"base64-sol/=lib/base64/",
"ds-test/=lib/ds-test/src/",
"forge-std/=lib/forge-std/src/",
"ozv4/=lib/ozv4/",
"script/=script/",
"solidity-lib/=lib/solidity-lib/contracts/",
"solidity-stringutils/=lib/solidity-stringutils/src/",
"solmate/=lib/solmate/src/",
"src/=src/",
"test/=test/"
],
"optimizer": {
"enabled": true,
"runs": 200
},
"metadata": {
"bytecodeHash": "ipfs"
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "london",
"debug": {
"revertStrings": "default"
},
"libraries": {}
}
}