Verified contractExactMIT
TokenFactory
Address0xd4c724acdbe0c7ed0aa0fbf38c71285df2c92419
- Balance
0 ETH
- Transactions
28
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,501,068
- Creation transaction
- 0x258262b9aa…ef00e1bb5c
8 files
- src/TokenFactory.solmain11.26 KB
- node_modules/@openzeppelin/contracts/access/Ownable.sol3.1 KB
- node_modules/@openzeppelin/contracts/access/Ownable2Step.sol2.48 KB
- node_modules/@openzeppelin/contracts/utils/Context.sol963 B
- node_modules/@openzeppelin/contracts/utils/Pausable.sol2.83 KB
- node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol3.38 KB
- src/FeeGate.sol16.03 KB
- src/interfaces/ITokenDeployer.sol2.26 KB
src/TokenFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {FeeGate} from "./FeeGate.sol";
import {ITokenDeployer, TokenParams} from "./interfaces/ITokenDeployer.sol";
/// @notice Creates fixed-template ERC20 tokens for a fee taken from the on-chain price table.
/// @dev Each template is a codehash-pinned typed deployer with its own base price item; the deployer
/// names the price items of the optional features a config selects, and the fee is their sum. The
/// CREATE2 salt is bound to the caller, so nobody can take another user's predicted address.
contract TokenFactory is FeeGate {
struct Template {
address deployer;
bytes32 priceId;
}
uint256 public constant MAX_NAME_BYTES = 64;
uint256 public constant MAX_SYMBOL_BYTES = 16;
uint8 public constant MAX_DECIMALS = 18;
uint256 public constant MAX_SUPPLY = type(uint112).max;
uint256 public constant MAX_RESERVED_BATCH = 64;
/// @notice Registered templates. Append only.
mapping(bytes32 templateId => Template) public templates;
bytes32[] public templateIds;
/// @notice Keyed by keccak256 of the ASCII upper-cased symbol.
mapping(bytes32 symbolHash => bool reserved) public isReservedSymbol;
mapping(address token => bool created) public isFactoryToken;
event TemplateAdded(bytes32 indexed templateId, address indexed deployer, bytes32 codehash, bytes32 indexed priceId);
event ReservedSymbolSet(bytes32 indexed symbolHash, string symbol, bool reserved);
event TokenCreated(address indexed token, address indexed creator, bytes32 indexed templateId);
error UnknownTemplate(bytes32 templateId);
error TemplateExists(bytes32 templateId);
error ZeroTemplateId();
error CodehashMismatch(bytes32 expected, bytes32 actual);
error DeployerFactoryMismatch();
error ReservedSymbol();
error InvalidName();
error InvalidSymbol();
error InvalidDecimals();
error InvalidSupply();
constructor(address initialOwner, address treasury_, address initialGuardian)
FeeGate(initialOwner, treasury_, initialGuardian)
{}
/// @notice Creates a token from a registered template. The creator receives the initial supply (minus
/// any initial allocations of the config) and, for templates with an owner, the owner role.
/// @param templateId Registered template; it selects the base price item and the deployer.
/// @param userSalt Caller chosen salt, combined with the caller address.
/// @param p Token parameters.
/// @param config ABI encoded config struct of the template (see `ITokenConfigs`), empty for the
/// templates without options. The deployer checks it and names the priced features it selects.
/// @param refTag Opaque tag copied into every `FeePaid`.
/// @dev The fee is the template's item plus one item per selected feature, paid as one sum; see
/// `FeeGate._chargeFeeSet`.
function createToken(
bytes32 templateId,
bytes32 userSalt,
TokenParams calldata p,
bytes calldata config,
bytes32 refTag
) external payable whenNotPaused nonReentrant onlyPayer balanceNeutral returns (address token) {
Template memory t = templates[templateId];
if (t.deployer == address(0)) revert UnknownTemplate(templateId);
_checkParams(p);
bytes32[] memory priceIds = _priceItems(t, p, config);
_chargeFeeSet(priceIds, msg.value, _paramsHash(templateId, userSalt, p, config), refTag);
token = ITokenDeployer(t.deployer).deploy(_tokenSalt(msg.sender, userSalt), p, config, msg.sender);
// Written after the deploy call because it needs the address. Safe: the call is nonReentrant,
// the deployer is codehash pinned and the token constructor makes no external call.
isFactoryToken[token] = true;
emit TokenCreated(token, msg.sender, templateId);
}
/// @notice What `createToken` would charge for these inputs. Runs every input check `createToken`
/// runs before the fee, so it reverts with the same errors on an invalid input.
/// @return priceIds The template's item, then one item per selected feature, in charge order.
/// @return fee Sum of the current fees.
/// @return previousFee The other accepted sum while some item is in its grace window, else zero.
/// @return graceEndsAt First timestamp at which `previousFee` is rejected, or zero.
/// @return enabled Whether every item is enabled. Pause and the gate are not considered.
function quoteCreateToken(bytes32 templateId, TokenParams calldata p, bytes calldata config)
external
view
returns (bytes32[] memory priceIds, uint256 fee, uint256 previousFee, uint64 graceEndsAt, bool enabled)
{
Template memory t = templates[templateId];
if (t.deployer == address(0)) revert UnknownTemplate(templateId);
_checkParams(p);
priceIds = _priceItems(t, p, config);
(fee, previousFee, graceEndsAt, enabled) = _quoteFeeSet(priceIds);
}
/// @notice Registers a template. Append only: no removal, no replacement.
/// A template is switched off by disabling its price item.
function addTemplate(bytes32 templateId, address deployer, bytes32 expectedCodehash, bytes32 priceId)
external
onlyOwner
{
if (templateId == bytes32(0)) revert ZeroTemplateId();
if (priceId == bytes32(0)) revert ZeroPriceId();
if (templates[templateId].deployer != address(0)) revert TemplateExists(templateId);
bytes32 actual = deployer.codehash;
if (deployer.code.length == 0 || actual != expectedCodehash) {
revert CodehashMismatch(expectedCodehash, actual);
}
if (ITokenDeployer(deployer).factory() != address(this)) revert DeployerFactoryMismatch();
templates[templateId] = Template({deployer: deployer, priceId: priceId});
templateIds.push(templateId);
emit TemplateAdded(templateId, deployer, actual, priceId);
}
/// @notice Reserves or releases symbols, stored ASCII upper-cased. `createToken` rejects a symbol
/// whose upper-cased form, or whose ASCII letters and digits alone, match a listed symbol.
function setReservedSymbols(string[] calldata symbols, bool reserved) external onlyOwner {
uint256 n = symbols.length;
if (n == 0) revert EmptyBatch();
if (n > MAX_RESERVED_BATCH) revert BatchTooLarge();
for (uint256 i = 0; i < n; ++i) {
uint256 len = bytes(symbols[i]).length;
if (len == 0 || len > MAX_SYMBOL_BYTES) revert InvalidSymbol();
bytes32 symbolHash = _symbolHash(symbols[i]);
isReservedSymbol[symbolHash] = reserved;
emit ReservedSymbolSet(symbolHash, symbols[i], reserved);
}
}
/// @notice The address `createToken` gives `creator` for these arguments.
function predictTokenAddress(
bytes32 templateId,
address creator,
bytes32 userSalt,
TokenParams calldata p,
bytes calldata config
) external view returns (address) {
address deployer = templates[templateId].deployer;
if (deployer == address(0)) revert UnknownTemplate(templateId);
return ITokenDeployer(deployer).computeAddress(_tokenSalt(creator, userSalt), p, config, creator);
}
function templateCount() external view returns (uint256) {
return templateIds.length;
}
function _checkParams(TokenParams calldata p) private view {
uint256 nameLen = bytes(p.name).length;
if (nameLen == 0 || nameLen > MAX_NAME_BYTES) revert InvalidName();
uint256 symbolLen = bytes(p.symbol).length;
if (symbolLen == 0 || symbolLen > MAX_SYMBOL_BYTES) revert InvalidSymbol();
if (p.decimals > MAX_DECIMALS) revert InvalidDecimals();
if (p.supply == 0 || p.supply > MAX_SUPPLY) revert InvalidSupply();
if (_isReserved(p.symbol)) revert ReservedSymbol();
}
/// @dev The template's item first, then the features the codehash-pinned deployer reports for the
/// config (the deployer reverts on an invalid one).
function _priceItems(Template memory t, TokenParams calldata p, bytes calldata config)
private
view
returns (bytes32[] memory ids)
{
bytes32[] memory features = ITokenDeployer(t.deployer).features(p, config);
uint256 n = features.length;
ids = new bytes32[](n + 1);
ids[0] = t.priceId;
for (uint256 i = 0; i < n; ++i) {
ids[i + 1] = features[i];
}
}
function _paramsHash(bytes32 templateId, bytes32 userSalt, TokenParams calldata p, bytes calldata config)
private
pure
returns (bytes32)
{
return keccak256(
abi.encode(
templateId,
keccak256(bytes(p.name)),
keccak256(bytes(p.symbol)),
p.supply,
p.decimals,
userSalt,
p.cap,
keccak256(config)
)
);
}
function _validatePriceShape(bytes32 id, uint96 newBase, uint96 newPerUnit) internal pure override {
_requireFixedShape(id, newBase, newPerUnit);
}
function _tokenSalt(address creator, bytes32 userSalt) private pure returns (bytes32) {
return keccak256(abi.encode(creator, userSalt));
}
/// @dev keccak256 of the symbol with bytes 0x61..0x7a mapped to 0x41..0x5a. Other bytes unchanged.
function _symbolHash(string calldata symbol) private pure returns (bytes32) {
return keccak256(_asciiUpper(symbol));
}
/// @dev Reserved when the upper-cased symbol is listed, or when its ASCII letters and digits alone
/// are. The second form drops spaces, punctuation, control bytes and every non-ASCII byte, so
/// invisible or separator bytes around a listed symbol do not get past the list.
function _isReserved(string calldata symbol) private view returns (bool) {
bytes memory upper = _asciiUpper(symbol);
if (isReservedSymbol[keccak256(upper)]) return true;
uint256 len = upper.length;
uint256 kept = 0;
for (uint256 i = 0; i < len; ++i) {
if (_isUpperAlnum(upper[i])) ++kept;
}
// Nothing dropped: same hash as above. Nothing kept: the empty string is never listed.
if (kept == len || kept == 0) return false;
bytes memory core = new bytes(kept);
uint256 k = 0;
for (uint256 i = 0; i < len; ++i) {
bytes1 c = upper[i];
if (_isUpperAlnum(c)) {
core[k] = c;
++k;
}
}
return isReservedSymbol[keccak256(core)];
}
function _asciiUpper(string calldata s) private pure returns (bytes memory b) {
b = bytes(s);
uint256 len = b.length;
for (uint256 i = 0; i < len; ++i) {
bytes1 c = b[i];
if (c >= 0x61 && c <= 0x7a) {
b[i] = bytes1(uint8(c) - 32);
}
}
}
function _isUpperAlnum(bytes1 c) private pure returns (bool) {
return (c >= 0x30 && c <= 0x39) || (c >= 0x41 && c <= 0x5a);
}
}
node_modules/@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
node_modules/@openzeppelin/contracts/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
node_modules/@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
node_modules/@openzeppelin/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
src/FeeGate.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
/// @notice On-chain price table, access gate, pause switch and fee charge shared by every paid contract.
/// @dev Each concrete contract has its own table, gate, previewer list, pause flag and guardian.
/// The fee is forwarded to the immutable treasury in the same call; the contract never holds a balance.
abstract contract FeeGate is Ownable2Step, Pausable, ReentrancyGuard {
/// @dev Two storage slots. `version == 0` means the item was never priced.
struct PriceEntry {
uint96 base;
uint96 perUnit;
uint32 version;
bool enabled;
bool prevEnabled;
uint96 prevBase;
uint96 prevPerUnit;
uint48 changedAt;
}
/// @notice How long the previous price stays payable after a change.
uint256 public constant PRICE_GRACE = 15 minutes;
/// @notice Largest factor one `setPrices` write may move a non-zero price component, up or down.
uint256 public constant MAX_PRICE_STEP = 5;
/// @notice Largest number of ids per `setPrices` call and of accounts per `setPreviewers` call.
uint256 public constant MAX_BATCH = 32;
/// @notice Receives every fee: a multisig or a plain wallet. Fixed at construction; does not follow
/// ownership transfers.
address public immutable treasury;
/// @notice May only pause.
address public guardian;
/// @notice While true, only previewers may pay. Starts true and can only be switched off once.
bool public restricted;
mapping(address account => bool allowed) public isPreviewer;
mapping(bytes32 priceId => PriceEntry) internal _prices;
event FeePaid(
bytes32 indexed priceId,
address indexed payer,
bytes32 indexed refTag,
uint256 amount,
uint256 units,
uint32 priceVersion,
bytes32 paramsHash
);
event PriceSet(bytes32 indexed priceId, uint32 version, uint96 base, uint96 perUnit, bool enabled);
event PreviewerSet(address indexed account, bool allowed);
event OpenedToPublic();
event GuardianSet(address indexed previous, address indexed next);
error NotOpen();
error WrongFee(uint256 paid, uint256 expected);
error ZeroFee(bytes32 priceId);
error PriceDisabled(bytes32 priceId);
error PriceStepTooLarge(bytes32 priceId);
error PriceChangeTooSoon(bytes32 priceId);
error PerUnitNotSupported(bytes32 priceId);
error DuplicatePriceId(bytes32 priceId);
error ZeroPriceId();
error LengthMismatch();
error EmptyBatch();
error BatchTooLarge();
error ZeroAddress();
error AlreadyOpen();
error NotGuardian();
error RenounceDisabled();
error FeeForwardFailed();
error BalanceMismatch();
/// @param initialOwner Runs the price table, the gate, pause and unpause: a multisig or a plain wallet.
/// Never zero.
/// @param treasury_ Receives every fee in the same call: a multisig or a plain wallet, no code required.
/// Never zero. May equal the owner.
/// @param initialGuardian The pause-only account. May be zero.
constructor(address initialOwner, address treasury_, address initialGuardian)
Ownable(_requireNonZero(initialOwner))
{
treasury = _requireNonZero(treasury_);
restricted = true;
guardian = initialGuardian;
emit GuardianSet(address(0), initialGuardian);
}
// ---------------------------------------------------------------------------------------------
// Paid entry point helpers
// ---------------------------------------------------------------------------------------------
/// @dev Gate on the direct caller. Applied after `whenNotPaused` and `nonReentrant`.
modifier onlyPayer() {
if (!canPay(msg.sender)) revert NotOpen();
_;
}
/// @dev The native balance after the call must equal the balance before it, excluding this call's value.
modifier balanceNeutral() {
uint256 balanceBefore = address(this).balance - msg.value;
_;
// Compared by difference on purpose: forced or stray balance cancels out.
// slither-disable-next-line incorrect-equality
if (address(this).balance != balanceBefore) revert BalanceMismatch();
}
/// @dev Checks `paid` against the current price, or the previous price inside the grace window,
/// emits `FeePaid` and forwards `paid` to the treasury. Nothing runs between the event and the
/// forwarding call, so the treasury's receive log directly follows `FeePaid` in the receipt.
function _chargeFee(bytes32 priceId, uint256 units, uint256 paid, bytes32 paramsHash, bytes32 refTag) internal {
PriceEntry storage e = _prices[priceId];
if (!e.enabled) revert PriceDisabled(priceId);
uint256 current = _fee(e.base, e.perUnit, units);
uint32 usedVersion = 0;
if (paid == current) {
usedVersion = e.version;
} else if (
e.prevEnabled && block.timestamp < uint256(e.changedAt) + PRICE_GRACE
&& paid == _fee(e.prevBase, e.prevPerUnit, units)
) {
usedVersion = e.version - 1;
} else {
revert WrongFee(paid, current);
}
if (paid == 0) revert ZeroFee(priceId);
emit FeePaid(priceId, msg.sender, refTag, paid, units, usedVersion, paramsHash);
// The destination is the immutable treasury. All gas is forwarded: a Safe proxy needs more than 2300.
// slither-disable-next-line arbitrary-send-eth,low-level-calls
(bool ok,) = treasury.call{value: paid}("");
if (!ok) revert FeeForwardFailed();
}
/// @dev Charges several fixed price items (units 0) with one payment. `paid` must equal the sum of
/// the current fees, or, while any item is in its grace window, the sum in which every item still in
/// grace takes its previous fee and every other item its current fee. Each item then gets its own
/// `FeePaid` (with the version actually used) immediately followed by its own forwarding call, in
/// list order, so the treasury's receive log still directly follows every `FeePaid`.
/// The caller passes a non-empty list of distinct ids.
function _chargeFeeSet(bytes32[] memory ids, uint256 paid, bytes32 paramsHash, bytes32 refTag) internal {
uint256 n = ids.length;
uint256 current = 0;
uint256 previous = 0;
for (uint256 i = 0; i < n; ++i) {
PriceEntry storage e = _prices[ids[i]];
if (!e.enabled) revert PriceDisabled(ids[i]);
current += e.base;
previous += _inGrace(e) ? e.prevBase : e.base;
}
bool usePrevious = false;
if (paid != current) {
if (previous == current || paid != previous) revert WrongFee(paid, current);
usePrevious = true;
}
if (paid == 0) revert ZeroFee(ids[0]);
for (uint256 i = 0; i < n; ++i) {
_payItem(ids[i], usePrevious, paramsHash, refTag);
}
}
/// @dev One item of `_chargeFeeSet`: its `FeePaid`, then its forwarding call.
function _payItem(bytes32 id, bool usePrevious, bytes32 paramsHash, bytes32 refTag) private {
PriceEntry storage e = _prices[id];
bool usePrev = usePrevious && _inGrace(e);
uint256 amount = usePrev ? e.prevBase : e.base;
emit FeePaid(id, msg.sender, refTag, amount, 0, usePrev ? e.version - 1 : e.version, paramsHash);
// The destination is the immutable treasury. All gas is forwarded: a Safe proxy needs more than 2300.
// slither-disable-next-line arbitrary-send-eth,low-level-calls
(bool ok,) = treasury.call{value: amount}("");
if (!ok) revert FeeForwardFailed();
}
/// @dev Quote of `_chargeFeeSet`: the current sum, the grace sum while it differs from the current sum
/// (else zero), the first moment the grace sum stops being accepted, and whether every item is enabled.
function _quoteFeeSet(bytes32[] memory ids)
internal
view
returns (uint256 fee, uint256 previousFee, uint64 graceEndsAt, bool enabled)
{
enabled = true;
uint256 endsAt = type(uint256).max;
uint256 n = ids.length;
for (uint256 i = 0; i < n; ++i) {
PriceEntry storage e = _prices[ids[i]];
if (!e.enabled) enabled = false;
fee += e.base;
if (_inGrace(e)) {
previousFee += e.prevBase;
uint256 itemEnd = uint256(e.changedAt) + PRICE_GRACE;
if (itemEnd < endsAt) endsAt = itemEnd;
} else {
previousFee += e.base;
}
}
if (!enabled || previousFee == fee) {
previousFee = 0;
} else {
graceEndsAt = uint64(endsAt);
}
}
/// @dev Whether the previous price of an item is still accepted.
function _inGrace(PriceEntry storage e) private view returns (bool) {
return e.prevEnabled && block.timestamp < uint256(e.changedAt) + PRICE_GRACE;
}
/// @dev Current fee of an item for `units`, without the enabled check.
function _currentFee(bytes32 priceId, uint256 units) internal view returns (uint256) {
PriceEntry storage e = _prices[priceId];
return _fee(e.base, e.perUnit, units);
}
function _fee(uint256 base, uint256 perUnit, uint256 units) internal pure returns (uint256) {
uint256 variable = perUnit * units;
return variable > base ? variable : base;
}
// ---------------------------------------------------------------------------------------------
// Owner and guardian
// ---------------------------------------------------------------------------------------------
/// @notice Writes prices. Every write moves the current values to `prev*` and bumps `version`.
function setPrices(
bytes32[] calldata ids,
uint96[] calldata bases,
uint96[] calldata perUnits,
bool[] calldata enabledFlags
) external onlyOwner {
uint256 n = ids.length;
if (bases.length != n || perUnits.length != n || enabledFlags.length != n) revert LengthMismatch();
if (n == 0) revert EmptyBatch();
if (n > MAX_BATCH) revert BatchTooLarge();
for (uint256 i = 0; i < n; ++i) {
bytes32 id = ids[i];
if (id == bytes32(0)) revert ZeroPriceId();
for (uint256 j = 0; j < i; ++j) {
if (ids[j] == id) revert DuplicatePriceId(id);
}
_writePrice(id, bases[i], perUnits[i], enabledFlags[i]);
}
}
function _writePrice(bytes32 id, uint96 newBase, uint96 newPerUnit, bool newEnabled) private {
_validatePriceShape(id, newBase, newPerUnit);
PriceEntry storage e = _prices[id];
uint32 oldVersion = e.version;
if (oldVersion != 0) {
_checkStep(id, e.base, newBase);
_checkStep(id, e.perUnit, newPerUnit);
// changedAt is never ahead of the block, so `>=` means "written in this second".
if (e.changedAt >= block.timestamp) revert PriceChangeTooSoon(id);
}
uint32 newVersion = oldVersion + 1;
e.prevBase = e.base;
e.prevPerUnit = e.perUnit;
e.prevEnabled = e.enabled;
e.base = newBase;
e.perUnit = newPerUnit;
e.enabled = newEnabled;
e.version = newVersion;
e.changedAt = uint48(block.timestamp);
emit PriceSet(id, newVersion, newBase, newPerUnit, newEnabled);
}
/// @dev A non-zero component may move at most `MAX_PRICE_STEP` times up or down per write.
/// A zero component is free to move.
function _checkStep(bytes32 id, uint256 oldValue, uint256 newValue) private pure {
if (oldValue == 0) return;
if (newValue > oldValue * MAX_PRICE_STEP || newValue * MAX_PRICE_STEP < oldValue) {
revert PriceStepTooLarge(id);
}
}
/// @dev Contract specific rule for a price entry, applied to every write, enabled or not.
function _validatePriceShape(bytes32 id, uint96 newBase, uint96 newPerUnit) internal pure virtual;
/// @dev Shape of a fixed price item: no per unit component and a non-zero base.
function _requireFixedShape(bytes32 id, uint96 newBase, uint96 newPerUnit) internal pure {
if (newPerUnit != 0) revert PerUnitNotSupported(id);
if (newBase == 0) revert ZeroFee(id);
}
/// @notice Adds or removes accounts that may pay while the contract is restricted.
function setPreviewers(address[] calldata accounts, bool allowed) external onlyOwner {
uint256 n = accounts.length;
if (n == 0) revert EmptyBatch();
if (n > MAX_BATCH) revert BatchTooLarge();
for (uint256 i = 0; i < n; ++i) {
address account = accounts[i];
if (account == address(0)) revert ZeroAddress();
isPreviewer[account] = allowed;
emit PreviewerSet(account, allowed);
}
}
/// @notice Lets everyone pay. One way: nothing can restrict the contract again.
function openToPublic() external onlyOwner {
if (!restricted) revert AlreadyOpen();
restricted = false;
emit OpenedToPublic();
}
/// @notice Stops every paid entry point. Guardian or owner.
function pause() external {
if (msg.sender != guardian && msg.sender != owner()) revert NotGuardian();
_pause();
}
/// @notice Resumes paid entry points. Owner only.
function unpause() external onlyOwner {
_unpause();
}
/// @notice Replaces the guardian. Zero removes it.
function setGuardian(address newGuardian) external onlyOwner {
address previous = guardian;
guardian = newGuardian;
emit GuardianSet(previous, newGuardian);
}
/// @notice Disabled: the contract always has an owner.
function renounceOwnership() public pure override {
revert RenounceDisabled();
}
// ---------------------------------------------------------------------------------------------
// Views
// ---------------------------------------------------------------------------------------------
/// @notice Fee for `units` now, and the previous fee while it is still accepted.
/// @return fee Current fee.
/// @return previousFee Previous fee if the grace window is open now, else zero.
/// @return graceEndsAt First timestamp at which the previous fee is rejected, or zero.
/// @return enabled Whether the item is enabled. Pause is not considered.
function quoteFee(bytes32 id, uint256 units)
external
view
returns (uint256 fee, uint256 previousFee, uint64 graceEndsAt, bool enabled)
{
PriceEntry storage e = _prices[id];
fee = _fee(e.base, e.perUnit, units);
enabled = e.enabled;
uint256 endsAt = uint256(e.changedAt) + PRICE_GRACE;
if (enabled && e.prevEnabled && block.timestamp < endsAt) {
previousFee = _fee(e.prevBase, e.prevPerUnit, units);
graceEndsAt = uint64(endsAt);
}
}
/// @notice The full price entry of an item.
function getPrice(bytes32 id) external view returns (PriceEntry memory) {
return _prices[id];
}
/// @notice Gate only: whether `account` passes the restricted mode check.
function canPay(address account) public view returns (bool) {
return !restricted || isPreviewer[account];
}
function _requireNonZero(address account) private pure returns (address) {
if (account == address(0)) revert ZeroAddress();
return account;
}
}
src/interfaces/ITokenDeployer.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
/// @notice Parameters every template shares.
/// @dev `cap` is read only by the capped templates (capped-mintable, utility-mintable, managed-mintable)
/// and must be zero for the others.
struct TokenParams {
string name;
string symbol;
uint8 decimals;
uint256 supply;
uint256 cap;
}
/// @notice A typed deployer for one fixed token template. Only its factory may deploy.
/// @dev `config` is the ABI encoding of the template's config struct (see `ITokenConfigs`), or empty
/// for the templates without options. The deployer checks it in full before the factory charges the
/// fee, and again when it deploys.
interface ITokenDeployer {
error NotFactory();
error InvalidCap();
error DeployFailed();
/// @dev The config is empty where one is required, not empty where none is allowed, or selects
/// no feature where the template needs one.
error InvalidConfig();
error InvalidAllocations();
error InvalidMetadata();
error InvalidTaxRates();
error InvalidTaxWallets();
error InvalidLimits();
error InvalidLaunchSettings();
error InvalidSwapThreshold();
error InvalidRewardSettings();
error InvalidControlWindow();
/// @notice The only address allowed to call `deploy`.
function factory() external view returns (address);
/// @notice Checks `p` and `config` for this template and returns the price items of the selected
/// optional features, in a fixed order. Reverts with the errors above on an invalid input.
function features(TokenParams calldata p, bytes calldata config) external view returns (bytes32[] memory priceIds);
/// @notice Deploys one token with CREATE2. The creator receives the initial supply (minus any
/// initial allocations) and, for the templates that have one, the owner role.
function deploy(bytes32 salt, TokenParams calldata p, bytes calldata config, address creator)
external
returns (address token);
/// @notice The address `deploy` produces for the same arguments.
function computeAddress(bytes32 salt, TokenParams calldata p, bytes calldata config, address creator)
external
view
returns (address);
}
Compiler settingsShow
{
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/=node_modules/@openzeppelin/",
"@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
"forge-std/=node_modules/forge-std/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.