Verified contractExactMIT
HookdToken
Address0x0cdb0458285a2f0966196f5f863f22f3cd4d6954
- Balance
0 ETH
- Transactions
251
- Compiler
solc 0.8.26
- Same code
2 more contracts
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,068,908
- Creation transaction
- 0x62f35f9d19…d73c69f9c9
29 files
- src/HookdToken.solmain21.07 KB
- dependencies/@openzeppelin-contracts-5.0.2/access/Ownable.sol3.1 KB
- dependencies/@openzeppelin-contracts-5.0.2/interfaces/draft-IERC6093.sol6.53 KB
- dependencies/@openzeppelin-contracts-5.0.2/token/ERC20/ERC20.sol11.14 KB
- dependencies/@openzeppelin-contracts-5.0.2/token/ERC20/IERC20.sol2.78 KB
- dependencies/@openzeppelin-contracts-5.0.2/token/ERC20/extensions/IERC20Metadata.sol683 B
- dependencies/@openzeppelin-contracts-5.0.2/utils/Base64.sol3.86 KB
- dependencies/@openzeppelin-contracts-5.0.2/utils/Context.sol963 B
- dependencies/@openzeppelin-contracts-5.0.2/utils/Strings.sol3.1 KB
- dependencies/@openzeppelin-contracts-5.0.2/utils/math/Math.sol15.12 KB
- dependencies/@openzeppelin-contracts-5.0.2/utils/math/SignedMath.sol1.26 KB
- dependencies/v4-core-4.0.0/src/interfaces/IExtsload.sol1.02 KB
- dependencies/v4-core-4.0.0/src/interfaces/IExttload.sol699 B
- dependencies/v4-core-4.0.0/src/interfaces/IHooks.sol8.3 KB
- dependencies/v4-core-4.0.0/src/interfaces/IPoolManager.sol13.45 KB
- dependencies/v4-core-4.0.0/src/interfaces/IProtocolFees.sol2.49 KB
- dependencies/v4-core-4.0.0/src/interfaces/external/IERC20Minimal.sol3.04 KB
- dependencies/v4-core-4.0.0/src/interfaces/external/IERC6909Claims.sol3.16 KB
- dependencies/v4-core-4.0.0/src/libraries/CustomRevert.sol5.17 KB
- dependencies/v4-core-4.0.0/src/libraries/SafeCast.sol2.27 KB
- dependencies/v4-core-4.0.0/src/types/BalanceDelta.sol2.34 KB
- dependencies/v4-core-4.0.0/src/types/BeforeSwapDelta.sol1.47 KB
- dependencies/v4-core-4.0.0/src/types/Currency.sol5.46 KB
- dependencies/v4-core-4.0.0/src/types/PoolId.sol539 B
- dependencies/v4-core-4.0.0/src/types/PoolKey.sol805 B
- src/ERC3232.sol16.14 KB
- src/interfaces/IERC3232.sol6.03 KB
- src/interfaces/IERC3232Hook.sol494 B
- src/types/HookdArt.sol473 B
src/HookdToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {ERC3232} from "./ERC3232.sol";
import {IERC3232Hook} from "./interfaces/IERC3232Hook.sol";
import {HookdArt} from "./types/HookdArt.sol";
import {Ownable} from "@openzeppelin-contracts-5.0.2/access/Ownable.sol";
import {Base64} from "@openzeppelin-contracts-5.0.2/utils/Base64.sol";
import {Strings} from "@openzeppelin-contracts-5.0.2/utils/Strings.sol";
import {PoolKey} from "v4-core-4.0.0/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core-4.0.0/src/types/PoolId.sol";
import {Currency} from "v4-core-4.0.0/src/types/Currency.sol";
/// @title HookdToken
/// @notice Generic ERC3232 implementation with pure on-chain SVG art and uPEG-style pool-gated generation.
/// @dev Objects are minted only when the configured PoolManager transfers tokens out to a buyer.
contract HookdToken is ERC3232, Ownable {
using Strings for uint256;
using PoolIdLibrary for PoolKey;
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
uint256 public constant MAX_TRADING_WHITELIST_DURATION = 30 minutes;
event Started(address indexed pool, address indexed hook);
event GenerationPoolConfigured(bytes32 indexed poolId);
event HookSet(address indexed hook);
event ArtInitialized(uint8 width, uint8 height, uint256 layers, uint256 styles);
event ArtTraitsAdded(uint256 indexed layerIndex, uint256 startTraitIndex, uint256 count);
event ArtFinalized(uint256 totalTraitCombinations);
event TradingWhitelistDurationConfigured(uint256 durationSeconds);
event TradingWhitelistUpdated(address indexed account, bool allowed);
error AlreadyStarted();
error ArtAlreadyFinalized();
error ArtAlreadyInitialized();
error ArtNotFinalized();
error ArtNotInitialized();
error TraitCombinationsExhausted();
error InsufficientTraitCombinations(uint256 totalTraitCombinations, uint256 maxObjects);
error HookNotSet();
error InvalidArt();
error InvalidPool();
error TradingWhitelistDurationTooLong(uint256 durationSeconds);
error TradingNotAllowed(address account, uint256 expiresAt);
error ZeroHook();
address public hook;
address public pool;
bool public isStarted;
bool public artFinalized;
bytes32 public generationPoolId;
uint256 public tradingStartedAt;
uint256 public tradingWhitelistDuration;
uint256 public totalTraitCombinations;
uint256 public availableTraitCombinations;
mapping(address account => bool allowed) public tradingWhitelist;
mapping(address beneficiary => bytes32 seed) private _lastAutoGeneratedSeed;
mapping(uint256 tokenId => uint256 combination) private _objectCombinations;
mapping(uint256 index => uint256 combinationPlusOne) private _availableCombinationPlusOne;
uint8 private _artWidth;
uint8 private _artHeight;
string[] private _layerNames;
string[][] private _traitNames;
bytes[][] private _traitRects;
bytes private _styles;
uint256[] private _expectedTraitCounts;
/// @notice Deploys the token and mints the full ERC20 supply to `initialOwner`.
constructor(
string memory name_,
string memory symbol_,
uint256 initialSupply,
address initialOwner,
HookdArt memory art
) ERC3232(name_, symbol_, initialSupply, initialOwner) Ownable(initialOwner) {
if (art.layerNames.length != 0) _setArt(art);
}
function artLayersCount() external view returns (uint256) {
return _layerNames.length;
}
function artWidth() external view returns (uint256) {
return _artWidth;
}
function artHeight() external view returns (uint256) {
return _artHeight;
}
function artLayerName(uint256 layerIndex) external view returns (string memory) {
return _layerNames[layerIndex];
}
function artTraitsCount(uint256 layerIndex) external view returns (uint256) {
return _traitNames[layerIndex].length;
}
function artTraitName(uint256 layerIndex, uint256 traitIndex) external view returns (string memory) {
return _traitNames[layerIndex][traitIndex];
}
function artTraitRects(uint256 layerIndex, uint256 traitIndex) external view returns (bytes memory) {
return _traitRects[layerIndex][traitIndex];
}
function artStylesCount() external view returns (uint256) {
return _styleCount();
}
function artStyle(uint256 styleIndex) external view returns (string memory) {
return _style(styleIndex);
}
function objectCombination(uint256 tokenId) external view returns (uint256) {
return _objectCombination(tokenId);
}
/// @notice Initializes empty art storage so large collections can install traits over several transactions.
/// @dev `styles` is packed RGB data: 3 bytes per style, referenced by each trait rect's style index.
function initializeArt(
uint8 width,
uint8 height,
string[] calldata layerNames,
uint256[] calldata traitCounts,
bytes calldata styles
) external onlyOwner {
_initializeArt(width, height, layerNames, traitCounts, styles);
}
/// @notice Adds a batch of traits to one layer before launch.
function addArtTraits(uint256 layerIndex, string[] calldata traitNames, bytes[] calldata traitRects)
external
onlyOwner
{
_addArtTraits(layerIndex, traitNames, traitRects);
}
/// @notice Locks art configuration before pool-gated object generation can start.
function finalizeArt() external onlyOwner {
_finalizeArt();
}
/// @notice Configures how long pool buys/sells are restricted to the trading whitelist after launch.
/// @dev Must be set before launch so the first-window trading policy is fixed once trading starts.
function configureTradingWhitelist(uint256 durationSeconds) external onlyOwner {
if (isStarted) revert AlreadyStarted();
if (durationSeconds > MAX_TRADING_WHITELIST_DURATION) {
revert TradingWhitelistDurationTooLong(durationSeconds);
}
tradingWhitelistDuration = durationSeconds;
emit TradingWhitelistDurationConfigured(durationSeconds);
}
/// @notice Adds or removes accounts allowed to buy/sell through the pool during the initial restricted window.
/// @dev Must be set before launch. Holder-to-holder ERC20/object transfers are not restricted.
function setTradingWhitelist(address[] calldata accounts, bool allowed) external onlyOwner {
if (isStarted) revert AlreadyStarted();
for (uint256 i; i < accounts.length; i++) {
address account = accounts[i];
if (account == address(0)) revert ZeroAddress();
tradingWhitelist[account] = allowed;
emit TradingWhitelistUpdated(account, allowed);
}
}
/// @notice Sets the generation hook before launch.
function setHook(address newHook) public onlyOwner {
if (isStarted) revert AlreadyStarted();
if (newHook == address(0)) revert ZeroHook();
hook = newHook;
emit HookSet(newHook);
}
/// @notice Starts pool-gated automatic generation for the canonical v4 PoolManager/key.
/// @param newPool PoolManager address whose ERC20 transfers may trigger automatic generation.
/// @param key Pool key that must include this token and the configured hook.
function start(address newPool, PoolKey calldata key) external onlyOwner {
if (isStarted) revert AlreadyStarted();
if (!artFinalized) revert ArtNotFinalized();
if (newPool == address(0)) revert InvalidPool();
if (hook == address(0)) revert HookNotSet();
if (address(key.hooks) != hook) revert InvalidPool();
if (Currency.unwrap(key.currency0) != address(this) && Currency.unwrap(key.currency1) != address(this)) {
revert InvalidPool();
}
pool = newPool;
generationPoolId = PoolId.unwrap(key.toId());
tradingStartedAt = block.timestamp;
isStarted = true;
emit Started(newPool, hook);
emit GenerationPoolConfigured(generationPoolId);
}
function tradingWhitelistExpiresAt() public view returns (uint256) {
if (!isStarted || tradingWhitelistDuration == 0) return 0;
return tradingStartedAt + tradingWhitelistDuration;
}
function tradingWhitelistActive() public view returns (bool) {
uint256 expiresAt = tradingWhitelistExpiresAt();
return isStarted && expiresAt != 0 && block.timestamp < expiresAt;
}
/// @notice Returns base64 JSON metadata with embedded base64 SVG for a Hookd object.
function tokenURI(uint256 tokenId) public view override returns (string memory) {
objectSeed(tokenId);
string memory image = Base64.encode(bytes(_hookdSvg(tokenId)));
string memory json = Base64.encode(
bytes(
string.concat(
'{"name":"',
name(),
" #",
tokenId.toString(),
'","description":"A Hookd ERC3232 object: liquid-token triggered, NFT-readable, and fully rendered on-chain as SVG.",',
'"attributes":[',
_attributes(tokenId),
'],"image":"data:image/svg+xml;base64,',
image,
'"}'
)
)
);
return string.concat("data:application/json;base64,", json);
}
function _hookdSvg(uint256 tokenId) internal view returns (string memory) {
uint256 combination = _objectCombination(tokenId);
string memory dimension = uint256(_artWidth).toString();
string memory svg = string.concat(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ',
dimension,
" ",
uint256(_artHeight).toString(),
'" shape-rendering="crispEdges">'
);
for (uint256 layerIndex; layerIndex < _traitRects.length; layerIndex++) {
uint256 traitCount = _traitRects[layerIndex].length;
uint256 traitIndex = combination % traitCount;
combination /= traitCount;
svg = string.concat(svg, _renderTrait(_traitRects[layerIndex][traitIndex]));
}
return string.concat(svg, "</svg>");
}
function _update(address from, address to, uint256 value) internal override {
_enforceTradingWhitelist(from, to);
super._update(from, to, value);
if (!isStarted || to == address(0) || from != pool) return;
uint256 objectCount = value / tokensPerObject;
if (objectCount == 0) return;
// Bounds gas for pool-triggered generation. Excess tokens beyond the cap become
// available balance immediately and can be used to mint objects via other means.
if (objectCount > MAX_OBJECT_RECONCILIATION) objectCount = MAX_OBJECT_RECONCILIATION;
for (uint256 i; i < objectCount; i++) {
uint256 tokenId = _nextObjectIdValue();
bytes32 seed = _hookdSeed(to, tokenId);
_objectCombinations[tokenId] = _drawTraitCombination(seed, tokenId);
_mintObject(to, seed);
}
}
function _hookdSeed(address to, uint256 tokenId) internal returns (bytes32 seed) {
bytes32 hookSeed = IERC3232Hook(hook).randomSeed();
seed = keccak256(
abi.encode(
"HOOKD_POOL_AUTO_GENERATION",
hookSeed,
_lastAutoGeneratedSeed[to],
address(this),
msg.sender,
to,
tokenId,
ownerObjectsCount(to),
balanceOf(to),
block.chainid
)
);
_lastAutoGeneratedSeed[to] = seed;
}
function _enforceTradingWhitelist(address from, address to) internal view {
if (!tradingWhitelistActive()) return;
address trader;
if (from == pool && to != address(0)) {
trader = to;
} else if (to == pool && from != address(0)) {
trader = from;
} else {
return;
}
if (trader == owner() || tradingWhitelist[trader]) return;
revert TradingNotAllowed(trader, tradingWhitelistExpiresAt());
}
function _setArt(HookdArt memory art) internal {
if (
art.layerNames.length == 0 || art.layerNames.length != art.traitNames.length
|| art.layerNames.length != art.traitRects.length
) {
revert InvalidArt();
}
uint256[] memory traitCounts = new uint256[](art.traitNames.length);
for (uint256 layerIndex; layerIndex < art.traitNames.length; layerIndex++) {
traitCounts[layerIndex] = art.traitNames[layerIndex].length;
}
_initializeArt(art.width, art.height, art.layerNames, traitCounts, art.styles);
for (uint256 layerIndex; layerIndex < art.traitNames.length; layerIndex++) {
_addArtTraits(layerIndex, art.traitNames[layerIndex], art.traitRects[layerIndex]);
}
_finalizeArt();
}
function _initializeArt(
uint8 width,
uint8 height,
string[] memory layerNames,
uint256[] memory traitCounts,
bytes memory styles
) internal {
if (isStarted) revert AlreadyStarted();
if (_layerNames.length != 0 || artFinalized) revert ArtAlreadyInitialized();
if (layerNames.length == 0 || layerNames.length != traitCounts.length) revert InvalidArt();
if (!_validArtDimension(width) || !_validArtDimension(height)) revert InvalidArt();
if (styles.length == 0 || styles.length % 3 != 0 || styles.length / 3 > 256) revert InvalidArt();
_artWidth = width;
_artHeight = height;
_styles = styles;
totalTraitCombinations = 1;
for (uint256 layerIndex; layerIndex < layerNames.length; layerIndex++) {
uint256 traitCount = traitCounts[layerIndex];
if (bytes(layerNames[layerIndex]).length == 0 || traitCount == 0) revert InvalidArt();
if (totalTraitCombinations > type(uint256).max / traitCount) revert InvalidArt();
totalTraitCombinations *= traitCount;
_layerNames.push(layerNames[layerIndex]);
_traitNames.push();
_traitRects.push();
_expectedTraitCounts.push(traitCount);
}
emit ArtInitialized(width, height, layerNames.length, _styleCount());
}
function _addArtTraits(uint256 layerIndex, string[] memory traitNames, bytes[] memory traitRects) internal {
if (isStarted) revert AlreadyStarted();
if (_layerNames.length == 0) revert ArtNotInitialized();
if (artFinalized) revert ArtAlreadyFinalized();
if (layerIndex >= _layerNames.length || traitNames.length == 0 || traitNames.length != traitRects.length) {
revert InvalidArt();
}
uint256 startTraitIndex = _traitNames[layerIndex].length;
if (startTraitIndex + traitNames.length > _expectedTraitCounts[layerIndex]) revert InvalidArt();
for (uint256 traitIndex; traitIndex < traitNames.length; traitIndex++) {
if (bytes(traitNames[traitIndex]).length == 0) revert InvalidArt();
_validatePackedRects(traitRects[traitIndex], _styleCount(), _artWidth, _artHeight);
_traitNames[layerIndex].push(traitNames[traitIndex]);
_traitRects[layerIndex].push(traitRects[traitIndex]);
}
emit ArtTraitsAdded(layerIndex, startTraitIndex, traitNames.length);
}
function _finalizeArt() internal {
if (_layerNames.length == 0) revert ArtNotInitialized();
if (artFinalized) revert ArtAlreadyFinalized();
if (_styleCount() == 0) revert InvalidArt();
for (uint256 layerIndex; layerIndex < _layerNames.length; layerIndex++) {
if (_traitNames[layerIndex].length != _expectedTraitCounts[layerIndex]) revert InvalidArt();
}
uint256 maxObjectCount = maxObjects();
if (totalTraitCombinations < maxObjectCount) {
revert InsufficientTraitCombinations(totalTraitCombinations, maxObjectCount);
}
availableTraitCombinations = totalTraitCombinations;
artFinalized = true;
emit ArtFinalized(totalTraitCombinations);
}
function _validArtDimension(uint8 dimension) internal pure returns (bool) {
return dimension == 16 || dimension == 32 || dimension == 48;
}
function _validatePackedRects(bytes memory data, uint256 styleCount, uint256 artWidth_, uint256 artHeight_)
internal
pure
{
if (data.length == 0 || data.length % 5 != 0) revert InvalidArt();
for (uint256 offset; offset < data.length; offset += 5) {
uint256 x = uint8(data[offset]);
uint256 y = uint8(data[offset + 1]);
uint256 width = uint8(data[offset + 2]);
uint256 height = uint8(data[offset + 3]);
uint256 styleIndex = uint8(data[offset + 4]);
if (
width == 0 || height == 0 || x + width > artWidth_ || y + height > artHeight_
|| styleIndex >= styleCount
) {
revert InvalidArt();
}
}
}
function _attributes(uint256 tokenId) internal view returns (string memory output) {
uint256 combination = _objectCombination(tokenId);
for (uint256 layerIndex; layerIndex < _layerNames.length; layerIndex++) {
uint256 traitCount = _traitNames[layerIndex].length;
uint256 traitIndex = combination % traitCount;
combination /= traitCount;
if (layerIndex != 0) output = string.concat(output, ",");
output = string.concat(
output,
'{"trait_type":"',
_layerNames[layerIndex],
'","value":"',
_traitNames[layerIndex][traitIndex],
'"}'
);
}
}
function _renderTrait(bytes memory data) internal view returns (string memory output) {
for (uint256 offset; offset < data.length; offset += 5) {
output = string.concat(
output,
'<rect x="',
uint256(uint8(data[offset])).toString(),
'" y="',
uint256(uint8(data[offset + 1])).toString(),
'" width="',
uint256(uint8(data[offset + 2])).toString(),
'" height="',
uint256(uint8(data[offset + 3])).toString(),
'" fill="',
_style(uint8(data[offset + 4])),
'"/>'
);
}
}
function _styleCount() internal view returns (uint256) {
return _styles.length / 3;
}
function _style(uint256 styleIndex) internal view returns (string memory) {
if (styleIndex >= _styleCount()) revert InvalidArt();
uint256 offset = styleIndex * 3;
return string.concat(
"#",
_hexByte(uint8(_styles[offset])),
_hexByte(uint8(_styles[offset + 1])),
_hexByte(uint8(_styles[offset + 2]))
);
}
function _hexByte(uint8 value) internal pure returns (string memory) {
bytes memory output = new bytes(2);
output[0] = _HEX_SYMBOLS[value >> 4];
output[1] = _HEX_SYMBOLS[value & 0x0f];
return string(output);
}
function _objectCombination(uint256 tokenId) internal view returns (uint256) {
objectSeed(tokenId);
return _objectCombinations[tokenId];
}
function _drawTraitCombination(bytes32 seed, uint256 tokenId) internal returns (uint256 combination) {
uint256 remaining = availableTraitCombinations;
if (remaining == 0) revert TraitCombinationsExhausted();
uint256 selectedIndex =
uint256(keccak256(abi.encode("HOOKD_TRAIT_COMBINATION", seed, tokenId, remaining))) % remaining;
combination = _availableCombinationAt(selectedIndex);
uint256 lastIndex = remaining - 1;
if (selectedIndex != lastIndex) {
_availableCombinationPlusOne[selectedIndex] = _availableCombinationAt(lastIndex) + 1;
}
delete _availableCombinationPlusOne[lastIndex];
availableTraitCombinations = lastIndex;
}
function _availableCombinationAt(uint256 index) internal view returns (uint256 combination) {
uint256 stored = _availableCombinationPlusOne[index];
return stored == 0 ? index : stored - 1;
}
function _beforeBurnObject(address owner, uint256 objectId) internal override {
owner;
uint256 combination = _objectCombinations[objectId];
delete _objectCombinations[objectId];
_availableCombinationPlusOne[availableTraitCombinations] = combination + 1;
availableTraitCombinations += 1;
}
}
dependencies/@openzeppelin-contracts-5.0.2/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);
}
}
dependencies/@openzeppelin-contracts-5.0.2/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
dependencies/@openzeppelin-contracts-5.0.2/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
* ```
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
dependencies/@openzeppelin-contracts-5.0.2/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
dependencies/@openzeppelin-contracts-5.0.2/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
dependencies/@openzeppelin-contracts-5.0.2/utils/Base64.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.2) (utils/Base64.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides a set of functions to operate with Base64 strings.
*/
library Base64 {
/**
* @dev Base64 Encoding/Decoding Table
*/
string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* @dev Converts a `bytes` to its Bytes64 `string` representation.
*/
function encode(bytes memory data) internal pure returns (string memory) {
/**
* Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
* https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
*/
if (data.length == 0) return "";
// Loads the table into memory
string memory table = _TABLE;
// Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
// and split into 4 numbers of 6 bits.
// The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
// - `data.length + 2` -> Round up
// - `/ 3` -> Number of 3-bytes chunks
// - `4 *` -> 4 characters for each chunk
string memory result = new string(4 * ((data.length + 2) / 3));
/// @solidity memory-safe-assembly
assembly {
// Prepare the lookup table (skip the first "length" byte)
let tablePtr := add(table, 1)
// Prepare result pointer, jump over length
let resultPtr := add(result, 0x20)
let dataPtr := data
let endPtr := add(data, mload(data))
// In some cases, the last iteration will read bytes after the end of the data. We cache the value, and
// set it to zero to make sure no dirty bytes are read in that section.
let afterPtr := add(endPtr, 0x20)
let afterCache := mload(afterPtr)
mstore(afterPtr, 0x00)
// Run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
// Advance 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// To write each character, shift the 3 byte (24 bits) chunk
// 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
// and apply logical AND with 0x3F to bitmask the least significant 6 bits.
// Use this as an index into the lookup table, mload an entire word
// so the desired character is in the least significant byte, and
// mstore8 this least significant byte into the result and continue.
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
}
// Reset the value that was cached
mstore(afterPtr, afterCache)
// When data `bytes` is not exactly 3 bytes long
// it is padded with `=` characters at the end
switch mod(mload(data), 3)
case 1 {
mstore8(sub(resultPtr, 1), 0x3d)
mstore8(sub(resultPtr, 2), 0x3d)
}
case 2 {
mstore8(sub(resultPtr, 1), 0x3d)
}
}
return result;
}
}
dependencies/@openzeppelin-contracts-5.0.2/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;
}
}
dependencies/@openzeppelin-contracts-5.0.2/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
dependencies/@openzeppelin-contracts-5.0.2/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
dependencies/@openzeppelin-contracts-5.0.2/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
dependencies/v4-core-4.0.0/src/interfaces/IExtsload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
/// @notice Called by external contracts to access granular pool state
/// @param slot Key of slot to sload
/// @return value The value of the slot as bytes32
function extsload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access granular pool state
/// @param startSlot Key of slot to start sloading from
/// @param nSlots Number of slots to load into return value
/// @return values List of loaded values.
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);
/// @notice Called by external contracts to access sparse pool state
/// @param slots List of slots to SLOAD from.
/// @return values List of loaded values.
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
dependencies/v4-core-4.0.0/src/interfaces/IExttload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
/// @notice Called by external contracts to access transient storage of the contract
/// @param slot Key of slot to tload
/// @return value The value of the slot as bytes32
function exttload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse transient pool state
/// @param slots List of slots to tload
/// @return values List of loaded values
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
dependencies/v4-core-4.0.0/src/interfaces/IHooks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {IPoolManager} from "./IPoolManager.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
bytes calldata hookData
) external returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}
dependencies/v4-core-4.0.0/src/interfaces/IPoolManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
/// @notice Thrown when a currency is not netted out after the contract is unlocked
error CurrencyNotSettled();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when unlock is called, but the contract is already unlocked
error AlreadyUnlocked();
/// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
error ManagerLocked();
/// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
error TickSpacingTooLarge(int24 tickSpacing);
/// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
error TickSpacingTooSmall(int24 tickSpacing);
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);
/// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
/// or on a pool that does not have a dynamic swap fee.
error UnauthorizedDynamicLPFeeUpdate();
/// @notice Thrown when trying to swap amount of 0
error SwapAmountCannotBeZero();
///@notice Thrown when native currency is passed to a non native settlement
error NonzeroNativeValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @notice Emitted when a new pool is initialized
/// @param id The abi encoded hash of the pool key struct for the new pool
/// @param currency0 The first currency of the pool by address sort order
/// @param currency1 The second currency of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param hooks The hooks contract address for the pool, or address(0) if none
/// @param sqrtPriceX96 The price of the pool on initialization
/// @param tick The initial tick of the pool corresponding to the initialized price
event Initialize(
PoolId indexed id,
Currency indexed currency0,
Currency indexed currency1,
uint24 fee,
int24 tickSpacing,
IHooks hooks,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted when a liquidity position is modified
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param liquidityDelta The amount of liquidity that was added or removed
/// @param salt The extra data to make positions unique
event ModifyLiquidity(
PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
);
/// @notice Emitted for swaps between currency0 and currency1
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that initiated the swap call, and that received the callback
/// @param amount0 The delta of the currency0 balance of the pool
/// @param amount1 The delta of the currency1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of the price of the pool after the swap
/// @param fee The swap fee in hundredths of a bip
event Swap(
PoolId indexed id,
address indexed sender,
int128 amount0,
int128 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick,
uint24 fee
);
/// @notice Emitted for donations
/// @param id The abi encoded hash of the pool key struct for the pool that was donated to
/// @param sender The address that initiated the donate call
/// @param amount0 The amount donated in currency0
/// @param amount1 The amount donated in currency1
event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);
/// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
/// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
/// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
/// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
/// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
function unlock(bytes calldata data) external returns (bytes memory);
/// @notice Initialize the state for a given pool ID
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The pool key for the pool to initialize
/// @param sqrtPriceX96 The initial square root price
/// @return tick The initial tick of the pool
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Modify the liquidity for the given pool
/// @dev Poke by calling with a zero liquidityDelta
/// @param key The pool to modify liquidity in
/// @param params The parameters for modifying the liquidity
/// @param hookData The data to pass through to the add/removeLiquidity hooks
/// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
/// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
/// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
/// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
/// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
external
returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}
/// @notice Swap against the given pool
/// @param key The pool to swap in
/// @param params The parameters for swapping
/// @param hookData The data to pass through to the swap hooks
/// @return swapDelta The balance delta of the address swapping
/// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
/// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
/// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
external
returns (BalanceDelta swapDelta);
/// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
/// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
/// Donors should keep this in mind when designing donation mechanisms.
/// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
/// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
/// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
/// Read the comments in `Pool.swap()` for more information about this.
/// @param key The key of the pool to donate to
/// @param amount0 The amount of currency0 to donate
/// @param amount1 The amount of currency1 to donate
/// @param hookData The data to pass through to the donate hooks
/// @return BalanceDelta The delta of the caller after the donate
function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
external
returns (BalanceDelta);
/// @notice Writes the current ERC20 balance of the specified currency to transient storage
/// This is used to checkpoint balances for the manager and derive deltas for the caller.
/// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
/// for native tokens because the amount to settle is determined by the sent value.
/// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
/// native funds, this function can be called with the native currency to then be able to settle the native currency
function sync(Currency currency) external;
/// @notice Called by the user to net out some value owed to the user
/// @dev Will revert if the requested amount is not available, consider using `mint` instead
/// @dev Can also be used as a mechanism for free flash loans
/// @param currency The currency to withdraw from the pool manager
/// @param to The address to withdraw to
/// @param amount The amount of currency to withdraw
function take(Currency currency, address to, uint256 amount) external;
/// @notice Called by the user to pay what is owed
/// @return paid The amount of currency settled
function settle() external payable returns (uint256 paid);
/// @notice Called by the user to pay on behalf of another address
/// @param recipient The address to credit for the payment
/// @return paid The amount of currency settled
function settleFor(address recipient) external payable returns (uint256 paid);
/// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
/// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
/// @dev This could be used to clear a balance that is considered dust.
/// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
function clear(Currency currency, uint256 amount) external;
/// @notice Called by the user to move value into ERC6909 balance
/// @param to The address to mint the tokens to
/// @param id The currency address to mint to ERC6909s, as a uint256
/// @param amount The amount of currency to mint
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function mint(address to, uint256 id, uint256 amount) external;
/// @notice Called by the user to move value from ERC6909 balance
/// @param from The address to burn the tokens from
/// @param id The currency address to burn from ERC6909s, as a uint256
/// @param amount The amount of currency to burn
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function burn(address from, uint256 id, uint256 amount) external;
/// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The key of the pool to update dynamic LP fees for
/// @param newDynamicLPFee The new dynamic pool LP fee
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}
dependencies/v4-core-4.0.0/src/interfaces/IProtocolFees.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
/// @notice Thrown when protocol fee is set too high
error ProtocolFeeTooLarge(uint24 fee);
/// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
error InvalidCaller();
/// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
error ProtocolFeeCurrencySynced();
/// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
event ProtocolFeeControllerUpdated(address indexed protocolFeeController);
/// @notice Emitted when the protocol fee is updated for a pool.
event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);
/// @notice Given a currency address, returns the protocol fees accrued in that currency
/// @param currency The currency to check
/// @return amount The amount of protocol fees accrued in the currency
function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);
/// @notice Sets the protocol fee for the given pool
/// @param key The key of the pool to set a protocol fee for
/// @param newProtocolFee The fee to set
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;
/// @notice Sets the protocol fee controller
/// @param controller The new protocol fee controller
function setProtocolFeeController(address controller) external;
/// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
/// @dev This will revert if the contract is unlocked
/// @param recipient The address to receive the protocol fees
/// @param currency The currency to withdraw
/// @param amount The amount of currency to withdraw
/// @return amountCollected The amount of currency successfully withdrawn
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected);
/// @notice Returns the current protocol fee controller address
/// @return address The current protocol fee controller address
function protocolFeeController() external view returns (address);
}
dependencies/v4-core-4.0.0/src/interfaces/external/IERC20Minimal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
/// @notice Returns an account's balance in the token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}
dependencies/v4-core-4.0.0/src/interfaces/external/IERC6909Claims.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Owner balance of an id.
/// @param owner The address of the owner.
/// @param id The id of the token.
/// @return amount The balance of the token.
function balanceOf(address owner, uint256 id) external view returns (uint256 amount);
/// @notice Spender allowance of an id.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @return amount The allowance of the token.
function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);
/// @notice Checks if a spender is approved by an owner as an operator
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @return approved The approval status.
function isOperator(address owner, address spender) external view returns (bool approved);
/// @notice Transfers an amount of an id from the caller to a receiver.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Transfers an amount of an id from a sender to a receiver.
/// @param sender The address of the sender.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Approves an amount of an id to a spender.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always
function approve(address spender, uint256 id, uint256 amount) external returns (bool);
/// @notice Sets or removes an operator for the caller.
/// @param operator The address of the operator.
/// @param approved The approval status.
/// @return bool True, always
function setOperator(address operator, bool approved) external returns (bool);
}
dependencies/v4-core-4.0.0/src/libraries/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
dependencies/v4-core-4.0.0/src/libraries/SafeCast.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}
dependencies/v4-core-4.0.0/src/types/BalanceDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice A BalanceDelta of 0
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}
dependencies/v4-core-4.0.0/src/types/BeforeSwapDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice A BeforeSwapDelta of 0
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// returned by beforeSwap
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// returned by beforeSwap and afterSwap
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}
dependencies/v4-core-4.0.0/src/types/Currency.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isAddressZero()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
}
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success :=
and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isAddressZero()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}
dependencies/v4-core-4.0.0/src/types/PoolId.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}
dependencies/v4-core-4.0.0/src/types/PoolKey.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}
src/ERC3232.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {ERC20} from "@openzeppelin-contracts-5.0.2/token/ERC20/ERC20.sol";
import {IERC3232} from "./interfaces/IERC3232.sol";
import {Base64} from "@openzeppelin-contracts-5.0.2/utils/Base64.sol";
import {Strings} from "@openzeppelin-contracts-5.0.2/utils/Strings.sol";
/// @title ERC3232 base implementation
/// @notice Combines ERC20 accounting with ERC721-style on-chain objects that are backed by whole token balances.
/// @dev Objects are not ERC721 tokens directly; they expose wallet/indexer-friendly ownership and metadata helpers.
contract ERC3232 is ERC20, IERC3232 {
using Strings for uint256;
/// @notice Maximum objects that can be minted or burned by one ERC20 transfer reconciliation.
/// @dev This bounds gas for automatic object burns in ERC3232 and pool-triggered generation in HookdToken.
/// Transfers or pool buys requiring more than this many object changes must be split into chunks.
uint256 public constant MAX_OBJECT_RECONCILIATION = 500;
uint256 public immutable tokensPerObject;
uint256 internal _nextObjectId = 1;
uint256 private _activeObjects;
mapping(uint256 tokenId => ObjectData data) private _objects;
mapping(address owner => uint256 count) private _objectBalance;
mapping(address owner => ObjectSeedData[] objects) private _ownerObjects;
mapping(address owner => mapping(uint256 objectId => uint256 indexPlusOne)) private _ownerObjectIndexPlusOne;
mapping(uint256 objectId => address approved) private _objectApprovals;
mapping(address owner => mapping(address operator => bool approved)) private _objectOperatorApprovals;
constructor(string memory name_, string memory symbol_, uint256 initialSupply_, address initialHolder_)
ERC20(name_, symbol_)
{
if (initialHolder_ == address(0)) revert ZeroAddress();
tokensPerObject = 10 ** decimals();
_mint(initialHolder_, initialSupply_);
}
function _mintObject(address to, bytes32 seed) internal returns (uint256 tokenId) {
if (to == address(0)) revert ZeroAddress();
if (_activeObjects >= maxObjects()) revert MaxObjectsReached();
_requireCanReceiveObject(to);
tokenId = _nextObjectId;
_nextObjectId = tokenId + 1;
_objects[tokenId] = ObjectData({owner: to, seed: seed});
_addObjectToOwner(to, tokenId, seed);
_activeObjects += 1;
emit ObjectTransfer(address(0), to, tokenId);
emit ObjectGenerated(tokenId, to, seed);
}
/// @notice Transfers an object and one backing ERC20 unit to `to`.
/// @dev This clears any object-specific approval. The recipient must have capacity after receiving the backing unit.
/// Unlike ERC721, self-transfer reverts because ERC3232 object transfer also moves backing ERC20 units.
function transferObject(address to, uint256 objectId) public {
ObjectData storage object = _objectDataView(objectId);
_transferObjectFrom(object.owner, to, objectId);
}
/// @notice Transfers an object and one backing ERC20 unit from `from` to `to`.
/// @dev Object approval authorizes movement of both the object and the backing ERC20 unit.
/// Unlike ERC721, self-transfer reverts because ERC3232 object transfer also moves backing ERC20 units.
function transferObjectFrom(address from, address to, uint256 objectId) public {
_transferObjectFrom(from, to, objectId);
}
/// @notice Approves an address to transfer a specific object and one backing ERC20 unit.
/// @dev This approval is intentionally stronger than display-only object approval: it authorizes `approved`
/// to move the object and `tokensPerObject` ERC20 base units together.
function approveObject(address approved, uint256 objectId) external {
ObjectData storage object = _objectDataView(objectId);
address owner = object.owner;
if (approved == owner) revert SelfApproval();
if (msg.sender != owner && !isApprovedForAllObjects(owner, msg.sender)) {
revert NotAuthorizedToApprove(msg.sender, objectId);
}
_objectApprovals[objectId] = approved;
emit ObjectApproval(owner, approved, objectId);
}
/// @notice Returns the address approved to transfer a specific object.
function getApprovedObject(uint256 objectId) public view returns (address) {
_objectDataView(objectId);
return _objectApprovals[objectId];
}
/// @notice Approves or revokes an operator for all caller-owned objects and their backing ERC20 units.
/// @dev Approved operators can move each owned object together with one backing ERC20 unit.
function setApprovalForAllObjects(address operator, bool approved) external {
if (operator == address(0)) revert ZeroAddress();
if (operator == msg.sender) revert SelfApproval();
_objectOperatorApprovals[msg.sender][operator] = approved;
emit ObjectApprovalForAll(msg.sender, operator, approved);
}
/// @notice Returns whether an operator may transfer all objects owned by `owner`.
function isApprovedForAllObjects(address owner, address operator) public view returns (bool) {
return _objectOperatorApprovals[owner][operator];
}
function _transferObjectFrom(address from, address to, uint256 objectId) internal {
if (!_isObjectApprovedOrOwner(msg.sender, from, objectId)) revert NotObjectApproved(msg.sender, objectId);
_transferObjectWithUnit(from, to, objectId);
}
function _transferObjectWithUnit(address from, address to, uint256 objectId) internal virtual {
if (to == address(0)) revert ZeroAddress();
ObjectData storage object = _objectDataView(objectId);
if (object.owner != from) revert NotObjectOwner();
if (to == from) revert SelfTransfer();
if (balanceOf(from) < tokensPerObject) {
revert InsufficientAvailableBalance(from, balanceOf(from), tokensPerObject);
}
_moveObjectOnly(from, to, objectId, object);
_transfer(from, to, tokensPerObject);
}
function _moveObjectOnly(address from, address to, uint256 objectId, ObjectData storage object) internal {
_requireCanReceiveObjectWithBalance(to, balanceOf(to) + tokensPerObject);
_moveObjectBetweenOwners(from, to, objectId, object.seed);
object.owner = to;
emit ObjectTransfer(from, to, objectId);
}
/// @notice Returns the current owner of an object.
function ownerOf(uint256 tokenId) public view returns (address) {
return _objectDataView(tokenId).owner;
}
/// @notice Returns full object data for a live object.
function objectData(uint256 tokenId) public view returns (ObjectData memory) {
ObjectData storage object = _objectDataView(tokenId);
return ObjectData({owner: object.owner, seed: object.seed});
}
/// @notice Returns whether an object currently exists.
function objectExists(uint256 tokenId) public view returns (bool) {
return _objects[tokenId].owner != address(0);
}
/// @notice Returns the stored seed for an object.
function objectSeed(uint256 tokenId) public view returns (bytes32) {
return _objectDataView(tokenId).seed;
}
/// @notice Returns token balance not currently represented by live objects.
function availableBalanceOf(address owner) public view returns (uint256) {
if (owner == address(0)) revert ZeroAddress();
uint256 balance = balanceOf(owner);
uint256 used = _objectBalance[owner] * tokensPerObject;
if (used >= balance) return 0;
return balance - used;
}
/// @notice Returns the maximum possible live object count from current ERC20 supply.
function maxObjects() public view returns (uint256) {
return totalSupply() / tokensPerObject;
}
/// @notice Returns the number of currently live objects.
function totalObjects() external view returns (uint256) {
return _activeObjects;
}
/// @notice Returns an owner's current live object count.
function ownerObjectsCount(address owner) public view returns (uint256) {
if (owner == address(0)) revert ZeroAddress();
return _objectBalance[owner];
}
/// @notice Returns whether an owner currently owns an object.
function ownerOwns(address owner, uint256 objectId) external view returns (bool) {
if (owner == address(0)) revert ZeroAddress();
return _ownerObjectIndexPlusOne[owner][objectId] != 0;
}
/// @notice Returns one object entry from an owner's list.
function ownerObject(address owner, uint256 index) external view returns (ObjectSeedData memory) {
if (owner == address(0)) revert ZeroAddress();
if (index >= _ownerObjects[owner].length) revert ObjectIndexOutOfRange();
return _ownerObjects[owner][index];
}
/// @notice Returns a page of object entries from an owner's list.
function ownerObjectsPage(address owner, uint256 page, uint256 pageSize)
external
view
returns (ObjectSeedData[] memory objects)
{
if (owner == address(0)) revert ZeroAddress();
if (pageSize == 0 || page > type(uint256).max / pageSize) return new ObjectSeedData[](0);
uint256 start = page * pageSize;
uint256 length = _ownerObjects[owner].length;
if (start >= length) return new ObjectSeedData[](0);
uint256 end = start + pageSize;
if (end > length) end = length;
objects = new ObjectSeedData[](end - start);
for (uint256 i; i < objects.length; i++) {
objects[i] = _ownerObjects[owner][start + i];
}
}
/// @notice Returns base64 JSON metadata with an embedded on-chain SVG image.
function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
ObjectData storage object = _objectDataView(tokenId);
string memory image = Base64.encode(bytes(_svg(tokenId, object.seed)));
string memory json = Base64.encode(
bytes(
string.concat(
'{"name":"ERC3232 Object #',
tokenId.toString(),
'","description":"An ERC3232 on-chain generative artwork.","attributes":[{"trait_type":"Hue","value":"',
_trait(object.seed, 0, 360).toString(),
'"}],"image":"data:image/svg+xml;base64,',
image,
'"}'
)
)
);
return string.concat("data:application/json;base64,", json);
}
/// @dev Standard ERC20 transfers may burn the sender's newest excess objects if their post-transfer
/// balance can no longer back the previous object count. A transfer that would burn more than
/// `MAX_OBJECT_RECONCILIATION` objects reverts so very large exits must be split into chunks.
function _update(address from, address to, uint256 value) internal virtual override {
super._update(from, to, value);
if (from != address(0)) {
_burnExcessObjects(from);
}
}
function _objectDataView(uint256 tokenId) internal view returns (ObjectData storage object) {
object = _objects[tokenId];
if (object.owner == address(0)) revert ObjectDoesNotExist(tokenId);
}
function _requireCanReceiveObject(address owner) internal view {
_requireCanReceiveObjectWithBalance(owner, balanceOf(owner));
}
function _requireCanReceiveObjectWithBalance(address owner, uint256 effectiveBalance) internal view {
uint256 maxObjectCount = effectiveBalance / tokensPerObject;
if (maxObjectCount == 0) revert InsufficientAvailableBalance(owner, effectiveBalance, tokensPerObject);
if (_objectBalance[owner] >= maxObjectCount) {
revert MaxObjectsPerBalanceReached(owner, effectiveBalance, _objectBalance[owner], maxObjectCount);
}
}
function _addObjectToOwner(address owner, uint256 objectId, bytes32 seed) internal {
_objectBalance[owner] += 1;
_ownerObjects[owner].push(ObjectSeedData({id: objectId, seed: seed}));
_ownerObjectIndexPlusOne[owner][objectId] = _ownerObjects[owner].length;
}
function _removeObjectFromOwner(address owner, uint256 objectId) internal {
uint256 indexPlusOne = _ownerObjectIndexPlusOne[owner][objectId];
if (indexPlusOne == 0) revert ObjectIndexOutOfRange();
uint256 index = indexPlusOne - 1;
uint256 lastIndex = _ownerObjects[owner].length - 1;
if (index != lastIndex) {
ObjectSeedData memory last = _ownerObjects[owner][lastIndex];
_ownerObjects[owner][index] = last;
_ownerObjectIndexPlusOne[owner][last.id] = index + 1;
}
_ownerObjects[owner].pop();
delete _ownerObjectIndexPlusOne[owner][objectId];
_clearObjectApproval(owner, objectId);
_objectBalance[owner] -= 1;
}
function _moveObjectBetweenOwners(address from, address to, uint256 objectId, bytes32 seed) internal {
_removeObjectFromOwner(from, objectId);
_addObjectToOwner(to, objectId, seed);
}
function _burnExcessObjects(address owner) internal {
uint256 allowedObjects = balanceOf(owner) / tokensPerObject;
uint256 objectBalance = _objectBalance[owner];
if (objectBalance > allowedObjects) {
uint256 burnCount = objectBalance - allowedObjects;
if (burnCount > MAX_OBJECT_RECONCILIATION) {
revert TooManyObjectsToReconcile(burnCount, MAX_OBJECT_RECONCILIATION);
}
}
while (_objectBalance[owner] > allowedObjects) {
uint256 lastIndex = _ownerObjects[owner].length - 1;
uint256 objectId = _ownerObjects[owner][lastIndex].id;
_burnObject(owner, objectId);
}
}
function _burnObject(address owner, uint256 objectId) internal {
_beforeBurnObject(owner, objectId);
_removeObjectFromOwner(owner, objectId);
delete _objects[objectId];
_activeObjects -= 1;
emit ObjectTransfer(owner, address(0), objectId);
}
function _isObjectApprovedOrOwner(address spender, address owner, uint256 objectId) internal view returns (bool) {
return spender == owner || _objectApprovals[objectId] == spender || isApprovedForAllObjects(owner, spender);
}
function _clearObjectApproval(address owner, uint256 objectId) internal {
if (_objectApprovals[objectId] == address(0)) return;
delete _objectApprovals[objectId];
emit ObjectApproval(owner, address(0), objectId);
}
function _nextObjectIdValue() internal view returns (uint256) {
return _nextObjectId;
}
function _beforeBurnObject(address owner, uint256 objectId) internal virtual {
owner;
objectId;
}
function _svg(uint256 tokenId, bytes32 seed) internal view virtual returns (string memory) {
uint256 hue = _trait(seed, 0, 360);
uint256 accent = _trait(seed, 1, 360);
uint256 radius = 42 + _trait(seed, 2, 22);
return string.concat(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">',
'<rect width="512" height="512" fill="hsl(',
hue.toString(),
',70%,18%)"/>',
'<circle cx="256" cy="230" r="',
radius.toString(),
'" fill="hsl(',
accent.toString(),
',78%,62%)"/>',
'<path d="M156 372c40-84 160-84 200 0" fill="none" stroke="white" stroke-width="18" stroke-linecap="round"/>',
'<text x="256" y="72" text-anchor="middle" fill="white" font-family="monospace" font-size="28">ERC3232 #',
tokenId.toString(),
"</text></svg>"
);
}
function _trait(bytes32 seed, uint256 slot, uint256 modulo) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(seed, slot))) % modulo;
}
}
src/interfaces/IERC3232.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin-contracts-5.0.2/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin-contracts-5.0.2/token/ERC20/extensions/IERC20Metadata.sol";
/// @title ERC3232 object standard interface
/// @notice Defines a hybrid ERC20/object surface where one whole ERC20 unit can support one generated on-chain object.
interface IERC3232 is IERC20, IERC20Metadata {
/// @notice Lightweight owner-list entry returned by pagination and object lookup helpers.
/// @param id Object identifier.
/// @param seed Deterministic seed used by the renderer.
struct ObjectSeedData {
uint256 id;
bytes32 seed;
}
/// @notice Full object storage view.
/// @param owner Current object owner.
/// @param seed Deterministic seed used by the renderer.
struct ObjectData {
address owner;
bytes32 seed;
}
/// @notice Emitted when a new object is generated.
event ObjectGenerated(uint256 indexed tokenId, address indexed owner, bytes32 seed);
/// @notice Emitted when an object is minted, burned, or transferred.
event ObjectTransfer(address indexed from, address indexed to, uint256 indexed tokenId);
/// @notice Emitted when a specific object transfer approval changes.
event ObjectApproval(address indexed owner, address indexed approved, uint256 indexed objectId);
/// @notice Emitted when an owner grants or revokes object operator approval.
event ObjectApprovalForAll(address indexed owner, address indexed operator, bool approved);
error InsufficientAvailableBalance(address owner, uint256 available, uint256 required);
error MaxObjectsPerBalanceReached(address owner, uint256 balance, uint256 objectCount, uint256 maxObjectCount);
error MaxObjectsReached();
error NotObjectOwner();
error NotObjectApproved(address caller, uint256 objectId);
error NotAuthorizedToApprove(address caller, uint256 objectId);
error ObjectDoesNotExist(uint256 tokenId);
error ObjectIndexOutOfRange();
error SelfApproval();
error SelfTransfer();
/// @notice Reverts when one transfer would mint or burn more objects than the implementation's gas-bounded cap.
error TooManyObjectsToReconcile(uint256 count, uint256 max);
error ZeroAddress();
/// @notice ERC20 base units required to support one object.
function tokensPerObject() external view returns (uint256);
/// @notice Transfers an object and one backing ERC20 unit.
/// @dev Reverts on self-transfer. This deliberately differs from ERC721 because ERC3232 object transfer also moves
/// backing ERC20 units.
function transferObject(address to, uint256 objectId) external;
/// @notice Transfers an object and one backing ERC20 unit from `from` to `to`.
/// @dev Object approval authorizes movement of both the object and the backing ERC20 unit. Reverts on self-transfer.
/// This deliberately differs from ERC721 because ERC3232 object transfer also moves backing ERC20 units.
function transferObjectFrom(address from, address to, uint256 objectId) external;
/// @notice Approves an address to transfer a specific object and one backing ERC20 unit.
/// @dev This approval authorizes movement of both the object and one backing ERC20 unit.
function approveObject(address approved, uint256 objectId) external;
/// @notice Returns the address approved to transfer a specific object.
function getApprovedObject(uint256 objectId) external view returns (address);
/// @notice Grants or revokes operator approval for all caller-owned objects and their backing ERC20 units.
/// @dev Approved operators can move each owned object together with one backing ERC20 unit.
function setApprovalForAllObjects(address operator, bool approved) external;
/// @notice Returns whether `operator` can transfer all objects owned by `owner`.
function isApprovedForAllObjects(address owner, address operator) external view returns (bool);
/// @notice Returns the current object owner.
function ownerOf(uint256 tokenId) external view returns (address);
/// @notice Returns full object data for a live object.
function objectData(uint256 tokenId) external view returns (ObjectData memory);
/// @notice Returns whether an object currently exists.
function objectExists(uint256 tokenId) external view returns (bool);
/// @notice Returns the stored generation seed for an object.
function objectSeed(uint256 tokenId) external view returns (bytes32);
/// @notice Returns whole-token capacity not currently represented by objects.
function availableBalanceOf(address owner) external view returns (uint256);
/// @notice Returns the maximum possible live object count based on ERC20 supply.
function maxObjects() external view returns (uint256);
/// @notice Returns the current live object count.
function totalObjects() external view returns (uint256);
/// @notice Returns the current live object count owned by an address.
function ownerObjectsCount(address owner) external view returns (uint256);
/// @notice Returns whether an owner currently owns an object.
/// @dev Reverts for the zero address.
function ownerOwns(address owner, uint256 objectId) external view returns (bool);
/// @notice Returns one object entry from an owner's object list.
/// @dev Reverts for the zero address.
function ownerObject(address owner, uint256 index) external view returns (ObjectSeedData memory);
/// @notice Returns a page of an owner's object list.
/// @dev Reverts for the zero address.
function ownerObjectsPage(address owner, uint256 page, uint256 pageSize)
external
view
returns (ObjectSeedData[] memory objects);
/// @notice Returns ERC721-style metadata with embedded on-chain SVG.
function tokenURI(uint256 tokenId) external view returns (string memory);
}
src/interfaces/IERC3232Hook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @title Hookd random hook extension interface
/// @notice Shared interface for hook-aware ERC3232 implementations.
interface IERC3232Hook {
/// @notice Returns the pool id allowed to trigger automatic object generation, or zero if unrestricted.
function generationPoolId() external view returns (bytes32);
/// @notice Returns the latest hook-maintained seed.
function randomSeed() external view returns (bytes32);
}
src/types/HookdArt.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Constructor payload for a Hookd on-chain SVG collection.
/// @dev Each trait is packed as repeated 5-byte SVG rect records:
/// x, y, width, height, styleIndex.
/// Styles are packed as repeated 3-byte RGB records:
/// red, green, blue.
struct HookdArt {
uint8 width;
uint8 height;
string[] layerNames;
string[][] traitNames;
bytes[][] traitRects;
bytes styles;
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin-contracts-5.0.2/=dependencies/@openzeppelin-contracts-5.0.2/",
"forge-std-1.16.0/=dependencies/forge-std-1.16.0/",
"v4-core-4.0.0/=dependencies/v4-core-4.0.0/",
"v4-periphery-4.0.0/=dependencies/v4-periphery-4.0.0/",
"@uniswap/v4-core/=dependencies/v4-core-4.0.0/",
"@uniswap/v4-periphery/=dependencies/v4-periphery-4.0.0/",
"permit2/=dependencies/v4-periphery-4.0.0/lib/permit2/",
"@ensdomains/=dependencies/v4-core-4.0.0/node_modules/@ensdomains/",
"@openzeppelin/=dependencies/v4-core-4.0.0/lib/openzeppelin-contracts/",
"ds-test/=dependencies/v4-core-4.0.0/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=dependencies/v4-core-4.0.0/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=dependencies/v4-periphery-4.0.0/lib/permit2/lib/forge-gas-snapshot/src/",
"forge-std/=dependencies/v4-core-4.0.0/lib/forge-std/src/",
"hardhat/=dependencies/v4-core-4.0.0/node_modules/hardhat/",
"openzeppelin-contracts/=dependencies/v4-core-4.0.0/lib/openzeppelin-contracts/",
"solmate/=dependencies/v4-core-4.0.0/lib/solmate/",
"v4-core/=dependencies/v4-periphery-4.0.0/lib/v4-core/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.