zellic-audit
Initial commit
f998fcd
raw
history blame
43.7 kB
{
"language": "Solidity",
"sources": {
"@metalabel/solmate/src/tokens/ERC721.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Data stored per-token, fits into a single storage word\nstruct TokenData {\n address owner;\n uint16 sequenceId;\n uint80 data;\n}\n\n/// @notice Modern, minimalist, and gas efficient ERC-721 implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)\nabstract contract ERC721 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Transfer(address indexed from, address indexed to, uint256 indexed id);\n\n event Approval(address indexed owner, address indexed spender, uint256 indexed id);\n\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /*//////////////////////////////////////////////////////////////\n METADATA STORAGE/LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function tokenURI(uint256 id) public view virtual returns (string memory);\n\n /*//////////////////////////////////////////////////////////////\n ERC721 BALANCE/OWNER STORAGE\n //////////////////////////////////////////////////////////////*/\n\n mapping(uint256 => TokenData) internal _tokenData;\n\n mapping(address => uint256) internal _balanceOf;\n\n function ownerOf(uint256 id) public view virtual returns (address owner) {\n require((owner = _tokenData[id].owner) != address(0), \"NOT_MINTED\");\n }\n\n function balanceOf(address owner) public view virtual returns (uint256) {\n require(owner != address(0), \"ZERO_ADDRESS\");\n\n return _balanceOf[owner];\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC721 APPROVAL STORAGE\n //////////////////////////////////////////////////////////////*/\n\n mapping(uint256 => address) public getApproved;\n\n mapping(address => mapping(address => bool)) public isApprovedForAll;\n\n /*//////////////////////////////////////////////////////////////\n ERC721 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function approve(address spender, uint256 id) public virtual {\n address owner = _tokenData[id].owner;\n\n require(msg.sender == owner || isApprovedForAll[owner][msg.sender], \"NOT_AUTHORIZED\");\n\n getApproved[id] = spender;\n\n emit Approval(owner, spender, id);\n }\n\n function setApprovalForAll(address operator, bool approved) public virtual {\n isApprovedForAll[msg.sender][operator] = approved;\n\n emit ApprovalForAll(msg.sender, operator, approved);\n }\n\n function transferFrom(\n address from,\n address to,\n uint256 id\n ) public virtual {\n require(from == _tokenData[id].owner, \"WRONG_FROM\");\n\n require(to != address(0), \"INVALID_RECIPIENT\");\n\n require(\n msg.sender == from || isApprovedForAll[from][msg.sender] || msg.sender == getApproved[id],\n \"NOT_AUTHORIZED\"\n );\n\n // Underflow of the sender's balance is impossible because we check for\n // ownership above and the recipient's balance can't realistically overflow.\n unchecked {\n _balanceOf[from]--;\n\n _balanceOf[to]++;\n }\n\n _tokenData[id].owner = to;\n\n delete getApproved[id];\n\n emit Transfer(from, to, id);\n }\n\n function safeTransferFrom(\n address from,\n address to,\n uint256 id\n ) public virtual {\n transferFrom(from, to, id);\n\n require(\n to.code.length == 0 ||\n ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, \"\") ==\n ERC721TokenReceiver.onERC721Received.selector,\n \"UNSAFE_RECIPIENT\"\n );\n }\n\n function safeTransferFrom(\n address from,\n address to,\n uint256 id,\n bytes calldata data\n ) public virtual {\n transferFrom(from, to, id);\n\n require(\n to.code.length == 0 ||\n ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) ==\n ERC721TokenReceiver.onERC721Received.selector,\n \"UNSAFE_RECIPIENT\"\n );\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC165 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n return\n interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165\n interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721\n interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL MINT/BURN LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function _mint(address to, uint256 id) internal virtual {\n return _mint(to, id, 0, 0);\n }\n\n function _mint(address to, uint256 id, uint16 sequenceId, uint80 data) internal virtual {\n require(to != address(0), \"INVALID_RECIPIENT\");\n\n require(_tokenData[id].owner == address(0), \"ALREADY_MINTED\");\n\n // Counter overflow is incredibly unrealistic.\n unchecked {\n _balanceOf[to]++;\n }\n\n _tokenData[id] = TokenData({\n owner: to,\n sequenceId: sequenceId,\n data: data\n });\n\n emit Transfer(address(0), to, id);\n }\n\n function _burn(uint256 id) internal virtual {\n address owner = _tokenData[id].owner;\n\n require(owner != address(0), \"NOT_MINTED\");\n\n // Ownership check above ensures no underflow.\n unchecked {\n _balanceOf[owner]--;\n }\n\n delete _tokenData[id];\n\n delete getApproved[id];\n\n emit Transfer(owner, address(0), id);\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL SAFE MINT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function _safeMint(address to, uint256 id) internal virtual {\n _mint(to, id);\n\n require(\n to.code.length == 0 ||\n ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, \"\") ==\n ERC721TokenReceiver.onERC721Received.selector,\n \"UNSAFE_RECIPIENT\"\n );\n }\n\n function _safeMint(\n address to,\n uint256 id,\n bytes memory data\n ) internal virtual {\n _mint(to, id);\n\n require(\n to.code.length == 0 ||\n ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, data) ==\n ERC721TokenReceiver.onERC721Received.selector,\n \"UNSAFE_RECIPIENT\"\n );\n }\n\n /*//////////////////////////////////////////////////////////////\n METALABEL ADDED FUNCTIONALITY\n //////////////////////////////////////////////////////////////*/\n\n function getTokenData(uint256 id) external view virtual returns (TokenData memory) {\n TokenData memory data = _tokenData[id];\n require(data.owner != address(0), \"NOT_MINTED\");\n return data;\n }\n}\n\n/// @notice A generic interface for a contract which properly accepts ERC721 tokens.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)\nabstract contract ERC721TokenReceiver {\n function onERC721Received(\n address,\n address,\n uint256,\n bytes calldata\n ) external virtual returns (bytes4) {\n return ERC721TokenReceiver.onERC721Received.selector;\n }\n}\n"
},
"@metalabel/solmate/src/utils/MerkleProofLib.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\n/// @notice Gas optimized merkle proof verification library.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/MerkleProofLib.sol)\n/// @author Modified from Solady (https://github.com/Vectorized/solady/blob/main/src/utils/MerkleProofLib.sol)\nlibrary MerkleProofLib {\n function verify(\n bytes32[] calldata proof,\n bytes32 root,\n bytes32 leaf\n ) internal pure returns (bool isValid) {\n assembly {\n if proof.length {\n // Left shifting by 5 is like multiplying by 32.\n let end := add(proof.offset, shl(5, proof.length))\n\n // Initialize offset to the offset of the proof in calldata.\n let offset := proof.offset\n\n // Iterate over proof elements to compute root hash.\n // prettier-ignore\n for {} 1 {} {\n // Slot where the leaf should be put in scratch space. If\n // leaf > calldataload(offset): slot 32, otherwise: slot 0.\n let leafSlot := shl(5, gt(leaf, calldataload(offset)))\n\n // Store elements to hash contiguously in scratch space.\n // The xor puts calldataload(offset) in whichever slot leaf\n // is not occupying, so 0 if leafSlot is 32, and 32 otherwise.\n mstore(leafSlot, leaf)\n mstore(xor(leafSlot, 32), calldataload(offset))\n\n // Reuse leaf to store the hash to reduce stack operations.\n leaf := keccak256(0, 64) // Hash both slots of scratch space.\n\n offset := add(offset, 32) // Shift 1 word per cycle.\n\n // prettier-ignore\n if iszero(lt(offset, end)) { break }\n }\n }\n\n isValid := eq(leaf, root) // The proof is valid if the roots match.\n }\n }\n}\n"
},
"@metalabel/solmate/src/utils/SSTORE2.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Read and write to persistent storage at a fraction of the cost.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SSTORE2.sol)\n/// @author Modified from 0xSequence (https://github.com/0xSequence/sstore2/blob/master/contracts/SSTORE2.sol)\nlibrary SSTORE2 {\n uint256 internal constant DATA_OFFSET = 1; // We skip the first byte as it's a STOP opcode to ensure the contract can't be called.\n\n /*//////////////////////////////////////////////////////////////\n WRITE LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function write(bytes memory data) internal returns (address pointer) {\n // Prefix the bytecode with a STOP opcode to ensure it cannot be called.\n bytes memory runtimeCode = abi.encodePacked(hex\"00\", data);\n\n bytes memory creationCode = abi.encodePacked(\n //---------------------------------------------------------------------------------------------------------------//\n // Opcode | Opcode + Arguments | Description | Stack View //\n //---------------------------------------------------------------------------------------------------------------//\n // 0x60 | 0x600B | PUSH1 11 | codeOffset //\n // 0x59 | 0x59 | MSIZE | 0 codeOffset //\n // 0x81 | 0x81 | DUP2 | codeOffset 0 codeOffset //\n // 0x38 | 0x38 | CODESIZE | codeSize codeOffset 0 codeOffset //\n // 0x03 | 0x03 | SUB | (codeSize - codeOffset) 0 codeOffset //\n // 0x80 | 0x80 | DUP | (codeSize - codeOffset) (codeSize - codeOffset) 0 codeOffset //\n // 0x92 | 0x92 | SWAP3 | codeOffset (codeSize - codeOffset) 0 (codeSize - codeOffset) //\n // 0x59 | 0x59 | MSIZE | 0 codeOffset (codeSize - codeOffset) 0 (codeSize - codeOffset) //\n // 0x39 | 0x39 | CODECOPY | 0 (codeSize - codeOffset) //\n // 0xf3 | 0xf3 | RETURN | //\n //---------------------------------------------------------------------------------------------------------------//\n hex\"60_0B_59_81_38_03_80_92_59_39_F3\", // Returns all code in the contract except for the first 11 (0B in hex) bytes.\n runtimeCode // The bytecode we want the contract to have after deployment. Capped at 1 byte less than the code size limit.\n );\n\n assembly {\n // Deploy a new contract with the generated creation code.\n // We start 32 bytes into the code to avoid copying the byte length.\n pointer := create(0, add(creationCode, 32), mload(creationCode))\n }\n\n require(pointer != address(0), \"DEPLOYMENT_FAILED\");\n }\n\n /*//////////////////////////////////////////////////////////////\n READ LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function read(address pointer) internal view returns (bytes memory) {\n return readBytecode(pointer, DATA_OFFSET, pointer.code.length - DATA_OFFSET);\n }\n\n function read(address pointer, uint256 start) internal view returns (bytes memory) {\n start += DATA_OFFSET;\n\n return readBytecode(pointer, start, pointer.code.length - start);\n }\n\n function read(\n address pointer,\n uint256 start,\n uint256 end\n ) internal view returns (bytes memory) {\n start += DATA_OFFSET;\n end += DATA_OFFSET;\n\n require(pointer.code.length >= end, \"OUT_OF_BOUNDS\");\n\n return readBytecode(pointer, start, end - start);\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL HELPER LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function readBytecode(\n address pointer,\n uint256 start,\n uint256 size\n ) private view returns (bytes memory data) {\n assembly {\n // Get a pointer to some free memory.\n data := mload(0x40)\n\n // Update the free memory pointer to prevent overriding our data.\n // We use and(x, not(31)) as a cheaper equivalent to sub(x, mod(x, 32)).\n // Adding 31 to size and running the result through the logic above ensures\n // the memory pointer remains word-aligned, following the Solidity convention.\n mstore(0x40, add(data, and(add(add(size, 32), 31), not(31))))\n\n // Store the size of the data in the first 32 byte chunk of free memory.\n mstore(data, size)\n\n // Copy the code into memory right after the 32 bytes we used to store the size.\n extcodecopy(pointer, add(data, 32), start, size)\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"contracts/interfaces/INodeRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nenum NodeType {\n INVALID_NODE_TYPE,\n METALABEL,\n RELEASE\n}\n\n/// @notice Data stored per node.\nstruct NodeData {\n NodeType nodeType;\n uint64 owner;\n uint64 parent;\n uint64 groupNode;\n // 7 bytes remaining\n}\n\n/// @notice The node registry maintains a tree of ownable nodes that are used to\n/// catalog logical entities and manage access control in the Metalabel\n/// universe.\ninterface INodeRegistry {\n /// @notice Create a new node. Child nodes can specify an group node that\n /// will be used to determine ownership, and a separate logical parent that\n /// expresses the entity relationship. Child nodes can only be created if\n /// msg.sender is an authorized manager of the parent node.\n function createNode(\n NodeType nodeType,\n uint64 owner,\n uint64 parent,\n uint64 groupNode,\n address[] memory initialControllers,\n string memory metadata\n ) external returns (uint64 id);\n\n /// @notice Determine if an address is authorized to manage a node.\n /// A node can be managed by an address if any of the following conditions\n /// are true:\n /// - The address's account is the owner of the node\n /// - The address's account is the owner of the node's group node\n /// - The address is an authorized controller of the node\n /// - The address is an authorized controller of the node's group node\n function isAuthorizedAddressForNode(uint64 node, address subject)\n external\n view\n returns (bool isAuthorized);\n\n /// @notice Resolve node owner account.\n function ownerOf(uint64 id) external view returns (uint64);\n}\n"
},
"contracts/interfaces/IResource.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {INodeRegistry} from \"./INodeRegistry.sol\";\n\n/// @notice An on-chain resource that is intended to be cataloged within the\n/// Metalabel universe\ninterface IResource {\n /// @notice Broadcast an arbitrary message.\n event Broadcast(string topic, string message);\n\n /// @notice Return the node registry contract address.\n function nodeRegistry() external view returns (INodeRegistry);\n\n /// @notice Return the control node ID for this resource.\n function controlNode() external view returns (uint64 nodeId);\n\n /// @notice Return true if the given address is authorized to manage this\n /// resource.\n function isAuthorized(address subject)\n external\n view\n returns (bool authorized);\n\n /// @notice Emit an on-chain message. msg.sender must be authorized to\n /// manage this resource's control node\n function broadcast(string calldata topic, string calldata message) external;\n}\n"
},
"contracts/Memberships.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/*\n\n███╗ ███╗███████╗████████╗ █████╗ ██╗ █████╗ ██████╗ ███████╗██╗\n████╗ ████║██╔════╝╚══██╔══╝██╔══██╗██║ ██╔══██╗██╔══██╗██╔════╝██║\n██╔████╔██║█████╗ ██║ ███████║██║ ███████║██████╔╝█████╗ ██║\n██║╚██╔╝██║██╔══╝ ██║ ██╔══██║██║ ██╔══██║██╔══██╗██╔══╝ ██║\n██║ ╚═╝ ██║███████╗ ██║ ██║ ██║███████╗██║ ██║██████╔╝███████╗███████╗\n╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚══════╝╚══════╝\n\n\nDeployed by Metalabel with 💖 as a permanent application on the Ethereum blockchain.\n\nMetalabel is a growing universe of tools, knowledge, and resources for\nmetalabels and cultural collectives.\n\nOur purpose is to establish the metalabel as key infrastructure for creative\ncollectives and to inspire a new culture of creative collaboration and mutual\nsupport.\n\nOUR SQUAD\n\nAnna Bulbrook (Curator)\nAustin Robey (Community)\nBrandon Valosek (Engineer)\nIlya Yudanov (Designer)\nLauren Dorman (Engineer)\nRob Kalin (Board)\nYancey Strickler (Director)\n\nhttps://metalabel.xyz\n\n*/\n\nimport {ERC721} from \"@metalabel/solmate/src/tokens/ERC721.sol\";\nimport {MerkleProofLib} from \"@metalabel/solmate/src/utils/MerkleProofLib.sol\";\nimport {SSTORE2} from \"@metalabel/solmate/src/utils/SSTORE2.sol\";\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\nimport {INodeRegistry} from \"./interfaces/INodeRegistry.sol\";\nimport {Resource, AccessControlData} from \"./Resource.sol\";\n\n/// @notice Immutable data stored per-collection.\n/// @dev This is stored via SSTORE2 to save gas.\nstruct ImmutableCollectionData {\n string name;\n string symbol;\n string baseURI;\n}\n\n/// @notice Data required when doing a permissionless mint via proof.\nstruct MembershipMint {\n address to;\n uint16 sequenceId;\n bytes32[] proof;\n}\n\n/// @notice Data required when doing an admin mint.\n/// @dev Admin mints do not require a providing a proof to keep gas down.\nstruct AdminMembershipMint {\n address to;\n uint16 sequenceId;\n}\n\n/// @notice Data for supply and next ID.\n/// @dev Fits into a single storage slot to keep gas cost down during minting.\nstruct MembershipsState {\n uint128 totalSupply;\n uint128 totalMinted;\n}\n\n/// @notice Membership collections can have their metadata resolver set to an\n/// external contract\n/// @dev This is used to futureproof the membership collection -- if a squad\n/// wants to move to a more onchain approach to membership metadata or have an\n/// alternative renderer, this gives them the option\ninterface ICustomMetadataResolver {\n /// @notice Resolve the token URI for a collection / token.\n function tokenURI(address collection, uint256 tokenId)\n external\n view\n returns (string memory);\n\n /// @notice Resolve the collection URI for a collection.\n function contractURI(address collection)\n external\n view\n returns (string memory);\n}\n\n/// @notice An ERC721 collection of NFTs representing memberships.\n/// - NFTs are non-transferable\n/// - Each membership collection has a control node, determining who the admin is\n/// - Admin can unilaterally mint and burn memberships, without proofs to keep\n/// gas down.\n/// - Admin can use a merkle root to set a large list of memberships that can be\n/// minted by anyone with a valid proof to socialize gas\n/// - Token URI computation defaults to baseURI + tokenID, but can be modified\n/// by a future external metadata resolver contract that implements\n/// ICustomMetadataResolver\n/// - Each token stores the mint timestamp, as well as an arbitrary sequence ID.\n/// Sequence ID has no onchain consequence, but can be set by the admin if\n/// desired\ncontract Memberships is ERC721, Resource {\n // ---\n // Errors\n // ---\n\n /// @notice The init function was called more than once.\n error AlreadyInitialized();\n\n /// @notice Attempted to transfer a membership NFT.\n error TransferNotAllowed();\n\n /// @notice Attempted to mint an invalid membership.\n error InvalidMint();\n\n /// @notice Attempted to burn an invalid or unowned membership token.\n error InvalidBurn();\n\n /// @notice Attempted to admin transfer a membership to somebody who already has one.\n error InvalidTransfer();\n\n // ---\n // Events\n // ---\n\n /// @notice A new membership NFT was minted.\n /// @dev The underlying ERC721 implementation already emits a Transfer event\n /// on mint, this additional event announces the sequence ID and timestamp\n /// associated with that membership.\n event MembershipCreated(\n uint256 indexed tokenId,\n uint16 sequenceId,\n uint80 timestamp\n );\n\n /// @notice The merkle root of the membership list was updated.\n event MembershipListRootUpdated(bytes32 root);\n\n /// @notice The custom metadata resolver was updated.\n event CustomMetadataResolverUpdated(ICustomMetadataResolver resolver);\n\n /// @notice The owner address of this memberships collection was updated.\n event OwnershipTransferred(\n address indexed previousOwner,\n address indexed newOwner\n );\n\n // ---\n // Storage\n // ---\n\n /// @notice Only for marketplace interop, can be set by owner of the control\n /// node.\n address public owner;\n\n /// @notice Merkle root of the membership list.\n bytes32 public membershipListRoot;\n\n /// @notice If a custom metadata resolver is set, it will be used to resolve\n /// tokenURI and collectionURI values\n ICustomMetadataResolver public customMetadataResolver;\n\n /// @notice Tracks total supply and next ID\n /// @dev These values are exposed via totalSupply and totalMinted views.\n MembershipsState internal membershipState;\n\n /// @notice The SSTORE2 storage pointer for immutable collection data.\n /// @dev These values are exposed via name/symbol/contractURI views.\n address internal immutableStoragePointer;\n\n // ---\n // Constructor\n // ---\n\n /// @dev Constructor only called during deployment of the implementation,\n /// all storage should be set up in init function which is called atomically\n /// after clone deployment\n constructor() {\n // Write dummy data to the immutable storage pointer to prevent\n // initialization of the implementation contract.\n immutableStoragePointer = SSTORE2.write(\n abi.encode(\n ImmutableCollectionData({name: \"\", symbol: \"\", baseURI: \"\"})\n )\n );\n }\n\n // ---\n // Clone init\n // ---\n\n /// @notice Initialize contract state.\n /// @dev Should be called immediately after deploying the clone in the same transaction.\n function init(\n address _owner,\n AccessControlData calldata _accessControl,\n string calldata _metadata,\n ImmutableCollectionData calldata _data\n ) external {\n if (immutableStoragePointer != address(0)) revert AlreadyInitialized();\n immutableStoragePointer = SSTORE2.write(abi.encode(_data));\n\n // Set ERC721 market interop.\n owner = _owner;\n emit OwnershipTransferred(address(0), owner);\n\n // Assign access control data.\n accessControl = _accessControl;\n\n // This memberships collection is a resource that can be cataloged -\n // emit the initial metadata value\n emit Broadcast(\"metadata\", _metadata);\n }\n\n // ---\n // Admin functionality\n // ---\n\n /// @notice Change the owner address of this collection.\n /// @dev This is only here for market interop, access control is handled via\n /// the control node.\n function setOwner(address _owner) external onlyAuthorized {\n address previousOwner = owner;\n owner = _owner;\n emit OwnershipTransferred(previousOwner, _owner);\n }\n\n /// @notice Change the merkle root of the membership list. Only callable by\n /// the admin\n function setMembershipListRoot(bytes32 _root) external onlyAuthorized {\n membershipListRoot = _root;\n emit MembershipListRootUpdated(_root);\n }\n\n /// @notice Set the custom metadata resolver. Passing in address(0) will\n /// effectively clear the custom resolver. Only callable by the admin.\n function setCustomMetadataResolver(ICustomMetadataResolver _resolver)\n external\n onlyAuthorized\n {\n customMetadataResolver = _resolver;\n emit CustomMetadataResolverUpdated(_resolver);\n }\n\n /// @notice Issue or revoke memberships without having to provide proofs.\n /// Only callable by the admin.\n function batchMintAndBurn(\n AdminMembershipMint[] calldata mints,\n uint256[] calldata burns\n ) external onlyAuthorized {\n _mintAndBurn(mints, burns);\n }\n\n /// @notice Update the membership list root and burn / mint memberships.\n /// @dev This is a convenience function for the admin to update things all\n /// at once; when adding or removing members, we can update the root, and\n /// issue/revoke memberships for the changes.\n function updateMemberships(\n bytes32 _root,\n AdminMembershipMint[] calldata mints,\n uint256[] calldata burns\n ) external onlyAuthorized {\n membershipListRoot = _root;\n emit MembershipListRootUpdated(_root);\n _mintAndBurn(mints, burns);\n }\n\n /// @dev Admin (proofless) mint and burn implementation\n function _mintAndBurn(\n AdminMembershipMint[] memory mints,\n uint256[] memory burns\n ) internal {\n MembershipsState storage state = membershipState;\n uint128 minted = state.totalMinted;\n\n // mint new ones\n for (uint256 i = 0; i < mints.length; i++) {\n // enforce at-most-one membership per address\n if (balanceOf(mints[i].to) > 0) revert InvalidMint();\n _mint(\n mints[i].to,\n ++minted,\n mints[i].sequenceId,\n uint80(block.timestamp)\n );\n emit MembershipCreated(\n minted,\n mints[i].sequenceId,\n uint80(block.timestamp)\n );\n }\n\n // burn old ones - the underlying implementation will revert if tokenID\n // is invalid\n for (uint256 i = 0; i < burns.length; i++) {\n _burn(burns[i]);\n }\n\n // update state\n state.totalMinted = minted;\n state.totalSupply =\n state.totalSupply +\n uint128(mints.length) -\n uint128(burns.length);\n }\n\n // ---\n // Permissionless mint\n // ---\n\n /// @notice Mint any unminted memberships that are on the membership list.\n /// Can be called by anyone since each mint requires a proof.\n function mintMemberships(MembershipMint[] calldata mints) external {\n MembershipsState storage state = membershipState;\n uint128 minted = state.totalMinted;\n uint128 supply = state.totalSupply;\n\n // for each mint request, verify the proof and mint the token\n for (uint256 i = 0; i < mints.length; i++) {\n // enforce at-most-one membership per address\n if (balanceOf(mints[i].to) > 0) revert InvalidMint();\n bool isValid = MerkleProofLib.verify(\n mints[i].proof,\n membershipListRoot,\n keccak256(abi.encodePacked(mints[i].to, mints[i].sequenceId))\n );\n if (!isValid) revert InvalidMint();\n _mint(\n mints[i].to,\n ++minted,\n mints[i].sequenceId,\n uint80(block.timestamp)\n );\n emit MembershipCreated(\n minted,\n mints[i].sequenceId,\n uint80(block.timestamp)\n );\n supply++;\n }\n\n // Write new counts back to storage\n state.totalMinted = minted;\n state.totalSupply = supply;\n }\n\n // ---\n // Token holder functionality\n // ---\n\n /// @notice Burn a membership. Msg sender must own token.\n function burnMembership(uint256 tokenId) external {\n if (ownerOf(tokenId) != msg.sender) revert InvalidBurn();\n _burn(tokenId);\n membershipState.totalSupply--;\n }\n\n // ---\n // ERC721 functionality - non-transferability / admin transfers\n // ---\n\n /// @notice Transfer is not allowed on this token.\n function transferFrom(\n address,\n address,\n uint256\n ) public pure override {\n revert TransferNotAllowed();\n }\n\n /// @notice Transfer an existing membership from one address to another. Only\n /// callable by the admin.\n function adminTransferFrom(\n address from,\n address to,\n uint256 id\n ) external onlyAuthorized {\n if (from == address(0)) revert InvalidTransfer();\n if (to == address(0)) revert InvalidTransfer();\n if (balanceOf(to) != 0) revert InvalidTransfer();\n if (from != _tokenData[id].owner) revert InvalidTransfer();\n\n //\n // The below code was copied from the solmate transferFrom source,\n // removing the checks (which we've already done above)\n //\n // --- START COPIED CODE ---\n //\n\n // Underflow of the sender's balance is impossible because we check for\n // ownership above and the recipient's balance can't realistically overflow.\n unchecked {\n _balanceOf[from]--;\n _balanceOf[to]++;\n }\n\n _tokenData[id].owner = to;\n delete getApproved[id];\n emit Transfer(from, to, id);\n\n //\n // --- END COPIED CODE ---\n //\n }\n\n // ---\n // ERC721 views\n // ---\n\n /// @notice The collection name.\n function name() public view virtual returns (string memory value) {\n value = _resolveImmutableStorage().name;\n }\n\n /// @notice The collection symbol.\n function symbol() public view virtual returns (string memory value) {\n value = _resolveImmutableStorage().symbol;\n }\n\n /// @inheritdoc ERC721\n function tokenURI(uint256 tokenId)\n public\n view\n virtual\n override\n returns (string memory uri)\n {\n // If a custom metadata resolver is set, use it to get the token URI\n // instead of the default behavior\n if (customMetadataResolver != ICustomMetadataResolver(address(0))) {\n return customMetadataResolver.tokenURI(address(this), tokenId);\n }\n\n // Form URI from base + collection + token ID\n uri = string.concat(\n _resolveImmutableStorage().baseURI,\n Strings.toHexString(address(this)),\n \"/\",\n Strings.toString(tokenId),\n \".json\"\n );\n }\n\n /// @notice Get the collection URI\n function contractURI() public view virtual returns (string memory uri) {\n // If a custom metadata resolver is set, use it to get the collection\n // URI instead of the default behavior\n if (customMetadataResolver != ICustomMetadataResolver(address(0))) {\n return customMetadataResolver.contractURI(address(this));\n }\n\n // Form URI from base + collection\n uri = string.concat(\n _resolveImmutableStorage().baseURI,\n Strings.toHexString(address(this)),\n \"/collection.json\"\n );\n }\n\n // ---\n // Misc views\n // ---\n\n /// @notice Get a membership's sequence ID.\n function tokenSequenceId(uint256 tokenId)\n external\n view\n returns (uint16 sequenceId)\n {\n sequenceId = _tokenData[tokenId].sequenceId;\n }\n\n /// @notice Get a membership's mint timestamp.\n function tokenMintTimestamp(uint256 tokenId)\n external\n view\n returns (uint80 timestamp)\n {\n timestamp = _tokenData[tokenId].data;\n }\n\n /// @notice Get total supply of existing memberships.\n function totalSupply() public view virtual returns (uint256) {\n return membershipState.totalSupply;\n }\n\n /// @notice Get total count of minted memberships, including burned ones.\n function totalMinted() public view virtual returns (uint256) {\n return membershipState.totalMinted;\n }\n\n // ---\n // Internal views\n // ---\n\n function _resolveImmutableStorage()\n internal\n view\n returns (ImmutableCollectionData memory data)\n {\n data = abi.decode(\n SSTORE2.read(immutableStoragePointer),\n (ImmutableCollectionData)\n );\n }\n}\n"
},
"contracts/Resource.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/*\n\n███╗ ███╗███████╗████████╗ █████╗ ██╗ █████╗ ██████╗ ███████╗██╗\n████╗ ████║██╔════╝╚══██╔══╝██╔══██╗██║ ██╔══██╗██╔══██╗██╔════╝██║\n██╔████╔██║█████╗ ██║ ███████║██║ ███████║██████╔╝█████╗ ██║\n██║╚██╔╝██║██╔══╝ ██║ ██╔══██║██║ ██╔══██║██╔══██╗██╔══╝ ██║\n██║ ╚═╝ ██║███████╗ ██║ ██║ ██║███████╗██║ ██║██████╔╝███████╗███████╗\n╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚══════╝╚══════╝\n\n\nDeployed by Metalabel with 💖 as a permanent application on the Ethereum blockchain.\n\nMetalabel is a growing universe of tools, knowledge, and resources for\nmetalabels and cultural collectives.\n\nOur purpose is to establish the metalabel as key infrastructure for creative\ncollectives and to inspire a new culture of creative collaboration and mutual\nsupport.\n\nOUR SQUAD\n\nAnna Bulbrook (Curator)\nAustin Robey (Community)\nBrandon Valosek (Engineer)\nIlya Yudanov (Designer)\nLauren Dorman (Engineer)\nRob Kalin (Board)\nYancey Strickler (Director)\n\nhttps://metalabel.xyz\n\n*/\n\nimport {IResource} from \"./interfaces/IResource.sol\";\nimport {INodeRegistry} from \"./interfaces/INodeRegistry.sol\";\n\n/// @notice Data stored for handling access control resolution.\nstruct AccessControlData {\n INodeRegistry nodeRegistry;\n uint64 controlNodeId;\n // 4 bytes remaining\n}\n\n/// @notice A resource that can be cataloged on the Metalabel protocol.\ncontract Resource is IResource {\n // ---\n // Errors\n // ---\n\n /// @notice Unauthorized msg.sender attempted to interact with this resource\n error NotAuthorized();\n\n // ---\n // Storage\n // ---\n\n /// @notice Access control data for this resource.\n AccessControlData public accessControl;\n\n // ---\n // Modifiers\n // ---\n\n /// @dev Make a function only callable by a msg.sender that is authorized to\n /// manage the control node of this resource\n modifier onlyAuthorized() {\n if (\n !accessControl.nodeRegistry.isAuthorizedAddressForNode(\n accessControl.controlNodeId,\n msg.sender\n )\n ) {\n revert NotAuthorized();\n }\n _;\n }\n\n // ---\n // Admin functionality\n // ---\n\n /// @inheritdoc IResource\n function broadcast(string calldata topic, string calldata message)\n external\n onlyAuthorized\n {\n emit Broadcast(topic, message);\n }\n\n // ---\n // Resource views\n // ---\n\n /// @inheritdoc IResource\n function nodeRegistry() external view virtual returns (INodeRegistry) {\n return accessControl.nodeRegistry;\n }\n\n /// @inheritdoc IResource\n function controlNode() external view virtual returns (uint64 nodeId) {\n return accessControl.controlNodeId;\n }\n\n /// @inheritdoc IResource\n function isAuthorized(address subject)\n public\n view\n virtual\n returns (bool authorized)\n {\n authorized = accessControl.nodeRegistry.isAuthorizedAddressForNode(\n accessControl.controlNodeId,\n subject\n );\n }\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 1000
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}
}