Verified contractExactMIT
Manager
Address0xe03c76388be1c5008e8aee10534dc68c290c8783
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.35
- Same code
Only this contract
Details
- Compiler
- solc 0.8.35+commit.47b9dedd
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- osaka
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,895,936
- Creation transaction
- 0xaff07ae60c…5cbddc685e
47 files
- src/manager/Manager.solmain31.78 KB
- node_modules/@openzeppelin/contracts/interfaces/draft-IERC1822.sol882 B
- node_modules/@openzeppelin/contracts/proxy/Proxy.sol2.7 KB
- node_modules/@openzeppelin/contracts/utils/StorageSlot.sol4.18 KB
- src/VersionedContract.sol403 B
- src/auction/IAuction.sol7.93 KB
- src/auction/types/AuctionTypesV2.sol437 B
- src/factory/IDAOFactory.sol2.71 KB
- src/governance/governor/IGovernor.sol21.24 KB
- src/governance/governor/ProposalHasher.sol1.08 KB
- src/governance/governor/types/GovernorTypesV1.sol2.54 KB
- src/governance/treasury/ITreasury.sol5.14 KB
- src/governance/treasury/Treasury.sol10.95 KB
- src/governance/treasury/storage/TreasuryStorageV1.sol505 B
- src/governance/treasury/types/TreasuryTypesV1.sol432 B
- src/lib/interfaces/IEIP712.sol1.05 KB
- src/lib/interfaces/IERC1967Upgrade.sol1.17 KB
- src/lib/interfaces/IERC721.sol4.32 KB
- src/lib/interfaces/IERC721Votes.sol2.99 KB
- src/lib/interfaces/IInitializable.sol1.12 KB
- src/lib/interfaces/IOwnable.sol2.47 KB
- src/lib/interfaces/IPausable.sol1.36 KB
- src/lib/interfaces/IUUPS.sol1.41 KB
- src/lib/interfaces/IVersionedContract.sol160 B
- src/lib/proxy/ERC1967Proxy.sol1.42 KB
- src/lib/proxy/ERC1967Upgrade.sol3.37 KB
- src/lib/proxy/UUPS.sol2.59 KB
- src/lib/token/ERC721.sol8.16 KB
- src/lib/token/ERC721Votes.sol12.99 KB
- src/lib/utils/Address.sol2.22 KB
- src/lib/utils/EIP712.sol2.97 KB
- src/lib/utils/Initializable.sol2.63 KB
- src/lib/utils/Ownable.sol3.48 KB
- src/lib/utils/ReentrancyGuard.sol1.65 KB
- src/lib/utils/SafeCast.sol1.32 KB
- src/lib/utils/TokenReceiver.sol874 B
- src/manager/IManager.sol10.92 KB
- src/manager/storage/ManagerStorageV1.sol624 B
- src/manager/types/ManagerTypesV1.sol704 B
- src/token/IToken.sol7.88 KB
- src/token/Token.sol22.07 KB
- src/token/metadata/interfaces/IBaseMetadata.sol1.67 KB
- src/token/storage/TokenStorageV1.sol594 B
- src/token/storage/TokenStorageV2.sol341 B
- src/token/storage/TokenStorageV3.sol263 B
- src/token/types/TokenTypesV1.sol1.15 KB
- src/token/types/TokenTypesV2.sol250 B
src/manager/Manager.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
import { UUPS } from "../lib/proxy/UUPS.sol";
import { Ownable } from "../lib/utils/Ownable.sol";
import { ERC1967Proxy } from "../lib/proxy/ERC1967Proxy.sol";
import { ManagerStorageV1 } from "./storage/ManagerStorageV1.sol";
import { IManager } from "./IManager.sol";
import { IToken } from "../token/IToken.sol";
import { IBaseMetadata } from "../token/metadata/interfaces/IBaseMetadata.sol";
import { IAuction } from "../auction/IAuction.sol";
import { ITreasury } from "../governance/treasury/ITreasury.sol";
import { IGovernor } from "../governance/governor/IGovernor.sol";
import { IOwnable } from "../lib/interfaces/IOwnable.sol";
import { IDAOFactory } from "../factory/IDAOFactory.sol";
import { VersionedContract } from "../VersionedContract.sol";
import { IVersionedContract } from "../lib/interfaces/IVersionedContract.sol";
/// @title Manager
/// @author Neokry & Rohan Kulkarni
/// @custom:repo github.com/ourzora/nouns-protocol
/// @notice The DAO deployer and upgrade manager
contract Manager is IManager, VersionedContract, UUPS, Ownable, ManagerStorageV1 {
bytes32 internal constant TOKEN_SALT_LABEL = keccak256("TOKEN");
bytes32 internal constant METADATA_SALT_LABEL = keccak256("METADATA");
bytes32 internal constant AUCTION_SALT_LABEL = keccak256("AUCTION");
bytes32 internal constant TREASURY_SALT_LABEL = keccak256("TREASURY");
bytes32 internal constant GOVERNOR_SALT_LABEL = keccak256("GOVERNOR");
error IMPLEMENTATION_REQUIRED();
error INVALID_IMPLEMENTATION();
error DAO_FACTORY_NOT_DEPLOYED();
error FACTORY_DEPLOYMENT_FAILED();
error INVALID_FACTORY_CONTRACT(address providedAddress);
error INVALID_FACTORY_BINDING(address factory, address expectedManager, address actualManager);
/// ///
/// IMMUTABLES ///
/// ///
// forge-lint: disable-next-line(screaming-snake-case-immutable)
/// @notice The token implementation address
address public immutable tokenImpl;
// forge-lint: disable-next-line(screaming-snake-case-immutable)
/// @notice The metadata renderer implementation address
address public immutable metadataImpl;
// forge-lint: disable-next-line(screaming-snake-case-immutable)
/// @notice The auction house implementation address
address public immutable auctionImpl;
// forge-lint: disable-next-line(screaming-snake-case-immutable)
/// @notice The treasury implementation address
address public immutable treasuryImpl;
// forge-lint: disable-next-line(screaming-snake-case-immutable)
/// @notice The governor implementation address
address public immutable governorImpl;
// forge-lint: disable-next-line(screaming-snake-case-immutable)
/// @notice The address to send Builder DAO rewards to
address public immutable builderRewardsRecipient;
// forge-lint: disable-next-line(screaming-snake-case-immutable)
/// @notice The DAOFactory address for canonical deterministic deployments
/// @dev DAOFactory acts as the canonical deployer for all DAO proxies, ensuring cross-chain
/// deterministic addresses regardless of Manager address. The factory should be deployed
/// at the same address on all chains using CREATE3Factory.
address public immutable daoFactory;
/// ///
/// CONSTRUCTOR ///
/// ///
constructor(
address _tokenImpl,
address _metadataImpl,
address _auctionImpl,
address _treasuryImpl,
address _governorImpl,
address _builderRewardsRecipient,
address _daoFactory
) payable initializer {
// Constructors run in the implementation context, so they can verify the factory contract but not proxy binding.
_validateDAOFactoryContract(_daoFactory);
tokenImpl = _tokenImpl;
metadataImpl = _metadataImpl;
auctionImpl = _auctionImpl;
treasuryImpl = _treasuryImpl;
governorImpl = _governorImpl;
builderRewardsRecipient = _builderRewardsRecipient;
daoFactory = _daoFactory;
}
/// ///
/// INITIALIZER ///
/// ///
/// @notice Initializes ownership of the manager contract
/// @param _newOwner The owner address to set (will be transferred to the Builder DAO once its deployed)
function initialize(address _newOwner) external initializer {
// Ensure an owner is specified
if (_newOwner == address(0)) revert ADDRESS_ZERO();
// Set the contract owner
__Ownable_init(_newOwner);
}
/// ///
/// DAO DEPLOY ///
/// ///
/// @notice Deprecated: deploys a DAO with custom token, auction, and governance settings for backward compatibility only.
/// @dev New integrations should use deterministic deployment with explicit ImplementationParams.
/// @param _founderParams The DAO founders
/// @param _tokenParams The ERC-721 token settings
/// @param _auctionParams The auction settings
/// @param _govParams The governance settings
/// @return token The deployed token address
/// @return metadata The deployed metadata renderer address
/// @return auction The deployed auction address
/// @return treasury The deployed treasury address
/// @return governor The deployed governor address
function deploy(
FounderParams[] calldata _founderParams,
TokenParams calldata _tokenParams,
AuctionParams calldata _auctionParams,
GovParams calldata _govParams
) external returns (address token, address metadata, address auction, address treasury, address governor) {
return _deploy(_founderParams, _tokenParams, _auctionParams, _govParams);
}
/// @notice Deploys a DAO with deterministic contract addresses using CREATE2 and explicit implementation addresses
/// @param _founderParams The DAO founders
/// @param _tokenParams The ERC-721 token settings
/// @param _auctionParams The auction settings
/// @param _govParams The governance settings
/// @param _deploySalt The base salt used to derive per-contract salts
/// @return token The deployed token address
/// @return metadata The deployed metadata renderer address
/// @return auction The deployed auction address
/// @return treasury The deployed treasury address
/// @return governor The deployed governor address
function deployDeterministic(
FounderParams[] calldata _founderParams,
TokenParams calldata _tokenParams,
AuctionParams calldata _auctionParams,
GovParams calldata _govParams,
bytes32 _deploySalt
) external returns (address token, address metadata, address auction, address treasury, address governor) {
// Validate DAOFactory binding for clear error messages
// This prevents confusing UNAUTHORIZED errors from DAOFactory if binding is wrong
// Gas cost: ~2,600 gas per deployment for improved UX
_validateDAOFactory(daoFactory);
return _deployDeterministic(_founderParams, _tokenParams, _auctionParams, _govParams, _deploySalt);
}
/// @notice Predicts deterministic DAO addresses using an explicit implementation bundle
/// @param _deployer The deployer address used to namespace the deterministic salt
/// @param _deploySalt The base salt used to derive per-contract salts
/// @return token The predicted token address
/// @return metadata The predicted metadata renderer address
/// @return auction The predicted auction address
/// @return treasury The predicted treasury address
/// @return governor The predicted governor address
function predictDeterministicAddresses(address _deployer, bytes32 _deploySalt)
external
view
returns (address token, address metadata, address auction, address treasury, address governor)
{
return _predictDeterministicAddresses(_deployer, _deploySalt);
}
/// ///
/// SET METADATA ///
/// ///
/// @notice Set a new metadata renderer
/// @param _token The token address
/// @param _newRendererImpl new renderer address to use
/// @param _setupRenderer data to setup new renderer with
/// @return metadata The deployed metadata renderer address
function setMetadataRenderer(address _token, address _newRendererImpl, bytes memory _setupRenderer) external returns (address metadata) {
if (msg.sender != IOwnable(_token).owner()) {
revert ONLY_TOKEN_OWNER();
}
metadata = address(new ERC1967Proxy(_newRendererImpl, ""));
daoAddressesByToken[_token].metadata = metadata;
if (_setupRenderer.length > 0) {
IBaseMetadata(metadata).initialize(_setupRenderer, _token);
}
IToken(_token).setMetadataRenderer(IBaseMetadata(metadata));
emit MetadataRendererUpdated({ sender: msg.sender, renderer: metadata });
}
/// ///
/// DAO ADDRESSES ///
/// ///
/// @notice A DAO's contract addresses from its token
/// @param _token The ERC-721 token address
/// @return metadata Metadata deployed address
/// @return auction Auction deployed address
/// @return treasury Treasury deployed address
/// @return governor Governor deployed address
function getAddresses(address _token) public view returns (address metadata, address auction, address treasury, address governor) {
DAOAddresses storage addresses = daoAddressesByToken[_token];
metadata = addresses.metadata;
auction = addresses.auction;
treasury = addresses.treasury;
governor = addresses.governor;
}
/// ///
/// DAO UPGRADES ///
/// ///
/// @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) {
return isUpgrade[_baseImpl][_upgradeImpl];
}
/// @notice Called by the Builder DAO to offer implementation upgrades for created DAOs
/// @param _baseImpl The base implementation address
/// @param _upgradeImpl The upgrade implementation address
function registerUpgrade(address _baseImpl, address _upgradeImpl) external onlyOwner {
isUpgrade[_baseImpl][_upgradeImpl] = true;
emit UpgradeRegistered(_baseImpl, _upgradeImpl);
}
/// @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 onlyOwner {
delete isUpgrade[_baseImpl][_upgradeImpl];
emit UpgradeRemoved(_baseImpl, _upgradeImpl);
}
/// @notice Safely get the contract version of a target contract.
/// @param target The ERC-721 token address
/// @dev Assume `target` is a contract
/// @return Contract version if found, empty string if not.
function _safeGetVersion(address target) internal pure returns (string memory) {
try IVersionedContract(target).contractVersion() returns (string memory version) {
return version;
} catch {
return "";
}
}
// forge-lint: disable-next-line(mixed-case-function)
/// @notice Safely get the contract version of all DAO contracts given a token address
/// @param token The ERC-721 token address
/// @return daoVersionInfo Contract versions if found, empty string if not
function getDAOVersions(address token) external view returns (DAOVersionInfo memory daoVersionInfo) {
(address metadata, address auction, address treasury, address governor) = getAddresses(token);
return DAOVersionInfo({
token: _safeGetVersion(token),
metadata: _safeGetVersion(metadata),
auction: _safeGetVersion(auction),
treasury: _safeGetVersion(treasury),
governor: _safeGetVersion(governor)
});
}
/// @notice Returns the latest implementation versions
function getLatestVersions() external view returns (DAOVersionInfo memory) {
return DAOVersionInfo({
token: _safeGetVersion(tokenImpl),
metadata: _safeGetVersion(metadataImpl),
auction: _safeGetVersion(auctionImpl),
treasury: _safeGetVersion(treasuryImpl),
governor: _safeGetVersion(governorImpl)
});
}
/// ///
/// MANAGER UPGRADE ///
/// ///
/// @notice Ensures the caller is authorized to upgrade the contract
/// @dev This function is called in `upgradeTo` & `upgradeToAndCall`
/// @param _newImpl The new implementation address
function _authorizeUpgrade(address _newImpl) internal override onlyOwner { }
/// @notice Initializes all DAO contracts with provided parameters
/// @dev Shared initialization logic used by both legacy and deterministic deployment
/// @param token The deployed token proxy address
/// @param metadata The deployed metadata renderer proxy address
/// @param auction The deployed auction proxy address
/// @param treasury The deployed treasury proxy address
/// @param governor The deployed governor proxy address
/// @param founder The founder address who will receive initial ownership
/// @param _founderParams The DAO founders
/// @param _tokenParams The ERC-721 token settings
/// @param _auctionParams The auction settings
/// @param _govParams The governance settings
// forge-lint: disable-next-line(mixed-case-function)
function _initializeDAO(
address token,
address metadata,
address auction,
address treasury,
address governor,
address founder,
FounderParams[] calldata _founderParams,
TokenParams calldata _tokenParams,
AuctionParams calldata _auctionParams,
GovParams calldata _govParams
) internal {
IToken(token)
.initialize({
founders: _founderParams,
initStrings: _tokenParams.initStrings,
reservedUntilTokenId: _tokenParams.reservedUntilTokenId,
metadataRenderer: metadata,
auction: auction,
initialOwner: founder
});
IBaseMetadata(metadata).initialize({ initStrings: _tokenParams.initStrings, token: token });
IAuction(auction)
.initialize({
token: token,
founder: founder,
treasury: treasury,
duration: _auctionParams.duration,
reservePrice: _auctionParams.reservePrice,
founderRewardRecipent: _auctionParams.founderRewardRecipent,
founderRewardBps: _auctionParams.founderRewardBps
});
ITreasury(treasury).initialize({ governor: governor, timelockDelay: _govParams.timelockDelay });
IGovernor(governor)
.initialize({
treasury: treasury,
token: token,
vetoer: _govParams.vetoer,
votingDelay: _govParams.votingDelay,
votingPeriod: _govParams.votingPeriod,
proposalThresholdBps: _govParams.proposalThresholdBps,
quorumThresholdBps: _govParams.quorumThresholdBps,
proposalUpdatablePeriod: _govParams.proposalUpdatablePeriod
});
emit DAODeployed({ token: token, metadata: metadata, auction: auction, treasury: treasury, governor: governor });
}
/// @notice Internal function for legacy DAO deployment
/// @dev Uses non-deterministic salt based on token address for backward compatibility
/// @param _founderParams The DAO founders
/// @param _tokenParams The ERC-721 token settings
/// @param _auctionParams The auction settings
/// @param _govParams The governance settings
/// @return token The deployed token address
/// @return metadata The deployed metadata renderer address
/// @return auction The deployed auction address
/// @return treasury The deployed treasury address
/// @return governor The deployed governor address
function _deploy(
FounderParams[] calldata _founderParams,
TokenParams calldata _tokenParams,
AuctionParams calldata _auctionParams,
GovParams calldata _govParams
) internal returns (address token, address metadata, address auction, address treasury, address governor) {
if (_founderParams.length == 0) revert FOUNDER_REQUIRED();
address founder = _founderParams[0].wallet;
if (founder == address(0)) revert FOUNDER_REQUIRED();
(token, metadata, auction, treasury, governor) = _deployLegacyProxies(_getMetadataImpl(_tokenParams));
daoAddressesByToken[token] = DAOAddresses({ metadata: metadata, auction: auction, treasury: treasury, governor: governor });
_initializeDAO(token, metadata, auction, treasury, governor, founder, _founderParams, _tokenParams, _auctionParams, _govParams);
}
/// @notice Internal function for deterministic DAO deployment using CREATE2
/// @dev Deploys all contracts with predictable addresses using Manager's immutable implementations
/// @param _founderParams The DAO founders
/// @param _tokenParams The ERC-721 token settings
/// @param _auctionParams The auction settings
/// @param _govParams The governance settings
/// @param _deploySalt The base salt used to derive per-contract salts
/// @return token The deployed token address
/// @return metadata The deployed metadata renderer address
/// @return auction The deployed auction address
/// @return treasury The deployed treasury address
/// @return governor The deployed governor address
function _deployDeterministic(
FounderParams[] calldata _founderParams,
TokenParams calldata _tokenParams,
AuctionParams calldata _auctionParams,
GovParams calldata _govParams,
bytes32 _deploySalt
) internal returns (address token, address metadata, address auction, address treasury, address governor) {
if (_founderParams.length == 0) revert FOUNDER_REQUIRED();
address founder = _founderParams[0].wallet;
if (founder == address(0)) revert FOUNDER_REQUIRED();
(token, metadata, auction, treasury, governor) = _deployDeterministicProxies(msg.sender, _deploySalt, _tokenParams);
daoAddressesByToken[token] = DAOAddresses({ metadata: metadata, auction: auction, treasury: treasury, governor: governor });
emit DAODeployedDeterministic(msg.sender, _deploySalt, token, metadata, auction, treasury, governor);
_initializeDAO(token, metadata, auction, treasury, governor, founder, _founderParams, _tokenParams, _auctionParams, _govParams);
}
/// @notice Deploys all DAO proxies using legacy non-deterministic pattern
/// @dev Token is deployed first without salt, then its address (shifted left 96 bits) becomes the salt for other contracts.
/// The bit shift (<< 96) moves the 160-bit address into the upper portion of the 256-bit salt,
/// leaving lower bits as zeros. This ensures a unique salt per deployment while maintaining backward compatibility.
/// Uses CREATE for token (no salt) and CREATE2 for other contracts (with salt), NOT CREATE3.
/// @param _metadataImplToUse The metadata renderer implementation to use (can be custom or default)
/// @return token The deployed token proxy address
/// @return metadata The deployed metadata renderer proxy address
/// @return auction The deployed auction proxy address
/// @return treasury The deployed treasury proxy address
/// @return governor The deployed governor proxy address
function _deployLegacyProxies(address _metadataImplToUse)
internal
returns (address token, address metadata, address auction, address treasury, address governor)
{
// Deploy token using CREATE (no salt) - non-deterministic
token = address(new ERC1967Proxy(tokenImpl, ""));
// Use the token address to precompute the DAO's remaining addresses
bytes32 salt = bytes32(uint256(uint160(token)) << 96);
// Deploy remaining DAO contracts using CREATE2 (with salt) - deterministic based on token address
metadata = address(new ERC1967Proxy{ salt: salt }(_metadataImplToUse, ""));
auction = address(new ERC1967Proxy{ salt: salt }(auctionImpl, ""));
treasury = address(new ERC1967Proxy{ salt: salt }(treasuryImpl, ""));
governor = address(new ERC1967Proxy{ salt: salt }(governorImpl, ""));
}
/// @notice Deploys all DAO proxies with deterministic addresses using CREATE2
/// @dev Each contract uses a namespaced salt derived from deployer address, base salt, and contract-specific label.
/// This prevents collisions across deployers and ensures unique addresses per contract type.
/// @param _deployer The address initiating the deployment (used in salt derivation to prevent cross-deployer collisions)
/// @param _deploySalt The base salt provided by caller (should be unique per DAO deployment)
/// @param _tokenParams The token parameters containing optional custom renderer
/// @return token The deployed token proxy address
/// @return metadata The deployed metadata renderer proxy address
/// @return auction The deployed auction proxy address
/// @return treasury The deployed treasury proxy address
/// @return governor The deployed governor proxy address
function _deployDeterministicProxies(address _deployer, bytes32 _deploySalt, TokenParams calldata _tokenParams)
internal
returns (address token, address metadata, address auction, address treasury, address governor)
{
address metadataImplToUse = _getMetadataImpl(_tokenParams);
token = _deployProxy(tokenImpl, _deriveSalt(_deployer, _deploySalt, TOKEN_SALT_LABEL));
metadata = _deployProxy(metadataImplToUse, _deriveSalt(_deployer, _deploySalt, METADATA_SALT_LABEL));
auction = _deployProxy(auctionImpl, _deriveSalt(_deployer, _deploySalt, AUCTION_SALT_LABEL));
treasury = _deployProxy(treasuryImpl, _deriveSalt(_deployer, _deploySalt, TREASURY_SALT_LABEL));
governor = _deployProxy(governorImpl, _deriveSalt(_deployer, _deploySalt, GOVERNOR_SALT_LABEL));
}
/// @notice Returns the metadata renderer implementation to use
/// @dev Allows custom renderer or defaults to the Manager's immutable metadataImpl
/// @param _tokenParams The token parameters containing optional custom renderer
/// @return The metadata renderer implementation address to use
function _getMetadataImpl(TokenParams calldata _tokenParams) internal view returns (address) {
return _tokenParams.metadataRenderer != address(0) ? _tokenParams.metadataRenderer : metadataImpl;
}
/// @notice Predicts deterministic DAO contract addresses without deploying
/// @dev Uses same salt derivation as _deployDeterministicProxies for accurate prediction
/// @param _deployer The address that will deploy (affects salt calculation)
/// @param _deploySalt The base salt to be used
/// @return token The predicted token address
/// @return metadata The predicted metadata renderer address
/// @return auction The predicted auction address
/// @return treasury The predicted treasury address
/// @return governor The predicted governor address
function _predictDeterministicAddresses(address _deployer, bytes32 _deploySalt)
internal
view
returns (address token, address metadata, address auction, address treasury, address governor)
{
token = _predictProxyAddress(_deriveSalt(_deployer, _deploySalt, TOKEN_SALT_LABEL));
metadata = _predictProxyAddress(_deriveSalt(_deployer, _deploySalt, METADATA_SALT_LABEL));
auction = _predictProxyAddress(_deriveSalt(_deployer, _deploySalt, AUCTION_SALT_LABEL));
treasury = _predictProxyAddress(_deriveSalt(_deployer, _deploySalt, TREASURY_SALT_LABEL));
governor = _predictProxyAddress(_deriveSalt(_deployer, _deploySalt, GOVERNOR_SALT_LABEL));
}
/// @notice Validates that the DAOFactory is deployed and bound to this Manager proxy
/// @dev This function provides explicit binding validation with clear error messages.
/// It is intentionally NOT called in the constructor because address(this) would
/// be the implementation address, not the proxy address that the factory is bound to.
/// Constructors must use _validateDAOFactoryContract instead.
///
/// Design decision: This validation is called in deployDeterministic for better UX
/// (clear INVALID_FACTORY_BINDING errors) at the cost of ~2,600 gas per deployment.
/// Wrong bindings would otherwise fail at DAOFactory with UNAUTHORIZED error.
/// @param _daoFactory The DAOFactory address to validate
// forge-lint: disable-next-line(mixed-case-function)
function _validateDAOFactory(address _daoFactory) internal view {
_validateDAOFactoryContract(_daoFactory);
address boundManager = _getFactoryManager(_daoFactory);
if (boundManager != address(this)) {
revert INVALID_FACTORY_BINDING(_daoFactory, address(this), boundManager);
}
}
/// @notice Validates that a DAOFactory contract is deployed and exposes the expected interface
/// @dev This function only validates contract existence and interface, not binding to this Manager
/// @param _daoFactory The DAOFactory address to validate
function _validateDAOFactoryContract(address _daoFactory) private view {
if (_daoFactory.code.length == 0) {
revert DAO_FACTORY_NOT_DEPLOYED();
}
_getFactoryManager(_daoFactory);
}
/// @notice Reads the manager address bound to a DAOFactory contract
/// @dev Helper function to read factory binding and validate interface support
/// @param _factory The factory address to check
/// @return boundManager The address of the manager bound to the factory
function _getFactoryManager(address _factory) private view returns (address boundManager) {
(bool success, bytes memory data) = _factory.staticcall(abi.encodeWithSelector(IDAOFactory.manager.selector));
if (!success || data.length != 32) {
revert INVALID_FACTORY_CONTRACT(_factory);
}
boundManager = abi.decode(data, (address));
}
/// @notice Predicts the address of a CREATE3-deployed proxy via DAOFactory
/// @dev Delegates to DAOFactory's predictAddress function for accurate predictions
/// CRITICAL: Address depends ONLY on (DAOFactory, salt), NOT on Manager address or bytecode
/// This enables cross-chain determinism - same DAOFactory + salt = same address
/// regardless of which Manager is calling it or what the implementation address is
/// @param _salt The salt to use for CREATE3 deployment
/// @return The predicted proxy address
function _predictProxyAddress(bytes32 _salt) internal view returns (address) {
// Use DAOFactory's prediction function - DAOFactory is the canonical deployer
// This ensures all Managers produce identical predictions
return IDAOFactory(daoFactory).predictAddress(_salt);
}
/// @notice Deploys an ERC1967 proxy without salt (non-deterministic)
/// @dev Used by legacy deployment for the initial token contract
/// @param _implementation The implementation address
/// @return The deployed proxy address
function _deployProxy(address _implementation) internal returns (address) {
return address(new ERC1967Proxy(_implementation, ""));
}
/// @notice Deploys an ERC1967 proxy with CREATE3 salt (deterministic) via DAOFactory
/// @dev Uses DAOFactory as canonical deployer for bytecode-independent cross-chain determinism
/// This enables identical DAO addresses across chains REGARDLESS of Manager or implementation addresses
/// DAOFactory interface: deployProxy(bytes32 salt, bytes memory creationCode) returns (address)
/// @param _implementation The implementation address
/// @param _salt The CREATE3 salt
/// @return The deployed proxy address
function _deployProxy(address _implementation, bytes32 _salt) internal returns (address) {
// Build the initialization code for ERC1967Proxy
bytes memory creationCode = abi.encodePacked(type(ERC1967Proxy).creationCode, abi.encode(_implementation, ""));
// Deploy via DAOFactory - this is the canonical deployer for all DAO proxies
address deployed = IDAOFactory(daoFactory).deployProxy(_salt, creationCode);
// Verify the deployed address matches our prediction
address predicted = _predictProxyAddress(_salt);
if (deployed != predicted) revert FACTORY_DEPLOYMENT_FAILED();
// Verify contract was actually deployed
if (deployed.code.length == 0) revert FACTORY_DEPLOYMENT_FAILED();
return deployed;
}
/// @notice Derives a unique salt for CREATE3 deployment by combining deployer, user salt, and contract label
/// @dev This three-part derivation prevents collisions:
/// - _deployer prevents different users from interfering with each other's deployments
/// - _deploySalt allows same user to deploy multiple DAOs with different addresses
/// - _label ensures each contract type gets a unique salt within the same deployment
/// SECURITY: Deployers should use unique _deploySalt values to avoid collisions
/// Works identically for CREATE2 and CREATE3 - only the address calculation differs
/// @param _deployer The address initiating deployment (typically msg.sender)
/// @param _deploySalt The base salt chosen by the deployer
/// @param _label The contract-specific label (TOKEN_SALT_LABEL, METADATA_SALT_LABEL, etc.)
/// @return The derived salt for CREATE3 deployment
function _deriveSalt(address _deployer, bytes32 _deploySalt, bytes32 _label) internal pure returns (bytes32) {
return keccak256(abi.encode(_deployer, _deploySalt, _label));
}
}
node_modules/@openzeppelin/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)
pragma solidity >=0.4.16;
/**
* @dev ERC-1822: 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/proxy/Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (proxy/Proxy.sol)
pragma solidity ^0.8.20;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0x00, 0x00, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0x00, calldatasize(), 0x00, 0x00)
// Copy the returned data.
returndatacopy(0x00, 0x00, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0x00, returndatasize())
}
default {
return(0x00, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overridden so it returns the address to which the fallback
* function and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
}
node_modules/@openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @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 ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
src/VersionedContract.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
/// @title VersionedContract
/// @author Builder Protocol
/// @notice Abstract contract that provides version information for deployed contracts
abstract contract VersionedContract {
/// @notice Returns the current version of the contract
function contractVersion() external pure returns (string memory) {
return "3.0.0";
}
}
src/auction/IAuction.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
import { IUUPS } from "../lib/interfaces/IUUPS.sol";
import { IOwnable } from "../lib/interfaces/IOwnable.sol";
import { IPausable } from "../lib/interfaces/IPausable.sol";
import { AuctionTypesV2 } from "./types/AuctionTypesV2.sol";
/// @title IAuction
/// @author Rohan Kulkarni
/// @notice The external Auction events, errors, and functions
interface IAuction is IUUPS, IOwnable, IPausable {
/// ///
/// EVENTS ///
/// ///
/// @notice Emitted when a bid is placed
/// @param tokenId The ERC-721 token id
/// @param bidder The address of the bidder
/// @param amount The amount of ETH
/// @param extended If the bid extended the auction
/// @param endTime The end time of the auction
event AuctionBid(uint256 tokenId, address bidder, uint256 amount, bool extended, uint256 endTime);
/// @notice Emitted when an auction is settled
/// @param tokenId The ERC-721 token id of the settled auction
/// @param winner The address of the winning bidder
/// @param amount The amount of ETH raised from the winning bid
event AuctionSettled(uint256 tokenId, address winner, uint256 amount);
/// @notice Emitted when an auction is created
/// @param tokenId The ERC-721 token id of the created auction
/// @param startTime The start time of the created auction
/// @param endTime The end time of the created auction
event AuctionCreated(uint256 tokenId, uint256 startTime, uint256 endTime);
/// @notice Emitted when the auction duration is updated
/// @param duration The new auction duration
event DurationUpdated(uint256 duration);
/// @notice Emitted when the reserve price is updated
/// @param reservePrice The new reserve price
event ReservePriceUpdated(uint256 reservePrice);
/// @notice Emitted when the min bid increment percentage is updated
/// @param minBidIncrementPercentage The new min bid increment percentage
event MinBidIncrementPercentageUpdated(uint256 minBidIncrementPercentage);
/// @notice Emitted when the time buffer is updated
/// @param timeBuffer The new time buffer
event TimeBufferUpdated(uint256 timeBuffer);
/// @notice Emitted when the founder reward recipient is updated
/// @param reward The new founder reward
event FounderRewardUpdated(AuctionTypesV2.FounderReward reward);
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if a bid is placed for the wrong token
error INVALID_TOKEN_ID();
/// @dev Reverts if a bid is placed for an auction thats over
error AUCTION_OVER();
/// @dev Reverts if a bid is placed for an auction that hasn't started
error AUCTION_NOT_STARTED();
/// @dev Reverts if attempting to settle an active auction
error AUCTION_ACTIVE();
/// @dev Reverts if attempting to settle an auction that was already settled
error AUCTION_SETTLED();
/// @dev Reverts if a bid does not meet the reserve price
error RESERVE_PRICE_NOT_MET();
/// @dev Reverts if a bid does not meet the minimum bid
error MINIMUM_BID_NOT_MET();
/// @dev Error for when the bid increment is set to 0.
error MIN_BID_INCREMENT_1_PERCENT();
/// @dev Reverts if the contract does not have enough ETH
error INSOLVENT();
/// @dev Reverts if the caller was not the contract manager
error ONLY_MANAGER();
/// @dev Thrown if the WETH contract throws a failure on transfer
error FAILING_WETH_TRANSFER();
/// @dev Thrown if the auction creation failed
error AUCTION_CREATE_FAILED_TO_LAUNCH();
/// @dev Reverts if caller is not the token owner
error INVALID_REWARDS_BPS();
/// @dev Reverts if caller is not the token owner
error INVALID_REWARDS_RECIPIENT();
/// @dev Thrown if the rewards total is greater than 100%
error INVALID_REWARD_TOTAL();
/// @dev Thrown if a new auction cannot be created
error CANNOT_CREATE_AUCTION();
/// ///
/// STRUCTS ///
/// ///
struct RewardSplits {
//// @notice Total rewards amount
uint256 totalRewards;
/// @param recipients recipients to send the amount to, array aligns with amounts
address[] recipients;
/// @param amounts amounts to send to each recipient, array aligns with recipients
uint256[] amounts;
/// @param reasons optional bytes4 hash for indexing
bytes4[] reasons;
}
/// ///
/// FUNCTIONS ///
/// ///
/// @notice Initializes a DAO's auction house
/// @param token The ERC-721 token address
/// @param founder The founder responsible for starting the first auction
/// @param treasury The treasury address where ETH will be sent
/// @param duration The duration of each auction
/// @param reservePrice The reserve price of each auction
/// @param founderRewardRecipent The address to receive founder rewards
/// @param founderRewardBps The founder reward in basis points
function initialize(
address token,
address founder,
address treasury,
uint256 duration,
uint256 reservePrice,
address founderRewardRecipent,
uint16 founderRewardBps
) external;
/// @notice Creates a bid for the current token
/// @param tokenId The ERC-721 token id
function createBid(uint256 tokenId) external payable;
/// @notice Settles the current auction and creates the next one
function settleCurrentAndCreateNewAuction() external;
/// @notice Settles the latest auction when the contract is paused
function settleAuction() external;
/// @notice Pauses the auction house
function pause() external;
/// @notice Unpauses the auction house
function unpause() external;
/// @notice The time duration of each auction
function duration() external view returns (uint256);
/// @notice The reserve price of each auction
function reservePrice() external view returns (uint256);
/// @notice The minimum amount of time to place a bid during an active auction
function timeBuffer() external view returns (uint256);
/// @notice The minimum percentage an incoming bid must raise the highest bid
function minBidIncrement() external view returns (uint256);
/// @notice Updates the time duration of each auction
/// @param duration The new time duration
function setDuration(uint256 duration) external;
/// @notice Updates the reserve price of each auction
/// @param reservePrice The new reserve price
function setReservePrice(uint256 reservePrice) external;
/// @notice Updates the time buffer of each auction
/// @param timeBuffer The new time buffer
function setTimeBuffer(uint256 timeBuffer) external;
/// @notice Updates the minimum bid increment of each subsequent bid
/// @param percentage The new percentage
function setMinimumBidIncrement(uint256 percentage) external;
/// @notice Updates the founder reward settings
/// @param reward The new founder reward settings
function setFounderReward(AuctionTypesV2.FounderReward calldata reward) external;
/// @notice Get the address of the treasury
function treasury() external returns (address);
}
src/auction/types/AuctionTypesV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
/// @title AuctionTypesV2
/// @author Neokry
/// @notice The Auction custom data types
contract AuctionTypesV2 {
/// @notice The settings type
/// @param recipient The DAO founder collecting protocol rewards
/// @param percentBps The rewards to be paid to the DAO founder in BPS
struct FounderReward {
address recipient;
uint16 percentBps;
}
}
src/factory/IDAOFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
/// @title IDAOFactory
/// @author Nouns Builder Team
/// @notice Interface for the canonical DAO deployment factory
/// @dev This factory acts as the canonical deployer for all DAO proxies, enabling cross-chain
/// deterministic deployments regardless of the Manager contract's address.
interface IDAOFactory {
/// ///
/// EVENTS ///
/// ///
/// @notice Emitted when a proxy is deployed
/// @param deployer The address that initiated the deployment (typically a Manager contract)
/// @param deployed The address of the deployed proxy
/// @param salt The salt used for deployment
event ProxyDeployed(address indexed deployer, address deployed, bytes32 salt);
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if the CREATE3 deployment fails
error DEPLOYMENT_FAILED();
/// @dev Reverts if the deployed address doesn't match prediction
error ADDRESS_MISMATCH();
/// @dev Reverts if caller is not the authorized Manager
error UNAUTHORIZED();
/// ///
/// FUNCTIONS ///
/// ///
/// @notice The Manager contract authorized to use this factory
/// @return The Manager address set in the constructor
function manager() external view returns (address);
/// @notice Deploys a proxy contract using CREATE3
/// @dev Uses this contract (DAOFactory) as the canonical deployer, ensuring all Manager
/// contracts produce identical DAO addresses when using the same salt.
/// @param salt The salt to use for CREATE3 deployment
/// @param creationCode The creation code for the proxy (typically ERC1967Proxy)
/// @return deployed The address of the deployed proxy
function deployProxy(bytes32 salt, bytes memory creationCode) external payable returns (address deployed);
/// @notice Predicts the address of a proxy that would be deployed with the given salt
/// @dev This prediction is independent of the caller's address since DAOFactory is the deployer
/// @param salt The salt to use for prediction
/// @return predicted The predicted address
function predictAddress(bytes32 salt) external view returns (address predicted);
}
src/governance/governor/IGovernor.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
import { IUUPS } from "../../lib/interfaces/IUUPS.sol";
import { IOwnable } from "../../lib/utils/Ownable.sol";
import { IEIP712 } from "../../lib/utils/EIP712.sol";
import { GovernorTypesV1 } from "./types/GovernorTypesV1.sol";
/// @title IGovernor
/// @author Rohan Kulkarni
/// @notice The external Governor events, errors and functions
interface IGovernor is IUUPS, IOwnable, IEIP712, GovernorTypesV1 {
/// ///
/// EVENTS ///
/// ///
/// @notice Emitted when a proposal is created
/// @param proposalId The proposal ID
/// @param targets The target addresses
/// @param values The ETH values
/// @param calldatas The calldata payloads
/// @param description The proposal description
/// @param descriptionHash The hash of the description
/// @param proposal The proposal struct
event ProposalCreated(
bytes32 proposalId, address[] targets, uint256[] values, bytes[] calldatas, string description, bytes32 descriptionHash, Proposal proposal
);
/// @notice Emitted when a proposal is updated and replaced with a new id
/// @param oldProposalId The old proposal ID
/// @param newProposalId The new proposal ID
/// @param proposer The proposer address
/// @param targets The target addresses
/// @param values The ETH values
/// @param calldatas The calldata payloads
/// @param description The proposal description
/// @param updateMessage The update message
event ProposalUpdated(
bytes32 oldProposalId,
bytes32 newProposalId,
address proposer,
address[] targets,
uint256[] values,
bytes[] calldatas,
string description,
string updateMessage
);
/// @notice Emitted when proposal signers are set on signed proposal creation
/// @param proposalId The proposal ID
/// @param signers The signer addresses
event ProposalSignersSet(bytes32 proposalId, address[] signers);
/// @notice Emitted when a proposal is queued
/// @param proposalId The proposal ID
/// @param eta The execution timestamp
event ProposalQueued(bytes32 proposalId, uint256 eta);
/// @notice Emitted when a proposal is executed
/// @param proposalId The proposal id
event ProposalExecuted(bytes32 proposalId);
/// @notice Emitted when a proposal is canceled
/// @param proposalId The proposal ID
event ProposalCanceled(bytes32 proposalId);
/// @notice Emitted when a proposal is vetoed
/// @param proposalId The proposal ID
event ProposalVetoed(bytes32 proposalId);
/// @notice Emitted when a vote is cast for a proposal
/// @param voter The voter address
/// @param proposalId The proposal ID
/// @param support The vote support (0=against, 1=for, 2=abstain)
/// @param weight The vote weight
/// @param reason The vote reason
event VoteCast(address voter, bytes32 proposalId, uint256 support, uint256 weight, string reason);
/// @notice Emitted when the governor's voting delay is updated
/// @param prevVotingDelay The previous voting delay
/// @param newVotingDelay The new voting delay
event VotingDelayUpdated(uint256 prevVotingDelay, uint256 newVotingDelay);
/// @notice Emitted when the governor's voting period is updated
/// @param prevVotingPeriod The previous voting period
/// @param newVotingPeriod The new voting period
event VotingPeriodUpdated(uint256 prevVotingPeriod, uint256 newVotingPeriod);
/// @notice Emitted when the basis points of the governor's proposal threshold is updated
/// @param prevBps The previous basis points
/// @param newBps The new basis points
event ProposalThresholdBpsUpdated(uint256 prevBps, uint256 newBps);
/// @notice Emitted when the basis points of the governor's quorum votes is updated
/// @param prevBps The previous basis points
/// @param newBps The new basis points
event QuorumVotesBpsUpdated(uint256 prevBps, uint256 newBps);
//// @notice Emitted when the governor's vetoer is updated
/// @param prevVetoer The previous vetoer address
/// @param newVetoer The new vetoer address
event VetoerUpdated(address prevVetoer, address newVetoer);
/// @notice Emitted when the governor's delay is updated
/// @param prevTimestamp The previous timestamp
/// @param newTimestamp The new timestamp
event DelayedGovernanceExpirationTimestampUpdated(uint256 prevTimestamp, uint256 newTimestamp);
/// @notice Emitted when proposal updatable period is updated
/// @param prevProposalUpdatablePeriod The previous updatable period
/// @param newProposalUpdatablePeriod The new updatable period
event ProposalUpdatablePeriodUpdated(uint256 prevProposalUpdatablePeriod, uint256 newProposalUpdatablePeriod);
/// ///
/// ERRORS ///
/// ///
error INVALID_PROPOSAL_THRESHOLD_BPS();
error INVALID_QUORUM_THRESHOLD_BPS();
error INVALID_VOTING_DELAY();
error INVALID_VOTING_PERIOD();
error INVALID_DELAYED_GOVERNANCE_EXPIRATION();
/// @dev Reverts if a proposal already exists
/// @param proposalId The proposal id
error PROPOSAL_EXISTS(bytes32 proposalId);
/// @dev Reverts if a proposal isn't queued
/// @param proposalId The proposal id
error PROPOSAL_NOT_QUEUED(bytes32 proposalId);
/// @dev Reverts if the proposer didn't specify a target address
error PROPOSAL_TARGET_MISSING();
/// @dev Reverts if the number of targets, values, and calldatas does not match
error PROPOSAL_LENGTH_MISMATCH();
/// @dev Reverts if a proposal didn't succeed
error PROPOSAL_UNSUCCESSFUL();
/// @dev Reverts if a proposal was already executed
error PROPOSAL_ALREADY_EXECUTED();
/// @dev Reverts if a proposal is in a terminal state and cannot be canceled
error PROPOSAL_IN_TERMINAL_STATE();
/// @dev Reverts if a specified proposal doesn't exist
error PROPOSAL_DOES_NOT_EXIST();
/// @dev Reverts if the proposer's voting weight is below the proposal threshold
error BELOW_PROPOSAL_THRESHOLD();
/// @dev Reverts if a vote was prematurely cast
error VOTING_NOT_STARTED();
/// @dev Reverts if the caller wasn't the vetoer
error ONLY_VETOER();
/// @dev Reverts if the caller already voted
error ALREADY_VOTED();
/// @dev Reverts if a proposal was attempted to be canceled incorrectly
error INVALID_CANCEL();
/// @dev Reverts if a vote was attempted to be cast incorrectly
error INVALID_VOTE();
/// @dev Reverts if a proposal was attempted to be created before expiration or all tokens have been claimed
error WAITING_FOR_TOKENS_TO_CLAIM_OR_EXPIRATION();
/// @dev Reverts if governance cannot be delayed
error CANNOT_DELAY_GOVERNANCE();
/// @dev Reverts if the caller was not the token owner
error ONLY_TOKEN_OWNER();
/// @dev Reverts if the caller was not the contract manager
error ONLY_MANAGER();
error INVALID_PROPOSAL_UPDATABLE_PERIOD();
error CAN_ONLY_EDIT_UPDATABLE_PROPOSALS();
error ONLY_PROPOSER_CAN_EDIT();
error MUST_PROVIDE_SIGNATURES();
error TOO_MANY_SIGNERS();
error VOTES_BELOW_PROPOSAL_THRESHOLD();
error INVALID_SIGNATURE_ORDER();
error INVALID_SIGNATURE_NONCE();
error PROPOSER_CANNOT_BE_SIGNER();
error SIGNED_PROPOSAL_MUST_USE_SIGNATURES();
error NO_OP_PROPOSAL_UPDATE();
/// ///
/// FUNCTIONS ///
/// ///
/// @notice Initializes a DAO's governor
/// @param treasury The DAO's treasury address
/// @param token The DAO's governance token address
/// @param vetoer The address eligible to veto proposals
/// @param votingDelay The voting delay
/// @param votingPeriod The voting period
/// @param proposalThresholdBps The proposal threshold basis points
/// @param quorumThresholdBps The quorum threshold basis points
/// @param proposalUpdatablePeriod The proposal updatable period
function initialize(
address treasury,
address token,
address vetoer,
uint256 votingDelay,
uint256 votingPeriod,
uint256 proposalThresholdBps,
uint256 quorumThresholdBps,
uint256 proposalUpdatablePeriod
) external;
/// @notice Creates a proposal
/// @param targets The target addresses to call
/// @param values The ETH values of each call
/// @param calldatas The calldata of each call
/// @param description The proposal description
function propose(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description)
external
returns (bytes32);
/// @notice Creates a proposal from msg.sender backed by offchain signer sponsorships
/// @dev CRITICAL: Signatures MUST be sorted by signer address in ascending order
///
/// Gas Warning: All signatures are validated (~30k gas each) BEFORE threshold check.
/// If combined votes don't meet threshold, gas is wasted. Pre-validate voting power!
///
/// Requirements:
/// - At least one signature required
/// - Maximum 16 signers (MAX_PROPOSAL_SIGNERS)
/// - Signers MUST be sorted ascending: signers[i].address < signers[i+1].address
/// - Proposer (msg.sender) cannot also be a signer
/// - Combined voting power (proposer + signers) must exceed proposal threshold
///
/// Example sorting (JavaScript):
/// ```javascript
/// const signers = [...]; // Array of {address, signature}
/// const sorted = signers.sort((a, b) =>
/// a.address.toLowerCase().localeCompare(b.address.toLowerCase())
/// );
/// ```
///
/// @param proposerSignatures The proposer signatures (MUST BE SORTED BY SIGNER ADDRESS)
/// @param targets The target addresses to call
/// @param values The ETH values of each call
/// @param calldatas The calldata of each call
/// @param description The proposal description
function proposeBySigs(
ProposerSignature[] memory proposerSignatures,
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) external returns (bytes32);
/// @notice Updates an existing proposal during updatable period
/// @param proposalId The proposal ID to update
/// @param targets The target addresses to call
/// @param values The ETH values of each call
/// @param calldatas The calldata of each call
/// @param description The proposal description
/// @param updateMessage The update message
function updateProposal(
bytes32 proposalId,
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description,
string memory updateMessage
) external returns (bytes32);
/// @notice Updates a signed proposal with signer approvals
/// @dev CRITICAL: Signatures MUST be sorted by signer address in ascending order
///
/// Gas Warning: All signatures are validated (~30k gas each) BEFORE threshold check.
/// If combined votes don't meet threshold, gas is wasted. Pre-validate voting power!
///
/// Requirements:
/// - At least one signature required
/// - Maximum 16 signers (MAX_PROPOSAL_SIGNERS)
/// - Signers MUST be sorted ascending: signers[i].address < signers[i+1].address
/// - Proposer (msg.sender) cannot also be a signer
/// - Combined voting power (proposer + signers) must exceed proposal threshold
/// - Proposal must be in updatable period
///
/// Example sorting (JavaScript):
/// ```javascript
/// const signers = [...]; // Array of {address, signature}
/// const sorted = signers.sort((a, b) =>
/// a.address.toLowerCase().localeCompare(b.address.toLowerCase())
/// );
/// ```
///
/// @param proposalId The proposal ID to update
/// @param proposerSignatures The proposer signatures (MUST BE SORTED BY SIGNER ADDRESS)
/// @param targets The target addresses to call
/// @param values The ETH values of each call
/// @param calldatas The calldata of each call
/// @param description The proposal description
/// @param updateMessage The update message
function updateProposalBySigs(
bytes32 proposalId,
ProposerSignature[] memory proposerSignatures,
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description,
string memory updateMessage
) external returns (bytes32);
/// @notice Casts a vote
/// @param proposalId The proposal id
/// @param support The support value (0 = Against, 1 = For, 2 = Abstain)
function castVote(bytes32 proposalId, uint256 support) external returns (uint256);
/// @notice Casts a vote with a reason
/// @param proposalId The proposal id
/// @param support The support value (0 = Against, 1 = For, 2 = Abstain)
/// @param reason The vote reason
function castVoteWithReason(bytes32 proposalId, uint256 support, string memory reason) external returns (uint256);
/// @notice Casts a signed vote
/// @dev BREAKING CHANGE (V2 → V3): Function signature AND EIP-712 typehash changed
///
/// V2: castVoteBySig(voter, proposalId, support, deadline, v, r, s)
/// V3: castVoteBySig(voter, proposalId, support, nonce, deadline, sig)
///
/// CRITICAL: Old V2 signatures are INVALID and cannot be reused
/// - V2 VOTE_TYPEHASH did not include nonce
/// - V3 VOTE_TYPEHASH includes nonce for replay protection
/// - Signers MUST create NEW signatures using the V3 typehash
///
/// Migration: Users must re-sign votes with:
/// 1. Updated function signature (add nonce parameter, use bytes sig)
/// 2. Updated EIP-712 domain/typehash (includes nonce in struct)
/// 3. Fetch current nonce from nonces[voter] before signing
///
/// Rationale: ERC-1271 smart wallet support, explicit replay protection
///
/// @param voter The voter address
/// @param proposalId The proposal id
/// @param support The support value (0 = Against, 1 = For, 2 = Abstain)
/// @param nonce The expected vote signature nonce
/// @param deadline The signature deadline
/// @param sig The EIP-712 signature bytes
function castVoteBySig(address voter, bytes32 proposalId, uint256 support, uint256 nonce, uint256 deadline, bytes calldata sig)
external
returns (uint256);
/// @notice Queues a proposal
/// @param proposalId The proposal id
/// @return eta The execution timestamp
function queue(bytes32 proposalId) external returns (uint256 eta);
/// @notice Executes a proposal
/// @param targets The target addresses to call
/// @param values The ETH values of each call
/// @param calldatas The calldata of each call
/// @param descriptionHash The hash of the description
/// @param proposer The proposal creator
function execute(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash, address proposer)
external
payable
returns (bytes32);
/// @notice Cancels a proposal
/// @param proposalId The proposal id
function cancel(bytes32 proposalId) external;
/// @notice Vetoes a proposal
/// @param proposalId The proposal id
function veto(bytes32 proposalId) external;
/// @notice The state of a proposal
/// @param proposalId The proposal id
function state(bytes32 proposalId) external view returns (ProposalState);
/// @notice The voting weight of an account at a timestamp
/// @param account The account address
/// @param timestamp The specific timestamp
function getVotes(address account, uint256 timestamp) external view returns (uint256);
/// @notice The current number of votes required to submit a proposal
function proposalThreshold() external view returns (uint256);
/// @notice The current number of votes required to be in favor of a proposal in order to reach quorum
function quorum() external view returns (uint256);
/// @notice The details of a proposal
/// @param proposalId The proposal id
function getProposal(bytes32 proposalId) external view returns (Proposal memory);
/// @notice The signers that sponsored a signed proposal
/// @param proposalId The proposal id
function getProposalSigners(bytes32 proposalId) external view returns (address[] memory);
/// @notice The timestamp until which proposal updates are allowed
/// @param proposalId The proposal id
function proposalUpdatePeriodEnd(bytes32 proposalId) external view returns (uint256);
/// @notice The timestamp when voting starts for a proposal
/// @param proposalId The proposal id
function proposalSnapshot(bytes32 proposalId) external view returns (uint256);
/// @notice The timestamp when voting ends for a proposal
/// @param proposalId The proposal id
function proposalDeadline(bytes32 proposalId) external view returns (uint256);
/// @notice The vote counts for a proposal
/// @param proposalId The proposal id
/// @return againstVotes The number of votes against
/// @return forVotes The number of votes for
/// @return abstainVotes The number of abstain votes
function proposalVotes(bytes32 proposalId) external view returns (uint256 againstVotes, uint256 forVotes, uint256 abstainVotes);
/// @notice The timestamp valid to execute a proposal
/// @param proposalId The proposal id
function proposalEta(bytes32 proposalId) external view returns (uint256);
/// @notice The minimum basis points of the total token supply required to submit a proposal
function proposalThresholdBps() external view returns (uint256);
/// @notice The minimum basis points of the total token supply required to reach quorum
function quorumThresholdBps() external view returns (uint256);
/// @notice The amount of time until voting begins after a proposal is created
function votingDelay() external view returns (uint256);
/// @notice The amount of time to vote on a proposal
function votingPeriod() external view returns (uint256);
/// @notice The amount of time a proposal is editable after creation
function proposalUpdatablePeriod() external view returns (uint256);
/// @notice The current proposal-signature nonce for an account
/// @param account The signer address
function proposeSignatureNonce(address account) external view returns (uint256);
/// @notice The address eligible to veto any proposal (address(0) if burned)
function vetoer() external view returns (address);
/// @notice The address of the governance token
function token() external view returns (address);
/// @notice The address of the DAO treasury
function treasury() external view returns (address);
/// @notice Updates the voting delay
/// @param newVotingDelay The new voting delay
function updateVotingDelay(uint256 newVotingDelay) external;
/// @notice Updates the voting period
/// @param newVotingPeriod The new voting period
function updateVotingPeriod(uint256 newVotingPeriod) external;
/// @notice Updates the proposal updatable period
/// @param newProposalUpdatablePeriod The new proposal updatable period
function updateProposalUpdatablePeriod(uint256 newProposalUpdatablePeriod) external;
/// @notice Updates the minimum proposal threshold
/// @param newProposalThresholdBps The new proposal threshold basis points
function updateProposalThresholdBps(uint256 newProposalThresholdBps) external;
/// @notice Updates the minimum quorum threshold
/// @param newQuorumVotesBps The new quorum votes basis points
function updateQuorumThresholdBps(uint256 newQuorumVotesBps) external;
/// @notice Updates the delayed governance expiration timestamp
/// @param _newDelayedTimestamp The new delayed governance expiration timestamp
function updateDelayedGovernanceExpirationTimestamp(uint256 _newDelayedTimestamp) external;
/// @notice Updates the vetoer
/// @param newVetoer The new vetoer address
function updateVetoer(address newVetoer) external;
/// @notice Burns the vetoer
function burnVetoer() external;
/// @notice The EIP-712 typehash to vote with a signature
function VOTE_TYPEHASH() external view returns (bytes32);
}
src/governance/governor/ProposalHasher.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
/// @title ProposalHasher
/// @author tbtstl
/// @notice Helper contract to ensure proposal hashing functions are unified
abstract contract ProposalHasher {
/// ///
/// HASH PROPOSAL ///
/// ///
/// @notice Hashes a proposal's details into a proposal id
/// @param _targets The target addresses to call
/// @param _values The ETH values of each call
/// @param _calldatas The calldata of each call
/// @param _descriptionHash The hash of the description
/// @param _proposer The original proposer of the transaction
function hashProposal(address[] memory _targets, uint256[] memory _values, bytes[] memory _calldatas, bytes32 _descriptionHash, address _proposer)
public
pure
returns (bytes32)
{
return keccak256(abi.encode(_targets, _values, _calldatas, _descriptionHash, _proposer));
}
}
src/governance/governor/types/GovernorTypesV1.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
import { Token } from "../../../token/Token.sol";
import { Treasury } from "../../treasury/Treasury.sol";
/// @title GovernorTypesV1
/// @author Rohan Kulkarni
/// @notice The Governor custom data types
interface GovernorTypesV1 {
/// @notice The governor settings
/// @param token The DAO governance token
/// @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 treasury The DAO treasury
/// @param votingDelay The time delay to vote on a created proposal
/// @param votingPeriod The time period to vote on a proposal
/// @param vetoer The address with the ability to veto proposals
struct Settings {
Token token;
uint16 proposalThresholdBps;
uint16 quorumThresholdBps;
Treasury treasury;
uint48 votingDelay;
uint48 votingPeriod;
address vetoer;
}
/// @notice A governance proposal
/// @param proposer The proposal creator
/// @param timeCreated The timestamp that the proposal was created
/// @param againstVotes The number of votes against
/// @param forVotes The number of votes in favor
/// @param abstainVotes The number of votes abstained
/// @param voteStart The timestamp that voting starts
/// @param voteEnd The timestamp that voting ends
/// @param proposalThreshold The proposal threshold when the proposal was created
/// @param quorumVotes The quorum threshold when the proposal was created
/// @param executed If the proposal was executed
/// @param canceled If the proposal was canceled
/// @param vetoed If the proposal was vetoed
struct Proposal {
address proposer;
uint32 timeCreated;
uint32 againstVotes;
uint32 forVotes;
uint32 abstainVotes;
uint32 voteStart;
uint32 voteEnd;
uint32 proposalThreshold;
uint32 quorumVotes;
bool executed;
bool canceled;
bool vetoed;
}
struct ProposerSignature {
address signer;
uint256 nonce;
uint256 deadline;
bytes sig;
}
/// @notice The proposal state type
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed,
Vetoed,
Updatable,
Replaced
}
}
src/governance/treasury/ITreasury.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
import { IOwnable } from "../../lib/utils/Ownable.sol";
import { IUUPS } from "../../lib/interfaces/IUUPS.sol";
/// @title ITreasury
/// @author Rohan Kulkarni
/// @notice The external Treasury events, errors and functions
interface ITreasury is IUUPS, IOwnable {
/// ///
/// EVENTS ///
/// ///
/// @notice Emitted when a transaction is scheduled
/// @param proposalId The proposal ID
/// @param timestamp The scheduled execution timestamp
event TransactionScheduled(bytes32 proposalId, uint256 timestamp);
/// @notice Emitted when a transaction is canceled
/// @param proposalId The proposal ID
event TransactionCanceled(bytes32 proposalId);
/// @notice Emitted when a transaction is executed
/// @param proposalId The proposal ID
/// @param targets The target addresses
/// @param values The ETH values
/// @param payloads The calldata payloads
event TransactionExecuted(bytes32 proposalId, address[] targets, uint256[] values, bytes[] payloads);
/// @notice Emitted when the transaction delay is updated
/// @param prevDelay The previous delay
/// @param newDelay The new delay
event DelayUpdated(uint256 prevDelay, uint256 newDelay);
/// @notice Emitted when the grace period is updated
/// @param prevGracePeriod The previous grace period
/// @param newGracePeriod The new grace period
event GracePeriodUpdated(uint256 prevGracePeriod, uint256 newGracePeriod);
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if tx was already queued
error PROPOSAL_ALREADY_QUEUED();
/// @dev Reverts if tx was not queued
error PROPOSAL_NOT_QUEUED();
/// @dev Reverts if a tx isn't ready to execute
/// @param proposalId The proposal id
error EXECUTION_NOT_READY(bytes32 proposalId);
/// @dev Reverts if a tx failed
/// @param txIndex The index of the tx
error EXECUTION_FAILED(uint256 txIndex);
/// @dev Reverts if execution was attempted after the grace period
error EXECUTION_EXPIRED();
/// @dev Reverts if the caller was not the treasury itself
error ONLY_TREASURY();
/// @dev Reverts if the caller was not the contract manager
error ONLY_MANAGER();
/// ///
/// FUNCTIONS ///
/// ///
/// @notice Initializes a DAO's treasury
/// @param governor The governor address
/// @param timelockDelay The time delay to execute a queued transaction
function initialize(address governor, uint256 timelockDelay) external;
/// @notice The timestamp that a proposal is valid to execute
/// @param proposalId The proposal id
function timestamp(bytes32 proposalId) external view returns (uint256);
/// @notice If a proposal has been queued
/// @param proposalId The proposal ids
function isQueued(bytes32 proposalId) external view returns (bool);
/// @notice If a proposal is ready to execute (does not consider if a proposal has expired)
/// @param proposalId The proposal id
function isReady(bytes32 proposalId) external view returns (bool);
/// @notice If a proposal has expired to execute
/// @param proposalId The proposal id
function isExpired(bytes32 proposalId) external view returns (bool);
/// @notice Schedules a proposal for execution
/// @param proposalId The proposal id
/// @return eta The execution timestamp
function queue(bytes32 proposalId) external returns (uint256 eta);
/// @notice Removes a queued proposal
/// @param proposalId The proposal id
function cancel(bytes32 proposalId) external;
/// @notice Executes a queued proposal
/// @param targets The target addresses to call
/// @param values The ETH values of each call
/// @param calldatas The calldata of each call
/// @param descriptionHash The hash of the description
/// @param proposer The proposal creator
function execute(address[] calldata targets, uint256[] calldata values, bytes[] calldata calldatas, bytes32 descriptionHash, address proposer)
external
payable;
/// @notice The time delay to execute a queued transaction
function delay() external view returns (uint256);
/// @notice The time period to execute a transaction
function gracePeriod() external view returns (uint256);
/// @notice Updates the time delay
/// @param newDelay The new time delay
function updateDelay(uint256 newDelay) external;
/// @notice Updates the grace period
/// @param newGracePeriod The grace period
function updateGracePeriod(uint256 newGracePeriod) external;
}
src/governance/treasury/Treasury.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
import { UUPS } from "../../lib/proxy/UUPS.sol";
import { Ownable } from "../../lib/utils/Ownable.sol";
import { ERC721TokenReceiver, ERC1155TokenReceiver } from "../../lib/utils/TokenReceiver.sol";
import { SafeCast } from "../../lib/utils/SafeCast.sol";
import { TreasuryStorageV1 } from "./storage/TreasuryStorageV1.sol";
import { ITreasury } from "./ITreasury.sol";
import { ProposalHasher } from "../governor/ProposalHasher.sol";
import { IManager } from "../../manager/IManager.sol";
import { VersionedContract } from "../../VersionedContract.sol";
/// @title Treasury
/// @author Rohan Kulkarni
/// @notice A DAO's treasury and transaction executor
/// @custom:repo github.com/ourzora/nouns-protocol
/// Modified from:
/// - OpenZeppelin Contracts v4.7.3 (governance/TimelockController.sol)
/// - NounsDAOExecutor.sol commit 2cbe6c7 - licensed under the BSD-3-Clause license.
contract Treasury is ITreasury, VersionedContract, UUPS, Ownable, ProposalHasher, TreasuryStorageV1 {
/// ///
/// CONSTANTS ///
/// ///
/// @notice The default grace period setting
uint128 private constant INITIAL_GRACE_PERIOD = 2 weeks;
/// ///
/// IMMUTABLES ///
/// ///
/// @notice The contract upgrade manager
IManager private immutable manager;
/// ///
/// CONSTRUCTOR ///
/// ///
/// @notice Initializes the treasury with the manager address
/// @param _manager The contract upgrade manager address
constructor(address _manager) payable initializer {
manager = IManager(_manager);
}
/// ///
/// INITIALIZER ///
/// ///
/// @notice Initializes an instance of a DAO's treasury
/// @param _governor The DAO's governor address
/// @param _delay The time delay to execute a queued transaction
function initialize(address _governor, uint256 _delay) external initializer {
// Ensure the caller is the contract manager
if (msg.sender != address(manager)) revert ONLY_MANAGER();
// Ensure a governor address was provided
if (_governor == address(0)) revert ADDRESS_ZERO();
// Grant ownership to the governor
__Ownable_init(_governor);
// Store the time delay
settings.delay = SafeCast.toUint128(_delay);
// Set the default grace period
settings.gracePeriod = INITIAL_GRACE_PERIOD;
emit DelayUpdated(0, _delay);
}
/// ///
/// TRANSACTION STATE ///
/// ///
/// @notice The timestamp that a proposal is valid to execute
/// @param _proposalId The proposal id
function timestamp(bytes32 _proposalId) external view returns (uint256) {
return timestamps[_proposalId];
}
/// @notice If a queued proposal can no longer be executed
/// @param _proposalId The proposal id
function isExpired(bytes32 _proposalId) external view returns (bool) {
unchecked {
return block.timestamp > (timestamps[_proposalId] + settings.gracePeriod);
}
}
/// @notice If a proposal is queued
/// @param _proposalId The proposal id
function isQueued(bytes32 _proposalId) public view returns (bool) {
return timestamps[_proposalId] != 0;
}
/// @notice If a proposal is ready to execute (does not consider expiration)
/// @param _proposalId The proposal id
function isReady(bytes32 _proposalId) public view returns (bool) {
return timestamps[_proposalId] != 0 && block.timestamp >= timestamps[_proposalId];
}
/// ///
/// QUEUE PROPOSAL ///
/// ///
/// @notice Schedules a proposal for execution
/// @param _proposalId The proposal id
/// @return eta The execution timestamp
function queue(bytes32 _proposalId) external onlyOwner returns (uint256 eta) {
// Ensure the proposal was not already queued
if (isQueued(_proposalId)) revert PROPOSAL_ALREADY_QUEUED();
// Cannot realistically overflow
unchecked {
// Compute the timestamp that the proposal will be valid to execute
eta = block.timestamp + settings.delay;
}
// Store the timestamp
timestamps[_proposalId] = eta;
emit TransactionScheduled(_proposalId, eta);
}
/// ///
/// EXECUTE PROPOSAL ///
/// ///
/// @notice Executes a queued proposal
/// @param _targets The target addresses to call
/// @param _values The ETH values of each call
/// @param _calldatas The calldata of each call
/// @param _descriptionHash The hash of the description
/// @param _proposer The proposal creator
function execute(
address[] calldata _targets,
uint256[] calldata _values,
bytes[] calldata _calldatas,
bytes32 _descriptionHash,
address _proposer
) external payable onlyOwner {
// Get the proposal id
bytes32 proposalId = hashProposal(_targets, _values, _calldatas, _descriptionHash, _proposer);
// Ensure the proposal is ready to execute
if (!isReady(proposalId)) revert EXECUTION_NOT_READY(proposalId);
// Remove the proposal from the queue
delete timestamps[proposalId];
// Cache the number of targets
uint256 numTargets = _targets.length;
// Cannot realistically overflow
unchecked {
// For each target:
for (uint256 i = 0; i < numTargets; ++i) {
// Execute the transaction
(bool success,) = _targets[i].call{ value: _values[i] }(_calldatas[i]);
// Ensure the transaction succeeded
if (!success) revert EXECUTION_FAILED(i);
}
}
emit TransactionExecuted(proposalId, _targets, _values, _calldatas);
}
/// ///
/// CANCEL PROPOSAL ///
/// ///
/// @notice Removes a queued proposal
/// @param _proposalId The proposal id
function cancel(bytes32 _proposalId) external onlyOwner {
// Ensure the proposal is queued
if (!isQueued(_proposalId)) revert PROPOSAL_NOT_QUEUED();
// Remove the proposal from the queue
delete timestamps[_proposalId];
emit TransactionCanceled(_proposalId);
}
/// ///
/// TREASURY SETTINGS ///
/// ///
/// @notice The time delay to execute a queued transaction
function delay() external view returns (uint256) {
return settings.delay;
}
/// @notice The time period to execute a proposal
function gracePeriod() external view returns (uint256) {
return settings.gracePeriod;
}
/// ///
/// UPDATE SETTINGS ///
/// ///
/// @notice Updates the transaction delay
/// @param _newDelay The new time delay
function updateDelay(uint256 _newDelay) external {
// Ensure the caller is the treasury itself
if (msg.sender != address(this)) revert ONLY_TREASURY();
emit DelayUpdated(settings.delay, _newDelay);
// Update the delay
settings.delay = SafeCast.toUint128(_newDelay);
}
/// @notice Updates the execution grace period
/// @param _newGracePeriod The new grace period
function updateGracePeriod(uint256 _newGracePeriod) external {
// Ensure the caller is the treasury itself
if (msg.sender != address(this)) revert ONLY_TREASURY();
emit GracePeriodUpdated(settings.gracePeriod, _newGracePeriod);
// Update the grace period
settings.gracePeriod = SafeCast.toUint128(_newGracePeriod);
}
/// ///
/// RECEIVE TOKENS ///
/// ///
/// @notice Accepts all ERC-721 transfers
function onERC721Received(address, address, uint256, bytes memory) public pure returns (bytes4) {
return ERC721TokenReceiver.onERC721Received.selector;
}
/// @notice Accepts all ERC-1155 single id transfers
function onERC1155Received(address, address, uint256, uint256, bytes memory) public pure returns (bytes4) {
return ERC1155TokenReceiver.onERC1155Received.selector;
}
/// @notice Accept all ERC-1155 batch id transfers
function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public pure returns (bytes4) {
return ERC1155TokenReceiver.onERC1155BatchReceived.selector;
}
/// @notice Accepts ETH transfers
receive() external payable { }
/// ///
/// TREASURY UPGRADE ///
/// ///
/// @notice Ensures the caller is authorized to upgrade the contract and that the new implementation is valid
/// @dev This function is called in `upgradeTo` & `upgradeToAndCall`
/// @param _newImpl The new implementation address
function _authorizeUpgrade(address _newImpl) internal view override {
// Ensure the caller is the treasury itself
if (msg.sender != address(this)) revert ONLY_TREASURY();
// Ensure the new implementation is a registered upgrade
if (!manager.isRegisteredUpgrade(_getImplementation(), _newImpl)) revert INVALID_UPGRADE(_newImpl);
}
}
src/governance/treasury/storage/TreasuryStorageV1.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
import { TreasuryTypesV1 } from "../types/TreasuryTypesV1.sol";
/// @title TreasuryStorageV1
/// @author Rohan Kulkarni
/// @notice The Treasury storage contract
contract TreasuryStorageV1 is TreasuryTypesV1 {
/// @notice The treasury settings
Settings internal settings;
/// @notice The timestamp that a queued proposal is ready to execute
/// @dev Proposal Id => Timestamp
mapping(bytes32 => uint256) internal timestamps;
}
src/governance/treasury/types/TreasuryTypesV1.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
/// @title TreasuryTypesV1
/// @author Rohan Kulkarni
/// @notice The treasury's custom data types
contract TreasuryTypesV1 {
/// @notice The settings type
/// @param gracePeriod The time period to execute a proposal
/// @param delay The time delay to execute a queued transaction
struct Settings {
uint128 gracePeriod;
uint128 delay;
}
}
src/lib/interfaces/IEIP712.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
/// @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.35;
/// @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.35;
/// @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.35;
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.35;
/// @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.35;
/// @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/IPausable.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
/// @title IPausable
/// @author Rohan Kulkarni
/// @notice The external Pausable events, errors, and functions
interface IPausable {
/// ///
/// EVENTS ///
/// ///
/// @notice Emitted when the contract is paused
/// @param user The address that paused the contract
event Paused(address user);
/// @notice Emitted when the contract is unpaused
/// @param user The address that unpaused the contract
event Unpaused(address user);
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if called when the contract is paused
error PAUSED();
/// @dev Reverts if called when the contract is unpaused
error UNPAUSED();
/// ///
/// FUNCTIONS ///
/// ///
/// @notice If the contract is paused
function paused() external view returns (bool);
}
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/interfaces/IVersionedContract.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
interface IVersionedContract {
function contractVersion() external pure returns (string memory);
}
src/lib/proxy/ERC1967Proxy.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
import { Proxy } from "@openzeppelin/contracts/proxy/Proxy.sol";
import { IERC1967Upgrade } from "../interfaces/IERC1967Upgrade.sol";
import { ERC1967Upgrade } from "./ERC1967Upgrade.sol";
/// @title ERC1967Proxy
/// @author Rohan Kulkarni
/// @notice Modified from OpenZeppelin Contracts v4.7.3 (proxy/ERC1967/ERC1967Proxy.sol)
/// - Inherits a modern, minimal ERC1967Upgrade
contract ERC1967Proxy is IERC1967Upgrade, Proxy, ERC1967Upgrade {
/// ///
/// CONSTRUCTOR ///
/// ///
/// @dev Initializes the proxy with an implementation contract and encoded function call
/// @param _logic The implementation address
/// @param _data The encoded function call
constructor(address _logic, bytes memory _data) payable {
_upgradeToAndCall(_logic, _data, false);
}
/// ///
/// FUNCTIONS ///
/// ///
/// @dev The address of the current implementation
function _implementation() internal view virtual override returns (address) {
return ERC1967Upgrade._getImplementation();
}
}
src/lib/proxy/ERC1967Upgrade.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
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.35;
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.35;
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/token/ERC721Votes.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
import { IERC721Votes } from "../interfaces/IERC721Votes.sol";
import { ERC721 } from "../token/ERC721.sol";
import { EIP712 } from "../utils/EIP712.sol";
/// @title ERC721Votes
/// @author Rohan Kulkarni
/// @notice Modified from OpenZeppelin Contracts v4.7.3 (token/ERC721/extensions/draft-ERC721Votes.sol) & Nouns DAO ERC721Checkpointable.sol commit 2cbe6c7 - licensed under the BSD-3-Clause license.
/// - Uses custom errors defined in IERC721Votes
/// - Checkpoints are based on timestamps instead of block numbers
/// - Tokens are self-delegated by default
/// - The total number of votes is the token supply itself
abstract contract ERC721Votes is IERC721Votes, EIP712, ERC721 {
/// ///
/// CONSTANTS ///
/// ///
/// @dev The EIP-712 typehash to delegate with a signature
bytes32 internal constant DELEGATION_TYPEHASH = keccak256("Delegation(address from,address to,uint256 nonce,uint256 deadline)");
/// ///
/// STORAGE ///
/// ///
/// @notice The delegate for an account
/// @notice Account => Delegate
mapping(address => address) internal delegation;
/// @notice The number of checkpoints for an account
/// @dev Account => Num Checkpoints
mapping(address => uint256) internal numCheckpoints;
/// @notice The checkpoint for an account
/// @dev Account => Checkpoint Id => Checkpoint
mapping(address => mapping(uint256 => Checkpoint)) internal checkpoints;
/// ///
/// VOTING WEIGHT ///
/// ///
/// @notice The current number of votes for an account
/// @param _account The account address
function getVotes(address _account) public view returns (uint256) {
// Get the account's number of checkpoints
uint256 nCheckpoints = numCheckpoints[_account];
// Cannot underflow as `nCheckpoints` is ensured to be greater than 0 if reached
unchecked {
// Return the number of votes at the latest checkpoint if applicable
return nCheckpoints != 0 ? checkpoints[_account][nCheckpoints - 1].votes : 0;
}
}
/// @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) public view returns (uint256) {
// Ensure the given timestamp is in the past
if (_timestamp >= block.timestamp) revert INVALID_TIMESTAMP();
// Get the account's number of checkpoints
uint256 nCheckpoints = numCheckpoints[_account];
// If there are none return 0
if (nCheckpoints == 0) return 0;
// Get the account's checkpoints
mapping(uint256 => Checkpoint) storage accountCheckpoints = checkpoints[_account];
unchecked {
// Get the latest checkpoint id
// Cannot underflow as `nCheckpoints` is ensured to be greater than 0
uint256 lastCheckpoint = nCheckpoints - 1;
// If the latest checkpoint has a valid timestamp, return its number of votes
if (accountCheckpoints[lastCheckpoint].timestamp <= _timestamp) return accountCheckpoints[lastCheckpoint].votes;
// If the first checkpoint doesn't have a valid timestamp, return 0
if (accountCheckpoints[0].timestamp > _timestamp) return 0;
// Otherwise, find a checkpoint with a valid timestamp
// Use the latest id as the initial upper bound
uint256 high = lastCheckpoint;
uint256 low;
uint256 middle;
// Used to temporarily hold a checkpoint
Checkpoint memory cp;
// While a valid checkpoint is to be found:
while (high > low) {
// Find the id of the middle checkpoint
middle = high - (high - low) / 2;
// Get the middle checkpoint
cp = accountCheckpoints[middle];
// If the timestamp is a match:
if (cp.timestamp == _timestamp) {
// Return the voting weight
return cp.votes;
// Else if the timestamp is before the one looking for:
} else if (cp.timestamp < _timestamp) {
// Update the lower bound
low = middle;
// Else update the upper bound
} else {
high = middle - 1;
}
}
return accountCheckpoints[low].votes;
}
}
/// ///
/// DELEGATION ///
/// ///
/// @notice The delegate for an account
/// @param _account The account address
function delegates(address _account) public view returns (address) {
address current = delegation[_account];
return current == address(0) ? _account : current;
}
/// @notice Delegates votes to an account
/// @param _to The address delegating votes to
function delegate(address _to) external {
_delegate(msg.sender, _to);
}
/// @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 {
// Ensure the signature has not expired
if (block.timestamp > _deadline) revert EXPIRED_SIGNATURE();
// Used to store the digest
bytes32 digest;
// Cannot realistically overflow
unchecked {
// Compute the hash of the domain seperator with the typed delegation data
digest = keccak256(
abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR(), keccak256(abi.encode(DELEGATION_TYPEHASH, _from, _to, nonces[_from]++, _deadline)))
);
}
// Recover the message signer
address recoveredAddress = ecrecover(digest, _v, _r, _s);
// Ensure the recovered signer is the voter
if (recoveredAddress == address(0) || recoveredAddress != _from) revert INVALID_SIGNATURE();
// Update the delegate
_delegate(_from, _to);
}
/// @dev Updates delegate addresses
/// @param _from The address delegating votes from
/// @param _to The address delegating votes to
function _delegate(address _from, address _to) internal {
// If address(0) is being delegated to, update the op as a self-delegate
if (_to == address(0)) _to = _from;
// Get the previous delegate
address prevDelegate = delegates(_from);
// Store the new delegate
delegation[_from] = _to;
emit DelegateChanged(_from, prevDelegate, _to);
// Transfer voting weight from the previous delegate to the new delegate
_moveDelegateVotes(prevDelegate, _to, balanceOf(_from));
}
/// @dev Transfers voting weight
/// @param _from The address delegating votes from
/// @param _to The address delegating votes to
/// @param _amount The number of votes delegating
function _moveDelegateVotes(address _from, address _to, uint256 _amount) internal {
unchecked {
// If voting weight is being transferred:
if (_from != _to && _amount > 0) {
// If this isn't a token mint:
if (_from != address(0)) {
// Get the sender's number of checkpoints
uint256 newCheckpointId = numCheckpoints[_from];
// Used to store their previous checkpoint id
uint256 prevCheckpointId;
// Used to store their previous checkpoint's voting weight
uint256 prevTotalVotes;
// Used to store their previous checkpoint's timestamp
uint256 prevTimestamp;
// If this isn't the sender's first checkpoint:
if (newCheckpointId != 0) {
// Get their previous checkpoint's id
prevCheckpointId = newCheckpointId - 1;
// Get their previous checkpoint's voting weight
prevTotalVotes = checkpoints[_from][prevCheckpointId].votes;
// Get their previous checkpoint's timestamp
prevTimestamp = checkpoints[_from][prevCheckpointId].timestamp;
}
// Update their voting weight
_writeCheckpoint(_from, newCheckpointId, prevCheckpointId, prevTimestamp, prevTotalVotes, prevTotalVotes - _amount);
}
// If this isn't a token burn:
if (_to != address(0)) {
// Get the recipients's number of checkpoints
uint256 nCheckpoints = numCheckpoints[_to];
// Used to store their previous checkpoint id
uint256 prevCheckpointId;
// Used to store their previous checkpoint's voting weight
uint256 prevTotalVotes;
// Used to store their previous checkpoint's timestamp
uint256 prevTimestamp;
// If this isn't the recipient's first checkpoint:
if (nCheckpoints != 0) {
// Get their previous checkpoint's id
prevCheckpointId = nCheckpoints - 1;
// Get their previous checkpoint's voting weight
prevTotalVotes = checkpoints[_to][prevCheckpointId].votes;
// Get their previous checkpoint's timestamp
prevTimestamp = checkpoints[_to][prevCheckpointId].timestamp;
}
// Update their voting weight
_writeCheckpoint(_to, nCheckpoints, prevCheckpointId, prevTimestamp, prevTotalVotes, prevTotalVotes + _amount);
}
}
}
}
/// @dev Records a checkpoint
/// @param _account The account address
/// @param _newId The new checkpoint id
/// @param _prevId The previous checkpoint id
/// @param _prevTimestamp The previous checkpoint timestamp
/// @param _prevTotalVotes The previous checkpoint voting weight
/// @param _newTotalVotes The new checkpoint voting weight
function _writeCheckpoint(
address _account,
uint256 _newId,
uint256 _prevId,
uint256 _prevTimestamp,
uint256 _prevTotalVotes,
uint256 _newTotalVotes
) private {
unchecked {
// If the new checkpoint is not the user's first AND has the timestamp of the previous checkpoint:
if (_newId > 0 && _prevTimestamp == block.timestamp) {
// Just update the previous checkpoint's votes
checkpoints[_account][_prevId].votes = uint192(_newTotalVotes);
// Else write a new checkpoint:
} else {
// Get the pointer to store the checkpoint
Checkpoint storage checkpoint = checkpoints[_account][_newId];
// Store the new voting weight and the current time
checkpoint.votes = uint192(_newTotalVotes);
checkpoint.timestamp = uint64(block.timestamp);
// Increment the account's number of checkpoints
++numCheckpoints[_account];
}
emit DelegateVotesChanged(_account, _prevTotalVotes, _newTotalVotes);
}
}
/// @dev Enables each NFT to equal 1 vote
/// @param _from The token sender
/// @param _to The token recipient
/// @param _tokenId The ERC-721 token id
function _afterTokenTransfer(address _from, address _to, uint256 _tokenId) internal override {
// Transfer 1 vote from the sender to the recipient
_moveDelegateVotes(delegates(_from), delegates(_to), 1);
super._afterTokenTransfer(_from, _to, _tokenId);
}
}
src/lib/utils/Address.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
/// @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/EIP712.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
import { IEIP712 } from "../interfaces/IEIP712.sol";
import { Initializable } from "../utils/Initializable.sol";
/// @title EIP712
/// @author Rohan Kulkarni
/// @notice Modified from OpenZeppelin Contracts v4.7.3 (utils/cryptography/draft-EIP712Upgradeable.sol)
/// - Uses custom errors declared in IEIP712
/// - Caches `INITIAL_CHAIN_ID` and `INITIAL_DOMAIN_SEPARATOR` upon initialization
/// - Adds mapping for account nonces
abstract contract EIP712 is IEIP712, Initializable {
/// ///
/// CONSTANTS ///
/// ///
/// @dev The EIP-712 domain typehash
bytes32 internal constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/// ///
/// STORAGE ///
/// ///
/// @notice The hash of the EIP-712 domain name
bytes32 internal HASHED_NAME;
/// @notice The hash of the EIP-712 domain version
bytes32 internal HASHED_VERSION;
/// @notice The domain separator computed upon initialization
bytes32 internal INITIAL_DOMAIN_SEPARATOR;
/// @notice The chain id upon initialization
uint256 internal INITIAL_CHAIN_ID;
/// @notice The account nonces
/// @dev Account => Nonce
mapping(address => uint256) internal nonces;
/// ///
/// FUNCTIONS ///
/// ///
/// @dev Initializes EIP-712 support
/// @param _name The EIP-712 domain name
/// @param _version The EIP-712 domain version
function __EIP712_init(string memory _name, string memory _version) internal onlyInitializing {
HASHED_NAME = keccak256(bytes(_name));
HASHED_VERSION = keccak256(bytes(_version));
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = _computeDomainSeparator();
}
/// @notice The current nonce for an account
/// @param _account The account address
function nonce(address _account) external view returns (uint256) {
return nonces[_account];
}
/// @notice The EIP-712 domain separator
function DOMAIN_SEPARATOR() public view returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : _computeDomainSeparator();
}
/// @dev Computes the EIP-712 domain separator
function _computeDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_TYPEHASH, HASHED_NAME, HASHED_VERSION, block.chainid, address(this)));
}
}
src/lib/utils/Initializable.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
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/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
import { IOwnable } from "../interfaces/IOwnable.sol";
import { Initializable } from "../utils/Initializable.sol";
/// @title Ownable
/// @author Rohan Kulkarni
/// @notice Modified from OpenZeppelin Contracts v4.7.3 (access/OwnableUpgradeable.sol)
/// - Uses custom errors declared in IOwnable
/// - Adds optional two-step ownership transfer (`safeTransferOwnership` + `acceptOwnership`)
abstract contract Ownable is IOwnable, Initializable {
/// ///
/// STORAGE ///
/// ///
/// @dev The address of the owner
address internal _owner;
/// @dev The address of the pending owner
address internal _pendingOwner;
/// ///
/// MODIFIERS ///
/// ///
/// @dev Ensures the caller is the owner
modifier onlyOwner() {
if (msg.sender != _owner) revert ONLY_OWNER();
_;
}
/// @dev Ensures the caller is the pending owner
modifier onlyPendingOwner() {
if (msg.sender != _pendingOwner) revert ONLY_PENDING_OWNER();
_;
}
/// ///
/// FUNCTIONS ///
/// ///
/// @dev Initializes contract ownership
/// @param _initialOwner The initial owner address
function __Ownable_init(address _initialOwner) internal onlyInitializing {
_owner = _initialOwner;
emit OwnerUpdated(address(0), _initialOwner);
}
/// @notice The address of the owner
function owner() public view virtual returns (address) {
return _owner;
}
/// @notice The address of the pending owner
function pendingOwner() public view returns (address) {
return _pendingOwner;
}
/// @notice Forces an ownership transfer from the last owner
/// @param _newOwner The new owner address
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/// @notice Forces an ownership transfer from any sender
/// @param _newOwner New owner to transfer contract to
/// @dev Ensure is called only from trusted internal code, no access control checks.
function _transferOwnership(address _newOwner) internal {
emit OwnerUpdated(_owner, _newOwner);
_owner = _newOwner;
if (_pendingOwner != address(0)) delete _pendingOwner;
}
/// @notice Initiates a two-step ownership transfer
/// @param _newOwner The new owner address
function safeTransferOwnership(address _newOwner) public onlyOwner {
_pendingOwner = _newOwner;
emit OwnerPending(_owner, _newOwner);
}
/// @notice Accepts an ownership transfer
function acceptOwnership() public onlyPendingOwner {
emit OwnerUpdated(_owner, msg.sender);
_owner = _pendingOwner;
delete _pendingOwner;
}
/// @notice Cancels a pending ownership transfer
function cancelOwnershipTransfer() public onlyOwner {
emit OwnerCanceled(_owner, _pendingOwner);
delete _pendingOwner;
}
}
src/lib/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
import { Initializable } from "../utils/Initializable.sol";
/// @notice Modified from OpenZeppelin Contracts v4.7.3 (security/ReentrancyGuardUpgradeable.sol)
/// - Uses custom error `REENTRANCY()`
abstract contract ReentrancyGuard is Initializable {
/// ///
/// STORAGE ///
/// ///
/// @dev Indicates a function has not been entered
uint256 internal constant _NOT_ENTERED = 1;
/// @dev Indicates a function has been entered
uint256 internal constant _ENTERED = 2;
/// @notice The reentrancy status of a function
uint256 internal _status;
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if attempted reentrancy
error REENTRANCY();
/// ///
/// FUNCTIONS ///
/// ///
/// @dev Initializes the reentrancy guard
function __ReentrancyGuard_init() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/// @dev Ensures a function cannot be reentered
modifier nonReentrant() {
if (_status == _ENTERED) revert REENTRANCY();
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
src/lib/utils/SafeCast.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
/// @notice Modified from OpenZeppelin Contracts v4.7.3 (utils/math/SafeCast.sol)
/// - Uses custom error `UNSAFE_CAST()`
library SafeCast {
error UNSAFE_CAST();
function toUint128(uint256 x) internal pure returns (uint128) {
if (x > type(uint128).max) revert UNSAFE_CAST();
return uint128(x);
}
function toUint64(uint256 x) internal pure returns (uint64) {
if (x > type(uint64).max) revert UNSAFE_CAST();
return uint64(x);
}
function toUint48(uint256 x) internal pure returns (uint48) {
if (x > type(uint48).max) revert UNSAFE_CAST();
return uint48(x);
}
function toUint40(uint256 x) internal pure returns (uint40) {
if (x > type(uint40).max) revert UNSAFE_CAST();
return uint40(x);
}
function toUint32(uint256 x) internal pure returns (uint32) {
if (x > type(uint32).max) revert UNSAFE_CAST();
return uint32(x);
}
function toUint16(uint256 x) internal pure returns (uint16) {
if (x > type(uint16).max) revert UNSAFE_CAST();
return uint16(x);
}
function toUint8(uint256 x) internal pure returns (uint8) {
if (x > type(uint8).max) revert UNSAFE_CAST();
return uint8(x);
}
}
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.35;
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 a DAO is deployed deterministically
/// @param deployer The deployer address
/// @param deploySalt The base salt used for deterministic deployment
/// @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 DAODeployedDeterministic(
address indexed deployer, bytes32 indexed deploySalt, 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);
/// @notice Event emitted when metadata renderer is updated.
/// @param sender address of the updater
/// @param renderer new metadata renderer address
event MetadataRendererUpdated(address sender, address renderer);
/// ///
/// ERRORS ///
/// ///
/// @dev Reverts if at least one founder is not provided upon deploy
error FOUNDER_REQUIRED();
/// @dev Reverts if caller is not the token owner
error ONLY_TOKEN_OWNER();
/// ///
/// 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
/// @param metadataRenderer Optional custom metadata renderer (uses Manager's default if address(0))
/// @param reservedUntilTokenId The tokenId that a DAO's auctions will start at
struct TokenParams {
bytes initStrings;
address metadataRenderer;
uint256 reservedUntilTokenId;
}
/// @notice The auction parameters
/// @param reservePrice The reserve price of each auction
/// @param duration The duration of each auction
/// @param founderRewardRecipent The address to send founder rewards to
/// @param founderRewardBps Percent of the auction bid in BPS to send to the founder recipient
struct AuctionParams {
uint256 reservePrice;
uint256 duration;
address founderRewardRecipent;
uint16 founderRewardBps;
}
/// @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)
/// @param proposalUpdatablePeriod The time period a proposal is editable after creation
struct GovParams {
uint256 timelockDelay;
uint256 votingDelay;
uint256 votingPeriod;
uint256 proposalThresholdBps;
uint256 quorumThresholdBps;
address vetoer;
uint256 proposalUpdatablePeriod;
}
/// ///
/// 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 Deprecated: deploys a DAO with custom token, auction, and governance settings for backward compatibility only.
/// @dev New integrations should use deterministic deployment
/// @param founderParams The DAO founder(s)
/// @param tokenParams The ERC-721 token settings
/// @param auctionParams The auction settings
/// @param govParams The governance settings
/// @return token The deployed token address
/// @return metadataRenderer The deployed metadata renderer address
/// @return auction The deployed auction address
/// @return treasury The deployed treasury address
/// @return governor The deployed governor address
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 Deploys a DAO deterministically using CREATE2 and explicit implementation addresses
/// @dev SECURITY NOTES:
/// - deploySalt should be unique for each deployment. Using the same salt twice will cause revert.
/// - msg.sender is included in salt derivation to prevent cross-deployer collisions
/// - Recommended: use keccak256(abi.encode(daoName, timestamp, nonce)) or similar for deploySalt
///
/// GAS COSTS: Deterministic deployment may cost slightly more gas than legacy deploy()
/// due to CREATE2 overhead. However, benefits include:
/// - Predictable addresses for pre-funding or integration
/// - Custom implementation flexibility
/// - Cross-chain address consistency (if desired)
/// @param founderParams The DAO founder(s)
/// @param tokenParams The ERC-721 token settings
/// @param auctionParams The auction settings
/// @param govParams The governance settings
/// @param deploySalt The base salt used to derive per-contract CREATE2 salts (must be unique)
/// @return token The deployed token address
/// @return metadataRenderer The deployed metadata renderer address
/// @return auction The deployed auction address
/// @return treasury The deployed treasury address
/// @return governor The deployed governor address
function deployDeterministic(
FounderParams[] calldata founderParams,
TokenParams calldata tokenParams,
AuctionParams calldata auctionParams,
GovParams calldata govParams,
bytes32 deploySalt
) external returns (address token, address metadataRenderer, address auction, address treasury, address governor);
/// @notice Predicts deterministic DAO addresses using an explicit implementation bundle
/// @param deployer The deployer address used to namespace the deterministic salt
/// @param deploySalt The base salt used to derive per-contract CREATE2 salts
/// @return token The predicted token address
/// @return metadataRenderer The predicted metadata renderer address
/// @return auction The predicted auction address
/// @return treasury The predicted treasury address
/// @return governor The predicted governor address
function predictDeterministicAddresses(address deployer, bytes32 deploySalt)
external
view
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
/// @return metadataRenderer The metadata renderer address
/// @return auction The auction address
/// @return treasury The treasury address
/// @return governor The governor 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/manager/storage/ManagerStorageV1.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
import { ManagerTypesV1 } from "../types/ManagerTypesV1.sol";
/// @title Manager Storage V1
/// @author Rohan Kulkarni
/// @notice The Manager storage contract
contract ManagerStorageV1 is ManagerTypesV1 {
/// @notice If a contract has been registered as an upgrade
/// @dev Base impl => Upgrade impl
mapping(address => mapping(address => bool)) internal isUpgrade;
/// @notice Registers deployed addresses
/// @dev Token deployed address => Struct of all other DAO addresses
mapping(address => DAOAddresses) internal daoAddressesByToken;
}
src/manager/types/ManagerTypesV1.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
/// @title ManagerTypesV1
/// @author Iain Nash & Rohan Kulkarni
/// @notice The external Base Metadata errors and functions
interface ManagerTypesV1 {
/// @notice Stores deployed addresses for a given token's DAO
// forge-lint: disable-next-line(pascal-case-struct)
struct DAOAddresses {
/// @notice Address for deployed metadata contract
address metadata;
/// @notice Address for deployed auction contract
address auction;
/// @notice Address for deployed treasury contract
address treasury;
/// @notice Address for deployed governor contract
address governor;
}
}
src/token/IToken.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
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";
import { IBaseMetadata } from "./metadata/interfaces/IBaseMetadata.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);
/// @notice Event emitted when metadata renderer is updated.
/// @param renderer new metadata renderer address
event MetadataRendererUpdated(address renderer);
/// @notice Event emitted when the reserved token ID is updated
/// @param reservedUntilTokenId The new reserved until token ID
event ReservedUntilTokenIDUpdated(uint256 reservedUntilTokenId);
/// ///
/// 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();
/// @dev Reverts if the token is not reserved
error TOKEN_NOT_RESERVED();
/// @dev Reverts if the token reserve is being decreased
error CANNOT_DECREASE_RESERVE();
/// @dev Reverts if the token reserve cannot be changed
error CANNOT_CHANGE_RESERVE();
/// ///
/// FUNCTIONS ///
/// ///
/// @notice Initializes a DAO's ERC-721 token contract
/// @param founders The DAO founders
/// @param initStrings The encoded token and metadata initialization strings
/// @param reservedUntilTokenId The tokenId that a DAO's auctions will start at
/// @param metadataRenderer The token's metadata renderer
/// @param auction The token's auction house
/// @param initialOwner The initial owner of the token
function initialize(
IManager.FounderParams[] calldata founders,
bytes calldata initStrings,
uint256 reservedUntilTokenId,
address metadataRenderer,
address auction,
address initialOwner
) external;
/// @notice Mints tokens to the caller and handles founder vesting
/// @return tokenId The ID of the minted token
function mint() external returns (uint256 tokenId);
/// @notice Mints tokens to the recipient and handles founder vesting
/// @param recipient The address to mint tokens to
/// @return tokenId The ID of the minted token
function mintTo(address recipient) external returns (uint256 tokenId);
/// @notice Mints the specified amount of tokens to the recipient and handles founder vesting
/// @param amount The number of tokens to mint
/// @param recipient The address to mint tokens to
/// @return tokenIds The IDs of the minted tokens
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 number of tokens that can be claimed from the reserve
function remainingTokensInReserve() external view returns (uint256);
/// @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 Mints tokens from the reserve to the recipient
/// @param recipient The address to mint tokens to
/// @param tokenId The token ID to mint
function mintFromReserveTo(address recipient, uint256 tokenId) external;
/// @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;
/// @notice Set a new metadata renderer
/// @param newRenderer new renderer address to use
function setMetadataRenderer(IBaseMetadata newRenderer) external;
}
src/token/Token.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
import { UUPS } from "../lib/proxy/UUPS.sol";
import { ReentrancyGuard } from "../lib/utils/ReentrancyGuard.sol";
import { ERC721Votes } from "../lib/token/ERC721Votes.sol";
import { ERC721 } from "../lib/token/ERC721.sol";
import { Ownable } from "../lib/utils/Ownable.sol";
import { TokenStorageV1 } from "./storage/TokenStorageV1.sol";
import { TokenStorageV2 } from "./storage/TokenStorageV2.sol";
import { TokenStorageV3 } from "./storage/TokenStorageV3.sol";
import { IBaseMetadata } from "./metadata/interfaces/IBaseMetadata.sol";
import { IManager } from "../manager/IManager.sol";
import { IAuction } from "../auction/IAuction.sol";
import { IToken } from "./IToken.sol";
import { VersionedContract } from "../VersionedContract.sol";
/// @title Token
/// @author Rohan Kulkarni & Neokry
/// @custom:repo github.com/ourzora/nouns-protocol
/// @notice A DAO's ERC-721 governance token
contract Token is IToken, VersionedContract, UUPS, Ownable, ReentrancyGuard, ERC721Votes, TokenStorageV1, TokenStorageV2, TokenStorageV3 {
/// ///
/// IMMUTABLES ///
/// ///
/// @notice The contract upgrade manager
// forge-lint: disable-next-line(screaming-snake-case-immutable)
IManager private immutable manager;
/// ///
/// MODIFIERS ///
/// ///
/// @notice Reverts if caller is not an authorized minter
// forge-lint: disable-next-line(unwrapped-modifier-logic)
modifier onlyMinter() {
if (!minter[msg.sender]) {
revert ONLY_AUCTION_OR_MINTER();
}
_;
}
/// @notice Reverts if caller is not an authorized minter
// forge-lint: disable-next-line(unwrapped-modifier-logic)
modifier onlyAuctionOrMinter() {
if (msg.sender != settings.auction && !minter[msg.sender]) {
revert ONLY_AUCTION_OR_MINTER();
}
_;
}
/// ///
/// CONSTRUCTOR ///
/// ///
/// @notice Initializes the token contract with the manager address
/// @param _manager The contract upgrade manager address
constructor(address _manager) payable initializer {
manager = IManager(_manager);
}
/// ///
/// INITIALIZER ///
/// ///
/// @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 _reservedUntilTokenId The tokenId that a DAO's auctions will start at
/// @param _metadataRenderer The token's metadata renderer
/// @param _auction The token's auction house
/// @param _initialOwner The initial owner of the token
function initialize(
IManager.FounderParams[] calldata _founders,
bytes calldata _initStrings,
uint256 _reservedUntilTokenId,
address _metadataRenderer,
address _auction,
address _initialOwner
) external initializer {
// Ensure the caller is the contract manager
if (msg.sender != address(manager)) {
revert ONLY_MANAGER();
}
// Initialize the reentrancy guard
__ReentrancyGuard_init();
// Setup ownable
__Ownable_init(_initialOwner);
// Store the founders and compute their allocations
_addFounders(_founders);
// Decode the token name and symbol
(string memory _name, string memory _symbol,,,,) = abi.decode(_initStrings, (string, string, string, string, string, string));
// Initialize the ERC-721 token
__ERC721_init(_name, _symbol);
// Store the metadata renderer and auction house
settings.metadataRenderer = IBaseMetadata(_metadataRenderer);
settings.auction = _auction;
reservedUntilTokenId = _reservedUntilTokenId;
}
/// @notice Called by the auction upon the first unpause / token mint to transfer ownership from founder to treasury
/// @dev Only callable by the auction contract
function onFirstAuctionStarted() external override {
if (msg.sender != settings.auction) {
revert ONLY_AUCTION();
}
// Force transfer ownership to the treasury
_transferOwnership(IAuction(settings.auction).treasury());
}
/// @notice Called upon initialization to add founders and compute their vesting allocations
/// @dev We do this by reserving an mapping of [0-100] token indices, such that if a new token mint ID % 100 is reserved, it's sent to the appropriate founder.
/// @param _founders The list of DAO founders
function _addFounders(IManager.FounderParams[] calldata _founders) internal {
// Used to store the total percent ownership among the founders
uint256 totalOwnership;
uint8 numFoundersAdded = 0;
unchecked {
// For each founder:
for (uint256 i; i < _founders.length; ++i) {
// Cache the percent ownership
uint256 founderPct = _founders[i].ownershipPct;
// Continue if no ownership is specified
if (founderPct == 0) {
continue;
}
// Update the total ownership and ensure it's valid
totalOwnership += founderPct;
// Check that founders own less than 100% of tokens
if (totalOwnership > 99) {
revert INVALID_FOUNDER_OWNERSHIP();
}
// Compute the founder's id
uint256 founderId = numFoundersAdded++;
// Get the pointer to store the founder
Founder storage newFounder = founder[founderId];
// Store the founder's vesting details
newFounder.wallet = _founders[i].wallet;
newFounder.vestExpiry = uint32(_founders[i].vestExpiry);
// Total ownership cannot be above 100 so this fits safely in uint8
// forge-lint: disable-next-line(unsafe-typecast)
newFounder.ownershipPct = uint8(founderPct);
// Compute the vesting schedule
uint256 schedule = 100 / founderPct;
// Used to store the base token id the founder will receive
uint256 baseTokenId = 0;
// For each token to vest:
for (uint256 j; j < founderPct; ++j) {
// Get the available token id
baseTokenId = _getNextTokenId(baseTokenId);
// Store the founder as the recipient
tokenRecipient[baseTokenId] = newFounder;
emit MintScheduled(baseTokenId, founderId, newFounder);
// Update the base token id
baseTokenId = (baseTokenId + schedule) % 100;
}
}
// Store the founders' details
// forge-lint: disable-next-line(unsafe-typecast)
settings.totalOwnership = uint8(totalOwnership);
settings.numFounders = numFoundersAdded;
}
}
/// @notice Finds the next available base token id for a founder
/// @param _tokenId The ERC-721 token id
function _getNextTokenId(uint256 _tokenId) internal view returns (uint256) {
unchecked {
while (tokenRecipient[_tokenId].wallet != address(0)) {
_tokenId = (++_tokenId) % 100;
}
return _tokenId;
}
}
/// ///
/// MINT ///
/// ///
/// @notice Mints tokens to the caller and handles founder vesting
/// @return tokenId The ID of the minted token
function mint() external nonReentrant onlyAuctionOrMinter returns (uint256 tokenId) {
tokenId = _mintWithVesting(msg.sender);
}
/// @notice Mints tokens to the recipient and handles founder vesting
/// @param recipient The address to receive the minted token
/// @return tokenId The ID of the minted token
function mintTo(address recipient) external nonReentrant onlyAuctionOrMinter returns (uint256 tokenId) {
tokenId = _mintWithVesting(recipient);
}
/// @notice Mints tokens from the reserve to the recipient
/// @param recipient The address to receive the reserved token
/// @param tokenId The ID of the reserved token to mint
function mintFromReserveTo(address recipient, uint256 tokenId) external nonReentrant onlyMinter {
// Token must be reserved
if (tokenId >= reservedUntilTokenId) revert TOKEN_NOT_RESERVED();
// Mint the token without vesting (reserved tokens do not count towards founders vesting)
_mint(recipient, tokenId);
}
/// @notice Mints the specified amount of tokens to the recipient and handles founder vesting
/// @param amount The number of tokens to mint
/// @param recipient The address to receive the minted tokens
/// @return tokenIds Array of IDs of the minted tokens
function mintBatchTo(uint256 amount, address recipient) external nonReentrant onlyAuctionOrMinter returns (uint256[] memory tokenIds) {
tokenIds = new uint256[](amount);
for (uint256 i = 0; i < amount;) {
tokenIds[i] = _mintWithVesting(recipient);
unchecked {
++i;
}
}
}
function _mintWithVesting(address recipient) internal returns (uint256 tokenId) {
// Cannot realistically overflow
unchecked {
do {
// Get the next token to mint
tokenId = reservedUntilTokenId + settings.mintCount++;
// Lookup whether the token is for a founder, and mint accordingly if so
} while (_isForFounder(tokenId));
}
// Mint the next available token to the recipient for bidding
_mint(recipient, tokenId);
}
/// @notice Overrides _mint to include attribute generation
/// @param _to The token recipient
/// @param _tokenId The ERC-721 token id
function _mint(address _to, uint256 _tokenId) internal override {
// Mint the token
super._mint(_to, _tokenId);
// Increment the total supply
unchecked {
++settings.totalSupply;
}
// Generate the token attributes
if (!settings.metadataRenderer.onMinted(_tokenId)) revert NO_METADATA_GENERATED();
}
/// @notice Checks if a given token is for a founder and mints accordingly
/// @param _tokenId The ERC-721 token id
function _isForFounder(uint256 _tokenId) private returns (bool) {
// Get the base token id
uint256 baseTokenId = _tokenId % 100;
// If there is no scheduled recipient:
if (tokenRecipient[baseTokenId].wallet == address(0)) {
return false;
// Else if the founder is still vesting:
} else if (block.timestamp < tokenRecipient[baseTokenId].vestExpiry) {
// Mint the token to the founder
_mint(tokenRecipient[baseTokenId].wallet, _tokenId);
return true;
// Else the founder has finished vesting:
} else {
// Remove them from future lookups
delete tokenRecipient[baseTokenId];
return false;
}
}
/// ///
/// BURN ///
/// ///
/// @notice Burns a token owned by the caller
/// @param _tokenId The ERC-721 token id
function burn(uint256 _tokenId) external onlyAuctionOrMinter {
// Ensure the caller owns the token
if (ownerOf(_tokenId) != msg.sender) {
revert ONLY_TOKEN_OWNER();
}
_burn(_tokenId);
}
function _burn(uint256 _tokenId) internal override {
// Call the parent burn function
super._burn(_tokenId);
// Reduce the total supply
unchecked {
--settings.totalSupply;
}
}
/// ///
/// METADATA ///
/// ///
/// @notice The URI for a token
/// @param _tokenId The ERC-721 token id
function tokenURI(uint256 _tokenId) public view override(IToken, ERC721) returns (string memory) {
return settings.metadataRenderer.tokenURI(_tokenId);
}
/// @notice The URI for the contract
function contractURI() public view override(IToken, ERC721) returns (string memory) {
return settings.metadataRenderer.contractURI();
}
/// ///
/// FOUNDERS ///
/// ///
/// @notice The number of founders
function totalFounders() external view returns (uint256) {
return settings.numFounders;
}
/// @notice The founders total percent ownership
function totalFounderOwnership() external view returns (uint256) {
return settings.totalOwnership;
}
/// @notice The vesting details of a founder
/// @param _founderId The founder id
function getFounder(uint256 _founderId) external view returns (Founder memory) {
return founder[_founderId];
}
/// @notice The vesting details of all founders
function getFounders() external view returns (Founder[] memory) {
// Cache the number of founders
uint256 numFounders = settings.numFounders;
// Get a temporary array to hold all founders
Founder[] memory founders = new Founder[](numFounders);
// Cannot realistically overflow
unchecked {
// Add each founder to the array
for (uint256 i; i < numFounders; ++i) {
founders[i] = founder[i];
}
}
return founders;
}
/// @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) {
return tokenRecipient[_tokenId % 100];
}
/// @notice Update the list of allocation owners
/// @param newFounders the full list of founders
function updateFounders(IManager.FounderParams[] calldata newFounders) external onlyOwner {
// Cache the number of founders
uint256 numFounders = settings.numFounders;
// Get a temporary array to hold all founders
Founder[] memory cachedFounders = new Founder[](numFounders);
// Cannot realistically overflow
unchecked {
// Add each founder to the array
for (uint256 i; i < numFounders; ++i) {
cachedFounders[i] = founder[i];
}
}
// Keep a mapping of all the reserved token IDs we're set to clear.
bool[] memory clearedTokenIds = new bool[](100);
unchecked {
// for each existing founder:
for (uint256 i; i < cachedFounders.length; ++i) {
// copy the founder into memory
Founder memory cachedFounder = cachedFounders[i];
// Delete the founder from the stored mapping
delete founder[i];
// Some DAOs were initialized with 0 percentage ownership.
// This skips them to avoid a division by zero error.
if (cachedFounder.ownershipPct == 0) {
continue;
}
// using the ownership percentage, get reserved token percentages
uint256 schedule = 100 / cachedFounder.ownershipPct;
// Used to reverse engineer the indices the founder has reserved tokens in.
uint256 baseTokenId;
for (uint256 j; j < cachedFounder.ownershipPct; ++j) {
// Get the next index that hasn't already been cleared
while (clearedTokenIds[baseTokenId] != false) {
baseTokenId = (++baseTokenId) % 100;
}
delete tokenRecipient[baseTokenId];
clearedTokenIds[baseTokenId] = true;
emit MintUnscheduled(baseTokenId, i, cachedFounder);
// Update the base token id
baseTokenId = (baseTokenId + schedule) % 100;
}
}
}
// Clear values from storage before adding new founders
settings.numFounders = 0;
settings.totalOwnership = 0;
emit FounderAllocationsCleared(newFounders);
_addFounders(newFounders);
}
/// ///
/// SETTINGS ///
/// ///
/// @notice The total supply of tokens
function totalSupply() external view returns (uint256) {
return settings.totalSupply;
}
/// @notice The total number of tokens that can be claimed from the reserve
function remainingTokensInReserve() external view returns (uint256) {
// total supply - total minted from auctions and airdrops
uint256 totalMintedFromReserve = settings.totalSupply - settings.mintCount;
// reservedUntilTokenId is also the total number of tokens in the reserve since tokens 0 -> reservedUntilTokenId - 1 are reserved
return reservedUntilTokenId - totalMintedFromReserve;
}
/// @notice The address of the auction house
function auction() external view returns (address) {
return settings.auction;
}
/// @notice The address of the metadata renderer
function metadataRenderer() external view returns (address) {
return address(settings.metadataRenderer);
}
/// @notice The contract owner
function owner() public view override(IToken, Ownable) returns (address) {
return super.owner();
}
/// @notice Update minters
/// @param _minters Array of structs containing address status as a minter
function updateMinters(MinterParams[] calldata _minters) external onlyOwner {
// Update each minter
for (uint256 i; i < _minters.length; ++i) {
// Skip if the minter is already set to the correct value
if (minter[_minters[i].minter] == _minters[i].allowed) continue;
emit MinterUpdated(_minters[i].minter, _minters[i].allowed);
// Update the minter
minter[_minters[i].minter] = _minters[i].allowed;
}
}
/// @notice Check if an address is a minter
/// @param _minter Address to check
function isMinter(address _minter) external view returns (bool) {
return minter[_minter];
}
/// @notice Set the tokenId that the reserve will end at
/// @param newReservedUntilTokenId The tokenId that the reserve will end at
function setReservedUntilTokenId(uint256 newReservedUntilTokenId) external onlyOwner {
// Cannot change the reserve after any non reserved tokens have been minted
// Added to prevent making any tokens inaccessible
if (settings.mintCount > 0) {
revert CANNOT_CHANGE_RESERVE();
}
// Cannot decrease the reserve if any tokens have been minted
// Added to prevent collisions with tokens being auctioned / vested
if (settings.totalSupply > 0 && reservedUntilTokenId > newReservedUntilTokenId) {
revert CANNOT_DECREASE_RESERVE();
}
// Set the new reserve
reservedUntilTokenId = newReservedUntilTokenId;
emit ReservedUntilTokenIDUpdated(newReservedUntilTokenId);
}
/// @notice Set a new metadata renderer
/// @param newRenderer new renderer address to use
function setMetadataRenderer(IBaseMetadata newRenderer) external {
// Ensure the caller is the contract manager
if (msg.sender != address(manager)) {
revert ONLY_MANAGER();
}
settings.metadataRenderer = newRenderer;
}
/// ///
/// TOKEN UPGRADE ///
/// ///
/// @notice Ensures the caller is authorized to upgrade the contract and that the new implementation is valid
/// @dev This function is called in `upgradeTo` & `upgradeToAndCall`
/// @param _newImpl The new implementation address
function _authorizeUpgrade(address _newImpl) internal view override {
// Ensure the caller is the shared owner of the token and metadata renderer
if (msg.sender != owner()) revert ONLY_OWNER();
// Ensure the implementation is valid
if (!manager.isRegisteredUpgrade(_getImplementation(), _newImpl)) revert INVALID_UPGRADE(_newImpl);
}
}
src/token/metadata/interfaces/IBaseMetadata.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
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/storage/TokenStorageV1.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
import { TokenTypesV1 } from "../types/TokenTypesV1.sol";
/// @title TokenStorageV1
/// @author Rohan Kulkarni
/// @notice The Token storage contract
contract TokenStorageV1 is TokenTypesV1 {
/// @notice The token settings
Settings internal settings;
/// @notice The vesting details of a founder
/// @dev Founder id => Founder
mapping(uint256 => Founder) internal founder;
/// @notice The recipient of a token
/// @dev ERC-721 token id => Founder
mapping(uint256 => Founder) internal tokenRecipient;
}
src/token/storage/TokenStorageV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
import { TokenTypesV2 } from "../types/TokenTypesV2.sol";
/// @title TokenStorageV2
/// @author James Geary
/// @notice The Token storage contract
contract TokenStorageV2 is TokenTypesV2 {
/// @notice The minter status of an address
mapping(address => bool) public minter;
}
src/token/storage/TokenStorageV3.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
/// @title TokenStorageV3
/// @author Neokry
/// @notice The Token storage contract
contract TokenStorageV3 {
/// @notice Marks the first n tokens as reserved
uint256 public reservedUntilTokenId;
}
src/token/types/TokenTypesV1.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
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.35;
/// @title TokenTypesV2
/// @author James Geary
/// @notice The Token custom data types
interface TokenTypesV2 {
struct MinterParams {
address minter;
bool allowed;
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "osaka",
"remappings": [
"@openzeppelin/=node_modules/@openzeppelin/",
"sol2string/=node_modules/sol2string/",
"sol-uriencode/=node_modules/sol-uriencode/",
"forge-std/=node_modules/forge-std/src/",
"ds-test/=node_modules/ds-test/src/",
"micro-onchain-metadata-utils/=node_modules/micro-onchain-metadata-utils/src/",
"create3-factory/=lib/create3-factory/src/",
"solmate/=lib/create3-factory/lib/solmate/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.