Verified contractExactMIT
MetadataRenderer
Address0x5a28eef0ed8cce44cda9d7097ecce041bb51b9d4
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.16
- Same code
Only this contract
Details
- Compiler
- solc 0.8.16+commit.07a7930e
- Language
- solidity
- Optimization
- Yes, 500,000 runs
- EVM version
- london
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 16,585,896
- Creation transaction
- 0xb3cc29257a…dc3a9bf985
35 files
- src/token/metadata/MetadataRenderer.solmain19.67 KB
- node_modules/@openzeppelin/contracts/interfaces/draft-IERC1822.sol879 B
- node_modules/@openzeppelin/contracts/utils/Base64.sol3.53 KB
- node_modules/@openzeppelin/contracts/utils/StorageSlot.sol2.67 KB
- node_modules/@openzeppelin/contracts/utils/Strings.sol2.4 KB
- node_modules/micro-onchain-metadata-utils/src/MetadataBuilder.sol3.85 KB
- node_modules/micro-onchain-metadata-utils/src/MetadataJSONKeys.sol365 B
- node_modules/micro-onchain-metadata-utils/src/MetadataMIMETypes.sol236 B
- node_modules/micro-onchain-metadata-utils/src/lib/Base64.sol3.53 KB
- node_modules/micro-onchain-metadata-utils/src/lib/Strings.sol2.4 KB
- node_modules/sol-uriencode/src/UriEncode.sol3.11 KB
- src/VersionedContract.sol198 B
- src/lib/interfaces/IEIP712.sol1.06 KB
- src/lib/interfaces/IERC1967Upgrade.sol1.17 KB
- src/lib/interfaces/IERC721.sol4.42 KB
- src/lib/interfaces/IERC721Votes.sol3.05 KB
- src/lib/interfaces/IInitializable.sol1.12 KB
- src/lib/interfaces/IOwnable.sol2.47 KB
- src/lib/interfaces/IUUPS.sol1.41 KB
- src/lib/proxy/ERC1967Upgrade.sol3.43 KB
- src/lib/proxy/UUPS.sol2.59 KB
- src/lib/token/ERC721.sol8.32 KB
- src/lib/utils/Address.sol2.22 KB
- src/lib/utils/Initializable.sol2.63 KB
- src/lib/utils/TokenReceiver.sol1 KB
- src/manager/IManager.sol6.41 KB
- src/token/IToken.sol6.11 KB
- src/token/metadata/interfaces/IBaseMetadata.sol1.69 KB
- src/token/metadata/interfaces/IPropertyIPFSMetadataRenderer.sol4.24 KB
- src/token/metadata/storage/MetadataRendererStorageV1.sol871 B
- src/token/metadata/storage/MetadataRendererStorageV2.sol529 B
- src/token/metadata/types/MetadataRendererTypesV1.sol721 B
- src/token/metadata/types/MetadataRendererTypesV2.sol326 B
- src/token/types/TokenTypesV1.sol1.15 KB
- src/token/types/TokenTypesV2.sol250 B
src/token/metadata/MetadataRenderer.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
import { Base64 } from "@openzeppelin/contracts/utils/Base64.sol";
import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { UriEncode } from "sol-uriencode/src/UriEncode.sol";
import { MetadataBuilder } from "micro-onchain-metadata-utils/MetadataBuilder.sol";
import { MetadataJSONKeys } from "micro-onchain-metadata-utils/MetadataJSONKeys.sol";
import { UUPS } from "../../lib/proxy/UUPS.sol";
import { Initializable } from "../../lib/utils/Initializable.sol";
import { IOwnable } from "../../lib/interfaces/IOwnable.sol";
import { ERC721 } from "../../lib/token/ERC721.sol";
import { MetadataRendererStorageV1 } from "./storage/MetadataRendererStorageV1.sol";
import { MetadataRendererStorageV2 } from "./storage/MetadataRendererStorageV2.sol";
import { IToken } from "../../token/IToken.sol";
import { IPropertyIPFSMetadataRenderer } from "./interfaces/IPropertyIPFSMetadataRenderer.sol";
import { IManager } from "../../manager/IManager.sol";
import { VersionedContract } from "../../VersionedContract.sol";
/// @title Metadata Renderer
/// @author Iain Nash & Rohan Kulkarni
/// @notice A DAO's artwork generator and renderer
/// @custom:repo github.com/ourzora/nouns-protocol
contract MetadataRenderer is
IPropertyIPFSMetadataRenderer,
VersionedContract,
Initializable,
UUPS,
MetadataRendererStorageV1,
MetadataRendererStorageV2
{
/// ///
/// IMMUTABLES ///
/// ///
/// @notice The contract upgrade manager
IManager private immutable manager;
/// ///
/// MODIFIERS ///
/// ///
/// @notice Checks the token owner if the current action is allowed
modifier onlyOwner() {
if (owner() != msg.sender) {
revert IOwnable.ONLY_OWNER();
}
_;
}
/// ///
/// CONSTRUCTOR ///
/// ///
/// @param _manager The contract upgrade manager address
constructor(address _manager) payable initializer {
manager = IManager(_manager);
}
/// ///
/// INITIALIZER ///
/// ///
/// @notice Initializes a DAO's token metadata renderer
/// @param _initStrings The encoded token and metadata initialization strings
/// @param _token The ERC-721 token address
function initialize(bytes calldata _initStrings, address _token) external initializer {
// Ensure the caller is the contract manager
if (msg.sender != address(manager)) {
revert ONLY_MANAGER();
}
// Decode the token initialization strings
(, , string memory _description, string memory _contractImage, string memory _projectURI, string memory _rendererBase) = abi.decode(
_initStrings,
(string, string, string, string, string, string)
);
// Store the renderer settings
settings.projectURI = _projectURI;
settings.description = _description;
settings.contractImage = _contractImage;
settings.rendererBase = _rendererBase;
settings.projectURI = _projectURI;
settings.token = _token;
}
/// ///
/// PROPERTIES & ITEMS ///
/// ///
/// @notice The number of properties
/// @return properties array length
function propertiesCount() external view returns (uint256) {
return properties.length;
}
/// @notice The number of items in a property
/// @param _propertyId The property id
/// @return items array length
function itemsCount(uint256 _propertyId) external view returns (uint256) {
return properties[_propertyId].items.length;
}
/// @notice The number of items in the IPFS data store
/// @return ipfs data array size
function ipfsDataCount() external view returns (uint256) {
return ipfsData.length;
}
/// @notice Updates the additional token properties associated with the metadata.
/// @dev Be careful to not conflict with already used keys such as "name", "description", "properties",
function setAdditionalTokenProperties(AdditionalTokenProperty[] memory _additionalTokenProperties) external onlyOwner {
delete additionalTokenProperties;
for (uint256 i = 0; i < _additionalTokenProperties.length; i++) {
additionalTokenProperties.push(_additionalTokenProperties[i]);
}
emit AdditionalTokenPropertiesSet(_additionalTokenProperties);
}
/// @notice Adds properties and/or items to be pseudo-randomly chosen from during token minting
/// @param _names The names of the properties to add
/// @param _items The items to add to each property
/// @param _ipfsGroup The IPFS base URI and extension
function addProperties(
string[] calldata _names,
ItemParam[] calldata _items,
IPFSGroup calldata _ipfsGroup
) external onlyOwner {
_addProperties(_names, _items, _ipfsGroup);
}
/// @notice Deletes existing properties and/or items to be pseudo-randomly chosen from during token minting, replacing them with provided properties. WARNING: This function can alter or break existing token metadata if the number of properties for this renderer change before/after the upsert. If the properties selected in any tokens do not exist in the new version those token will not render
/// @dev We do not require the number of properties for an reset to match the existing property length, to allow multi-stage property additions (for e.g. when there are more properties than can fit in a single transaction)
/// @param _names The names of the properties to add
/// @param _items The items to add to each property
/// @param _ipfsGroup The IPFS base URI and extension
function deleteAndRecreateProperties(
string[] calldata _names,
ItemParam[] calldata _items,
IPFSGroup calldata _ipfsGroup
) external onlyOwner {
delete ipfsData;
delete properties;
_addProperties(_names, _items, _ipfsGroup);
}
function _addProperties(
string[] calldata _names,
ItemParam[] calldata _items,
IPFSGroup calldata _ipfsGroup
) internal {
// Cache the existing amount of IPFS data stored
uint256 dataLength = ipfsData.length;
// Add the IPFS group information
ipfsData.push(_ipfsGroup);
// Cache the number of existing properties
uint256 numStoredProperties = properties.length;
// Cache the number of new properties
uint256 numNewProperties = _names.length;
// Cache the number of new items
uint256 numNewItems = _items.length;
// If this is the first time adding metadata:
if (numStoredProperties == 0) {
// Ensure at least one property and one item are included
if (numNewProperties == 0 || numNewItems == 0) {
revert ONE_PROPERTY_AND_ITEM_REQUIRED();
}
}
unchecked {
// Check if not too many items are stored
if (numStoredProperties + numNewProperties > 15) {
revert TOO_MANY_PROPERTIES();
}
// For each new property:
for (uint256 i = 0; i < numNewProperties; ++i) {
// Append storage space
properties.push();
// Get the new property id
uint256 propertyId = numStoredProperties + i;
// Store the property name
properties[propertyId].name = _names[i];
emit PropertyAdded(propertyId, _names[i]);
}
// For each new item:
for (uint256 i = 0; i < numNewItems; ++i) {
// Cache the id of the associated property
uint256 _propertyId = _items[i].propertyId;
// Offset the id if the item is for a new property
// Note: Property ids under the hood are offset by 1
if (_items[i].isNewProperty) {
_propertyId += numStoredProperties;
}
// Ensure the item is for a valid property
if (_propertyId >= properties.length) {
revert INVALID_PROPERTY_SELECTED(_propertyId);
}
// Get the pointer to the other items for the property
Item[] storage items = properties[_propertyId].items;
// Append storage space
items.push();
// Get the index of the new item
// Cannot underflow as the items array length is ensured to be at least 1
uint256 newItemIndex = items.length - 1;
// Store the new item
Item storage newItem = items[newItemIndex];
// Store the new item's name and reference slot
newItem.name = _items[i].name;
newItem.referenceSlot = uint16(dataLength);
}
}
}
/// ///
/// ATTRIBUTE GENERATION ///
/// ///
/// @notice Generates attributes for a token upon mint
/// @param _tokenId The ERC-721 token id
function onMinted(uint256 _tokenId) external override returns (bool) {
// Ensure the caller is the token contract
if (msg.sender != settings.token) revert ONLY_TOKEN();
// Compute some randomness for the token id
uint256 seed = _generateSeed(_tokenId);
// Get the pointer to store generated attributes
uint16[16] storage tokenAttributes = attributes[_tokenId];
// Cache the total number of properties available
uint256 numProperties = properties.length;
if (numProperties == 0) {
return false;
}
// Store the total as reference in the first slot of the token's array of attributes
tokenAttributes[0] = uint16(numProperties);
unchecked {
// For each property:
for (uint256 i = 0; i < numProperties; ++i) {
// Get the number of items to choose from
uint256 numItems = properties[i].items.length;
// Use the token's seed to select an item
tokenAttributes[i + 1] = uint16(seed % numItems);
// Adjust the randomness
seed >>= 16;
}
}
return true;
}
/// @notice The properties and query string for a generated token
/// @param _tokenId The ERC-721 token id
function getAttributes(uint256 _tokenId) public view returns (string memory resultAttributes, string memory queryString) {
// Get the token's query string
queryString = string.concat(
"?contractAddress=",
Strings.toHexString(uint256(uint160(address(this))), 20),
"&tokenId=",
Strings.toString(_tokenId)
);
// Get the token's generated attributes
uint16[16] memory tokenAttributes = attributes[_tokenId];
// Cache the number of properties when the token was minted
uint256 numProperties = tokenAttributes[0];
// Ensure the given token was minted
if (numProperties == 0) revert TOKEN_NOT_MINTED(_tokenId);
// Get an array to store the token's generated attribtues
MetadataBuilder.JSONItem[] memory arrayAttributesItems = new MetadataBuilder.JSONItem[](numProperties);
unchecked {
// For each of the token's properties:
for (uint256 i = 0; i < numProperties; ++i) {
// Get its name and list of associated items
Property memory property = properties[i];
// Get the randomly generated index of the item to select for this token
uint256 attribute = tokenAttributes[i + 1];
// Get the associated item data
Item memory item = property.items[attribute];
// Store the encoded attributes and query string
MetadataBuilder.JSONItem memory itemJSON = arrayAttributesItems[i];
itemJSON.key = property.name;
itemJSON.value = item.name;
itemJSON.quote = true;
queryString = string.concat(queryString, "&images=", _getItemImage(item, property.name));
}
resultAttributes = MetadataBuilder.generateJSON(arrayAttributesItems);
}
}
/// @dev Generates a psuedo-random seed for a token id
function _generateSeed(uint256 _tokenId) private view returns (uint256) {
return uint256(keccak256(abi.encode(_tokenId, blockhash(block.number), block.coinbase, block.timestamp)));
}
/// @dev Encodes the reference URI of an item
function _getItemImage(Item memory _item, string memory _propertyName) private view returns (string memory) {
return
UriEncode.uriEncode(
string(
abi.encodePacked(ipfsData[_item.referenceSlot].baseUri, _propertyName, "/", _item.name, ipfsData[_item.referenceSlot].extension)
)
);
}
/// ///
/// URIs ///
/// ///
/// @notice Internal getter function for token name
function _name() internal view returns (string memory) {
return ERC721(settings.token).name();
}
/// @notice The contract URI
function contractURI() external view override returns (string memory) {
MetadataBuilder.JSONItem[] memory items = new MetadataBuilder.JSONItem[](4);
items[0] = MetadataBuilder.JSONItem({ key: MetadataJSONKeys.keyName, value: _name(), quote: true });
items[1] = MetadataBuilder.JSONItem({ key: MetadataJSONKeys.keyDescription, value: settings.description, quote: true });
items[2] = MetadataBuilder.JSONItem({ key: MetadataJSONKeys.keyImage, value: settings.contractImage, quote: true });
items[3] = MetadataBuilder.JSONItem({ key: "external_url", value: settings.projectURI, quote: true });
return MetadataBuilder.generateEncodedJSON(items);
}
/// @notice The token URI
/// @param _tokenId The ERC-721 token id
function tokenURI(uint256 _tokenId) external view returns (string memory) {
(string memory _attributes, string memory queryString) = getAttributes(_tokenId);
MetadataBuilder.JSONItem[] memory items = new MetadataBuilder.JSONItem[](4 + additionalTokenProperties.length);
items[0] = MetadataBuilder.JSONItem({
key: MetadataJSONKeys.keyName,
value: string.concat(_name(), " #", Strings.toString(_tokenId)),
quote: true
});
items[1] = MetadataBuilder.JSONItem({ key: MetadataJSONKeys.keyDescription, value: settings.description, quote: true });
items[2] = MetadataBuilder.JSONItem({
key: MetadataJSONKeys.keyImage,
value: string.concat(settings.rendererBase, queryString),
quote: true
});
items[3] = MetadataBuilder.JSONItem({ key: MetadataJSONKeys.keyProperties, value: _attributes, quote: false });
for (uint256 i = 0; i < additionalTokenProperties.length; i++) {
AdditionalTokenProperty memory tokenProperties = additionalTokenProperties[i];
items[4 + i] = MetadataBuilder.JSONItem({ key: tokenProperties.key, value: tokenProperties.value, quote: tokenProperties.quote });
}
return MetadataBuilder.generateEncodedJSON(items);
}
/// ///
/// METADATA SETTINGS ///
/// ///
/// @notice The associated ERC-721 token
function token() external view returns (address) {
return settings.token;
}
/// @notice The contract image
function contractImage() external view returns (string memory) {
return settings.contractImage;
}
/// @notice The renderer base
function rendererBase() external view returns (string memory) {
return settings.rendererBase;
}
/// @notice The collection description
function description() external view returns (string memory) {
return settings.description;
}
/// @notice The collection description
function projectURI() external view returns (string memory) {
return settings.projectURI;
}
/// @notice Get the owner of the metadata (here delegated to the token owner)
function owner() public view returns (address) {
return IOwnable(settings.token).owner();
}
/// ///
/// UPDATE SETTINGS ///
/// ///
/// @notice Updates the contract image
/// @param _newContractImage The new contract image
function updateContractImage(string memory _newContractImage) external onlyOwner {
emit ContractImageUpdated(settings.contractImage, _newContractImage);
settings.contractImage = _newContractImage;
}
/// @notice Updates the renderer base
/// @param _newRendererBase The new renderer base
function updateRendererBase(string memory _newRendererBase) external onlyOwner {
emit RendererBaseUpdated(settings.rendererBase, _newRendererBase);
settings.rendererBase = _newRendererBase;
}
/// @notice Updates the collection description
/// @param _newDescription The new description
function updateDescription(string memory _newDescription) external onlyOwner {
emit DescriptionUpdated(settings.description, _newDescription);
settings.description = _newDescription;
}
function updateProjectURI(string memory _newProjectURI) external onlyOwner {
emit WebsiteURIUpdated(settings.projectURI, _newProjectURI);
settings.projectURI = _newProjectURI;
}
/// ///
/// METADATA UPGRADE ///
/// ///
/// @notice Ensures the caller is authorized to upgrade the contract to a valid implementation
/// @dev This function is called in UUPS `upgradeTo` & `upgradeToAndCall`
/// @param _impl The address of the new implementation
function _authorizeUpgrade(address _impl) internal view override onlyOwner {
if (!manager.isRegisteredUpgrade(_getImplementation(), _impl)) revert INVALID_UPGRADE(_impl);
}
}
node_modules/@openzeppelin/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
node_modules/@openzeppelin/contracts/utils/Base64.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides a set of functions to operate with Base64 strings.
*
* _Available since v4.5._
*/
library Base64 {
/**
* @dev Base64 Encoding/Decoding Table
*/
string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* @dev Converts a `bytes` to its Bytes64 `string` representation.
*/
function encode(bytes memory data) internal pure returns (string memory) {
/**
* Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
* https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
*/
if (data.length == 0) return "";
// Loads the table into memory
string memory table = _TABLE;
// Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
// and split into 4 numbers of 6 bits.
// The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
// - `data.length + 2` -> Round up
// - `/ 3` -> Number of 3-bytes chunks
// - `4 *` -> 4 characters for each chunk
string memory result = new string(4 * ((data.length + 2) / 3));
/// @solidity memory-safe-assembly
assembly {
// Prepare the lookup table (skip the first "length" byte)
let tablePtr := add(table, 1)
// Prepare result pointer, jump over length
let resultPtr := add(result, 32)
// Run over the input, 3 bytes at a time
for {
let dataPtr := data
let endPtr := add(data, mload(data))
} lt(dataPtr, endPtr) {
} {
// Advance 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// To write each character, shift the 3 bytes (18 bits) chunk
// 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
// and apply logical AND with 0x3F which is the number of
// the previous character in the ASCII table prior to the Base64 Table
// The result is then added to the table to get the character to write,
// and finally write it in the result pointer but with a left shift
// of 256 (1 byte) - 8 (1 ASCII char) = 248 bits
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
}
// When data `bytes` is not exactly 3 bytes long
// it is padded with `=` characters at the end
switch mod(mload(data), 3)
case 1 {
mstore8(sub(resultPtr, 1), 0x3d)
mstore8(sub(resultPtr, 2), 0x3d)
}
case 2 {
mstore8(sub(resultPtr, 1), 0x3d)
}
}
return result;
}
}
node_modules/@openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
}
node_modules/@openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}
node_modules/micro-onchain-metadata-utils/src/MetadataBuilder.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
import {Base64} from "./lib/Base64.sol";
import {Strings} from "./lib/Strings.sol";
import {MetadataMIMETypes} from "./MetadataMIMETypes.sol";
library MetadataBuilder {
struct JSONItem {
string key;
string value;
bool quote;
}
function generateSVG(
string memory contents,
string memory viewBox,
string memory width,
string memory height
) internal pure returns (string memory) {
return
string.concat(
'<svg viewBox="',
viewBox,
'" xmlns="http://www.w3.org/2000/svg" width="',
width,
'" height="',
height,
'">',
contents,
"</svg>"
);
}
/// @notice prefer to use properties with key-value object instead of list
function generateAttributes(string memory displayType, string memory traitType, string memory value) internal pure returns (string memory) {
}
function generateEncodedSVG(
string memory contents,
string memory viewBox,
string memory width,
string memory height
) internal pure returns (string memory) {
return
encodeURI(
MetadataMIMETypes.mimeSVG,
generateSVG(contents, viewBox, width, height)
);
}
function encodeURI(string memory uriType, string memory result)
internal
pure
returns (string memory)
{
return
string.concat(
"data:",
uriType,
";base64,",
string(Base64.encode(bytes(result)))
);
}
function generateJSONArray(JSONItem[] memory items)
internal
pure
returns (string memory result)
{
result = "[";
uint256 added = 0;
for (uint256 i = 0; i < items.length; i++) {
if (bytes(items[i].value).length == 0) {
continue;
}
if (items[i].quote) {
result = string.concat(
result,
added == 0 ? "" : ",",
'"',
items[i].value,
'"'
);
} else {
result = string.concat(
result,
added == 0 ? "" : ",",
items[i].value
);
}
added += 1;
}
result = string.concat(result, "]");
}
function generateJSON(JSONItem[] memory items)
internal
pure
returns (string memory result)
{
result = "{";
uint256 added = 0;
for (uint256 i = 0; i < items.length; i++) {
if (bytes(items[i].value).length == 0) {
continue;
}
if (items[i].quote) {
result = string.concat(
result,
added == 0 ? "" : ",",
'"',
items[i].key,
'": "',
items[i].value,
'"'
);
} else {
result = string.concat(
result,
added == 0 ? "" : ",",
'"',
items[i].key,
'": ',
items[i].value
);
}
added += 1;
}
result = string.concat(result, "}");
}
function generateEncodedJSON(JSONItem[] memory items)
internal
pure
returns (string memory)
{
return encodeURI(MetadataMIMETypes.mimeJSON, generateJSON(items));
}
}
node_modules/micro-onchain-metadata-utils/src/MetadataJSONKeys.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
library MetadataJSONKeys {
string constant keyName = "name";
string constant keyDescription = "description";
string constant keyImage = "image";
string constant keyAnimationURL = "animation_url";
string constant keyAttributes = "attributes";
string constant keyProperties = "properties";
}node_modules/micro-onchain-metadata-utils/src/MetadataMIMETypes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
library MetadataMIMETypes {
string constant mimeJSON = "application/json";
string constant mimeSVG = "image/svg+xml";
string constant mimeTextPlain = "text/plain";
}
node_modules/micro-onchain-metadata-utils/src/lib/Base64.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides a set of functions to operate with Base64 strings.
*
* _Available since v4.5._
*/
library Base64 {
/**
* @dev Base64 Encoding/Decoding Table
*/
string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* @dev Converts a `bytes` to its Bytes64 `string` representation.
*/
function encode(bytes memory data) internal pure returns (string memory) {
/**
* Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
* https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
*/
if (data.length == 0) return "";
// Loads the table into memory
string memory table = _TABLE;
// Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
// and split into 4 numbers of 6 bits.
// The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
// - `data.length + 2` -> Round up
// - `/ 3` -> Number of 3-bytes chunks
// - `4 *` -> 4 characters for each chunk
string memory result = new string(4 * ((data.length + 2) / 3));
/// @solidity memory-safe-assembly
assembly {
// Prepare the lookup table (skip the first "length" byte)
let tablePtr := add(table, 1)
// Prepare result pointer, jump over length
let resultPtr := add(result, 32)
// Run over the input, 3 bytes at a time
for {
let dataPtr := data
let endPtr := add(data, mload(data))
} lt(dataPtr, endPtr) {
} {
// Advance 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// To write each character, shift the 3 bytes (18 bits) chunk
// 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
// and apply logical AND with 0x3F which is the number of
// the previous character in the ASCII table prior to the Base64 Table
// The result is then added to the table to get the character to write,
// and finally write it in the result pointer but with a left shift
// of 256 (1 byte) - 8 (1 ASCII char) = 248 bits
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
}
// When data `bytes` is not exactly 3 bytes long
// it is padded with `=` characters at the end
switch mod(mload(data), 3)
case 1 {
mstore8(sub(resultPtr, 1), 0x3d)
mstore8(sub(resultPtr, 2), 0x3d)
}
case 2 {
mstore8(sub(resultPtr, 1), 0x3d)
}
}
return result;
}
}
node_modules/micro-onchain-metadata-utils/src/lib/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}
node_modules/sol-uriencode/src/UriEncode.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
library UriEncode {
string internal constant _TABLE = "0123456789abcdef";
function uriEncode(string memory uri)
internal
pure
returns (string memory)
{
bytes memory bytesUri = bytes(uri);
string memory table = _TABLE;
// Max size is worse case all chars need to be encoded
bytes memory result = new bytes(3 * bytesUri.length);
/// @solidity memory-safe-assembly
assembly {
// Get the lookup table
let tablePtr := add(table, 1)
// Prepare result pointer, jump over length
let resultPtr := add(result, 32)
// Keep track of the final result size string length
let resultSize := 0
for {
let dataPtr := bytesUri
let endPtr := add(bytesUri, mload(bytesUri))
} lt(dataPtr, endPtr) {
} {
// advance 1 byte
dataPtr := add(dataPtr, 1)
// bytemask out a char
let input := and(mload(dataPtr), 255)
// Check if is valid URI character
let isValidUriChar := or(
and(gt(input, 96), lt(input, 134)), // a 97 / z 133
or(
and(gt(input, 64), lt(input, 91)), // A 65 / Z 90
or(
and(gt(input, 47), lt(input, 58)), // 0 48 / 9 57
or(
or(
eq(input, 46), // . 46
eq(input, 95) // _ 95
),
or(
eq(input, 45), // - 45
eq(input, 126) // ~ 126
)
)
)
)
)
switch isValidUriChar
// If is valid uri character copy character over and increment the result
case 1 {
mstore8(resultPtr, input)
resultPtr := add(resultPtr, 1)
resultSize := add(resultSize, 1)
}
// If the char is not a valid uri character, uriencode the character
case 0 {
mstore8(resultPtr, 37)
resultPtr := add(resultPtr, 1)
// table[character >> 4] (take the last 4 bits)
mstore8(resultPtr, mload(add(tablePtr, shr(4, input))))
resultPtr := add(resultPtr, 1)
// table & 15 (take the first 4 bits)
mstore8(resultPtr, mload(add(tablePtr, and(input, 15))))
resultPtr := add(resultPtr, 1)
resultSize := add(resultSize, 3)
}
}
// Set size of result string in memory
mstore(result, resultSize)
}
return string(result);
}
}
src/VersionedContract.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
abstract contract VersionedContract {
function contractVersion() external pure returns (string memory) {
return "1.2.0";
}
}
src/lib/interfaces/IEIP712.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
/// @title IEIP712
/// @author Rohan Kulkarni
/// @notice The external EIP712 errors and functions
interface IEIP712 {
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if the deadline has passed to submit a signature
error EXPIRED_SIGNATURE();
/// @dev Reverts if the recovered signature is invalid
error INVALID_SIGNATURE();
/// ///
/// FUNCTIONS ///
/// ///
/// @notice The sig nonce for an account
/// @param account The account address
function nonce(address account) external view returns (uint256);
/// @notice The EIP-712 domain separator
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
src/lib/interfaces/IERC1967Upgrade.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
/// @title IERC1967Upgrade
/// @author Rohan Kulkarni
/// @notice The external ERC1967Upgrade events and errors
interface IERC1967Upgrade {
/// ///
/// EVENTS ///
/// ///
/// @notice Emitted when the implementation is upgraded
/// @param impl The address of the implementation
event Upgraded(address impl);
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if an implementation is an invalid upgrade
/// @param impl The address of the invalid implementation
error INVALID_UPGRADE(address impl);
/// @dev Reverts if an implementation upgrade is not stored at the storage slot of the original
error UNSUPPORTED_UUID();
/// @dev Reverts if an implementation does not support ERC1822 proxiableUUID()
error ONLY_UUPS();
}
src/lib/interfaces/IERC721.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
/// @title IERC721
/// @author Rohan Kulkarni
/// @notice The external ERC721 events, errors, and functions
interface IERC721 {
/// ///
/// EVENTS ///
/// ///
/// @notice Emitted when a token is transferred from sender to recipient
/// @param from The sender address
/// @param to The recipient address
/// @param tokenId The ERC-721 token id
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/// @notice Emitted when an owner approves an account to manage a token
/// @param owner The owner address
/// @param approved The account address
/// @param tokenId The ERC-721 token id
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/// @notice Emitted when an owner sets an approval for a spender to manage all tokens
/// @param owner The owner address
/// @param operator The spender address
/// @param approved If the approval is being set or removed
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if a caller is not authorized to approve or transfer a token
error INVALID_APPROVAL();
/// @dev Reverts if a transfer is called with the incorrect token owner
error INVALID_OWNER();
/// @dev Reverts if a transfer is attempted to address(0)
error INVALID_RECIPIENT();
/// @dev Reverts if an existing token is called to be minted
error ALREADY_MINTED();
/// @dev Reverts if a non-existent token is called to be burned
error NOT_MINTED();
/// ///
/// FUNCTIONS ///
/// ///
/// @notice The number of tokens owned
/// @param owner The owner address
function balanceOf(address owner) external view returns (uint256);
/// @notice The owner of a token
/// @param tokenId The ERC-721 token id
function ownerOf(uint256 tokenId) external view returns (address);
/// @notice The account approved to manage a token
/// @param tokenId The ERC-721 token id
function getApproved(uint256 tokenId) external view returns (address);
/// @notice If an operator is authorized to manage all of an owner's tokens
/// @param owner The owner address
/// @param operator The operator address
function isApprovedForAll(address owner, address operator) external view returns (bool);
/// @notice Authorizes an account to manage a token
/// @param to The account address
/// @param tokenId The ERC-721 token id
function approve(address to, uint256 tokenId) external;
/// @notice Authorizes an account to manage all tokens
/// @param operator The account address
/// @param approved If permission is being given or removed
function setApprovalForAll(address operator, bool approved) external;
/// @notice Safe transfers a token from sender to recipient with additional data
/// @param from The sender address
/// @param to The recipient address
/// @param tokenId The ERC-721 token id
/// @param data The additional data sent in the call to the recipient
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
/// @notice Safe transfers a token from sender to recipient
/// @param from The sender address
/// @param to The recipient address
/// @param tokenId The ERC-721 token id
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/// @notice Transfers a token from sender to recipient
/// @param from The sender address
/// @param to The recipient address
/// @param tokenId The ERC-721 token id
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
}
src/lib/interfaces/IERC721Votes.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
import { IERC721 } from "./IERC721.sol";
import { IEIP712 } from "./IEIP712.sol";
/// @title IERC721Votes
/// @author Rohan Kulkarni
/// @notice The external ERC721Votes events, errors, and functions
interface IERC721Votes is IERC721, IEIP712 {
/// ///
/// EVENTS ///
/// ///
/// @notice Emitted when an account changes their delegate
event DelegateChanged(address indexed delegator, address indexed from, address indexed to);
/// @notice Emitted when a delegate's number of votes is updated
event DelegateVotesChanged(address indexed delegate, uint256 prevTotalVotes, uint256 newTotalVotes);
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if the timestamp provided isn't in the past
error INVALID_TIMESTAMP();
/// ///
/// STRUCTS ///
/// ///
/// @notice The checkpoint data type
/// @param timestamp The recorded timestamp
/// @param votes The voting weight
struct Checkpoint {
uint64 timestamp;
uint192 votes;
}
/// ///
/// FUNCTIONS ///
/// ///
/// @notice The current number of votes for an account
/// @param account The account address
function getVotes(address account) external view returns (uint256);
/// @notice The number of votes for an account at a past timestamp
/// @param account The account address
/// @param timestamp The past timestamp
function getPastVotes(address account, uint256 timestamp) external view returns (uint256);
/// @notice The delegate for an account
/// @param account The account address
function delegates(address account) external view returns (address);
/// @notice Delegates votes to an account
/// @param to The address delegating votes to
function delegate(address to) external;
/// @notice Delegates votes from a signer to an account
/// @param from The address delegating votes from
/// @param to The address delegating votes to
/// @param deadline The signature deadline
/// @param v The 129th byte and chain id of the signature
/// @param r The first 64 bytes of the signature
/// @param s Bytes 64-128 of the signature
function delegateBySig(
address from,
address to,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
src/lib/interfaces/IInitializable.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
/// @title IInitializable
/// @author Rohan Kulkarni
/// @notice The external Initializable events and errors
interface IInitializable {
/// ///
/// EVENTS ///
/// ///
/// @notice Emitted when the contract has been initialized or reinitialized
event Initialized(uint256 version);
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if incorrectly initialized with address(0)
error ADDRESS_ZERO();
/// @dev Reverts if disabling initializers during initialization
error INITIALIZING();
/// @dev Reverts if calling an initialization function outside of initialization
error NOT_INITIALIZING();
/// @dev Reverts if reinitializing incorrectly
error ALREADY_INITIALIZED();
}
src/lib/interfaces/IOwnable.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
/// @title IOwnable
/// @author Rohan Kulkarni
/// @notice The external Ownable events, errors, and functions
interface IOwnable {
/// ///
/// EVENTS ///
/// ///
/// @notice Emitted when ownership has been updated
/// @param prevOwner The previous owner address
/// @param newOwner The new owner address
event OwnerUpdated(address indexed prevOwner, address indexed newOwner);
/// @notice Emitted when an ownership transfer is pending
/// @param owner The current owner address
/// @param pendingOwner The pending new owner address
event OwnerPending(address indexed owner, address indexed pendingOwner);
/// @notice Emitted when a pending ownership transfer has been canceled
/// @param owner The current owner address
/// @param canceledOwner The canceled owner address
event OwnerCanceled(address indexed owner, address indexed canceledOwner);
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if an unauthorized user calls an owner function
error ONLY_OWNER();
/// @dev Reverts if an unauthorized user calls a pending owner function
error ONLY_PENDING_OWNER();
/// ///
/// FUNCTIONS ///
/// ///
/// @notice The address of the owner
function owner() external view returns (address);
/// @notice The address of the pending owner
function pendingOwner() external view returns (address);
/// @notice Forces an ownership transfer
/// @param newOwner The new owner address
function transferOwnership(address newOwner) external;
/// @notice Initiates a two-step ownership transfer
/// @param newOwner The new owner address
function safeTransferOwnership(address newOwner) external;
/// @notice Accepts an ownership transfer
function acceptOwnership() external;
/// @notice Cancels a pending ownership transfer
function cancelOwnershipTransfer() external;
}
src/lib/interfaces/IUUPS.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
import { IERC1822Proxiable } from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import { IERC1967Upgrade } from "./IERC1967Upgrade.sol";
/// @title IUUPS
/// @author Rohan Kulkarni
/// @notice The external UUPS errors and functions
interface IUUPS is IERC1967Upgrade, IERC1822Proxiable {
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if not called directly
error ONLY_CALL();
/// @dev Reverts if not called via delegatecall
error ONLY_DELEGATECALL();
/// @dev Reverts if not called via proxy
error ONLY_PROXY();
/// ///
/// FUNCTIONS ///
/// ///
/// @notice Upgrades to an implementation
/// @param newImpl The new implementation address
function upgradeTo(address newImpl) external;
/// @notice Upgrades to an implementation with an additional function call
/// @param newImpl The new implementation address
/// @param data The encoded function call
function upgradeToAndCall(address newImpl, bytes memory data) external payable;
}
src/lib/proxy/ERC1967Upgrade.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
import { IERC1822Proxiable } from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import { StorageSlot } from "@openzeppelin/contracts/utils/StorageSlot.sol";
import { IERC1967Upgrade } from "../interfaces/IERC1967Upgrade.sol";
import { Address } from "../utils/Address.sol";
/// @title ERC1967Upgrade
/// @author Rohan Kulkarni
/// @notice Modified from OpenZeppelin Contracts v4.7.3 (proxy/ERC1967/ERC1967Upgrade.sol)
/// - Uses custom errors declared in IERC1967Upgrade
/// - Removes ERC1967 admin and beacon support
abstract contract ERC1967Upgrade is IERC1967Upgrade {
/// ///
/// CONSTANTS ///
/// ///
/// @dev bytes32(uint256(keccak256('eip1967.proxy.rollback')) - 1)
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/// @dev bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/// ///
/// FUNCTIONS ///
/// ///
/// @dev Upgrades to an implementation with security checks for UUPS proxies and an additional function call
/// @param _newImpl The new implementation address
/// @param _data The encoded function call
function _upgradeToAndCallUUPS(
address _newImpl,
bytes memory _data,
bool _forceCall
) internal {
if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(_newImpl);
} else {
try IERC1822Proxiable(_newImpl).proxiableUUID() returns (bytes32 slot) {
if (slot != _IMPLEMENTATION_SLOT) revert UNSUPPORTED_UUID();
} catch {
revert ONLY_UUPS();
}
_upgradeToAndCall(_newImpl, _data, _forceCall);
}
}
/// @dev Upgrades to an implementation with an additional function call
/// @param _newImpl The new implementation address
/// @param _data The encoded function call
function _upgradeToAndCall(
address _newImpl,
bytes memory _data,
bool _forceCall
) internal {
_upgradeTo(_newImpl);
if (_data.length > 0 || _forceCall) {
Address.functionDelegateCall(_newImpl, _data);
}
}
/// @dev Performs an implementation upgrade
/// @param _newImpl The new implementation address
function _upgradeTo(address _newImpl) internal {
_setImplementation(_newImpl);
emit Upgraded(_newImpl);
}
/// @dev Stores the address of an implementation
/// @param _impl The implementation address
function _setImplementation(address _impl) private {
if (!Address.isContract(_impl)) revert INVALID_UPGRADE(_impl);
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = _impl;
}
/// @dev The address of the current implementation
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
}
src/lib/proxy/UUPS.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
import { IUUPS } from "../interfaces/IUUPS.sol";
import { ERC1967Upgrade } from "./ERC1967Upgrade.sol";
/// @title UUPS
/// @author Rohan Kulkarni
/// @notice Modified from OpenZeppelin Contracts v4.7.3 (proxy/utils/UUPSUpgradeable.sol)
/// - Uses custom errors declared in IUUPS
/// - Inherits a modern, minimal ERC1967Upgrade
abstract contract UUPS is IUUPS, ERC1967Upgrade {
/// ///
/// IMMUTABLES ///
/// ///
/// @dev The address of the implementation
address private immutable __self = address(this);
/// ///
/// MODIFIERS ///
/// ///
/// @dev Ensures that execution is via proxy delegatecall with the correct implementation
modifier onlyProxy() {
if (address(this) == __self) revert ONLY_DELEGATECALL();
if (_getImplementation() != __self) revert ONLY_PROXY();
_;
}
/// @dev Ensures that execution is via direct call
modifier notDelegated() {
if (address(this) != __self) revert ONLY_CALL();
_;
}
/// ///
/// FUNCTIONS ///
/// ///
/// @dev Hook to authorize an implementation upgrade
/// @param _newImpl The new implementation address
function _authorizeUpgrade(address _newImpl) internal virtual;
/// @notice Upgrades to an implementation
/// @param _newImpl The new implementation address
function upgradeTo(address _newImpl) external onlyProxy {
_authorizeUpgrade(_newImpl);
_upgradeToAndCallUUPS(_newImpl, "", false);
}
/// @notice Upgrades to an implementation with an additional function call
/// @param _newImpl The new implementation address
/// @param _data The encoded function call
function upgradeToAndCall(address _newImpl, bytes memory _data) external payable onlyProxy {
_authorizeUpgrade(_newImpl);
_upgradeToAndCallUUPS(_newImpl, _data, true);
}
/// @notice The storage slot of the implementation address
function proxiableUUID() external view notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
}
src/lib/token/ERC721.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
import { IERC721 } from "../interfaces/IERC721.sol";
import { Initializable } from "../utils/Initializable.sol";
import { ERC721TokenReceiver } from "../utils/TokenReceiver.sol";
import { Address } from "../utils/Address.sol";
/// @title ERC721
/// @author Rohan Kulkarni
/// @notice Modified from OpenZeppelin Contracts v4.7.3 (token/ERC721/ERC721Upgradeable.sol)
/// - Uses custom errors declared in IERC721
abstract contract ERC721 is IERC721, Initializable {
/// ///
/// STORAGE ///
/// ///
/// @notice The token name
string public name;
/// @notice The token symbol
string public symbol;
/// @notice The token owners
/// @dev ERC-721 token id => Owner
mapping(uint256 => address) internal owners;
/// @notice The owner balances
/// @dev Owner => Balance
mapping(address => uint256) internal balances;
/// @notice The token approvals
/// @dev ERC-721 token id => Manager
mapping(uint256 => address) internal tokenApprovals;
/// @notice The balance approvals
/// @dev Owner => Operator => Approved
mapping(address => mapping(address => bool)) internal operatorApprovals;
/// ///
/// FUNCTIONS ///
/// ///
/// @dev Initializes an ERC-721 token
/// @param _name The ERC-721 token name
/// @param _symbol The ERC-721 token symbol
function __ERC721_init(string memory _name, string memory _symbol) internal onlyInitializing {
name = _name;
symbol = _symbol;
}
/// @notice The token URI
/// @param _tokenId The ERC-721 token id
function tokenURI(uint256 _tokenId) public view virtual returns (string memory) {}
/// @notice The contract URI
function contractURI() public view virtual returns (string memory) {}
/// @notice If the contract implements an interface
/// @param _interfaceId The interface id
function supportsInterface(bytes4 _interfaceId) external pure returns (bool) {
return
_interfaceId == 0x01ffc9a7 || // ERC165 Interface ID
_interfaceId == 0x80ac58cd || // ERC721 Interface ID
_interfaceId == 0x5b5e139f; // ERC721Metadata Interface ID
}
/// @notice The account approved to manage a token
/// @param _tokenId The ERC-721 token id
function getApproved(uint256 _tokenId) external view returns (address) {
return tokenApprovals[_tokenId];
}
/// @notice If an operator is authorized to manage all of an owner's tokens
/// @param _owner The owner address
/// @param _operator The operator address
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/// @notice The number of tokens owned
/// @param _owner The owner address
function balanceOf(address _owner) public view returns (uint256) {
if (_owner == address(0)) revert ADDRESS_ZERO();
return balances[_owner];
}
/// @notice The owner of a token
/// @param _tokenId The ERC-721 token id
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = owners[_tokenId];
if (owner == address(0)) revert INVALID_OWNER();
return owner;
}
/// @notice Authorizes an account to manage a token
/// @param _to The account address
/// @param _tokenId The ERC-721 token id
function approve(address _to, uint256 _tokenId) external {
address owner = owners[_tokenId];
if (msg.sender != owner && !operatorApprovals[owner][msg.sender]) revert INVALID_APPROVAL();
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/// @notice Authorizes an account to manage all tokens
/// @param _operator The account address
/// @param _approved If permission is being given or removed
function setApprovalForAll(address _operator, bool _approved) external {
operatorApprovals[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/// @notice Transfers a token from sender to recipient
/// @param _from The sender address
/// @param _to The recipient address
/// @param _tokenId The ERC-721 token id
function transferFrom(
address _from,
address _to,
uint256 _tokenId
) public {
if (_from != owners[_tokenId]) revert INVALID_OWNER();
if (_to == address(0)) revert ADDRESS_ZERO();
if (msg.sender != _from && !operatorApprovals[_from][msg.sender] && msg.sender != tokenApprovals[_tokenId]) revert INVALID_APPROVAL();
_beforeTokenTransfer(_from, _to, _tokenId);
unchecked {
--balances[_from];
++balances[_to];
}
owners[_tokenId] = _to;
delete tokenApprovals[_tokenId];
emit Transfer(_from, _to, _tokenId);
_afterTokenTransfer(_from, _to, _tokenId);
}
/// @notice Safe transfers a token from sender to recipient
/// @param _from The sender address
/// @param _to The recipient address
/// @param _tokenId The ERC-721 token id
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
) external {
transferFrom(_from, _to, _tokenId);
if (
Address.isContract(_to) &&
ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, "") != ERC721TokenReceiver.onERC721Received.selector
) revert INVALID_RECIPIENT();
}
/// @notice Safe transfers a token from sender to recipient with additional data
/// @param _from The sender address
/// @param _to The recipient address
/// @param _tokenId The ERC-721 token id
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
) external {
transferFrom(_from, _to, _tokenId);
if (
Address.isContract(_to) &&
ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data) != ERC721TokenReceiver.onERC721Received.selector
) revert INVALID_RECIPIENT();
}
/// @dev Mints a token to a recipient
/// @param _to The recipient address
/// @param _tokenId The ERC-721 token id
function _mint(address _to, uint256 _tokenId) internal virtual {
if (_to == address(0)) revert ADDRESS_ZERO();
if (owners[_tokenId] != address(0)) revert ALREADY_MINTED();
_beforeTokenTransfer(address(0), _to, _tokenId);
unchecked {
++balances[_to];
}
owners[_tokenId] = _to;
emit Transfer(address(0), _to, _tokenId);
_afterTokenTransfer(address(0), _to, _tokenId);
}
/// @dev Burns a token to a recipient
/// @param _tokenId The ERC-721 token id
function _burn(uint256 _tokenId) internal virtual {
address owner = owners[_tokenId];
if (owner == address(0)) revert NOT_MINTED();
_beforeTokenTransfer(owner, address(0), _tokenId);
unchecked {
--balances[owner];
}
delete owners[_tokenId];
delete tokenApprovals[_tokenId];
emit Transfer(owner, address(0), _tokenId);
_afterTokenTransfer(owner, address(0), _tokenId);
}
/// @dev Hook called before a token transfer
/// @param _from The sender address
/// @param _to The recipient address
/// @param _tokenId The ERC-721 token id
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _tokenId
) internal virtual {}
/// @dev Hook called after a token transfer
/// @param _from The sender address
/// @param _to The recipient address
/// @param _tokenId The ERC-721 token id
function _afterTokenTransfer(
address _from,
address _to,
uint256 _tokenId
) internal virtual {}
}
src/lib/utils/Address.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
/// @title EIP712
/// @author Rohan Kulkarni
/// @notice Modified from OpenZeppelin Contracts v4.7.3 (utils/Address.sol)
/// - Uses custom errors `INVALID_TARGET()` & `DELEGATE_CALL_FAILED()`
/// - Adds util converting address to bytes32
library Address {
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if the target of a delegatecall is not a contract
error INVALID_TARGET();
/// @dev Reverts if a delegatecall has failed
error DELEGATE_CALL_FAILED();
/// ///
/// FUNCTIONS ///
/// ///
/// @dev Utility to convert an address to bytes32
function toBytes32(address _account) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_account)) << 96);
}
/// @dev If an address is a contract
function isContract(address _account) internal view returns (bool rv) {
assembly {
rv := gt(extcodesize(_account), 0)
}
}
/// @dev Performs a delegatecall on an address
function functionDelegateCall(address _target, bytes memory _data) internal returns (bytes memory) {
if (!isContract(_target)) revert INVALID_TARGET();
(bool success, bytes memory returndata) = _target.delegatecall(_data);
return verifyCallResult(success, returndata);
}
/// @dev Verifies a delegatecall was successful
function verifyCallResult(bool _success, bytes memory _returndata) internal pure returns (bytes memory) {
if (_success) {
return _returndata;
} else {
if (_returndata.length > 0) {
assembly {
let returndata_size := mload(_returndata)
revert(add(32, _returndata), returndata_size)
}
} else {
revert DELEGATE_CALL_FAILED();
}
}
}
}
src/lib/utils/Initializable.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
import { IInitializable } from "../interfaces/IInitializable.sol";
import { Address } from "../utils/Address.sol";
/// @title Initializable
/// @author Rohan Kulkarni
/// @notice Modified from OpenZeppelin Contracts v4.7.3 (proxy/utils/Initializable.sol)
/// - Uses custom errors declared in IInitializable
abstract contract Initializable is IInitializable {
/// ///
/// STORAGE ///
/// ///
/// @dev Indicates the contract has been initialized
uint8 internal _initialized;
/// @dev Indicates the contract is being initialized
bool internal _initializing;
/// ///
/// MODIFIERS ///
/// ///
/// @dev Ensures an initialization function is only called within an `initializer` or `reinitializer` function
modifier onlyInitializing() {
if (!_initializing) revert NOT_INITIALIZING();
_;
}
/// @dev Enables initializing upgradeable contracts
modifier initializer() {
bool isTopLevelCall = !_initializing;
if ((!isTopLevelCall || _initialized != 0) && (Address.isContract(address(this)) || _initialized != 1)) revert ALREADY_INITIALIZED();
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/// @dev Enables initializer versioning
/// @param _version The version to set
modifier reinitializer(uint8 _version) {
if (_initializing || _initialized >= _version) revert ALREADY_INITIALIZED();
_initialized = _version;
_initializing = true;
_;
_initializing = false;
emit Initialized(_version);
}
/// ///
/// FUNCTIONS ///
/// ///
/// @dev Prevents future initialization
function _disableInitializers() internal virtual {
if (_initializing) revert INITIALIZING();
if (_initialized < type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
}
src/lib/utils/TokenReceiver.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Modified from OpenZeppelin Contracts v4.7.3 (token/ERC721/utils/ERC721Holder.sol)
abstract contract ERC721TokenReceiver {
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external virtual returns (bytes4) {
return this.onERC721Received.selector;
}
}
/// @notice Modified from OpenZeppelin Contracts v4.7.3 (token/ERC1155/utils/ERC1155Holder.sol)
abstract contract ERC1155TokenReceiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) external virtual returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
) external virtual returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
src/manager/IManager.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
import { IUUPS } from "../lib/interfaces/IUUPS.sol";
import { IOwnable } from "../lib/interfaces/IOwnable.sol";
/// @title IManager
/// @author Rohan Kulkarni
/// @notice The external Manager events, errors, structs and functions
interface IManager is IUUPS, IOwnable {
/// ///
/// EVENTS ///
/// ///
/// @notice Emitted when a DAO is deployed
/// @param token The ERC-721 token address
/// @param metadata The metadata renderer address
/// @param auction The auction address
/// @param treasury The treasury address
/// @param governor The governor address
event DAODeployed(address token, address metadata, address auction, address treasury, address governor);
/// @notice Emitted when an upgrade is registered by the Builder DAO
/// @param baseImpl The base implementation address
/// @param upgradeImpl The upgrade implementation address
event UpgradeRegistered(address baseImpl, address upgradeImpl);
/// @notice Emitted when an upgrade is unregistered by the Builder DAO
/// @param baseImpl The base implementation address
/// @param upgradeImpl The upgrade implementation address
event UpgradeRemoved(address baseImpl, address upgradeImpl);
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if at least one founder is not provided upon deploy
error FOUNDER_REQUIRED();
/// ///
/// STRUCTS ///
/// ///
/// @notice The founder parameters
/// @param wallet The wallet address
/// @param ownershipPct The percent ownership of the token
/// @param vestExpiry The timestamp that vesting expires
struct FounderParams {
address wallet;
uint256 ownershipPct;
uint256 vestExpiry;
}
/// @notice DAO Version Information information struct
struct DAOVersionInfo {
string token;
string metadata;
string auction;
string treasury;
string governor;
}
/// @notice The ERC-721 token parameters
/// @param initStrings The encoded token name, symbol, collection description, collection image uri, renderer base uri
struct TokenParams {
bytes initStrings;
}
/// @notice The auction parameters
/// @param reservePrice The reserve price of each auction
/// @param duration The duration of each auction
struct AuctionParams {
uint256 reservePrice;
uint256 duration;
}
/// @notice The governance parameters
/// @param timelockDelay The time delay to execute a queued transaction
/// @param votingDelay The time delay to vote on a created proposal
/// @param votingPeriod The time period to vote on a proposal
/// @param proposalThresholdBps The basis points of the token supply required to create a proposal
/// @param quorumThresholdBps The basis points of the token supply required to reach quorum
/// @param vetoer The address authorized to veto proposals (address(0) if none desired)
struct GovParams {
uint256 timelockDelay;
uint256 votingDelay;
uint256 votingPeriod;
uint256 proposalThresholdBps;
uint256 quorumThresholdBps;
address vetoer;
}
/// ///
/// FUNCTIONS ///
/// ///
/// @notice The token implementation address
function tokenImpl() external view returns (address);
/// @notice The metadata renderer implementation address
function metadataImpl() external view returns (address);
/// @notice The auction house implementation address
function auctionImpl() external view returns (address);
/// @notice The treasury implementation address
function treasuryImpl() external view returns (address);
/// @notice The governor implementation address
function governorImpl() external view returns (address);
/// @notice Deploys a DAO with custom token, auction, and governance settings
/// @param founderParams The DAO founder(s)
/// @param tokenParams The ERC-721 token settings
/// @param auctionParams The auction settings
/// @param govParams The governance settings
function deploy(
FounderParams[] calldata founderParams,
TokenParams calldata tokenParams,
AuctionParams calldata auctionParams,
GovParams calldata govParams
)
external
returns (
address token,
address metadataRenderer,
address auction,
address treasury,
address governor
);
/// @notice A DAO's remaining contract addresses from its token address
/// @param token The ERC-721 token address
function getAddresses(address token)
external
returns (
address metadataRenderer,
address auction,
address treasury,
address governor
);
/// @notice If an implementation is registered by the Builder DAO as an optional upgrade
/// @param baseImpl The base implementation address
/// @param upgradeImpl The upgrade implementation address
function isRegisteredUpgrade(address baseImpl, address upgradeImpl) external view returns (bool);
/// @notice Called by the Builder DAO to offer opt-in implementation upgrades for all other DAOs
/// @param baseImpl The base implementation address
/// @param upgradeImpl The upgrade implementation address
function registerUpgrade(address baseImpl, address upgradeImpl) external;
/// @notice Called by the Builder DAO to remove an upgrade
/// @param baseImpl The base implementation address
/// @param upgradeImpl The upgrade implementation address
function removeUpgrade(address baseImpl, address upgradeImpl) external;
}
src/token/IToken.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
import { IUUPS } from "../lib/interfaces/IUUPS.sol";
import { IERC721Votes } from "../lib/interfaces/IERC721Votes.sol";
import { IManager } from "../manager/IManager.sol";
import { TokenTypesV1 } from "./types/TokenTypesV1.sol";
import { TokenTypesV2 } from "./types/TokenTypesV2.sol";
/// @title IToken
/// @author Rohan Kulkarni
/// @notice The external Token events, errors and functions
interface IToken is IUUPS, IERC721Votes, TokenTypesV1, TokenTypesV2 {
/// ///
/// EVENTS ///
/// ///
/// @notice Emitted when a token is scheduled to be allocated
/// @param baseTokenId The
/// @param founderId The founder's id
/// @param founder The founder's vesting details
event MintScheduled(uint256 baseTokenId, uint256 founderId, Founder founder);
/// @notice Emitted when a token allocation is unscheduled (removed)
/// @param baseTokenId The token ID % 100
/// @param founderId The founder's id
/// @param founder The founder's vesting details
event MintUnscheduled(uint256 baseTokenId, uint256 founderId, Founder founder);
/// @notice Emitted when a tokens founders are deleted from storage
/// @param newFounders the list of founders
event FounderAllocationsCleared(IManager.FounderParams[] newFounders);
/// @notice Emitted when minters are updated
/// @param minter Address of added or removed minter
/// @param allowed Whether address is allowed to mint
event MinterUpdated(address minter, bool allowed);
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if the founder ownership exceeds 100 percent
error INVALID_FOUNDER_OWNERSHIP();
/// @dev Reverts if the caller was not the auction contract
error ONLY_AUCTION();
/// @dev Reverts if the caller was not a minter
error ONLY_AUCTION_OR_MINTER();
/// @dev Reverts if the caller was not the token owner
error ONLY_TOKEN_OWNER();
/// @dev Reverts if no metadata was generated upon mint
error NO_METADATA_GENERATED();
/// @dev Reverts if the caller was not the contract manager
error ONLY_MANAGER();
/// ///
/// FUNCTIONS ///
/// ///
/// @notice Initializes a DAO's ERC-721 token
/// @param founders The founding members to receive vesting allocations
/// @param initStrings The encoded token and metadata initialization strings
/// @param metadataRenderer The token's metadata renderer
/// @param auction The token's auction house
function initialize(
IManager.FounderParams[] calldata founders,
bytes calldata initStrings,
address metadataRenderer,
address auction,
address initialOwner
) external;
/// @notice Mints tokens to the caller and handles founder vesting
function mint() external returns (uint256 tokenId);
/// @notice Mints tokens to the recipient and handles founder vesting
function mintTo(address recipient) external returns (uint256 tokenId);
/// @notice Mints the specified amount of tokens to the recipient and handles founder vesting
function mintBatchTo(uint256 amount, address recipient) external returns (uint256[] memory tokenIds);
/// @notice Burns a token owned by the caller
/// @param tokenId The ERC-721 token id
function burn(uint256 tokenId) external;
/// @notice The URI for a token
/// @param tokenId The ERC-721 token id
function tokenURI(uint256 tokenId) external view returns (string memory);
/// @notice The URI for the contract
function contractURI() external view returns (string memory);
/// @notice The number of founders
function totalFounders() external view returns (uint256);
/// @notice The founders total percent ownership
function totalFounderOwnership() external view returns (uint256);
/// @notice The vesting details of a founder
/// @param founderId The founder id
function getFounder(uint256 founderId) external view returns (Founder memory);
/// @notice The vesting details of all founders
function getFounders() external view returns (Founder[] memory);
/// @notice Update the list of allocation owners
/// @param newFounders the full list of FounderParam structs
function updateFounders(IManager.FounderParams[] calldata newFounders) external;
/// @notice The founder scheduled to receive the given token id
/// NOTE: If a founder is returned, there's no guarantee they'll receive the token as vesting expiration is not considered
/// @param tokenId The ERC-721 token id
function getScheduledRecipient(uint256 tokenId) external view returns (Founder memory);
/// @notice The total supply of tokens
function totalSupply() external view returns (uint256);
/// @notice The token's auction house
function auction() external view returns (address);
/// @notice The token's metadata renderer
function metadataRenderer() external view returns (address);
/// @notice The owner of the token and metadata renderer
function owner() external view returns (address);
/// @notice Update minters
/// @param _minters Array of structs containing address status as a minter
function updateMinters(MinterParams[] calldata _minters) external;
/// @notice Check if an address is a minter
/// @param _minter Address to check
function isMinter(address _minter) external view returns (bool);
/// @notice Callback called by auction on first auction started to transfer ownership to treasury from founder
function onFirstAuctionStarted() external;
}
src/token/metadata/interfaces/IBaseMetadata.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
import { IUUPS } from "../../../lib/interfaces/IUUPS.sol";
/// @title IBaseMetadata
/// @author Rohan Kulkarni
/// @notice The external Base Metadata errors and functions
interface IBaseMetadata is IUUPS {
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if the caller was not the contract manager
error ONLY_MANAGER();
/// ///
/// FUNCTIONS ///
/// ///
/// @notice Initializes a DAO's token metadata renderer
/// @param initStrings The encoded token and metadata initialization strings
/// @param token The associated ERC-721 token address
function initialize(
bytes calldata initStrings,
address token
) external;
/// @notice Generates attributes for a token upon mint
/// @param tokenId The ERC-721 token id
function onMinted(uint256 tokenId) external returns (bool);
/// @notice The token URI
/// @param tokenId The ERC-721 token id
function tokenURI(uint256 tokenId) external view returns (string memory);
/// @notice The contract URI
function contractURI() external view returns (string memory);
/// @notice The associated ERC-721 token
function token() external view returns (address);
/// @notice Get metadata owner address
function owner() external view returns (address);
}
src/token/metadata/interfaces/IPropertyIPFSMetadataRenderer.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
import { MetadataRendererTypesV1 } from "../types/MetadataRendererTypesV1.sol";
import { MetadataRendererTypesV2 } from "../types/MetadataRendererTypesV2.sol";
import { IBaseMetadata } from "./IBaseMetadata.sol";
/// @title IPropertyIPFSMetadataRenderer
/// @author Iain Nash & Rohan Kulkarni
/// @notice The external Metadata Renderer events, errors, and functions
interface IPropertyIPFSMetadataRenderer is IBaseMetadata, MetadataRendererTypesV1, MetadataRendererTypesV2 {
/// ///
/// EVENTS ///
/// ///
/// @notice Emitted when a property is added
event PropertyAdded(uint256 id, string name);
/// @notice Additional token properties have been set
event AdditionalTokenPropertiesSet(AdditionalTokenProperty[] _additionalJsonProperties);
/// @notice Emitted when the contract image is updated
event ContractImageUpdated(string prevImage, string newImage);
/// @notice Emitted when the renderer base is updated
event RendererBaseUpdated(string prevRendererBase, string newRendererBase);
/// @notice Emitted when the collection description is updated
event DescriptionUpdated(string prevDescription, string newDescription);
/// @notice Emitted when the collection uri is updated
event WebsiteURIUpdated(string lastURI, string newURI);
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if the caller isn't the token contract
error ONLY_TOKEN();
/// @dev Reverts if querying attributes for a token not minted
error TOKEN_NOT_MINTED(uint256 tokenId);
/// @dev Reverts if the founder does not include both a property and item during the initial artwork upload
error ONE_PROPERTY_AND_ITEM_REQUIRED();
/// @dev Reverts if an item is added for a non-existent property
error INVALID_PROPERTY_SELECTED(uint256 selectedPropertyId);
///
error TOO_MANY_PROPERTIES();
/// ///
/// FUNCTIONS ///
/// ///
/// @notice Adds properties and/or items to be pseudo-randomly chosen from during token minting
/// @param names The names of the properties to add
/// @param items The items to add to each property
/// @param ipfsGroup The IPFS base URI and extension
function addProperties(
string[] calldata names,
ItemParam[] calldata items,
IPFSGroup calldata ipfsGroup
) external;
/// @notice The number of properties
function propertiesCount() external view returns (uint256);
/// @notice The number of items in a property
/// @param propertyId The property id
function itemsCount(uint256 propertyId) external view returns (uint256);
/// @notice The properties and query string for a generated token
/// @param tokenId The ERC-721 token id
function getAttributes(uint256 tokenId) external view returns (string memory resultAttributes, string memory queryString);
/// @notice The contract image
function contractImage() external view returns (string memory);
/// @notice The renderer base
function rendererBase() external view returns (string memory);
/// @notice The collection description
function description() external view returns (string memory);
/// @notice Updates the contract image
/// @param newContractImage The new contract image
function updateContractImage(string memory newContractImage) external;
/// @notice Updates the renderer base
/// @param newRendererBase The new renderer base
function updateRendererBase(string memory newRendererBase) external;
/// @notice Updates the collection description
/// @param newDescription The new description
function updateDescription(string memory newDescription) external;
}
src/token/metadata/storage/MetadataRendererStorageV1.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
import { MetadataRendererTypesV1 } from "../types/MetadataRendererTypesV1.sol";
/// @title MetadataRendererTypesV1
/// @author Iain Nash & Rohan Kulkarni
/// @notice The Metadata Renderer storage contract
contract MetadataRendererStorageV1 is MetadataRendererTypesV1 {
/// @notice The metadata renderer settings
Settings public settings;
/// @notice The properties chosen from upon generation
Property[] public properties;
/// @notice The IPFS data of all property items
IPFSGroup[] public ipfsData;
/// @notice The attributes generated for a token - mapping of tokenID uint16 array
/// @dev Array of size 16 1st element [0] used for number of attributes chosen, next N elements for those selections
/// @dev token ID
mapping(uint256 => uint16[16]) public attributes;
}
src/token/metadata/storage/MetadataRendererStorageV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
import { MetadataRendererTypesV2 } from "../types/MetadataRendererTypesV2.sol";
/// @title MetadataRendererTypesV1
/// @author Iain Nash & Rohan Kulkarni
/// @notice The Metadata Renderer storage contract
contract MetadataRendererStorageV2 is MetadataRendererTypesV2 {
/// @notice Additional JSON key/value properties for each token.
/// @dev While strings are quoted, JSON needs to be escaped.
AdditionalTokenProperty[] internal additionalTokenProperties;
}
src/token/metadata/types/MetadataRendererTypesV1.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
/// @title MetadataRendererTypesV1
/// @author Iain Nash & Rohan Kulkarni
/// @notice The Metadata Renderer custom data types
interface MetadataRendererTypesV1 {
struct ItemParam {
uint256 propertyId;
string name;
bool isNewProperty;
}
struct IPFSGroup {
string baseUri;
string extension;
}
struct Item {
uint16 referenceSlot;
string name;
}
struct Property {
string name;
Item[] items;
}
struct Settings {
address token;
string projectURI;
string description;
string contractImage;
string rendererBase;
}
}
src/token/metadata/types/MetadataRendererTypesV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
/// @title MetadataRendererTypesV2
/// @author Iain Nash & Rohan Kulkarni
/// @notice The Metadata Renderer custom data types
interface MetadataRendererTypesV2 {
struct AdditionalTokenProperty {
string key;
string value;
bool quote;
}
}
src/token/types/TokenTypesV1.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
import { IBaseMetadata } from "../metadata/interfaces/IBaseMetadata.sol";
/// @title TokenTypesV1
/// @author Rohan Kulkarni
/// @notice The Token custom data types
interface TokenTypesV1 {
/// @notice The settings type
/// @param auction The DAO auction house
/// @param totalSupply The number of active tokens
/// @param numFounders The number of vesting recipients
/// @param metadatarenderer The token metadata renderer
/// @param mintCount The number of minted tokens
/// @param totalPercentage The total percentage owned by founders
struct Settings {
address auction;
uint88 totalSupply;
uint8 numFounders;
IBaseMetadata metadataRenderer;
uint88 mintCount;
uint8 totalOwnership;
}
/// @notice The founder type
/// @param wallet The address where tokens are sent
/// @param ownershipPct The percentage of token ownership
/// @param vestExpiry The timestamp when vesting ends
struct Founder {
address wallet;
uint8 ownershipPct;
uint32 vestExpiry;
}
}
src/token/types/TokenTypesV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
/// @title TokenTypesV2
/// @author James Geary
/// @notice The Token custom data types
interface TokenTypesV2 {
struct MinterParams {
address minter;
bool allowed;
}
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 500000,
"enabled": true
},
"evmVersion": "london",
"remappings": [
":@openzeppelin/=node_modules/@openzeppelin/",
":ds-test/=node_modules/ds-test/src/",
":forge-std/=node_modules/forge-std/src/",
":micro-onchain-metadata-utils/=node_modules/micro-onchain-metadata-utils/src/",
":sol-uriencode/=node_modules/sol-uriencode/",
":sol2string/=node_modules/sol2string/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.