Description:
Multi-signature wallet contract requiring multiple confirmations for transaction execution.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"src/NFTStrategyFactory.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;
import {Ownable} from "solady/auth/Ownable.sol";
import {NFTStrategy} from "./NFTStrategy.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {IPositionManager} from "@uniswap/v4-periphery/src/interfaces/IPositionManager.sol";
import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {Actions} from "@uniswap/v4-periphery/src/libraries/Actions.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {IUniswapV4Router04} from "v4-router/interfaces/IUniswapV4Router04.sol";
import "./Interfaces.sol";
import {ReentrancyGuard} from "solady/utils/ReentrancyGuard.sol";
/// @title NFTStrategyFactory
/// @author TokenWorks (https://token.works/)
contract NFTStrategyFactory is Ownable, ReentrancyGuard {
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™ ™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™ ™™™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* CONSTANTS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
uint256 private constant ethToPair = 2 wei;
uint256 private constant initialBuy = 0.125 ether;
IPositionManager private immutable posm;
IAllowanceTransfer private immutable permit2;
IUniswapV4Router04 private immutable router;
address public constant PNKSTR_ADDRESS = 0xc50673EDb3A7b94E8CAD8a7d4E0cD68864E33eDF;
address public constant PNKSTR_HOOK_ADDRESS = 0xfAaad5B731F52cDc9746F2414c823eca9B06E844;
address public constant DEADADDRESS = 0x000000000000000000000000000000000000dEaD;
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* STATE VARIABLES */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Mapping of contract addresses to their NFTStrategy contract
mapping(address => address) public collectionToNFTStrategy;
/// @notice Mapping of NFTStrategy addresses to their collection contract
mapping(address => address) public nftStrategyToCollection;
/// @notice Cost in wei of deploying an NFTStrategy contract
uint256 public feeToLaunch;
/// @notice The Uniswap V4 hook that control the logic of new deploys
address public hookAddress;
/// @notice The address to send deploy fees to
address public feeAddress;
/// @notice Gate the NFTStrategyHook to only when we're loading a new token
bool public loadingLiquidity;
/// @notice Skips buy fee for the deployer of a token
bool public deployerBuying;
/// @notice Enables public launches of NFTStrategy contracts
bool public publicLaunches;
/// @notice Enables collection-owner launches of NFTStrategy contracts
bool public collectionOwnerLaunches;
/// @notice twap increment when buying PNKSTR
uint256 public twapIncrement = 1 ether;
/// @notice twap delay when buying PNKSTR
uint256 public twapDelayInBlocks = 1;
/// @notice last twap block
uint256 public lastTwapBlock;
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* CUSTOM ERRORS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
error HookNotSet();
error CollectionAlreadyLaunched();
error WrongEthAmount();
error NotERC721();
error GatedByCollectionOwner();
error CannotLaunch();
error NoETHToTwap();
error TwapDelayNotMet();
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* CUSTOM EVENTS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Event emitted when a new NFTStrategy instance is launched
event NFTStrategyLaunched(
address indexed collection,
address indexed nftStrategy,
string tokenName,
string tokenSymbol
);
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* CONSTRUCTOR */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
constructor(
address _posm,
address _permit2,
address payable _router,
address _feeAddress
) {
router = IUniswapV4Router04(_router);
posm = IPositionManager(_posm);
permit2 = IAllowanceTransfer(_permit2);
feeAddress = _feeAddress;
_initializeOwner(msg.sender);
}
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* ADMIN FUNCTIONS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Enables or disables public launches of NFTStrategy contracts
/// @param _publicLaunches True to enable public launches, false to disable
/// @dev Only callable by owner
function setPublicLaunches(bool _publicLaunches) external onlyOwner {
publicLaunches = _publicLaunches;
}
/// @notice Enables or disables collection owner launches of NFTStrategy contracts
/// @param _collectionOwnerLaunches True to enable collection owner launches, false to disable
/// @dev Only callable by owner
function setCollectionOwnerLaunches(bool _collectionOwnerLaunches) external onlyOwner {
collectionOwnerLaunches = _collectionOwnerLaunches;
}
/// @notice Updates the fee required to launch a new NFTStrategy
/// @param _feeToLaunch New fee amount in wei
/// @dev Only callable by owner
function updateFeeToLaunch(uint256 _feeToLaunch) external onlyOwner {
feeToLaunch = _feeToLaunch;
}
/// @notice Updates the hook attached to new NFTStrategy pools
/// @param _hookAddress New Uniswap v4 hook address
/// @dev Only callable by owner
function updateHookAddress(address _hookAddress) external onlyOwner {
hookAddress = _hookAddress;
}
/// @notice Updates the name of a specific NFTStrategy token
/// @param nftStrategy Address of the NFTStrategy contract
/// @param tokenName New name for the token
function updateTokenName(address nftStrategy, string memory tokenName) external onlyOwner {
INFTStrategy(nftStrategy).updateName(tokenName);
}
/// @notice Updates the symbol of a specific NFTStrategy token
/// @param nftStrategy Address of the NFTStrategy contract
/// @param tokenSymbol New symbol for the token
function updateTokenSymbol(address nftStrategy, string memory tokenSymbol) external onlyOwner {
INFTStrategy(nftStrategy).updateSymbol(tokenSymbol);
}
/// @notice Updates the price multiplier for a specific NFTStrategy
/// @param nftStrategy Address of the NFTStrategy contract
/// @param newMultiplier New multiplier in basis points (1100 = 1.1x)
function updatePriceMultiplier(address nftStrategy, uint256 newMultiplier) external onlyOwner {
INFTStrategy(nftStrategy).setPriceMultiplier(newMultiplier);
}
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* INTERNAL FUNCTIONS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Internal function to load liquidity into the Uniswap V4 pool
/// @param _token Address of the NFTStrategy ERC20
function _loadLiquidity(address _token) internal {
loadingLiquidity = true;
// Create the pool with ETH (currency0) and TOKEN (currency1)
Currency currency0 = Currency.wrap(address(0)); // ETH
Currency currency1 = Currency.wrap(_token); // NFTStrategy Token
uint24 lpFee = 0;
int24 tickSpacing = 60;
uint256 token0Amount = 1; // 1 wei
uint256 token1Amount = 1_000_000_000 * 10**18; // 1B TOKEN
// 10e18 ETH = 1_000_000_000e18 TOKEN
uint160 startingPrice = 501082896750095888663770159906816;
int24 tickLower = TickMath.minUsableTick(tickSpacing);
int24 tickUpper = int24(175020);
PoolKey memory key = PoolKey(currency0, currency1, lpFee, tickSpacing, IHooks(hookAddress));
bytes memory hookData = new bytes(0);
// Hardcoded from LiquidityAmounts.getLiquidityForAmounts
uint128 liquidity = 158372218983990412488087;
uint256 amount0Max = token0Amount + 1 wei;
uint256 amount1Max = token1Amount + 1 wei;
(bytes memory actions, bytes[] memory mintParams) =
_mintLiquidityParams(key, tickLower, tickUpper, liquidity, amount0Max, amount1Max, address(this), hookData);
bytes[] memory params = new bytes[](2);
params[0] = abi.encodeWithSelector(posm.initializePool.selector, key, startingPrice, hookData);
params[1] = abi.encodeWithSelector(
posm.modifyLiquidities.selector, abi.encode(actions, mintParams), block.timestamp + 60
);
uint256 valueToPass = amount0Max;
permit2.approve(_token, address(posm), type(uint160).max, type(uint48).max);
posm.multicall{value: valueToPass}(params);
loadingLiquidity = false;
}
/// @notice Creates parameters for minting liquidity in Uniswap V4
function _mintLiquidityParams(
PoolKey memory poolKey,
int24 _tickLower,
int24 _tickUpper,
uint256 liquidity,
uint256 amount0Max,
uint256 amount1Max,
address recipient,
bytes memory hookData
) internal pure returns (bytes memory, bytes[] memory) {
bytes memory actions = abi.encodePacked(uint8(Actions.MINT_POSITION), uint8(Actions.SETTLE_PAIR));
bytes[] memory params = new bytes[](2);
params[0] = abi.encode(poolKey, _tickLower, _tickUpper, liquidity, amount0Max, amount1Max, recipient, hookData);
params[1] = abi.encode(poolKey.currency0, poolKey.currency1);
return (actions, params);
}
/// @notice Buys tokens with ETH and burns them by sending to deployer
/// @param amountIn The amount of ETH to spend on tokens that will be send to deployer
function _buyTokens(uint256 amountIn, address nftStrategy, address caller) internal {
deployerBuying = true;
PoolKey memory key = PoolKey(
Currency.wrap(address(0)),
Currency.wrap(nftStrategy),
0,
60,
IHooks(hookAddress)
);
router.swapExactTokensForTokens{value: amountIn}(
amountIn,
0,
true,
key,
"",
caller,
block.timestamp
);
deployerBuying = false;
}
/// @notice Buys PNKSTR with ETH and burns them by sending to dead address
/// @param amountIn The amount of ETH to spend on tokens that will be burned
function _buyAndBurnPNKSTR(uint256 amountIn) internal {
PoolKey memory key = PoolKey(
Currency.wrap(address(0)),
Currency.wrap(PNKSTR_ADDRESS),
0,
60,
IHooks(PNKSTR_HOOK_ADDRESS)
);
router.swapExactTokensForTokens{value: amountIn}(
amountIn,
0,
true,
key,
"",
DEADADDRESS,
block.timestamp
);
}
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* USER FUNCTIONS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Launches a new NFTStrategy contract for a collection with owner permissions
/// @param collection Address of the NFT collection contract
/// @param tokenName Name of the strategy token
/// @param tokenSymbol Symbol of the strategy token
/// @param collectionOwner Address that will receive fees from the strategy
/// @dev Only callable by contract owner. Deploys new NFTStrategy and initializes liquidity
function ownerLaunchNFTStrategy(
address collection,
string memory tokenName,
string memory tokenSymbol,
address collectionOwner
) external payable onlyOwner returns (NFTStrategy) {
// Validate the parameters passed
if (hookAddress == address(0)) revert HookNotSet();
if (collectionToNFTStrategy[collection] != address(0)) revert CollectionAlreadyLaunched();
NFTStrategy nftStrategy = new NFTStrategy(
address(this),
hookAddress,
router,
collection,
tokenName,
tokenSymbol
);
collectionToNFTStrategy[collection] = address(nftStrategy);
nftStrategyToCollection[address(nftStrategy)] = collection;
// Costs 2 wei
_loadLiquidity(address(nftStrategy));
// Set fees to collectionOwner
INFTStrategyHook(hookAddress).adminUpdateFeeAddress(address(nftStrategy), collectionOwner);
emit NFTStrategyLaunched(
collection,
address(nftStrategy),
tokenName,
tokenSymbol
);
return nftStrategy;
}
function launchNFTStrategy(
address collection,
string memory tokenName,
string memory tokenSymbol
) external payable nonReentrant returns (NFTStrategy) {
// Validate the parameters passed
if (hookAddress == address(0)) revert HookNotSet();
if (collectionToNFTStrategy[collection] != address(0)) revert CollectionAlreadyLaunched();
if (msg.value != feeToLaunch) revert WrongEthAmount();
if (!publicLaunches && !collectionOwnerLaunches) revert CannotLaunch();
if (!IERC721(collection).supportsInterface(0x80ac58cd) && msg.sender != owner()) revert NotERC721();
// Get collection owner
address collectionOwnerFromContract;
try IERC721(collection).owner() returns (address owner) {
collectionOwnerFromContract = owner;
} catch {
collectionOwnerFromContract = address(0);
}
// If publicLaunched is disabled, only allow collection owner to launch
if (!publicLaunches && msg.sender != collectionOwnerFromContract) revert GatedByCollectionOwner();
NFTStrategy nftStrategy = new NFTStrategy(
address(this),
hookAddress,
router,
collection,
tokenName,
tokenSymbol
);
collectionToNFTStrategy[collection] = address(nftStrategy);
nftStrategyToCollection[address(nftStrategy)] = collection;
// Costs 2 wei
_loadLiquidity(address(nftStrategy));
// Set fees if collectionOwnerFromContract is not address(0), otherwise TokenWorks
if (collectionOwnerFromContract != address(0)) {
INFTStrategyHook(hookAddress).adminUpdateFeeAddress(address(nftStrategy), collectionOwnerFromContract);
} else {
INFTStrategyHook(hookAddress).adminUpdateFeeAddress(address(nftStrategy), feeAddress);
}
// Buy 0.1e and send to deployer
// Get 1% of the token
_buyTokens(initialBuy, address(nftStrategy), msg.sender);
// Send remaining fee to feeAddress
uint256 ethToSend = msg.value - ethToPair - initialBuy;
SafeTransferLib.forceSafeTransferETH(feeAddress, ethToSend);
emit NFTStrategyLaunched(
collection,
address(nftStrategy),
tokenName,
tokenSymbol
);
return nftStrategy;
}
// This function lets someone process _buyAndBurnPNKSTR once every twapDelayInBlocks
// Eth amount to TWAP is twapIncrement, if we have less than that use the remaining amount
// Payout reward to the caller at the end, we also need to subtract this from burnAmount.
function processTokenTwap() external nonReentrant {
uint256 balance = address(this).balance;
if(balance == 0) revert NoETHToTwap();
// Check if enough blocks have passed since last TWAP
if(block.number < lastTwapBlock + twapDelayInBlocks) revert TwapDelayNotMet();
// Calculate amount to burn - either twapIncrement or remaining ethToTwap
uint256 burnAmount = twapIncrement;
if(balance < twapIncrement) {
burnAmount = balance;
}
// Set reward to 0.5% of burnAmount
uint256 reward = (burnAmount * 5) / 1000;
burnAmount -= reward;
// Update state
lastTwapBlock = block.number;
_buyAndBurnPNKSTR(burnAmount);
// Send reward to caller
SafeTransferLib.forceSafeTransferETH(msg.sender, reward);
}
/// @notice Allows the contract to receive ETH for twap
receive() external payable {}
}"
},
"lib/solady/src/auth/Ownable.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The caller is not authorized to call the function.
error Unauthorized();
/// @dev The `newOwner` cannot be the zero address.
error NewOwnerIsZeroAddress();
/// @dev The `pendingOwner` does not have a valid handover request.
error NoHandoverRequest();
/// @dev Cannot double-initialize.
error AlreadyInitialized();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ownership is transferred from `oldOwner` to `newOwner`.
/// This event is intentionally kept the same as OpenZeppelin's Ownable to be
/// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
/// despite it not being as lightweight as a single argument event.
event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
/// @dev An ownership handover to `pendingOwner` has been requested.
event OwnershipHandoverRequested(address indexed pendingOwner);
/// @dev The ownership handover to `pendingOwner` has been canceled.
event OwnershipHandoverCanceled(address indexed pendingOwner);
/// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;
/// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;
/// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The owner slot is given by:
/// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
/// It is intentionally chosen to be a high value
/// to avoid collision with lower slots.
/// The choice of manual storage layout is to enable compatibility
/// with both regular and upgradeable contracts.
bytes32 internal constant _OWNER_SLOT =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;
/// The ownership handover slot of `newOwner` is given by:
/// ```
/// mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
/// let handoverSlot := keccak256(0x00, 0x20)
/// ```
/// It stores the expiry timestamp of the two-step ownership handover.
uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
function _guardInitializeOwner() internal pure virtual returns (bool guard) {}
/// @dev Initializes the owner directly without authorization guard.
/// This function must be called upon initialization,
/// regardless of whether the contract is upgradeable or not.
/// This is to enable generalization to both regular and upgradeable contracts,
/// and to save gas in case the initial owner is not the caller.
/// For performance reasons, this function will not check if there
/// is an existing owner.
function _initializeOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
if sload(ownerSlot) {
mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
revert(0x1c, 0x04)
}
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
} else {
/// @solidity memory-safe-assembly
assembly {
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(_OWNER_SLOT, newOwner)
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
}
}
/// @dev Sets the owner directly without authorization guard.
function _setOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
}
} else {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, newOwner)
}
}
}
/// @dev Throws if the sender is not the owner.
function _checkOwner() internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// If the caller is not the stored owner, revert.
if iszero(eq(caller(), sload(_OWNER_SLOT))) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Returns how long a two-step ownership handover is valid for in seconds.
/// Override to return a different value if needed.
/// Made internal to conserve bytecode. Wrap it in a public function if needed.
function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
return 48 * 3600;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC UPDATE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Allows the owner to transfer the ownership to `newOwner`.
function transferOwnership(address newOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
if iszero(shl(96, newOwner)) {
mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
revert(0x1c, 0x04)
}
}
_setOwner(newOwner);
}
/// @dev Allows the owner to renounce their ownership.
function renounceOwnership() public payable virtual onlyOwner {
_setOwner(address(0));
}
/// @dev Request a two-step ownership handover to the caller.
/// The request will automatically expire in 48 hours (172800 seconds) by default.
function requestOwnershipHandover() public payable virtual {
unchecked {
uint256 expires = block.timestamp + _ownershipHandoverValidFor();
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to `expires`.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), expires)
// Emit the {OwnershipHandoverRequested} event.
log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
}
}
}
/// @dev Cancels the two-step ownership handover to the caller, if any.
function cancelOwnershipHandover() public payable virtual {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), 0)
// Emit the {OwnershipHandoverCanceled} event.
log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
}
}
/// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
/// Reverts if there is no existing ownership handover requested by `pendingOwner`.
function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
let handoverSlot := keccak256(0x0c, 0x20)
// If the handover does not exist, or has expired.
if gt(timestamp(), sload(handoverSlot)) {
mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
revert(0x1c, 0x04)
}
// Set the handover slot to 0.
sstore(handoverSlot, 0)
}
_setOwner(pendingOwner);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC READ FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the owner of the contract.
function owner() public view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_OWNER_SLOT)
}
}
/// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
function ownershipHandoverExpiresAt(address pendingOwner)
public
view
virtual
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
// Compute the handover slot.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
// Load the handover slot.
result := sload(keccak256(0x0c, 0x20))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* MODIFIERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Marks a function as only callable by the owner.
modifier onlyOwner() virtual {
_checkOwner();
_;
}
}
"
},
"src/NFTStrategy.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {ERC20} from "solady/tokens/ERC20.sol";
import {ReentrancyGuard} from "solady/utils/ReentrancyGuard.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {IUniswapV4Router04} from "v4-router/interfaces/IUniswapV4Router04.sol";
import "./Interfaces.sol";
/// @title NFTStrategy - An ERC20 token that constantly churns NFTs from a collection
/// @author TokenWorks (https://token.works/)
contract NFTStrategy is ERC20, ReentrancyGuard {
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™ ™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™ ™™™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* CONSTANTS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
IUniswapV4Router04 private immutable router;
string tokenName;
string tokenSymbol;
address public immutable hookAddress;
address public immutable factory;
IERC721 public immutable collection;
uint256 public constant MAX_SUPPLY = 1_000_000_000 * 1e18;
address public constant DEADADDRESS = 0x000000000000000000000000000000000000dEaD;
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* STATE VARIABLES */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
uint256 public priceMultiplier = 1200; // 1.2x
mapping(uint256 => uint256) public nftForSale; // tokenId => price
uint256 public currentFees;
uint256 public ethToTwap;
uint256 public twapIncrement = 1 ether;
uint256 public twapDelayInBlocks = 1;
uint256 public lastTwapBlock;
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* CUSTOM EVENTS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
event NFTBoughtByProtocol(uint256 indexed tokenId, uint256 purchasePrice, uint256 listPrice);
event NFTSoldByProtocol(uint256 indexed tokenId, uint256 price, address buyer);
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* CUSTOM ERRORS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
error NFTNotForSale();
error NFTPriceTooLow();
error InsufficientContractBalance();
error InvalidMultiplier();
error NoETHToTwap();
error TwapDelayNotMet();
error NotEnoughEth();
error NotFactory();
error AlreadyNFTOwner();
error NeedToBuyNFT();
error NotNFTOwner();
error OnlyHook();
error InvalidCollection();
error ExternalCallFailed(bytes reason);
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* CONSTRUCTOR */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Initializes the contract with required addresses and permissions
/// @param _factory Address of the NFTStrategyFactory contract
/// @param _hook Address of the NFTStrategyHook contract
/// @param _router Address of the Uniswap V4 Router contract
/// @param _collection Address of the NFT collection contract
/// @param _tokenName Name of the token
/// @param _tokenSymbol Symbol of the token
constructor(
address _factory,
address _hook,
IUniswapV4Router04 _router,
address _collection,
string memory _tokenName,
string memory _tokenSymbol
) {
factory = _factory;
router = _router;
hookAddress = _hook;
collection = IERC721(_collection);
tokenName = _tokenName;
tokenSymbol = _tokenSymbol;
_mint(factory, MAX_SUPPLY);
}
/// @notice Returns the name of the token
/// @return The token name as a string
function name() public view override returns (string memory) {
return tokenName;
}
/// @notice Returns the symbol of the token
/// @return The token symbol as a string
function symbol() public view override returns (string memory) {
return tokenSymbol;
}
/// @notice Updates the name of the token
/// @dev Can only be called by the factory
/// @param _tokenName New name for the token
function updateName(string memory _tokenName) external {
if (msg.sender != factory) revert NotFactory();
tokenName = _tokenName;
}
/// @notice Updates the symbol of the token
/// @dev Can only be called by the factory
/// @param _tokenSymbol New symbol for the token
function updateSymbol(string memory _tokenSymbol) external {
if (msg.sender != factory) revert NotFactory();
tokenSymbol = _tokenSymbol;
}
/// @notice Updates the price multiplier for relisting punks
/// @param _newMultiplier New multiplier in basis points (1100 = 1.1x, 10000 = 10.0x)
/// @dev Only callable by factory. Must be between 1.1x (1100) and 10.0x (10000)
function setPriceMultiplier(uint256 _newMultiplier) external {
if (msg.sender != factory) revert NotFactory();
if (_newMultiplier < 1100 || _newMultiplier > 10000) revert InvalidMultiplier();
priceMultiplier = _newMultiplier;
}
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* MECHANISM FUNCTIONS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Allows the hook to deposit trading fees into the contract
/// @dev Only callable by the hook contract
/// @dev Fees are added to currentFees balance
function addFees() external payable nonReentrant {
if (msg.sender != hookAddress) revert OnlyHook();
currentFees += msg.value;
}
function buyTargetNFT(uint256 value, bytes calldata data, uint256 expectedId, address target) external nonReentrant {
// Store both balance and nft amount before calling external
uint256 ethBalanceBefore = address(this).balance;
uint256 nftBalanceBefore = collection.balanceOf(address(this));
// Make sure we are not owner of the expected id
if (collection.ownerOf(expectedId) == address(this)) {
revert AlreadyNFTOwner();
}
// Ensure value is not more than currentFees
if (value > currentFees) {
revert NotEnoughEth();
}
// Call external
(bool success, bytes memory reason) = target.call{value: value}(data);
if (!success) {
revert ExternalCallFailed(reason);
}
// Ensure we now have one more NFT
uint256 nftBalanceAfter = collection.balanceOf(address(this));
if (nftBalanceAfter != nftBalanceBefore + 1) {
revert NeedToBuyNFT();
}
// Ensure we are now owner of expectedId
if (collection.ownerOf(expectedId) != address(this)) {
revert NotNFTOwner();
}
// Calculate actual cost of the NFT to base new price on
uint256 cost = ethBalanceBefore - address(this).balance;
currentFees -= cost;
// List NFT for sale at priceMultiplier times the cost
uint256 salePrice = cost * priceMultiplier / 1000;
nftForSale[expectedId] = salePrice;
emit NFTBoughtByProtocol(expectedId, cost, salePrice);
}
/// @notice Sells an NFT owned by the contract for the listed price
/// @param tokenId The ID of the NFT to sell
function sellTargetNFT(uint256 tokenId) external payable nonReentrant {
// Get sale price
uint256 salePrice = nftForSale[tokenId];
// Verify NFT is for sale
if (salePrice == 0) revert NFTNotForSale();
// Verify sent ETH matches sale price
if (msg.value != salePrice) revert NFTPriceTooLow();
// Verify contract owns the NFT
if (collection.ownerOf(tokenId) != address(this)) revert NotNFTOwner();
// Transfer NFT to buyer
collection.transferFrom(address(this), msg.sender, tokenId);
// Remove NFT from sale
delete nftForSale[tokenId];
// Add sale price to fees
ethToTwap += salePrice;
emit NFTSoldByProtocol(tokenId, salePrice, msg.sender);
}
// This function lets someone process _buyAndBurnTokens once every twapDelayInBlocks
// Eth amount to TWAP is twapIncrement, if we have less than that use the remaining amount
// Payout reward to the caller at the end, we also need to subtract this from burnAmount.
function processTokenTwap() external nonReentrant {
if(ethToTwap == 0) revert NoETHToTwap();
// Check if enough blocks have passed since last TWAP
if(block.number < lastTwapBlock + twapDelayInBlocks) revert TwapDelayNotMet();
// Calculate amount to burn - either twapIncrement or remaining ethToTwap
uint256 burnAmount = twapIncrement;
if(ethToTwap < twapIncrement) {
burnAmount = ethToTwap;
}
// Set reward to 0.5% of burnAmount
uint256 reward = (burnAmount * 5) / 1000;
burnAmount -= reward;
// Update state
ethToTwap -= burnAmount + reward;
lastTwapBlock = block.number;
_buyAndBurnTokens(burnAmount);
// Send reward to caller
SafeTransferLib.forceSafeTransferETH(msg.sender, reward);
}
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* INTERNAL FUNCTIONS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Buys tokens with ETH and burns them by sending to dead address
/// @param amountIn The amount of ETH to spend on tokens that will be burned
function _buyAndBurnTokens(uint256 amountIn) internal {
PoolKey memory key = PoolKey(
Currency.wrap(address(0)),
Currency.wrap(address(this)),
0,
60,
IHooks(hookAddress)
);
router.swapExactTokensForTokens{value: amountIn}(
amountIn,
0,
true,
key,
"",
DEADADDRESS,
block.timestamp
);
}
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external view returns (bytes4) {
if (msg.sender != address(collection)) {
revert InvalidCollection();
}
return this.onERC721Received.selector;
}
/// @notice Allows the contract to receive ETH
receive() external payable {}
}
"
},
"lib/solady/src/utils/SafeTransferLib.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/// @dev The ERC20 `transferFrom` has failed.
error TransferFromFailed();
/// @dev The ERC20 `transfer` has failed.
error TransferFailed();
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();
/// @dev The ERC20 `totalSupply` query has failed.
error TotalSupplyQueryFailed();
/// @dev The Permit2 operation has failed.
error Permit2Failed();
/// @dev The Permit2 amount must be less than `2**160 - 1`.
error Permit2AmountOverflow();
/// @dev The Permit2 approve operation has failed.
error Permit2ApproveFailed();
/// @dev The Permit2 lockdown operation has failed.
error Permit2LockdownFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev The unique EIP-712 domain separator for the DAI token contract.
bytes32 internal constant DAI_DOMAIN_SEPARATOR =
0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
/// @dev The address for the WETH9 contract on Ethereum mainnet.
address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @dev The canonical Permit2 address.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
/// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
/// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
//
// The regular variants:
// - Forwards all remaining gas to the target.
// - Reverts if the target reverts.
// - Reverts if the current contract has insufficient balance.
//
// The force variants:
// - Forwards with an optional gas stipend
// (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
// - If the target reverts, or if the gas stipend is exhausted,
// creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
// Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
// - Reverts if the current contract has insufficient balance.
//
// The try variants:
// - Forwards with a mandatory gas stipend.
// - Instead of reverting, returns whether the transfer succeeded.
/// @dev Sends `amount` (in wei) ETH to `to`.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Sends all the ETH in the current contract to `to`.
function safeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer all the ETH and check if it succeeded or not.
if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// forgefmt: disable-next-item
if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
function trySafeTransferAllETH(address to, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
/// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
/// and upon failure, deploys a minimal vault to accrue the ETH.
function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
/// @solidity memory-safe-assembly
assembly {
to := shr(96, shl(96, to)) // Clean upper 96 bits.
for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
let selfBalanceBefore := selfbalance()
if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if extcodesize(mover) {
let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
mstore(0x00, to)
pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
if iszero(lt(add(amount, balance(to)), balanceBefore)) { break }
if lt(selfBalanceBefore, selfbalance()) { invalid() } // Just in case.
}
let m := mload(0x40)
// If the mover is missing or bricked, deploy a minimal vault
// that withdraws all ETH to `to` when being called only by `to`.
// forgefmt: disable-next-item
mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
// Compute and store the bytecode hash.
mstore8(0x00, 0xff) // Write the prefix.
mstore(0x35, keccak256(m, 0x40))
mstore(0x01, shl(96, address())) // Deployer.
mstore(0x15, 0) // Salt.
vault := keccak256(0x00, 0x55)
pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
// The vault returns a single word on success. Failure reverts with empty data.
if iszero(returndatasize()) {
if iszero(create2(0, m, 0x40, 0)) { revert(co
Submitted on: 2025-09-19 11:27:08
Comments
Log in to comment.
No comments yet.