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/ChecksFeeHandler.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 {ReentrancyGuard} from "solady/utils/ReentrancyGuard.sol";
import {IERC721, INFTStrategy} from "./Interfaces.sol";
/// @title ChecksFeeHandler
/// @author TokenWorks (https://token.works/)
contract ChecksFeeHandler is Ownable, ReentrancyGuard {
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™ ™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™ ™™™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* VARIABLES */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
address public constant CHECKS_ADDRESS = 0x036721e5A769Cc48B3189EFbb9ccE4471E8A48B1;
address public checkStrategy;
address public destination;
uint256 public reward = 0.005 ether;
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* CUSTOM ERRORS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
error NFTNotOwned();
error NFTNotForSale();
error StrategyAlreadySet();
error StrategyNotSet();
error PriceTooLow();
error InsufficientBalance();
error NotOwnerOrDestination();
error DestinationNotSet();
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* CUSTOM EVENTS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Event emitted when a Check is purchased by the protocol
event CheckProcessed(uint256 cost, uint256 tokenId, address indexed destination);
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* CONSTRUCTOR */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
constructor(address _destination) {
destination = _destination;
_initializeOwner(msg.sender);
}
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* ADMIN FUNCTIONS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Updates the destination address for Checks NFTs
/// @param _destination New destination address
/// @dev Only callable by owner or current destination
function updateDestination(address _destination) external {
if (msg.sender != owner() && msg.sender != destination) revert NotOwnerOrDestination();
destination = _destination;
}
/// @notice Updates the reward amount for calling buyCheck
/// @param _newReward New reward amount in wei
/// @dev Only callable by owner or current destination
function updateReward(uint256 _newReward) external {
if (msg.sender != owner() && msg.sender != destination) revert NotOwnerOrDestination();
reward = _newReward;
}
/// @notice Updates the Check strategy contract address
/// @param _checkStrategy The Check strategy contract address
/// @dev Only callable by owner once
function setCheckStrategy(address _checkStrategy) external onlyOwner {
if (checkStrategy != address(0)) revert StrategyAlreadySet();
checkStrategy = _checkStrategy;
}
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* USER FUNCTIONS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Buys a check from the market and relists it, paying a reward to the caller
/// @param checkId The ID of the check to buy and relist
/// @dev Requires the check to be for sale to anyone and sufficient fees (price + reward)
function buyCheck(uint256 checkId) external nonReentrant returns (uint256) {
if (checkStrategy == address(0)) revert StrategyNotSet();
if (destination == address(0)) revert DestinationNotSet();
// Get price from strategy contract
uint256 price = INFTStrategy(checkStrategy).nftForSale(checkId);
// Make sure it's listed and less than reward.
if (price < reward) revert PriceTooLow();
// Make sure the protocol can afford the NFT + the reward
if (price + reward > address(this).balance) revert InsufficientBalance();
// Buy the NFT
INFTStrategy(checkStrategy).sellTargetNFT{value: price}(checkId);
// Make sure we own it
if (IERC721(CHECKS_ADDRESS).ownerOf(checkId) != address(this)) revert NFTNotOwned();
// Send to destination
IERC721(CHECKS_ADDRESS).transferFrom(address(this), destination, checkId);
// Send reward to caller
SafeTransferLib.forceSafeTransferETH(msg.sender, reward);
emit CheckProcessed(price, checkId, destination);
return price;
}
/// @notice Emergency function to rescue any ERC721 tokens accidentally sent to the contract
/// @param _token Address of the ERC721 token to rescue
/// @param _to Address to send the token to
/// @param _tokenId ID of the token to send
/// @dev Only callable by owner
function emergencySendERC721(address _token, address _to, uint256 _tokenId) external onlyOwner {
IERC721(_token).safeTransferFrom(address(this), _to, _tokenId);
}
/// @notice Emergency function to withdraw ETH from the contract
/// @param _to Address to send the ETH to
/// @dev Only callable by owner
function emergencyWithdrawETH(address _to) external onlyOwner {
uint256 balance = address(this).balance;
SafeTransferLib.forceSafeTransferETH(_to, balance);
}
/// @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.26;
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 {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import "./Interfaces.sol";
import {Initializable} from "solady/utils/Initializable.sol";
import {UUPSUpgradeable} from "solady/utils/UUPSUpgradeable.sol";
import {Ownable} from "solady/auth/Ownable.sol";
import {LibClone} from "solady/utils/LibClone.sol";
/// @title NFTStrategy - An ERC20 token that constantly churns NFTs from a collection
/// @author TokenWorks (https://token.works/)
/// @notice This contract implements an ERC20 token backed by NFTs from a specific collection.
/// Users can trade the token on Uniswap V4, and the contract uses trading fees to buy and sell NFTs.
/// @dev Uses ERC1967 proxy pattern with immutable args for gas-efficient upgrades
contract NFTStrategy is Initializable, UUPSUpgradeable, Ownable, ReentrancyGuard, ERC20 {
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™ ™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™ */
/* ™™™™™™™™™™™ ™™™™™™™™™™™™ ™™™™™™™™™™™™ */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* CONSTANTS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice The name of the ERC20 token
string tokenName;
/// @notice The symbol of the ERC20 token
string tokenSymbol;
/// @notice Address of the Uniswap V4 hook contract
address public hookAddress;
/// @notice The NFT collection this strategy is tied to
IERC721 public collection;
/// @notice Maximum token supply (1 billion tokens)
uint256 public constant MAX_SUPPLY = 1_000_000_000 * 1e18;
/// @notice Dead address for burning tokens
address public constant DEAD_ADDRESS = 0x000000000000000000000000000000000000dEaD;
/// @notice Contract version for upgrade tracking
uint256 public constant VERSION = 2;
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* STATE VARIABLES */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Multiplier for NFT resale price (in basis points, e.g., 1200 = 1.2x)
uint256 public priceMultiplier;
/// @notice Mapping of NFT token IDs to their sale prices
mapping(uint256 => uint256) public nftForSale;
/// @notice Current accumulated fees available for NFT purchases
uint256 public currentFees;
/// @notice ETH accumulated from NFT sales, waiting to be used for token buyback
uint256 public ethToTwap;
/// @notice Amount of ETH to use per TWAP buyback operation
uint256 public twapIncrement;
/// @notice Number of blocks to wait between TWAP operations
uint256 public twapDelayInBlocks;
/// @notice Block number of the last TWAP operation
uint256 public lastTwapBlock;
/// @notice Block number when the last NFT was bought
uint256 public lastBuyBlock;
/// @notice ETH amount increment for maximum buy price calculation
uint256 public buyIncrement;
/// @notice Mapping of addresses that can distribute tokens freely (team wallets, airdrop contracts)
mapping(address => bool) public isDistributor;
/// @notice Storage gap for future upgrades (prevents storage collisions)
uint256[49] private __gap;
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* CUSTOM EVENTS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Emitted when the protocol buys an NFT
event NFTBoughtByProtocol(uint256 indexed tokenId, uint256 purchasePrice, uint256 listPrice);
/// @notice Emitted when the protocol sells an NFT
event NFTSoldByProtocol(uint256 indexed tokenId, uint256 price, address buyer);
/// @notice Emitted when transfer allowance is increased by the hook
event AllowanceIncreased(uint256 amount);
/// @notice Emitted when transfer allowance is spent
event AllowanceSpent(address indexed from, address indexed to, uint256 amount);
/// @notice Emitted when the contract implementation is upgraded
event ContractUpgraded(address indexed oldImplementation, address indexed newImplementation, uint256 version);
/// @notice Emitted when a distributor's whitelist status is updated
event DistributorUpdated(address indexed distributor, bool status);
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* CUSTOM ERRORS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice NFT is not currently for sale
error NFTNotForSale();
/// @notice Sent ETH amount is less than the NFT sale price
error NFTPriceTooLow();
/// @notice Contract doesn't have enough ETH balance
error InsufficientContractBalance();
/// @notice Price multiplier is outside valid range
error InvalidMultiplier();
/// @notice No ETH available for TWAP operations
error NoETHToTwap();
/// @notice Not enough blocks have passed since last TWAP
error TwapDelayNotMet();
/// @notice Not enough ETH in fees to make purchase
error NotEnoughEth();
/// @notice Purchase price exceeds time-based maximum
error PriceTooHigh();
/// @notice Caller is not the factory contract
error NotFactory();
/// @notice Contract already owns this NFT
error AlreadyNFTOwner();
/// @notice External call didn't result in NFT acquisition
error NeedToBuyNFT();
/// @notice Contract doesn't own the specified NFT
error NotNFTOwner();
/// @notice Caller is not the authorized hook contract
error OnlyHook();
/// @notice Invalid NFT collection address
error InvalidCollection();
/// @notice External call to marketplace failed
error ExternalCallFailed(bytes reason);
/// @notice Invalid target address for external call
error InvalidTarget();
/// @notice Token transfer not authorized
error InvalidTransfer();
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* CONSTRUCTOR */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Constructor disables initializers to prevent implementation contract initialization
/// @dev This is required for the proxy pattern to work correctly
constructor() {
_disableInitializers();
}
/// @notice Initializes the contract with required addresses and permissions
/// @param _collection Address of the NFT collection contract
/// @param _hook Address of the NFTStrategyHook contract
/// @param _tokenName Name of the token
/// @param _tokenSymbol Symbol of the token
/// @param _buyIncrement Buy increment for the token
/// @param _owner Owner of the contract
function initialize(
address _collection,
address _hook,
string memory _tokenName,
string memory _tokenSymbol,
uint256 _buyIncrement,
address _owner
) external initializer {
require(_collection != address(0), "Invalid collection");
require(bytes(_tokenName).length > 0, "Empty name");
require(bytes(_tokenSymbol).length > 0, "Empty symbol");
collection = IERC721(_collection);
hookAddress = _hook;
tokenName = _tokenName;
tokenSymbol = _tokenSymbol;
lastBuyBlock = block.number;
buyIncrement = _buyIncrement;
// Initialize owner without validation in-case we want to disable upgradeability
_initializeOwner(_owner);
// Initialize state variables that have default values
priceMultiplier = 1200; // 1.2x
twapIncrement = 1 ether;
twapDelayInBlocks = 1;
_mint(factory(), MAX_SUPPLY);
}
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* MODIFIERS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Restricts function access to the factory contract only
modifier onlyFactory() {
if (msg.sender != factory()) revert NotFactory();
_;
}
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* ADMIN FUNCTIONS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Authorizes contract upgrades (UUPS pattern)
/// @param newImplementation Address of the new implementation contract
/// @dev Only callable by contract owner, validates implementation is a contract
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {
require(newImplementation != address(0), "Invalid implementation");
require(newImplementation.code.length > 0, "Implementation must be contract");
emit ContractUpgraded(address(this), newImplementation, VERSION);
}
/// @notice Updates the hook address
/// @dev Can only be called by the owner
/// @param _hookAddress New hook address
function updateHookAddress(address _hookAddress) external onlyOwner {
hookAddress = _hookAddress;
}
/// @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;
}
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* FACTORY FUNCTIONS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @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 onlyFactory {
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 onlyFactory {
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 onlyFactory {
if (_newMultiplier < 1100 || _newMultiplier > 10000) revert InvalidMultiplier();
priceMultiplier = _newMultiplier;
}
/// @notice Allows factory to whitelist addresses that can distribute tokens freely
/// @param distributor Address to whitelist
/// @param status True to whitelist, false to remove from whitelist
/// @dev Only callable by factory. Enables fee-free token distribution for whitelisted addresses
function setDistributor(address distributor, bool status) external onlyFactory {
isDistributor[distributor] = status;
emit DistributorUpdated(distributor, status);
}
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* MECHANISM FUNCTIONS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Returns the maximum price allowed for buying an NFT, increasing over time
/// @return The maximum price in ETH (wei) that can be used for buying
/// @dev Increases by buyIncrement per block from last buy
function getMaxPriceForBuy() public view returns (uint256) {
// Calculate blocks since last buy
uint256 blocksSinceLastBuy = block.number - lastBuyBlock;
// Return buyIncrement for each block, starting at 1 block minimum
return (blocksSinceLastBuy + 1) * buyIncrement;
}
/// @notice Allows the hook to deposit trading fees into the contract
/// @dev Only callable by the authorized hook contract, uses msg.value for fee amount
function addFees() external payable {
if (msg.sender != hookAddress) revert OnlyHook();
currentFees += msg.value;
}
/// @notice Increases the transient transfer allowance for pool operations
/// @param amountAllowed Amount to add to the current allowance
/// @dev Only callable by the hook contract, uses transient storage
function increaseTransferAllowance(uint256 amountAllowed) external {
if (msg.sender != hookAddress) revert OnlyHook();
uint256 currentAllowance = getTransferAllowance();
assembly {
tstore(0, add(currentAllowance, amountAllowed))
}
emit AllowanceIncreased(amountAllowed);
}
/// @notice Buys a specific NFT using accumulated fees
/// @param value Amount of ETH to spend on the NFT purchase
/// @param data Calldata for the external marketplace call
/// @param expectedId The token ID expected to be acquired
/// @param target The marketplace contract to call
/// @dev Protected against reentrancy, validates NFT acquisition
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();
}
// Ensure value doesn't exceed the time-based maximum price
if (value > getMaxPriceForBuy()) {
revert PriceTooHigh();
}
// Ensure target is not the collection itself
if (target == address(collection)) revert InvalidTarget();
// 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;
// Update last buy block to reset max price calculation
lastBuyBlock = block.number;
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);
}
/// @notice Processes token buyback using TWAP mechanism
/// @dev Can be called once every twapDelayInBlocks, uses ethToTwap for buyback
/// @dev Caller receives 0.5% reward, remaining ETH is used to buy and burn tokens
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
/// @dev Creates a pool key and swaps ETH for tokens, sending tokens to dead address
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, "", DEAD_ADDRESS, block.timestamp);
}
/// @notice Validates token transfers using a transient allowance system
/// @param from The address sending tokens
/// @param to The address receiving tokens
/// @param amount The amount of tokens being transferred
/// @dev Reverts if transfer isn't through the hook
function _afterTokenTransfer(address from, address to, uint256 amount) internal override {
// On strategy launch, we need to allow for supply mint transfer
if (from == address(0)) {
return;
}
// Allow whitelisted distributors to send tokens freely
if (isDistributor[from]) {
return;
}
// Transfers to and from the poolManager require a transient allowance thats set by the hook
if ((from == address(poolManager()) || to == address(poolManager()))) {
uint256 transferAllowance = getTransferAllowance();
require(transferAllowance >= amount, InvalidTransfer());
assembly {
let newAllowance := sub(transferAllowance, amount)
tstore(0, newAllowance)
}
emit AllowanceSpent(from, to, amount);
return;
}
revert InvalidTransfer();
}
/// @notice Gets the current transient transfer allowance
/// @return transferAllowance The current allowance amount
/// @dev Reads from transient storage slot 0
function getTransferAllowance() public view returns (uint256 transferAllowance) {
assembly {
transferAllowance := tload(0)
}
}
/// @notice Handles receipt of NFTs (ERC721 receiver)
/// @dev Only accepts NFTs from the designated collection
/// @return The function selector to confirm receipt
function onERC721Received(address, address, uint256, bytes calldata) external view returns (bytes4) {
if (msg.sender != address(collection)) {
revert InvalidCollection();
}
return this.onERC721Received.selector;
}
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/* GETTER FUNCTIONS */
/* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */
/// @notice Returns the factory address from proxy bytecode
/// @return The factory contract address
/// @dev Reads from bytes 0-20 of the proxy's immutable args
function factory() public view returns (address) {
bytes memory args = LibClone.argsOnERC1967(address(this), 0, 20);
return address(bytes20(args));
}
/// @notice Returns the router address from proxy bytecode
/// @return The Uniswap V4 router contract interface
/// @dev Reads from bytes 20-40 of the proxy's immutable args
function router() public view returns (IUniswapV4Router04) {
bytes memory args = LibClone.argsOnERC1967(address(this), 20, 40);
return IUniswapV4Router04(payable(address(bytes20(args))));
}
/// @notice Returns the pool manager address from proxy bytecode
/// @return The Uniswap V4 pool manager contract interface
/// @dev Reads from bytes 40-60 of the proxy's immutable args
function poolManager() public view returns (IPoolManager) {
bytes memory args = LibClone.argsOnERC1967(address(this), 40, 60);
return IPoolManager(address(bytes20(args)));
}
/// @notice Returns the current implementation address
/// @return result The address of the current implementation contract
/// @dev Reads from the ERC1967 implementation slot
function getImplementation() external view returns (address result) {
assembly {
result := sload(_ERC1967_IMPLEMENTATION_SLOT)
}
}
/// @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
Submitted on: 2025-10-08 18:45:19
Comments
Log in to comment.
No comments yet.