Проверенный контрактЧастичноеMIT
PoolBalancer
Адрес0x46516fe3bd20b210985be9b2e65c22e46c1ef6ca
- Баланс
0 ETH
- Транзакций
1
- Компилятор
solc 0.8.28
- Тот же код
Только этот контракт
Подробности
- Компилятор
- solc 0.8.28+commit.7893614a
- Язык
- solidity
- Оптимизация
- Да, 50 прогонов
- Версия EVM
- cancun
- Через IR
- да
- Лицензия
- MIT
- Совпадение
- Частичноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 26 453 684
- Транзакция создания
- 0x22bc859bc0…357cc78784
- Библиотеки
- src/PoolPage.sol:PoolPage0x67c8…07fbcfsrc/PoolInventory.sol:PoolInventory0x9154…dcff9esrc/KeeperPolicyCalls.sol:KeeperPolicyCalls0x1601…84b8fb
11 файлов
- src/PoolBalancer.solглавный45,8 КБ
- lib/solady/src/utils/LibBytes.sol38,18 КБ
- lib/solady/src/utils/LibString.sol44,25 КБ
- lib/solady/src/utils/ReentrancyGuard.sol2,33 КБ
- lib/solady/src/utils/SafeTransferLib.sol32,86 КБ
- lib/solady/src/utils/SignatureCheckerLib.sol25,76 КБ
- src/KeeperPolicyCalls.sol11,11 КБ
- src/PoolInventory.sol17,83 КБ
- src/PoolPage.sol2,05 КБ
- src/interfaces/External.sol7,05 КБ
- src/interfaces/IKeeperPolicy.sol1,13 КБ
src/PoolBalancer.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {ReentrancyGuard} from "solady/utils/ReentrancyGuard.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {PoolPage} from "./PoolPage.sol";
import {IKeeperPolicy} from "./interfaces/IKeeperPolicy.sol";
import {PoolInventory} from "./PoolInventory.sol";
import {KeeperPolicyCalls} from "./KeeperPolicyCalls.sol";
import {IFWAPoolFactory, IFWAPool, IShapes, IShapePacks, IERC721Min, IENS, IReverseRegistrar} from "./interfaces/External.sol";
/// @dev The deploying factory supplies initial policy selection and ongoing keeper eligibility.
interface IBalancerFactory {
function canKeep(address keeper) external view returns (bool);
function defaultKeeperPolicy() external view returns (address);
}
/// @title PoolBalancer
/// @notice Permanently owns one FWA standard pool. The creator lists NFTs and sets a target mix of Shape and Draw Pack
/// prizes; anyone (or, while its factory restricts upkeep, approved keepers and the creator) may call
/// `performUpkeep` to restock drawn prizes from this contract's ETH. Players buy on FWA directly; this contract is
/// FWA's purchase operator.
/// @dev Design:
/// - FWA prices every draw on its live inventory and refunds draws whose price moved past the player's
/// tolerance, so the gate does not need an exact inventory. It keeps the game close to its design:
/// no new request while initial setup is unfinished, while no curated NFT is listed (the pool exists to
/// give NFTs away), while at least MAX_BATCH draws are already unsettled, while the
/// Shapes mint fee is above what the creator accepted, while the prizes' weight, after assuming every
/// unreconciled draw took the heaviest possible prize, is below FILL_BPS of the target's weight. Purchases do not
/// wait for a fully funded target: expensive deficits may remain while sales replenish operating capital.
/// A stored share of actual collected owner proceeds is protected as creator credit.
/// `open` funds current inventory/setup work and a maintenance buffer, without duplicate prize backing.
/// - A curated NFT is listed at the creator's value, with no markup. Shape prizes carry the markup.
/// - Prices are set when a listing is made, at the markup in force then. Nothing is repriced. A Shape prize is
/// listed at its backing, its Shapes mint fees and the markup on its backing, plus a restocking fee per Shape
/// from the basefee then. The fee is the creator's income for keeper pay: the pool's ETH pays the keeper who
/// lists the prize; the fee is in the prize's price, which FWA's single draw price spreads over all buyers.
/// - Upkeep reconciles settled FWA sequences in order (MAX_RECONCILE per call) and restocks while draws are still
/// unsettled; FWA stages those listings and activates them in order.
/// - Withdrawals retain current missing inventory/setup, actual outstanding draw budgets and a working buffer.
/// Paid work may consume the buffer; low inventory can pause until proceeds or creator action restore it.
/// - Only this contract can list into the pool (FWA `OwnerOnlyInventory`).
/// - Prize tokens are held only inside a transaction: minted then listed, or withdrawn then redeemed. Any NFT this
/// contract owns between transactions is untracked and creator-recoverable.
/// - No function sends ETH or NFTs to an address chosen by anyone but the creator, except the bounded keeper
/// reward to `msg.sender` of `performUpkeep`.
contract PoolBalancer is ReentrancyGuard {
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
uint256 internal constant BPS = 10_000;
/// @dev FWA `maxAcquisitionsPerTx`; verified against the FWA factory at pool creation. Also the unsettled-draw cap.
uint256 public constant MAX_BATCH = 5;
/// @dev Prize sizes: indices 0-8 are the nine Shapes denominations (each prize one Shape); indices 9-15 are values
/// between them, each prize one Draw Pack holding the fewest Shapes that sum to it (see `_amount`, `_makeup`).
/// A target packs sixteen 16-bit counts into one uint256.
uint256 internal constant DENOMS = 16;
uint256 internal constant SHAPE_DENOMS = 9;
/// @dev Size values in units of 0.01 ETH, 16 bits each, size 0 in the low bits:
/// 0.01 0.05 0.1 0.5 1 5 10 50 100 | 0.02 0.03 0.2 0.25 2 2.5 25.
uint256 internal constant AMOUNTS = 0x9c400fa00c800190014000300022710138803e801f400640032000a00050001;
/// @dev Shapes inside one prize of each size, 4 bits each (1 for a Shape; 2 or 3 for a pack).
uint256 internal constant SHAPES_IN = 0x3323232111111111;
/// @dev Size indices in ascending value order, 4 bits each, smallest first.
uint256 internal constant BY_VALUE = 0x87f65ed43cb21a90;
/// @dev The most Shapes any one prize holds.
uint256 internal constant MAX_SHAPES_IN = 3;
/// @dev Inventory work per upkeep, in Shape units: minting+listing or withdrawing+redeeming one Shape is 1; a pack
/// counts as the Shapes it holds (measured: ~425k gas per Shape with its listing, ~870k per three-Shape pack).
/// Six units with five reconciles measured 3.13M against the 3.2M pay cap (the lowest maxGas allowed); five keeps a margin.
uint256 internal constant MAX_OPS = 5;
/// @dev Settled FWA sequences reconciled per upkeep call (~33k gas each), one FWA batch.
uint256 internal constant MAX_RECONCILE = 5;
/// @dev FWA draws processed per upkeep: keeps the worst upkeep under the 3.2M pay cap (the lowest maxGas allowed).
uint256 internal constant MAX_PROCESS = 2;
/// @dev Gas a failed processing call can hand back and still have been starved: FWA reverts on purpose when its
/// notifier would start with under 290,000 gas, and the pool is a proxy that keeps 1/64 of what it forwards,
/// so a starved failure hands back at most about 343,000 (measured, 48 to 2,048 listings). A failure with more
/// than this left was not for want of gas. The proxy's share grows with the gas processing needs, so the bound
/// holds for MAX_PROCESS = 2 and FWA's six-listing reservations (at most about 3.3M).
uint256 internal constant PROCESS_STARVED_GAS = 400_000;
/// @dev Prize sizes restocked per upkeep call: each size is its own mint call (~0.5M gas with its listing). Six sizes
/// in one call measured 3.19M against the 3.2M pay cap.
uint256 internal constant MAX_RESTOCK_SIZES = 4;
uint256 internal constant MAX_MARKUP_BPS = 10_000;
/// @dev Minimum markup for newly listed Shape prizes; revenue allocation is set independently.
uint256 internal constant MIN_MARKUP_BPS = 1_000;
/// @dev Purchases need the listed prizes' weight, less the unreconciled-draw allowance, at this share of the target's.
uint256 internal constant FILL_BPS = 7_000;
uint256 internal constant INVERSE_WEIGHT_NUMERATOR = 1e36; // FWA StandardPool constant
/// @dev The heaviest prize in the fill gate: the smallest backing (0.01 ETH). See `_weight`.
uint256 internal constant MAX_PRIZE_WEIGHT = INVERSE_WEIGHT_NUMERATOR / 0.01 ether;
uint256 public constant POLICY_DELAY = 2 days;
uint256 public constant HARD_MAX_KEEPER_REWARD = 0.311 ether;
uint256 public constant KEEPER_BURST = 0.622 ether;
uint256 public constant KEEPER_REFILL_PER_SECOND = uint256(0.05 ether) / 12;
uint256 public constant MAX_RESTOCK_SURCHARGE_PER_SHAPE = 0.102 ether;
uint256 internal constant ACQUISITIONS_ENABLED_KEY = 41; // FWAConfigKeys.ACQUISITIONS_ENABLED
bytes4 internal constant ERC1271_MAGIC = 0x1626ba7e;
bytes32 internal constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
// FWA ListingStatus / AcquisitionStatus values.
uint8 internal constant L_DELIVERY_REFUNDED = 7;
uint8 internal constant A_FULFILLED = 2;
// Item kinds and states.
uint8 internal constant CURATED = 1;
uint8 internal constant SHAPE = 2; // a Shape or Draw Pack prize
uint8 internal constant ACTIVE = 1;
uint8 internal constant PENDING = 2; // drawn, FWA delivery failed; resolved per item, never scanned
// `admissionStatus` codes. Zero means purchases are admitted.
uint8 internal constant OK = 0;
uint8 internal constant CLOSED = 1;
uint8 internal constant SETTING_UP = 2;
uint8 internal constant NO_CURATED = 3;
uint8 internal constant BUSY = 4;
uint8 internal constant MINT_FEE_ROSE = 5;
uint8 internal constant LOW_INVENTORY = 6;
uint8 internal constant CURATED_PROOF_REQUIRED = 7;
/*//////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
IFWAPoolFactory public immutable FWA_FACTORY;
address public immutable FWA_IMPLEMENTATION;
IShapes public immutable SHAPES;
IShapePacks public immutable PACKS;
IENS public immutable ENS;
/*//////////////////////////////////////////////////////////////
STORAGE
//////////////////////////////////////////////////////////////*/
address public creator;
address public pendingCreator;
IFWAPool public pool;
/// @dev Prize counts per size, sixteen 16-bit counts, size 0 in the low bits.
uint256 public target;
uint16 public markupBps;
bool public enabled;
/// @dev Initial opening setup remains true until the target is stocked; later ordinary depletion does not reset it.
bool public creatorWork;
uint64 public reconciledSequence;
/// @dev Only actual FWA owner proceeds create credit, including collections after closing.
uint256 public creatorCredit;
uint16 public creatorRevenueBps;
/// @dev The Shapes mint fee when the creator last configured; purchases and restocking stop above it.
uint256 public mintFeeCap;
/// @dev Weight (1e36 / `base`) of the listed prizes (staged or active, not yet reconciled as drawn) and of the
/// target. `base` leaves out the basefee-indexed restocking fee, so fill does not move with gas.
uint256 public prizeWeight;
uint256 public targetWeight;
PoolInventory.State internal _inventory;
/// @dev Pool-page approvals are valid only in the epoch they were made; `revokePoolPages` and every creator
/// change start a new epoch, so a former creator's approvals cannot be replayed.
uint256 public pageEpoch;
mapping(bytes32 digest => uint256) internal pageApprovedEpoch; // epoch + 1
/// @dev The factory that deployed this Balancer: its keeper list decides who besides the creator may run upkeep,
/// and its default policy is snapshotted at creation.
IBalancerFactory public factory;
KeeperPolicyCalls.State internal _keeper;
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Initialized(address indexed creator, address indexed pool);
event CreatorTransferStarted(address indexed creator, address indexed pendingCreator);
event CreatorTransferred(address indexed oldCreator, address indexed newCreator);
event Configured(uint16 markupBps, uint256 target, uint256 mintFeeCap);
event CreatorRevenueChanged(uint16 previousBps, uint16 newBps);
event KeeperPolicyProposed(address indexed policy, uint256 activationTime);
event KeeperPolicyCancelled(address indexed policy);
event KeeperPolicyChanged(address indexed previousPolicy, address indexed newPolicy);
event PaidUpkeepChanged(bool enabled);
event PurchasesOpened();
event PurchasesClosed();
event CuratedListed(uint256 indexed listingId, address indexed collection, uint256 tokenId, uint256 base, uint256 price);
event CuratedRepriced(uint256 indexed listingId, uint256 base, uint256 price);
event CuratedWithdrawn(uint256 indexed listingId, address indexed to);
event CuratedWitnessRefreshed(uint256 indexed listingId, uint256 slot);
event RefundedRecovered(uint256 indexed listingId, address indexed to, uint256 eth);
event UntrackedNFTRecovered(address indexed collection, uint256 tokenId, address indexed to);
event ItemDrawn(uint256 indexed listingId, uint8 kind, uint8 denom, bool delivered);
event ShapesMinted(uint8 indexed denom, uint256 firstTokenId, uint256 quantity, uint256 cost);
event ShapeListed(uint256 indexed listingId, uint8 indexed denom, uint256 tokenId, uint256 price);
event ShapesUnlisted(uint256 count, uint256 ethRedeemed);
event KeeperPaid(address indexed keeper, uint256 amount, uint256 gasUsed);
event Deposited(address indexed from, uint256 amount);
event ProceedsCollected(uint256 amount);
event SurplusClaimed(address indexed to, uint256 amount);
event PoolRetired();
event ENSNameSet(string name);
event PoolPageApproved(bytes32 indexed digest, string issuedAt, bytes32 metadataHash);
event PoolPagesRevoked(uint256 epoch);
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
error Unauthorized();
error KeeperNotApproved();
error StaleSettings();
error PolicyNotReady();
error PolicyUnavailable();
error PaymentUnavailable();
error MinimumPaymentNotMet();
error AlreadyInitialized();
error UnreviewedImplementation();
error UnsupportedFWAConfig();
error InvalidConfig();
error InvalidPlan();
error InvalidItem();
error InvalidRecipient();
error ValueTooHigh();
error ShapesNotCurated();
error NotClosed();
error InsufficientSurplus();
error ReserveNotFunded();
error NoUpkeepNeeded();
error InsufficientGas();
error InvalidBatch();
error ProtectedAsset();
/*//////////////////////////////////////////////////////////////
CONSTRUCTION
//////////////////////////////////////////////////////////////*/
constructor(address fwaFactory, address fwaImplementation, bytes32 fwaCodehash, address shapes, address packs, address ens) {
FWA_FACTORY = IFWAPoolFactory(fwaFactory);
FWA_IMPLEMENTATION = fwaImplementation;
// Deployed code cannot change (EIP-6780), so one check covers every clone.
if (fwaImplementation.codehash != fwaCodehash) revert UnreviewedImplementation();
SHAPES = IShapes(shapes);
PACKS = IShapePacks(packs);
ENS = IENS(ens);
// The size table below is hardcoded; refuse a Shapes deployment that disagrees, and a Packs instance that
// wraps other Shapes or cannot make the smallest pack size.
// Draw Packs takes one mint count per Shapes size (`_makeup` has nine).
if (IShapes(shapes).denominationCount() != SHAPE_DENOMS) revert UnsupportedFWAConfig();
for (uint256 d; d < SHAPE_DENOMS; ++d) {
if (IShapes(shapes).denominationAt(uint8(d)) != _amount(d)) revert UnsupportedFWAConfig();
}
if (IShapePacks(packs).shapes() != shapes || IShapePacks(packs).MIN_PACK_VALUE() > _amount(9)) {
revert UnsupportedFWAConfig();
}
creator = address(1); // lock the implementation
}
/// @notice Called once by BalancerFactory in the clone's deployment transaction. Creates the FWA
/// pool owned by this contract and installs this contract as its purchase operator.
struct CreationConfig {
uint16 markupBps;
uint16 creatorRevenueBps;
uint256 target;
uint256 mintFeeCap;
}
function initialize(address creator_, CreationConfig calldata config, CuratedInput[] calldata curated)
external payable nonReentrant
{
if (creator != address(0)) revert AlreadyInitialized();
if (creator_ == address(0)) revert InvalidRecipient();
creator = creator_;
factory = IBalancerFactory(msg.sender);
KeeperPolicyCalls.initialize(_keeper, factory.defaultKeeperPolicy());
IFWAPoolFactory fwa = FWA_FACTORY;
// A staging cap would make restocking while draws are unsettled revert (FWA StagingQueueFull), and with it upkeep.
if (fwa.maxAcquisitionsPerTx() != MAX_BATCH || fwa.maxStagedListings() != 0
|| fwa.maxActivationsPerAcquisition() != 6) revert UnsupportedFWAConfig();
// FWA reverts unless its implementation is the reviewed one, clones exactly that, and initialises the pool
// with this contract as owner.
address p = fwa.createPool(bytes32(0), FWA_IMPLEMENTATION);
pool = IFWAPool(p);
IFWAPool(p).setPurchaseOperator(address(this));
SHAPES.setApprovalForAll(p, true);
PACKS.setApprovalForAll(p, true);
if (SHAPES.mintFee() > config.mintFeeCap) revert InvalidConfig();
_configure(config.markupBps, config.target, config.mintFeeCap);
_setCreatorRevenueBps(config.creatorRevenueBps);
_listCurated(curated, creator_);
_open();
emit Initialized(creator_, p);
if (msg.value != 0) emit Deposited(creator_, msg.value);
}
modifier onlyCreator() {
if (msg.sender != creator) revert Unauthorized();
_;
}
/*//////////////////////////////////////////////////////////////
CREATOR AUTHORITY
//////////////////////////////////////////////////////////////*/
function transferCreator(address newCreator) external onlyCreator nonReentrant {
pendingCreator = newCreator;
emit CreatorTransferStarted(msg.sender, newCreator);
}
function acceptCreator() external nonReentrant {
if (msg.sender != pendingCreator || msg.sender == address(0)) revert Unauthorized();
emit CreatorTransferred(creator, msg.sender);
creator = msg.sender;
++pageEpoch;
pendingCreator = address(0);
_cancelKeeperPolicy();
}
/// @notice Set the markup for new listings and the target prize mix, and accept the current Shapes mint fee.
/// @dev Existing listings keep their prices. A smaller target leaves extra prizes listed until `unlistShapes`.
function configure(uint16 newMarkupBps, uint256 newTarget) external onlyCreator nonReentrant {
_configure(newMarkupBps, newTarget, SHAPES.mintFee());
}
function _configure(uint16 newMarkupBps, uint256 newTarget, uint256 fee) internal {
uint256 w = PoolInventory.validateTarget(newTarget, newMarkupBps);
markupBps = newMarkupBps;
target = newTarget;
targetWeight = w;
mintFeeCap = fee;
_creatorChanged();
emit Configured(newMarkupBps, newTarget, fee);
}
/// @notice Collect available proceeds at the old rate; later collections use the new rate, even for pending draws.
function setCreatorRevenueBps(uint16 newBps) external onlyCreator nonReentrant {
if (newBps > BPS) revert InvalidConfig();
_collect();
_setCreatorRevenueBps(newBps);
}
function _setCreatorRevenueBps(uint16 newBps) internal {
if (newBps > BPS) revert InvalidConfig();
emit CreatorRevenueChanged(creatorRevenueBps, newBps);
creatorRevenueBps = newBps;
}
function keeperPolicy() external view returns (address) { return _keeper.policy; }
function pendingKeeperPolicy() external view returns (address) { return _keeper.pending; }
function policyActivationTime() external view returns (uint64) { return _keeper.activationTime; }
function policyGeneration() external view returns (uint64) { return _keeper.generation; }
function paidUpkeepEnabled() external view returns (bool) { return _keeper.enabled; }
function policyMaxReward() external view returns (uint256) { return _keeper.maxReward; }
function keeperAllowance() external view returns (uint256) { return _keeper.allowance; }
function keeperAllowanceTime() external view returns (uint64) { return _keeper.allowanceTime; }
function proposeKeeperPolicy(address policy) external onlyCreator nonReentrant {
KeeperPolicyCalls.propose(_keeper, policy);
}
function cancelKeeperPolicy() external onlyCreator nonReentrant { _cancelKeeperPolicy(); }
function _cancelKeeperPolicy() internal { KeeperPolicyCalls.cancel(_keeper); }
function activateKeeperPolicy() external nonReentrant {
KeeperPolicyCalls.activate(_keeper, address(this).balance - creatorCredit, _maintenanceInput());
}
/// @notice Emergency stop. Re-enabling, including the same policy, always takes the full proposal delay.
function setPaidUpkeepEnabled(bool value) external onlyCreator nonReentrant {
KeeperPolicyCalls.disable(_keeper, value);
}
function policyFunding(address policy) external view returns (uint256 required, uint256 shortfall) {
KeeperPolicyCalls.Reserve memory snapshot = _maintenanceInput();
required = KeeperPolicyCalls.maintenanceBudget(KeeperPolicyCalls.validate(policy), snapshot);
uint256 previous = KeeperPolicyCalls.maintenanceBudget(_keeper.enabled ? _keeper.maxReward : 0, snapshot);
uint256 fund = address(this).balance - creatorCredit;
if (required > previous && required > fund) shortfall = required - fund;
}
/// @notice Fund initial inventory, its bounded setup work and short-term maintenance. Later large wins can
/// leave a partial target; admission depends on the actual remaining prize weight, not a spare board.
function open() external onlyCreator nonReentrant {
_open();
}
function _open() internal {
if (target == 0) revert InvalidConfig();
_collect();
if (!enabled) creatorWork = _missingUnits() != 0;
enabled = true;
if (address(this).balance - creatorCredit < requiredReserve()) revert ReserveNotFunded();
pool.setBool(ACQUISITIONS_ENABLED_KEY, true);
emit PurchasesOpened();
}
/// @notice Stop new purchases immediately. Creator credit, outstanding draws and purchaser refund rights survive.
function close() external onlyCreator nonReentrant {
enabled = false;
creatorWork = false;
if (!pool.retired()) pool.setBool(ACQUISITIONS_ENABLED_KEY, false);
emit PurchasesClosed();
}
/*//////////////////////////////////////////////////////////////
CURATED NFTS
//////////////////////////////////////////////////////////////*/
struct CuratedInput {
address collection;
uint256 tokenId;
uint256 base;
}
/// @notice Pull up to 20 NFTs from the creator (approve this contract first) and list each on FWA at its `base`
/// (its price; curated NFTs carry no markup).
function listCuratedBatch(CuratedInput[] calldata inputs)
external
onlyCreator
nonReentrant
returns (uint256[] memory listingIds)
{
if (markupBps == 0) revert InvalidConfig();
return _listCurated(inputs, creator);
}
function _listCurated(CuratedInput[] calldata inputs, address source) internal returns (uint256[] memory) {
return PoolInventory.listCurated(_inventory, pool, address(SHAPES), address(PACKS), source, inputs);
}
/// @notice Prove one tracked curated NFT is active. Anyone may refresh at their own gas cost; no assets move.
/// @dev Ambiguous curated availability pauses purchases until refresh or FWA activation. Valid proofs persist.
function refreshCuratedWitness(uint256 listingId) external nonReentrant returns (bool changed) {
return PoolInventory.refreshCuratedWitness(_inventory, pool, listingId);
}
/// @notice Set a curated NFT's value, which is its FWA price.
/// FWA allows this only while no draw is unsettled.
function updateCuratedPrice(uint256 listingId, uint256 newBase) external onlyCreator nonReentrant {
PoolInventory.updateCurated(_inventory, pool, listingId, newBase);
}
/// @notice Withdraw an active curated listing from FWA directly to `to`. FWA allows this only while no draw is
/// unsettled.
function withdrawCurated(uint256 listingId, address to) external onlyCreator nonReentrant {
PoolInventory.withdrawCurated(_inventory, pool, listingId, to);
}
/// @notice Recover an item whose FWA delivery was refunded to its winner: a curated NFT goes to `to`; a Shape or
/// pack is redeemed here for its backing. FWA allows the refund 7 days after the failed delivery.
/// Upkeep never touches curated collections, so a hostile collection cannot burn keeper gas or block upkeep.
function recoverRefunded(uint256 listingId, address to) external onlyCreator nonReentrant returns (uint256 eth) {
return PoolInventory.recoverRefunded(_inventory, pool, address(SHAPES), address(PACKS), listingId, to);
}
/// @notice Return an NFT this contract holds outside FWA, e.g. one sent to it directly.
/// @dev Tracked inventory is never held here between transactions: listings and pending deliveries
/// are owned by the FWA pool, prizes are minted-and-listed or withdrawn-and-redeemed within one
/// call, and refunded NFTs are pulled from FWA only inside `recoverRefunded`. So
/// `ownerOf == this` (checked under the reentrancy lock) proves the NFT is untracked. Only the
/// ERC721 transfer selector is called, and never on the FWA pool or factory.
function recoverUntrackedNFT(address collection, uint256 tokenId, address to) external onlyCreator nonReentrant {
PoolInventory.recoverUntracked(address(pool), address(FWA_FACTORY), collection, tokenId, to);
}
/*//////////////////////////////////////////////////////////////
FUNDS
//////////////////////////////////////////////////////////////*/
receive() external payable {}
function depositETH() external payable {
emit Deposited(msg.sender, msg.value);
}
/// @notice Pull settled FWA owner proceeds into this contract. Permissionless.
function collectProceeds() external nonReentrant returns (uint256 amount) {
amount = _collect();
}
/// @notice Existing credit claims make no external reads. Capital beyond credit must retain the full reserve.
function claimSurplus(uint256 amount, address to) external onlyCreator nonReentrant {
if (to == address(0)) revert InvalidRecipient();
uint256 mine = creatorCredit;
if (amount > mine && amount > withdrawableSurplus()) revert InsufficientSurplus();
creatorCredit = amount < mine ? mine - amount : 0;
SafeTransferLib.safeTransferETH(to, amount);
emit SurplusClaimed(to, amount);
}
/// @notice Withdraw up to 20 listed Shape or pack prizes from FWA and redeem them here for their backing: extra
/// prizes after a smaller target, or everything after closing. FWA allows this only while no draw is
/// unsettled. Prizes withdrawn below the target while open are restocked by upkeep.
function unlistShapes(uint256[] calldata listingIds) external onlyCreator nonReentrant {
uint256 n = listingIds.length;
if (n == 0 || n > 20) revert InvalidBatch();
prizeWeight -= PoolInventory.unlistShapes(_inventory, pool, address(SHAPES), address(PACKS), listingIds);
_creatorChanged();
}
/// @notice Irreversibly retire the FWA pool. Withdrawals, unlisting and recovery remain available.
function retire() external onlyCreator nonReentrant {
if (enabled) revert NotClosed();
pool.retirePool();
emit PoolRetired();
}
/*//////////////////////////////////////////////////////////////
ENS
//////////////////////////////////////////////////////////////*/
/// @notice Set this contract's ENS reverse record via the current `addr.reverse` registrar ("" clears it).
function setENSName(string calldata name) external onlyCreator nonReentrant {
IReverseRegistrar(ENS.owner(ADDR_REVERSE_NODE)).setName(name);
emit ENSNameSet(name);
}
/*//////////////////////////////////////////////////////////////
FWA POOL PAGE (ERC-1271)
//////////////////////////////////////////////////////////////*/
/// @notice Approve one FWA pool-page publication. FWA's site asks the pool owner to personal_sign a
/// fixed plain-text message; this contract rebuilds that exact message for its own pool and
/// approves only its digest. `issuedAt` is the ISO-8601 time the site will submit
/// (24 chars, e.g. 2026-11-10T12:34:56.789Z); `metadataHash` is keccak256 of the page JSON.
/// @dev Approved digests are always "Publish FWA Pools page" messages naming this pool, so
/// `isValidSignature` cannot authorize anything else (no FWA, Shapes or ERC721 function
/// accepts such a message).
function approvePoolPage(string calldata issuedAt, bytes32 metadataHash)
external
onlyCreator
nonReentrant
returns (bytes32 digest)
{
digest = PoolPage.digest(address(FWA_FACTORY), address(pool), issuedAt, metadataHash);
pageApprovedEpoch[digest] = pageEpoch + 1;
emit PoolPageApproved(digest, issuedAt, metadataHash);
}
/// @notice Invalidate every pool-page approval made so far.
function revokePoolPages() external onlyCreator nonReentrant {
emit PoolPagesRevoked(++pageEpoch);
}
/// @notice ERC-1271: valid only for digests approved by `approvePoolPage`; the signature bytes are ignored.
function isValidSignature(bytes32 hash, bytes calldata) external view returns (bytes4) {
return pageApprovedEpoch[hash] == pageEpoch + 1 ? ERC1271_MAGIC : bytes4(0xffffffff);
}
/*//////////////////////////////////////////////////////////////
ADMISSION GATE
//////////////////////////////////////////////////////////////*/
/// @notice FWA purchase-operator hook. Must stay read-only and under FWA's 100k gas stipend.
/// @dev FWA passes the purchaser it will deliver to. Refused: this contract (a failed delivery to it could never
/// be refunded, and a delivered NFT would be untracked), the Shapes and Draw Packs contracts (each rejects
/// self-custody, so a drawn prize could never be delivered or refunded) and the FWA pool itself.
function canPurchase(address purchaser) external view returns (bool) {
if (
purchaser == address(this) || purchaser == address(SHAPES) || purchaser == address(PACKS)
|| purchaser == address(pool)
) return false;
return admissionStatus() == OK;
}
/// @notice Why purchases are or are not admitted right now (see status codes).
/// @dev Preserve the pending-draw bound and bound selectable Shape weight at the first new selection,
/// including FWA's guaranteed activation. Curated ambiguity may require permissionless proof refresh;
/// a valid proof permits concurrent purchases without a synchronization barrier between batches.
function admissionStatus() public view returns (uint8) {
if (!enabled) return CLOSED;
if (creatorWork) return SETTING_UP;
return PoolInventory.admission(_inventory, pool, address(SHAPES), mintFeeCap, targetWeight, prizeWeight, reconciledSequence);
}
/*//////////////////////////////////////////////////////////////
UPKEEP
//////////////////////////////////////////////////////////////*/
/// @notice Price-indexed expense protection: reward must cover minimumFixed plus minimumGas at the mined price.
function performUpkeep(bytes32 expected, uint256 minimumFixed, uint256 minimumGas)
external nonReentrant returns (uint256)
{
return _performUpkeep(expected, minimumFixed + minimumGas * tx.gasprice, true);
}
/// @notice Anyone can maintain without compensation, even with a restricted keeper list. New listings use the
/// chosen policy's bounded quote, or the immutable V1 recovery surcharge if that quote fails.
function performUpkeepUnpaid() external nonReentrant returns (uint256) {
return _performUpkeep(bytes32(0), 0, false);
}
function _performUpkeep(bytes32 expected, uint256 minimumReward, bool paid) internal returns (uint256 reward) {
uint256 gasStart = gasleft();
if (paid) {
if (msg.sender != creator && !factory.canKeep(msg.sender)) revert KeeperNotApproved();
if (settingsHash() != expected) revert StaleSettings();
if (!_keeper.enabled) revert PaymentUnavailable();
}
IFWAPool p = pool;
// 0. Process FWA's queue. A draw whose request reserved a staged restock skips FWA's randomness fast path (which
// also only ever takes the queue's head), and a ready draw never expires, so it and every draw behind it wait
// for an explicit processAcquisitions that nobody else is bound to call. FWA stops at a draw still waiting
// for its randomness; a failure here never blocks the rest of upkeep. The draws it settles are reconciled
// below in the same call, so the work is paid like any reconcile.
// Gas spent on processing that reverted is not paid for (FWA reverts on purpose when its notifier is left too
// little gas, so a keeper could otherwise pick a gas limit that burns paid gas for nothing). Processing that
// failed for want of gas reverts the whole upkeep instead, at any pool size: a call never succeeds with
// processing starved, so a gas estimate is enough to process.
uint256 processed;
uint64 next = p.nextSequenceToProcess();
if (next <= p.lastIssuedSequence()) {
uint256 g = gasleft();
try p.processAcquisitions(MAX_PROCESS) {
processed = p.nextSequenceToProcess() - next;
} catch {
uint256 left = gasleft();
if (left < g / 64 + PROCESS_STARVED_GAS) revert InsufficientGas();
gasStart -= g - left;
}
}
// 1. Collect actual settled proceeds at the stored revenue share.
bool collected = _collect() != 0;
// 2. Reconcile settled FWA sequences in order. Processed sequences are final: their listing is fixed.
uint64 s = reconciledSequence;
uint64 end = p.nextSequenceToProcess() - 1;
if (end > s + MAX_RECONCILE) end = s + uint64(MAX_RECONCILE);
while (s < end) {
(,,, uint256 lid, uint8 aStatus,) = p.acquisitions(p.requestIdAtSequence(++s));
if (lid != 0) _onDrawn(lid, aStatus == A_FULFILLED);
}
uint256 draws = s - reconciledSequence;
bool reconciled = draws != 0;
if (reconciled) reconciledSequence = s;
// 3. Restock while open, in a call that settled no draw: a draw that reserved FWA's maximum six listings costs
// up to about 1.15M gas to process, so processing two and restocking in one call can pass the 3.2M pay cap and
// leave the keeper unpaid for the excess. The next call restocks.
uint256 ops;
uint256 listed;
bool wasSetup = creatorWork;
if (processed == 0 && enabled && !FWA_FACTORY.globalWithdrawOnly()) {
uint256 fee = SHAPES.mintFee();
if (fee <= mintFeeCap) {
(ops, listed) = _fillDeficit(p, fee, paid, draws);
if (wasSetup && _missingUnits() == 0) creatorWork = false;
}
}
if (!reconciled && ops == 0 && !collected && creatorWork == wasSetup) revert NoUpkeepNeeded();
if (paid && (ops != 0 || reconciled)) {
reward = _payKeeper(gasStart, draws, ops, listed, processed);
}
if (reward < minimumReward) revert MinimumPaymentNotMet();
}
function _onDrawn(uint256 lid, bool delivered) internal {
PoolInventory.Item storage it = _inventory.items[lid];
// Every pool listing is ours and tracked until drawn. Never revert here: reconciliation must not be bricked.
if (it.state != ACTIVE) return;
uint8 kind = it.kind;
uint8 d = it.denom;
_removeActive(lid);
if (kind == SHAPE) {
--_inventory.activeShapes[d];
prizeWeight -= _weight(d);
}
if (delivered) {
delete _inventory.items[lid];
} else {
it.state = PENDING;
}
emit ItemDrawn(lid, kind, d, delivered);
}
/// @dev Mint missing prizes, smallest value first, within MAX_OPS Shape units, MAX_RESTOCK_SIZES sizes and the ETH
/// left after this call's keeper reward, and list them at `_prizeBase` plus the restocking fees in one FWA
/// batch. FWA stages the batch while draws are unsettled. Returns Shape units used.
function _fillDeficit(IFWAPool p, uint256 fee, bool paid, uint256 draws) internal returns (uint256 used, uint256 listed) {
uint256 added;
(used, listed, added) = PoolInventory.fill(_inventory, PoolInventory.Fill(
target, markupBps, creatorCredit, _keeper.maxReward, draws, fee, address(SHAPES), address(PACKS),
address(p), _keeper.policy, paid
));
prizeWeight += added;
}
function _payKeeper(uint256 gasStart, uint256 draws, uint256 units, uint256 listed, uint256 processed)
internal returns (uint256 reward)
{
uint256 measured = gasStart - gasleft();
IKeeperPolicy.Work memory w = IKeeperPolicy.Work(measured, tx.gasprice, block.basefee, draws, units, listed, processed);
return KeeperPolicyCalls.pay(_keeper, w, address(this).balance - creatorCredit);
}
function availableKeeperAllowance() public view returns (uint256) { return KeeperPolicyCalls.available(_keeper); }
/*//////////////////////////////////////////////////////////////
VIEWS
//////////////////////////////////////////////////////////////*/
/// @notice Credit plus operating cash above the reserve. Credit is excluded before calculating the surplus.
function withdrawableSurplus() public view returns (uint256) {
uint256 mine = creatorCredit;
uint256 operating = address(this).balance - mine;
uint256 req = requiredReserve();
return mine + (operating > req ? operating - req : 0);
}
/// @notice Working capital for missing assets and their bounded listing work, actual unreconciled draws and
/// one maintenance call. It limits withdrawals, not legitimate maintenance spending. No policy is called.
function requiredReserve() public view returns (uint256) { return _requiredReserve(_keeper.enabled ? _keeper.maxReward : 0); }
function _requiredReserve(uint256 maxReward) internal view returns (uint256) {
return KeeperPolicyCalls.reserve(maxReward, _reserveInput());
}
function _maintenanceInput() internal view returns (KeeperPolicyCalls.Reserve memory r) {
r.enabled = enabled;
r.owed = pool.lastIssuedSequence() - reconciledSequence;
r.baseFee = block.basefee;
}
function _reserveInput() internal view returns (KeeperPolicyCalls.Reserve memory r) {
r = _maintenanceInput();
if (enabled) {
uint256 fee = SHAPES.mintFee();
r.mintFee = fee < mintFeeCap ? mintFeeCap : fee;
r.target = target;
r.have = _inventory.activeShapes;
}
}
/// @notice A tracked listing: kind (1 curated, 2 Shape or pack), size, state, `base` and FWA price.
function items(uint256 listingId) external view returns (uint8 kind, uint8 denom, uint8 state, uint112 base, uint112 price) {
PoolInventory.Item storage it = _inventory.items[listingId];
return (it.kind, it.denom, it.state, it.base, it.price);
}
function getActiveIds() external view returns (uint256[] memory) {
return _inventory.activeIds;
}
function getActiveShapes() external view returns (uint16[16] memory) {
return _inventory.activeShapes;
}
function denominationAmount(uint256 d) external pure returns (uint256) {
return _amount(d);
}
/*//////////////////////////////////////////////////////////////
INTERNALS
//////////////////////////////////////////////////////////////*/
function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {
return this.onERC721Received.selector;
}
/// @dev Opening needs full initial setup. Later edits must not turn ordinary partial depletion into setup again.
function _creatorChanged() internal {
creatorWork = enabled && creatorWork && _missingUnits() != 0;
}
/// @dev Collection is the rate boundary. Pending purchases have no historical rate snapshot.
function _collect() internal returns (uint256 amount) {
IFWAPool p = pool;
if (p.ownerProceeds() == 0) return 0;
uint256 before = address(this).balance;
p.withdrawOwnerProceeds();
amount = address(this).balance - before;
creatorCredit += (amount / BPS) * creatorRevenueBps + (amount % BPS) * creatorRevenueBps / BPS;
emit ProceedsCollected(amount);
}
function _removeActive(uint256 lid) internal { PoolInventory.removeActive(_inventory, lid); }
function listedShapePrizes() external view returns (uint256) { return _inventory.listedPrizes; }
function _listedShapes() internal view returns (uint256) { return _inventory.listedPrizes; }
/// @dev Shape units missing from the target.
function _missingUnits() internal view returns (uint256) { return PoolInventory.missingUnits(_inventory, target); }
/// @notice Identifies the exact policy selection, including disable/re-enable cycles and same-address changes.
function settingsHash() public view returns (bytes32) {
return keccak256(abi.encode(_keeper.policy, _keeper.maxReward, _keeper.generation, _keeper.enabled));
}
function restockFee() public view returns (uint256) { return _restockFee(0, 1, true); }
/// @notice Bounded active-policy estimate in this pool's caller context, not a promise of payable work.
function quoteKeeperReward(IKeeperPolicy.Work calldata work) external view returns (uint256) {
return _keeper.enabled ? KeeperPolicyCalls.reward(_keeper.policy, _keeper.maxReward, work) : 0;
}
function restockFeeFor(uint8 denomination) external view returns (uint256) {
if (denomination >= DENOMS) revert InvalidPlan();
return _restockFee(denomination, _shapesIn(denomination), true);
}
function _restockFee(uint8 d, uint256 units, bool paid) internal view returns (uint256 fee) {
return KeeperPolicyCalls.restock(_keeper.policy, d, units, paid, block.basefee);
}
/// @dev A prize's weight in the fill gate: 1 / its backing. Listed prices keep the markup and fees of their listing
/// block, so weighing by price would let a lower markup or mint fee push a full board under the gate with
/// nothing for upkeep to restock. Backing is fixed per size, so the gate measures the mix, not prices.
function _weight(uint256 d) internal pure returns (uint256) {
return INVERSE_WEIGHT_NUMERATOR / _amount(d);
}
/// @dev A Shape prize's price before restocking fees: what it costs to create plus the markup on its backing.
function _prizeBase(uint256 d, uint256 fee, uint256 markup) internal pure returns (uint256) {
return _cost(d, fee) + _amount(d) * markup / BPS;
}
/// @dev ETH to create one prize of size `d`: its backing plus the Shapes mint fee for each Shape inside.
function _cost(uint256 d, uint256 fee) internal pure returns (uint256) {
return _amount(d) + _shapesIn(d) * fee;
}
function _count(uint256 plan, uint256 d) internal pure returns (uint256) {
return (plan >> (16 * d)) & 0xFFFF;
}
/// @dev Sizes 0-8: the mainnet Shapes ladder, checked against `Shapes.denominationAt` in the constructor.
/// Sizes 9-15: pack values (see AMOUNTS).
function _amount(uint256 d) internal pure returns (uint256) {
return ((AMOUNTS >> (16 * d)) & 0xFFFF) * 0.01 ether;
}
/// @dev Shapes per denomination index inside a pack of size `d`: the ladder taken largest first, which gives the
/// fewest Shapes for every pack value (0.02 = 2x0.01, 0.03 = 3x0.01, 0.2 = 2x0.1, 0.25 = 2x0.1+0.05,
/// 2 = 2x1, 2.5 = 2x1+0.5, 25 = 2x10+5); the count matches SHAPES_IN.
function _makeup(uint256 d) internal pure returns (uint32[] memory m) {
m = new uint32[](SHAPE_DENOMS);
uint256 rest = _amount(d);
for (uint256 i = SHAPE_DENOMS; i != 0;) {
uint256 a = _amount(--i);
m[i] = uint32(rest / a);
rest %= a;
}
}
/// @dev Shapes inside one prize of size `d`, each paying the Shapes mint fee.
function _shapesIn(uint256 d) internal pure returns (uint256) {
return (SHAPES_IN >> (4 * d)) & 0xF;
}
}
lib/solady/src/utils/LibBytes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for byte related operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibBytes.sol)
library LibBytes {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Goated bytes storage struct that totally MOGs, no cap, fr.
/// Uses less gas and bytecode than Solidity's native bytes storage. It's meta af.
/// Packs length with the first 31 bytes if <255 bytes, so it’s mad tight.
struct BytesStorage {
bytes32 _spacer;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the bytes.
uint256 internal constant NOT_FOUND = type(uint256).max;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTE STORAGE OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sets the value of the bytes storage `$` to `s`.
function set(BytesStorage storage $, bytes memory s) internal {
/// @solidity memory-safe-assembly
assembly {
let n := mload(s)
let packed := or(0xff, shl(8, n))
for { let i := 0 } 1 {} {
if iszero(gt(n, 0xfe)) {
i := 0x1f
packed := or(n, shl(8, mload(add(s, i))))
if iszero(gt(n, i)) { break }
}
let o := add(s, 0x20)
mstore(0x00, $.slot)
for { let p := keccak256(0x00, 0x20) } 1 {} {
sstore(add(p, shr(5, i)), mload(add(o, i)))
i := add(i, 0x20)
if iszero(lt(i, n)) { break }
}
break
}
sstore($.slot, packed)
}
}
/// @dev Sets the value of the bytes storage `$` to `s`.
function setCalldata(BytesStorage storage $, bytes calldata s) internal {
/// @solidity memory-safe-assembly
assembly {
let packed := or(0xff, shl(8, s.length))
for { let i := 0 } 1 {} {
if iszero(gt(s.length, 0xfe)) {
i := 0x1f
packed := or(s.length, shl(8, shr(8, calldataload(s.offset))))
if iszero(gt(s.length, i)) { break }
}
mstore(0x00, $.slot)
for { let p := keccak256(0x00, 0x20) } 1 {} {
sstore(add(p, shr(5, i)), calldataload(add(s.offset, i)))
i := add(i, 0x20)
if iszero(lt(i, s.length)) { break }
}
break
}
sstore($.slot, packed)
}
}
/// @dev Sets the value of the bytes storage `$` to the empty bytes.
function clear(BytesStorage storage $) internal {
delete $._spacer;
}
/// @dev Returns whether the value stored is `$` is the empty bytes "".
function isEmpty(BytesStorage storage $) internal view returns (bool) {
return uint256($._spacer) & 0xff == uint256(0);
}
/// @dev Returns the length of the value stored in `$`.
function length(BytesStorage storage $) internal view returns (uint256 result) {
result = uint256($._spacer);
/// @solidity memory-safe-assembly
assembly {
let n := and(0xff, result)
result := or(mul(shr(8, result), eq(0xff, n)), mul(n, iszero(eq(0xff, n))))
}
}
/// @dev Returns the value stored in `$`.
function get(BytesStorage storage $) internal view returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let o := add(result, 0x20)
let packed := sload($.slot)
let n := shr(8, packed)
for { let i := 0 } 1 {} {
if iszero(eq(or(packed, 0xff), packed)) {
mstore(o, packed)
n := and(0xff, packed)
i := 0x1f
if iszero(gt(n, i)) { break }
}
mstore(0x00, $.slot)
for { let p := keccak256(0x00, 0x20) } 1 {} {
mstore(add(o, i), sload(add(p, shr(5, i))))
i := add(i, 0x20)
if iszero(lt(i, n)) { break }
}
break
}
mstore(result, n) // Store the length of the memory.
mstore(add(o, n), 0) // Zeroize the slot after the bytes.
mstore(0x40, add(add(o, n), 0x20)) // Allocate memory.
}
}
/// @dev Returns the uint8 at index `i`. If out-of-bounds, returns 0.
function uint8At(BytesStorage storage $, uint256 i) internal view returns (uint8 result) {
/// @solidity memory-safe-assembly
assembly {
for { let packed := sload($.slot) } 1 {} {
if iszero(eq(or(packed, 0xff), packed)) {
if iszero(gt(i, 0x1e)) {
result := byte(i, packed)
break
}
if iszero(gt(i, and(0xff, packed))) {
mstore(0x00, $.slot)
let j := sub(i, 0x1f)
result := byte(and(j, 0x1f), sload(add(keccak256(0x00, 0x20), shr(5, j))))
}
break
}
if iszero(gt(i, shr(8, packed))) {
mstore(0x00, $.slot)
result := byte(and(i, 0x1f), sload(add(keccak256(0x00, 0x20), shr(5, i))))
}
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTES OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `subject` all occurrences of `needle` replaced with `replacement`.
function replace(bytes memory subject, bytes memory needle, bytes memory replacement)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let needleLen := mload(needle)
let replacementLen := mload(replacement)
let d := sub(result, subject) // Memory difference.
let i := add(subject, 0x20) // Subject bytes pointer.
mstore(0x00, add(i, mload(subject))) // End of subject.
if iszero(gt(needleLen, mload(subject))) {
let subjectSearchEnd := add(sub(mload(0x00), needleLen), 1)
let h := 0 // The hash of `needle`.
if iszero(lt(needleLen, 0x20)) { h := keccak256(add(needle, 0x20), needleLen) }
let s := mload(add(needle, 0x20))
for { let m := shl(3, sub(0x20, and(needleLen, 0x1f))) } 1 {} {
let t := mload(i)
// Whether the first `needleLen % 32` bytes of `subject` and `needle` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(i, needleLen), h)) {
mstore(add(i, d), t)
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
// Copy the `replacement` one word at a time.
for { let j := 0 } 1 {} {
mstore(add(add(i, d), j), mload(add(add(replacement, 0x20), j)))
j := add(j, 0x20)
if iszero(lt(j, replacementLen)) { break }
}
d := sub(add(d, replacementLen), needleLen)
if needleLen {
i := add(i, needleLen)
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
mstore(add(i, d), t)
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
}
}
let end := mload(0x00)
let n := add(sub(d, add(result, 0x20)), end)
// Copy the rest of the bytes one word at a time.
for {} lt(i, end) { i := add(i, 0x20) } { mstore(add(i, d), mload(i)) }
let o := add(i, d)
mstore(o, 0) // Zeroize the slot after the bytes.
mstore(0x40, add(o, 0x20)) // Allocate memory.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(bytes memory subject, bytes memory needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
result := not(0) // Initialize to `NOT_FOUND`.
for { let subjectLen := mload(subject) } 1 {} {
if iszero(mload(needle)) {
result := from
if iszero(gt(from, subjectLen)) { break }
result := subjectLen
break
}
let needleLen := mload(needle)
let subjectStart := add(subject, 0x20)
subject := add(subjectStart, from)
let end := add(sub(add(subjectStart, subjectLen), needleLen), 1)
let m := shl(3, sub(0x20, and(needleLen, 0x1f)))
let s := mload(add(needle, 0x20))
if iszero(and(lt(subject, end), lt(from, subjectLen))) { break }
if iszero(lt(needleLen, 0x20)) {
for { let h := keccak256(add(needle, 0x20), needleLen) } 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
if eq(keccak256(subject, needleLen), h) {
result := sub(subject, subjectStart)
break
}
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
for {} 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
result := sub(subject, subjectStart)
break
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right, starting from `from`. Optimized for byte needles.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOfByte(bytes memory subject, bytes1 needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
result := not(0) // Initialize to `NOT_FOUND`.
if gt(mload(subject), from) {
let start := add(subject, 0x20)
let end := add(start, mload(subject))
let m := div(not(0), 255) // `0x0101 ... `.
let h := mul(byte(0, needle), m) // Replicating needle mask.
m := not(shl(7, m)) // `0x7f7f ... `.
for { let i := add(start, from) } 1 {} {
let c := xor(mload(i), h) // Load 32-byte chunk and xor with mask.
c := not(or(or(add(and(c, m), m), c), m)) // Each needle byte will be `0x80`.
if c {
c := and(not(shr(shl(3, sub(end, i)), not(0))), c) // Truncate bytes past the end.
if c {
let r := shl(7, lt(0x8421084210842108cc6318c6db6d54be, c)) // Save bytecode.
r := or(shl(6, lt(0xffffffffffffffff, shr(r, c))), r)
// forgefmt: disable-next-item
result := add(sub(i, start), shr(3, xor(byte(and(0x1f, shr(byte(24,
mul(0x02040810204081, shr(r, c))), 0x8421084210842108cc6318c6db6d54be)),
0xc0c8c8d0c8e8d0d8c8e8e0e8d0d8e0f0c8d0e8d0e0e0d8f0d0d0e0d8f8f8f8f8), r)))
break
}
}
i := add(i, 0x20)
if iszero(lt(i, end)) { break }
}
}
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right. Optimized for byte needles.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOfByte(bytes memory subject, bytes1 needle)
internal
pure
returns (uint256 result)
{
return indexOfByte(subject, needle, 0);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(bytes memory subject, bytes memory needle) internal pure returns (uint256) {
return indexOf(subject, needle, 0);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(bytes memory subject, bytes memory needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
for {} 1 {} {
result := not(0) // Initialize to `NOT_FOUND`.
let needleLen := mload(needle)
if gt(needleLen, mload(subject)) { break }
let w := result
let fromMax := sub(mload(subject), needleLen)
if iszero(gt(fromMax, from)) { from := fromMax }
let end := add(add(subject, 0x20), w)
subject := add(add(subject, 0x20), from)
if iszero(gt(subject, end)) { break }
// As this function is not too often used,
// we shall simply use keccak256 for smaller bytecode size.
for { let h := keccak256(add(needle, 0x20), needleLen) } 1 {} {
if eq(keccak256(subject, needleLen), h) {
result := sub(subject, add(end, 1))
break
}
subject := add(subject, w) // `sub(subject, 1)`.
if iszero(gt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(bytes memory subject, bytes memory needle)
internal
pure
returns (uint256)
{
return lastIndexOf(subject, needle, type(uint256).max);
}
/// @dev Returns true if `needle` is found in `subject`, false otherwise.
function contains(bytes memory subject, bytes memory needle) internal pure returns (bool) {
return indexOf(subject, needle) != NOT_FOUND;
}
/// @dev Returns whether `subject` starts with `needle`.
function startsWith(bytes memory subject, bytes memory needle)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(needle)
// Just using keccak256 directly is actually cheaper.
let t := eq(keccak256(add(subject, 0x20), n), keccak256(add(needle, 0x20), n))
result := lt(gt(n, mload(subject)), t)
}
}
/// @dev Returns whether `subject` ends with `needle`.
function endsWith(bytes memory subject, bytes memory needle)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(needle)
let notInRange := gt(n, mload(subject))
// `subject + 0x20 + max(subject.length - needle.length, 0)`.
let t := add(add(subject, 0x20), mul(iszero(notInRange), sub(mload(subject), n)))
// Just using keccak256 directly is actually cheaper.
result := gt(eq(keccak256(t, n), keccak256(add(needle, 0x20), n)), notInRange)
}
}
/// @dev Returns `subject` repeated `times`.
function repeat(bytes memory subject, uint256 times)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
let l := mload(subject) // Subject length.
if iszero(or(iszero(times), iszero(l))) {
result := mload(0x40)
subject := add(subject, 0x20)
let o := add(result, 0x20)
for {} 1 {} {
// Copy the `subject` one word at a time.
for { let j := 0 } 1 {} {
mstore(add(o, j), mload(add(subject, j)))
j := add(j, 0x20)
if iszero(lt(j, l)) { break }
}
o := add(o, l)
times := sub(times, 1)
if iszero(times) { break }
}
mstore(o, 0) // Zeroize the slot after the bytes.
mstore(0x40, add(o, 0x20)) // Allocate memory.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets.
function slice(bytes memory subject, uint256 start, uint256 end)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
let l := mload(subject) // Subject length.
if iszero(gt(l, end)) { end := l }
if iszero(gt(l, start)) { start := l }
if lt(start, end) {
result := mload(0x40)
let n := sub(end, start)
let i := add(subject, start)
let w := not(0x1f)
// Copy the `subject` one word at a time, backwards.
for { let j := and(add(n, 0x1f), w) } 1 {} {
mstore(add(result, j), mload(add(i, j)))
j := add(j, w) // `sub(j, 0x20)`.
if iszero(j) { break }
}
let o := add(add(result, 0x20), n)
mstore(o, 0) // Zeroize the slot after the bytes.
mstore(0x40, add(o, 0x20)) // Allocate memory.
mstore(result, n) // Store the length.
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the bytes.
/// `start` is a byte offset.
function slice(bytes memory subject, uint256 start)
internal
pure
returns (bytes memory result)
{
result = slice(subject, start, type(uint256).max);
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets. Faster than Solidity's native slicing.
function sliceCalldata(bytes calldata subject, uint256 start, uint256 end)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
end := xor(end, mul(xor(end, subject.length), lt(subject.length, end)))
start := xor(start, mul(xor(start, subject.length), lt(subject.length, start)))
result.offset := add(subject.offset, start)
result.length := mul(lt(start, end), sub(end, start))
}
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the bytes.
/// `start` is a byte offset. Faster than Solidity's native slicing.
function sliceCalldata(bytes calldata subject, uint256 start)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
start := xor(start, mul(xor(start, subject.length), lt(subject.length, start)))
result.offset := add(subject.offset, start)
result.length := mul(lt(start, subject.length), sub(subject.length, start))
}
}
/// @dev Reduces the size of `subject` to `n`.
/// If `n` is greater than the size of `subject`, this will be a no-op.
function truncate(bytes memory subject, uint256 n)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := subject
mstore(mul(lt(n, mload(result)), result), n)
}
}
/// @dev Returns a copy of `subject`, with the length reduced to `n`.
/// If `n` is greater than the size of `subject`, this will be a no-op.
function truncatedCalldata(bytes calldata subject, uint256 n)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
result.offset := subject.offset
result.length := xor(n, mul(xor(n, subject.length), lt(subject.length, n)))
}
}
/// @dev Returns all the indices of `needle` in `subject`.
/// The indices are byte offsets.
function indicesOf(bytes memory subject, bytes memory needle)
internal
pure
returns (uint256[] memory result)
{
/// @solidity memory-safe-assembly
assembly {
let searchLen := mload(needle)
if iszero(gt(searchLen, mload(subject))) {
result := mload(0x40)
let i := add(subject, 0x20)
let o := add(result, 0x20)
let subjectSearchEnd := add(sub(add(i, mload(subject)), searchLen), 1)
let h := 0 // The hash of `needle`.
if iszero(lt(searchLen, 0x20)) { h := keccak256(add(needle, 0x20), searchLen) }
let s := mload(add(needle, 0x20))
for { let m := shl(3, sub(0x20, and(searchLen, 0x1f))) } 1 {} {
let t := mload(i)
// Whether the first `searchLen % 32` bytes of `subject` and `needle` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(i, searchLen), h)) {
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
mstore(o, sub(i, add(subject, 0x20))) // Append to `result`.
o := add(o, 0x20)
i := add(i, searchLen) // Advance `i` by `searchLen`.
if searchLen {
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
}
mstore(result, shr(5, sub(o, add(result, 0x20)))) // Store the length of `result`.
// Allocate memory for result.
// We allocate one more word, so this array can be recycled for {split}.
mstore(0x40, add(o, 0x20))
}
}
}
/// @dev Returns an arrays of bytess based on the `delimiter` inside of the `subject` bytes.
function split(bytes memory subject, bytes memory delimiter)
internal
pure
returns (bytes[] memory result)
{
uint256[] memory indices = indicesOf(subject, delimiter);
/// @solidity memory-safe-assembly
assembly {
let w := not(0x1f)
let indexPtr := add(indices, 0x20)
let indicesEnd := add(indexPtr, shl(5, add(mload(indices), 1)))
mstore(add(indicesEnd, w), mload(subject))
mstore(indices, add(mload(indices), 1))
for { let prevIndex := 0 } 1 {} {
let index := mload(indexPtr)
mstore(indexPtr, 0x60)
if iszero(eq(index, prevIndex)) {
let element := mload(0x40)
let l := sub(index, prevIndex)
mstore(element, l) // Store the length of the element.
// Copy the `subject` one word at a time, backwards.
for { let o := and(add(l, 0x1f), w) } 1 {} {
mstore(add(element, o), mload(add(add(subject, prevIndex), o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
mstore(add(add(element, 0x20), l), 0) // Zeroize the slot after the bytes.
// Allocate memory for the length and the bytes, rounded up to a multiple of 32.
mstore(0x40, add(element, and(add(l, 0x3f), w)))
mstore(indexPtr, element) // Store the `element` into the array.
}
prevIndex := add(index, mload(delimiter))
indexPtr := add(indexPtr, 0x20)
if iszero(lt(indexPtr, indicesEnd)) { break }
}
result := indices
if iszero(mload(delimiter)) {
result := add(indices, 0x20)
mstore(result, sub(mload(indices), 2))
}
}
}
/// @dev Returns a concatenated bytes of `a` and `b`.
/// Cheaper than `bytes.concat()` and does not de-align the free memory pointer.
function concat(bytes memory a, bytes memory b) internal pure returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let w := not(0x1f)
let aLen := mload(a)
// Copy `a` one word at a time, backwards.
for { let o := and(add(aLen, 0x20), w) } 1 {} {
mstore(add(result, o), mload(add(a, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let bLen := mload(b)
let output := add(result, aLen)
// Copy `b` one word at a time, backwards.
for { let o := and(add(bLen, 0x20), w) } 1 {} {
mstore(add(output, o), mload(add(b, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let totalLen := add(aLen, bLen)
let last := add(add(result, 0x20), totalLen)
mstore(last, 0) // Zeroize the slot after the bytes.
mstore(result, totalLen) // Store the length.
mstore(0x40, add(last, 0x20)) // Allocate memory.
}
}
/// @dev Returns whether `a` equals `b`.
function eq(bytes memory a, bytes memory b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
}
}
/// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small bytes.
function eqs(bytes memory a, bytes32 b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
// These should be evaluated on compile time, as far as possible.
let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
let x := not(or(m, or(b, add(m, and(b, m)))))
let r := shl(7, iszero(iszero(shr(128, x))))
r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
}
}
/// @dev Returns 0 if `a == b`, -1 if `a < b`, +1 if `a > b`.
/// If `a` == b[:a.length]`, and `a.length < b.length`, returns -1.
function cmp(bytes memory a, bytes memory b) internal pure returns (int256 result) {
/// @solidity memory-safe-assembly
assembly {
let aLen := mload(a)
let bLen := mload(b)
let n := and(xor(aLen, mul(xor(aLen, bLen), lt(bLen, aLen))), not(0x1f))
if n {
for { let i := 0x20 } 1 {} {
let x := mload(add(a, i))
let y := mload(add(b, i))
if iszero(or(xor(x, y), eq(i, n))) {
i := add(i, 0x20)
continue
}
result := sub(gt(x, y), lt(x, y))
break
}
}
// forgefmt: disable-next-item
if iszero(result) {
let l := 0x201f1e1d1c1b1a191817161514131211100f0e0d0c0b0a090807060504030201
let x := and(mload(add(add(a, 0x20), n)), shl(shl(3, byte(sub(aLen, n), l)), not(0)))
let y := and(mload(add(add(b, 0x20), n)), shl(shl(3, byte(sub(bLen, n), l)), not(0)))
result := sub(gt(x, y), lt(x, y))
if iszero(result) { result := sub(gt(aLen, bLen), lt(aLen, bLen)) }
}
}
}
/// @dev Directly returns `a` without copying.
function directReturn(bytes memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
// Assumes that the bytes does not start from the scratch space.
let retStart := sub(a, 0x20)
let retUnpaddedSize := add(mload(a), 0x40)
// Right pad with zeroes. Just in case the bytes is produced
// by a method that doesn't zero right pad.
mstore(add(retStart, retUnpaddedSize), 0)
mstore(retStart, 0x20) // Store the return offset.
// End the transaction, returning the bytes.
return(retStart, and(not(0x1f), add(0x1f, retUnpaddedSize)))
}
}
/// @dev Directly returns `a` with minimal copying.
function directReturn(bytes[] memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
let n := mload(a) // `a.length`.
let o := add(a, 0x20) // Start of elements in `a`.
let u := a // Highest memory slot.
let w := not(0x1f)
for { let i := 0 } iszero(eq(i, n)) { i := add(i, 1) } {
let c := add(o, shl(5, i)) // Location of pointer to `a[i]`.
let s := mload(c) // `a[i]`.
let l := mload(s) // `a[i].length`.
let r := and(l, 0x1f) // `a[i].length % 32`.
let z := add(0x20, and(l, w)) // Offset of last word in `a[i]` from `s`.
// If `s` comes before `o`, or `s` is not zero right padded.
if iszero(lt(lt(s, o), or(iszero(r), iszero(shl(shl(3, r), mload(add(s, z))))))) {
let m := mload(0x40)
mstore(m, l) // Copy `a[i].length`.
for {} 1 {} {
mstore(add(m, z), mload(add(s, z))) // Copy `a[i]`, backwards.
z := add(z, w) // `sub(z, 0x20)`.
if iszero(z) { break }
}
let e := add(add(m, 0x20), l)
mstore(e, 0) // Zeroize the slot after the copied bytes.
mstore(0x40, add(e, 0x20)) // Allocate memory.
s := m
}
mstore(c, sub(s, o)) // Convert to calldata offset.
let t := add(l, add(s, 0x20))
if iszero(lt(t, u)) { u := t }
}
let retStart := add(a, w) // Assumes `a` doesn't start from scratch space.
mstore(retStart, 0x20) // Store the return offset.
return(retStart, add(0x40, sub(u, retStart))) // End the transaction.
}
}
/// @dev Returns the word at `offset`, without any bounds checks.
function load(bytes memory a, uint256 offset) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(a, 0x20), offset))
}
}
/// @dev Returns the word at `offset`, without any bounds checks.
function loadCalldata(bytes calldata a, uint256 offset)
internal
pure
returns (bytes32 result)
{
/// @solidity memory-safe-assembly
assembly {
result := calldataload(add(a.offset, offset))
}
}
/// @dev Returns a slice representing a static struct in the calldata. Performs bounds checks.
function staticStructInCalldata(bytes calldata a, uint256 offset)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
let l := sub(a.length, 0x20)
result.offset := add(a.offset, offset)
result.length := sub(a.length, offset)
if or(shr(64, or(l, a.offset)), gt(offset, l)) { revert(l, 0x00) }
}
}
/// @dev Returns a slice representing a dynamic struct in the calldata. Performs bounds checks.
function dynamicStructInCalldata(bytes calldata a, uint256 offset)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
let l := sub(a.length, 0x20)
let s := calldataload(add(a.offset, offset)) // Relative offset of `result` from `a.offset`.
result.offset := add(a.offset, s)
result.length := sub(a.length, s)
if or(shr(64, or(s, or(l, a.offset))), gt(offset, l)) { revert(l, 0x00) }
}
}
/// @dev Returns bytes in calldata. Performs bounds checks.
function bytesInCalldata(bytes calldata a, uint256 offset)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
let l := sub(a.length, 0x20)
let s := calldataload(add(a.offset, offset)) // Relative offset of `result` from `a.offset`.
result.offset := add(add(a.offset, s), 0x20)
result.length := calldataload(add(a.offset, s))
// forgefmt: disable-next-item
if or(shr(64, or(result.length, or(s, or(l, a.offset)))),
or(gt(add(s, result.length), l), gt(offset, l))) { revert(l, 0x00) }
}
}
/// @dev Checks if `x` is in `a`. Assumes `a` has been checked.
function checkInCalldata(bytes calldata x, bytes calldata a) internal pure {
/// @solidity memory-safe-assembly
assembly {
if or(
or(lt(x.offset, a.offset), gt(add(x.offset, x.length), add(a.length, a.offset))),
shr(64, or(x.length, x.offset))
) { revert(0x00, 0x00) }
}
}
/// @dev Checks if `x` is in `a`. Assumes `a` has been checked.
function checkInCalldata(bytes[] calldata x, bytes calldata a) internal pure {
/// @solidity memory-safe-assembly
assembly {
let e := sub(add(a.length, a.offset), 0x20)
if or(lt(x.offset, a.offset), shr(64, x.offset)) { revert(0x00, 0x00) }
for { let i := 0 } iszero(eq(x.length, i)) { i := add(i, 1) } {
let o := calldataload(add(x.offset, shl(5, i)))
let t := add(o, x.offset)
let l := calldataload(t)
if or(shr(64, or(l, o)), gt(add(t, l), e)) { revert(0x00, 0x00) }
}
}
}
/// @dev Returns empty calldata bytes. For silencing the compiler.
function emptyCalldata() internal pure returns (bytes calldata result) {
/// @solidity memory-safe-assembly
assembly {
result.length := 0
}
}
/// @dev Returns the most significant 20 bytes as an address.
function msbToAddress(bytes32 x) internal pure returns (address) {
return address(bytes20(x));
}
/// @dev Returns the least significant 20 bytes as an address.
function lsbToAddress(bytes32 x) internal pure returns (address) {
return address(uint160(uint256(x)));
}
}
lib/solady/src/utils/LibString.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {LibBytes} from "./LibBytes.sol";
/// @notice Library for converting numbers into strings and other string operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibString.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol)
///
/// @dev Note:
/// For performance and bytecode compactness, most of the string operations are restricted to
/// byte strings (7-bit ASCII), except where otherwise specified.
/// Usage of byte string operations on charsets with runes spanning two or more bytes
/// can lead to undefined behavior.
library LibString {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Goated string storage struct that totally MOGs, no cap, fr.
/// Uses less gas and bytecode than Solidity's native string storage. It's meta af.
/// Packs length with the first 31 bytes if <255 bytes, so it’s mad tight.
struct StringStorage {
bytes32 _spacer;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The length of the output is too small to contain all the hex digits.
error HexLengthInsufficient();
/// @dev The length of the string is more than 32 bytes.
error TooBigForSmallString();
/// @dev The input string must be a 7-bit ASCII.
error StringNot7BitASCII();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the string.
uint256 internal constant NOT_FOUND = type(uint256).max;
/// @dev Lookup for '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant ALPHANUMERIC_7_BIT_ASCII = 0x7fffffe07fffffe03ff000000000000;
/// @dev Lookup for 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant LETTERS_7_BIT_ASCII = 0x7fffffe07fffffe0000000000000000;
/// @dev Lookup for 'abcdefghijklmnopqrstuvwxyz'.
uint128 internal constant LOWERCASE_7_BIT_ASCII = 0x7fffffe000000000000000000000000;
/// @dev Lookup for 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant UPPERCASE_7_BIT_ASCII = 0x7fffffe0000000000000000;
/// @dev Lookup for '0123456789'.
uint128 internal constant DIGITS_7_BIT_ASCII = 0x3ff000000000000;
/// @dev Lookup for '0123456789abcdefABCDEF'.
uint128 internal constant HEXDIGITS_7_BIT_ASCII = 0x7e0000007e03ff000000000000;
/// @dev Lookup for '01234567'.
uint128 internal constant OCTDIGITS_7_BIT_ASCII = 0xff000000000000;
/// @dev Lookup for '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'.
uint128 internal constant PRINTABLE_7_BIT_ASCII = 0x7fffffffffffffffffffffff00003e00;
/// @dev Lookup for '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'.
uint128 internal constant PUNCTUATION_7_BIT_ASCII = 0x78000001f8000001fc00fffe00000000;
/// @dev Lookup for ' \t\n\r\x0b\x0c'.
uint128 internal constant WHITESPACE_7_BIT_ASCII = 0x100003e00;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRING STORAGE OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sets the value of the string storage `$` to `s`.
function set(StringStorage storage $, string memory s) internal {
LibBytes.set(bytesStorage($), bytes(s));
}
/// @dev Sets the value of the string storage `$` to `s`.
function setCalldata(StringStorage storage $, string calldata s) internal {
LibBytes.setCalldata(bytesStorage($), bytes(s));
}
/// @dev Sets the value of the string storage `$` to the empty string.
function clear(StringStorage storage $) internal {
delete $._spacer;
}
/// @dev Returns whether the value stored is `$` is the empty string "".
function isEmpty(StringStorage storage $) internal view returns (bool) {
return uint256($._spacer) & 0xff == uint256(0);
}
/// @dev Returns the length of the value stored in `$`.
function length(StringStorage storage $) internal view returns (uint256) {
return LibBytes.length(bytesStorage($));
}
/// @dev Returns the value stored in `$`.
function get(StringStorage storage $) internal view returns (string memory) {
return string(LibBytes.get(bytesStorage($)));
}
/// @dev Returns the uint8 at index `i`. If out-of-bounds, returns 0.
function uint8At(StringStorage storage $, uint256 i) internal view returns (uint8) {
return LibBytes.uint8At(bytesStorage($), i);
}
/// @dev Helper to cast `$` to a `BytesStorage`.
function bytesStorage(StringStorage storage $)
internal
pure
returns (LibBytes.BytesStorage storage casted)
{
/// @solidity memory-safe-assembly
assembly {
casted.slot := $.slot
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the base 10 decimal representation of `value`.
function toString(uint256 value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits.
result := add(mload(0x40), 0x80)
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end of the memory to calculate the length later.
let w := not(0) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
result := add(result, w) // `sub(result, 1)`.
// Store the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(result, add(48, mod(temp, 10)))
temp := div(temp, 10) // Keep dividing `temp` until zero.
if iszero(temp) { break }
}
let n := sub(end, result)
result := sub(result, 0x20) // Move the pointer 32 bytes back to make room for the length.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the base 10 decimal representation of `value`.
function toString(int256 value) internal pure returns (string memory result) {
if (value >= 0) return toString(uint256(value));
unchecked {
result = toString(~uint256(value) + 1);
}
/// @solidity memory-safe-assembly
assembly {
// We still have some spare memory space on the left,
// as we have allocated 3 words (96 bytes) for up to 78 digits.
let n := mload(result) // Load the string length.
mstore(result, 0x2d) // Store the '-' character.
result := sub(result, 1) // Move back the string pointer by a byte.
mstore(result, add(n, 1)) // Update the string length.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HEXADECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `byteCount` bytes.
/// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
/// giving a total length of `byteCount * 2 + 2` bytes.
/// Reverts if `byteCount` is too small for the output to contain all the digits.
function toHexString(uint256 value, uint256 byteCount)
internal
pure
returns (string memory result)
{
result = toHexStringNoPrefix(value, byteCount);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `byteCount` bytes.
/// The output is not prefixed with "0x" and is encoded using 2 hexadecimal digits per byte,
/// giving a total length of `byteCount * 2` bytes.
/// Reverts if `byteCount` is too small for the output to contain all the digits.
function toHexStringNoPrefix(uint256 value, uint256 byteCount)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, `byteCount * 2` bytes
// for the digits, 0x02 bytes for the prefix, and 0x20 bytes for the length.
// We add 0x20 to the total and round down to a multiple of 0x20.
// (0x20 + 0x20 + 0x02 + 0x20) = 0x62.
result := add(mload(0x40), and(add(shl(1, byteCount), 0x42), not(0x1f)))
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end to calculate the length later.
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let start := sub(result, add(byteCount, byteCount))
let w := not(1) // Tsk.
let temp := value
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for {} 1 {} {
result := add(result, w) // `sub(result, 2)`.
mstore8(add(result, 1), mload(and(temp, 15)))
mstore8(result, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(xor(result, start)) { break }
}
if temp {
mstore(0x00, 0x2194895a) // `HexLengthInsufficient()`.
revert(0x1c, 0x04)
}
let n := sub(end, result)
result := sub(result, 0x20)
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2 + 2` bytes.
function toHexString(uint256 value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x".
/// The output excludes leading "0" from the `toHexString` output.
/// `0x00: "0x0", 0x01: "0x1", 0x12: "0x12", 0x123: "0x123"`.
function toMinimalHexString(uint256 value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(result, 0x20))), 0x30) // Whether leading zero is present.
let n := add(mload(result), 2) // Compute the length.
mstore(add(result, o), 0x3078) // Store the "0x" prefix, accounting for leading zero.
result := sub(add(result, o), 2) // Move the pointer, accounting for leading zero.
mstore(result, sub(n, o)) // Store the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output excludes leading "0" from the `toHexStringNoPrefix` output.
/// `0x00: "0", 0x01: "1", 0x12: "12", 0x123: "123"`.
function toMinimalHexStringNoPrefix(uint256 value)
internal
pure
returns (string memory result)
{
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(result, 0x20))), 0x30) // Whether leading zero is present.
let n := mload(result) // Get the length.
result := add(result, o) // Move the pointer, accounting for leading zero.
mstore(result, sub(n, o)) // Store the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2` bytes.
function toHexStringNoPrefix(uint256 value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x40 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x40) is 0xa0.
result := add(mload(0x40), 0x80)
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end to calculate the length later.
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
let w := not(1) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
result := add(result, w) // `sub(result, 2)`.
mstore8(add(result, 1), mload(and(temp, 15)))
mstore8(result, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(temp) { break }
}
let n := sub(end, result)
result := sub(result, 0x20)
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x", encoded using 2 hexadecimal digits per byte,
/// and the alphabets are capitalized conditionally according to
/// https://eips.ethereum.org/EIPS/eip-55
function toHexStringChecksummed(address value) internal pure returns (string memory result) {
result = toHexString(value);
/// @solidity memory-safe-assembly
assembly {
let mask := shl(6, div(not(0), 255)) // `0b010000000100000000 ...`
let o := add(result, 0x22)
let hashed := and(keccak256(o, 40), mul(34, mask)) // `0b10001000 ... `
let t := shl(240, 136) // `0b10001000 << 240`
for { let i := 0 } 1 {} {
mstore(add(i, i), mul(t, byte(i, hashed)))
i := add(i, 1)
if eq(i, 20) { break }
}
mstore(o, xor(mload(o), shr(1, and(mload(0x00), and(mload(o), mask)))))
o := add(o, 0x20)
mstore(o, xor(mload(o), shr(1, and(mload(0x20), and(mload(o), mask)))))
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
function toHexString(address value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(address value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
// Allocate memory.
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x28 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x28) is 0x80.
mstore(0x40, add(result, 0x80))
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
result := add(result, 2)
mstore(result, 40) // Store the length.
let o := add(result, 0x20)
mstore(add(o, 40), 0) // Zeroize the slot after the string.
value := shl(96, value)
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let i := 0 } 1 {} {
let p := add(o, add(i, i))
let temp := byte(i, value)
mstore8(add(p, 1), mload(and(temp, 15)))
mstore8(p, mload(shr(4, temp)))
i := add(i, 1)
if eq(i, 20) { break }
}
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexString(bytes memory raw) internal pure returns (string memory result) {
result = toHexStringNoPrefix(raw);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(bytes memory raw) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(raw)
result := add(mload(0x40), 2) // Skip 2 bytes for the optional prefix.
mstore(result, add(n, n)) // Store the length of the output.
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
let o := add(result, 0x20)
let end := add(raw, n)
for {} iszero(eq(raw, end)) {} {
raw := add(raw, 1)
mstore8(add(o, 1), mload(and(mload(raw), 15)))
mstore8(o, mload(and(shr(4, mload(raw)), 15)))
o := add(o, 2)
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RUNE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the number of UTF characters in the string.
function runeCount(string memory s) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
if mload(s) {
mstore(0x00, div(not(0), 255))
mstore(0x20, 0x0202020202020202020202020202020202020202020202020303030304040506)
let o := add(s, 0x20)
let end := add(o, mload(s))
for { result := 1 } 1 { result := add(result, 1) } {
o := add(o, byte(0, mload(shr(250, mload(o)))))
if iszero(lt(o, end)) { break }
}
}
}
}
/// @dev Returns if this string is a 7-bit ASCII string.
/// (i.e. all characters codes are in [0..127])
function is7BitASCII(string memory s) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
let mask := shl(7, div(not(0), 255))
let n := mload(s)
if n {
let o := add(s, 0x20)
let end := add(o, n)
let last := mload(end)
mstore(end, 0)
for {} 1 {} {
if and(mask, mload(o)) {
result := 0
break
}
o := add(o, 0x20)
if iszero(lt(o, end)) { break }
}
mstore(end, last)
}
}
}
/// @dev Returns if this string is a 7-bit ASCII string,
/// AND all characters are in the `allowed` lookup.
/// Note: If `s` is empty, returns true regardless of `allowed`.
function is7BitASCII(string memory s, uint128 allowed) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
if mload(s) {
let allowed_ := shr(128, shl(128, allowed))
let o := add(s, 0x20)
for { let end := add(o, mload(s)) } 1 {} {
result := and(result, shr(byte(0, mload(o)), allowed_))
o := add(o, 1)
if iszero(and(result, lt(o, end))) { break }
}
}
}
}
/// @dev Converts the bytes in the 7-bit ASCII string `s` to
/// an allowed lookup for use in `is7BitASCII(s, allowed)`.
/// To save runtime gas, you can cache the result in an immutable variable.
function to7BitASCIIAllowedLookup(string memory s) internal pure returns (uint128 result) {
/// @solidity memory-safe-assembly
assembly {
if mload(s) {
let o := add(s, 0x20)
for { let end := add(o, mload(s)) } 1 {} {
result := or(result, shl(byte(0, mload(o)), 1))
o := add(o, 1)
if iszero(lt(o, end)) { break }
}
if shr(128, result) {
mstore(0x00, 0xc9807e0d) // `StringNot7BitASCII()`.
revert(0x1c, 0x04)
}
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// For performance and bytecode compactness, byte string operations are restricted
// to 7-bit ASCII strings. All offsets are byte offsets, not UTF character offsets.
// Usage of byte string operations on charsets with runes spanning two or more bytes
// can lead to undefined behavior.
/// @dev Returns `subject` all occurrences of `needle` replaced with `replacement`.
function replace(string memory subject, string memory needle, string memory replacement)
internal
pure
returns (string memory)
{
return string(LibBytes.replace(bytes(subject), bytes(needle), bytes(replacement)));
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(string memory subject, string memory needle, uint256 from)
internal
pure
returns (uint256)
{
return LibBytes.indexOf(bytes(subject), bytes(needle), from);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(string memory subject, string memory needle) internal pure returns (uint256) {
return LibBytes.indexOf(bytes(subject), bytes(needle), 0);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(string memory subject, string memory needle, uint256 from)
internal
pure
returns (uint256)
{
return LibBytes.lastIndexOf(bytes(subject), bytes(needle), from);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(string memory subject, string memory needle)
internal
pure
returns (uint256)
{
return LibBytes.lastIndexOf(bytes(subject), bytes(needle), type(uint256).max);
}
/// @dev Returns true if `needle` is found in `subject`, false otherwise.
function contains(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.contains(bytes(subject), bytes(needle));
}
/// @dev Returns whether `subject` starts with `needle`.
function startsWith(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.startsWith(bytes(subject), bytes(needle));
}
/// @dev Returns whether `subject` ends with `needle`.
function endsWith(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.endsWith(bytes(subject), bytes(needle));
}
/// @dev Returns `subject` repeated `times`.
function repeat(string memory subject, uint256 times) internal pure returns (string memory) {
return string(LibBytes.repeat(bytes(subject), times));
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets.
function slice(string memory subject, uint256 start, uint256 end)
internal
pure
returns (string memory)
{
return string(LibBytes.slice(bytes(subject), start, end));
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the string.
/// `start` is a byte offset.
function slice(string memory subject, uint256 start) internal pure returns (string memory) {
return string(LibBytes.slice(bytes(subject), start, type(uint256).max));
}
/// @dev Returns all the indices of `needle` in `subject`.
/// The indices are byte offsets.
function indicesOf(string memory subject, string memory needle)
internal
pure
returns (uint256[] memory)
{
return LibBytes.indicesOf(bytes(subject), bytes(needle));
}
/// @dev Returns an arrays of strings based on the `delimiter` inside of the `subject` string.
function split(string memory subject, string memory delimiter)
internal
pure
returns (string[] memory result)
{
bytes[] memory a = LibBytes.split(bytes(subject), bytes(delimiter));
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Returns a concatenated string of `a` and `b`.
/// Cheaper than `string.concat()` and does not de-align the free memory pointer.
function concat(string memory a, string memory b) internal pure returns (string memory) {
return string(LibBytes.concat(bytes(a), bytes(b)));
}
/// @dev Returns a copy of the string in either lowercase or UPPERCASE.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function toCase(string memory subject, bool toUpper)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(subject)
if n {
result := mload(0x40)
let o := add(result, 0x20)
let d := sub(subject, result)
let flags := shl(add(70, shl(5, toUpper)), 0x3ffffff)
for { let end := add(o, n) } 1 {} {
let b := byte(0, mload(add(d, o)))
mstore8(o, xor(and(shr(b, flags), 0x20), b))
o := add(o, 1)
if eq(o, end) { break }
}
mstore(result, n) // Store the length.
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
}
/// @dev Returns a string from a small bytes32 string.
/// `s` must be null-terminated, or behavior will be undefined.
function fromSmallString(bytes32 s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let n := 0
for {} byte(n, s) { n := add(n, 1) } {} // Scan for '\0'.
mstore(result, n) // Store the length.
let o := add(result, 0x20)
mstore(o, s) // Store the bytes of the string.
mstore(add(o, n), 0) // Zeroize the slot after the string.
mstore(0x40, add(result, 0x40)) // Allocate memory.
}
}
/// @dev Returns the small string, with all bytes after the first null byte zeroized.
function normalizeSmallString(bytes32 s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
for {} byte(result, s) { result := add(result, 1) } {} // Scan for '\0'.
mstore(0x00, s)
mstore(result, 0x00)
result := mload(0x00)
}
}
/// @dev Returns the string as a normalized null-terminated small string.
function toSmallString(string memory s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(s)
if iszero(lt(result, 33)) {
mstore(0x00, 0xec92f9a3) // `TooBigForSmallString()`.
revert(0x1c, 0x04)
}
result := shl(shl(3, sub(32, result)), mload(add(s, result)))
}
}
/// @dev Returns a lowercased copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function lower(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, false);
}
/// @dev Returns an UPPERCASED copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function upper(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, true);
}
/// @dev Escapes the string to be used within HTML tags.
function escapeHTML(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let end := add(s, mload(s))
let o := add(result, 0x20)
// Store the bytes of the packed offsets and strides into the scratch space.
// `packed = (stride << 5) | offset`. Max offset is 20. Max stride is 6.
mstore(0x1f, 0x900094)
mstore(0x08, 0xc0000000a6ab)
// Store ""&'<>" into the scratch space.
mstore(0x00, shl(64, 0x2671756f743b26616d703b262333393b266c743b2667743b))
for {} iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
// Not in `["\"","'","&","<",">"]`.
if iszero(and(shl(c, 1), 0x500000c400000000)) {
mstore8(o, c)
o := add(o, 1)
continue
}
let t := shr(248, mload(c))
mstore(o, mload(and(t, 0x1f)))
o := add(o, shr(5, t))
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
/// If `addDoubleQuotes` is true, the result will be enclosed in double-quotes.
function escapeJSON(string memory s, bool addDoubleQuotes)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let o := add(result, 0x20)
if addDoubleQuotes {
mstore8(o, 34)
o := add(1, o)
}
// Store "\\u0000" in scratch space.
// Store "0123456789abcdef" in scratch space.
// Also, store `{0x08:"b", 0x09:"t", 0x0a:"n", 0x0c:"f", 0x0d:"r"}`.
// into the scratch space.
mstore(0x15, 0x5c75303030303031323334353637383961626364656662746e006672)
// Bitmask for detecting `["\"","\\"]`.
let e := or(shl(0x22, 1), shl(0x5c, 1))
for { let end := add(s, mload(s)) } iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
if iszero(lt(c, 0x20)) {
if iszero(and(shl(c, 1), e)) {
// Not in `["\"","\\"]`.
mstore8(o, c)
o := add(o, 1)
continue
}
mstore8(o, 0x5c) // "\\".
mstore8(add(o, 1), c)
o := add(o, 2)
continue
}
if iszero(and(shl(c, 1), 0x3700)) {
// Not in `["\b","\t","\n","\f","\d"]`.
mstore8(0x1d, mload(shr(4, c))) // Hex value.
mstore8(0x1e, mload(and(c, 15))) // Hex value.
mstore(o, mload(0x19)) // "\\u00XX".
o := add(o, 6)
continue
}
mstore8(o, 0x5c) // "\\".
mstore8(add(o, 1), mload(add(c, 8)))
o := add(o, 2)
}
if addDoubleQuotes {
mstore8(o, 34)
o := add(1, o)
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
function escapeJSON(string memory s) internal pure returns (string memory result) {
result = escapeJSON(s, false);
}
/// @dev Encodes `s` so that it can be safely used in a URI,
/// just like `encodeURIComponent` in JavaScript.
/// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
/// See: https://datatracker.ietf.org/doc/html/rfc2396
/// See: https://datatracker.ietf.org/doc/html/rfc3986
function encodeURIComponent(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
// Store "0123456789ABCDEF" in scratch space.
// Uppercased to be consistent with JavaScript's implementation.
mstore(0x0f, 0x30313233343536373839414243444546)
let o := add(result, 0x20)
for { let end := add(s, mload(s)) } iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
// If not in `[0-9A-Z-a-z-_.!~*'()]`.
if iszero(and(1, shr(c, 0x47fffffe87fffffe03ff678200000000))) {
mstore8(o, 0x25) // '%'.
mstore8(add(o, 1), mload(and(shr(4, c), 15)))
mstore8(add(o, 2), mload(and(c, 15)))
o := add(o, 3)
continue
}
mstore8(o, c)
o := add(o, 1)
}
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Returns whether `a` equals `b`.
function eq(string memory a, string memory b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
}
}
/// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small string.
function eqs(string memory a, bytes32 b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
// These should be evaluated on compile time, as far as possible.
let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
let x := not(or(m, or(b, add(m, and(b, m)))))
let r := shl(7, iszero(iszero(shr(128, x))))
r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
}
}
/// @dev Returns 0 if `a == b`, -1 if `a < b`, +1 if `a > b`.
/// If `a` == b[:a.length]`, and `a.length < b.length`, returns -1.
function cmp(string memory a, string memory b) internal pure returns (int256) {
return LibBytes.cmp(bytes(a), bytes(b));
}
/// @dev Packs a single string with its length into a single word.
/// Returns `bytes32(0)` if the length is zero or greater than 31.
function packOne(string memory a) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
// We don't need to zero right pad the string,
// since this is our own custom non-standard packing scheme.
result :=
mul(
// Load the length and the bytes.
mload(add(a, 0x1f)),
// `length != 0 && length < 32`. Abuses underflow.
// Assumes that the length is valid and within the block gas limit.
lt(sub(mload(a), 1), 0x1f)
)
}
}
/// @dev Unpacks a string packed using {packOne}.
/// Returns the empty string if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packOne}, the output behavior is undefined.
function unpackOne(bytes32 packed) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40) // Grab the free memory pointer.
mstore(0x40, add(result, 0x40)) // Allocate 2 words (1 for the length, 1 for the bytes).
mstore(result, 0) // Zeroize the length slot.
mstore(add(result, 0x1f), packed) // Store the length and bytes.
mstore(add(add(result, 0x20), mload(result)), 0) // Right pad with zeroes.
}
}
/// @dev Packs two strings with their lengths into a single word.
/// Returns `bytes32(0)` if combined length is zero or greater than 30.
function packTwo(string memory a, string memory b) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let aLen := mload(a)
// We don't need to zero right pad the strings,
// since this is our own custom non-standard packing scheme.
result :=
mul(
or( // Load the length and the bytes of `a` and `b`.
shl(shl(3, sub(0x1f, aLen)), mload(add(a, aLen))), mload(sub(add(b, 0x1e), aLen))),
// `totalLen != 0 && totalLen < 31`. Abuses underflow.
// Assumes that the lengths are valid and within the block gas limit.
lt(sub(add(aLen, mload(b)), 1), 0x1e)
)
}
}
/// @dev Unpacks strings packed using {packTwo}.
/// Returns the empty strings if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packTwo}, the output behavior is undefined.
function unpackTwo(bytes32 packed)
internal
pure
returns (string memory resultA, string memory resultB)
{
/// @solidity memory-safe-assembly
assembly {
resultA := mload(0x40) // Grab the free memory pointer.
resultB := add(resultA, 0x40)
// Allocate 2 words for each string (1 for the length, 1 for the byte). Total 4 words.
mstore(0x40, add(resultB, 0x40))
// Zeroize the length slots.
mstore(resultA, 0)
mstore(resultB, 0)
// Store the lengths and bytes.
mstore(add(resultA, 0x1f), packed)
mstore(add(resultB, 0x1f), mload(add(add(resultA, 0x20), mload(resultA))))
// Right pad with zeroes.
mstore(add(add(resultA, 0x20), mload(resultA)), 0)
mstore(add(add(resultB, 0x20), mload(resultB)), 0)
}
}
/// @dev Directly returns `a` without copying.
function directReturn(string memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
// Assumes that the string does not start from the scratch space.
let retStart := sub(a, 0x20)
let retUnpaddedSize := add(mload(a), 0x40)
// Right pad with zeroes. Just in case the string is produced
// by a method that doesn't zero right pad.
mstore(add(retStart, retUnpaddedSize), 0)
mstore(retStart, 0x20) // Store the return offset.
// End the transaction, returning the string.
return(retStart, and(not(0x1f), add(0x1f, retUnpaddedSize)))
}
}
}
lib/solady/src/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Reentrancy guard mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unauthorized reentrant call.
error Reentrancy();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
/// 9 bytes is large enough to avoid collisions with lower slots,
/// but not too large to result in excessive bytecode bloat.
uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* REENTRANCY GUARD */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Guards a function from reentrancy.
modifier nonReentrant() virtual {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
sstore(_REENTRANCY_GUARD_SLOT, address())
}
_;
/// @solidity memory-safe-assembly
assembly {
sstore(_REENTRANCY_GUARD_SLOT, codesize())
}
}
/// @dev Guards a view function from read-only reentrancy.
modifier nonReadReentrant() virtual {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
}
_;
}
}
lib/solady/src/utils/SafeTransferLib.sol
// 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 `address(to).balance >= amount + balanceBefore`, skip vault workflow.
if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
// Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
if lt(selfBalanceBefore, selfbalance()) { invalid() }
}
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(codesize(), codesize()) } // For gas estimation.
}
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function trySafeTransferFrom(address token, address from, address to, uint256 amount)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends all of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have their entire balance approved for the current contract to manage.
function safeTransferAllFrom(address token, address from, address to)
internal
returns (uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransfer(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sends all of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransferAll(address token, address to) internal returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
mstore(0x20, address()) // Store the address of the current contract.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// Reverts upon failure.
function safeApprove(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
/// then retries the approval again (some tokens, e.g. USDT, requires this).
/// Reverts upon failure.
function safeApproveWithRetry(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, amount) // Store back the original `amount`.
// Retry the approval, reverting upon failure.
success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
// Check the `extcodesize` again just in case the token selfdestructs lol.
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
/// Returns zero if the `token` does not exist.
function balanceOf(address token, address account) internal view returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
amount :=
mul( // The arguments of `mul` are evaluated from right to left.
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
)
}
}
/// @dev Performs a `token.balanceOf(account)` check.
/// `implemented` denotes whether the `token` does not implement `balanceOf`.
/// `amount` is zero if the `token` does not implement `balanceOf`.
function checkBalanceOf(address token, address account)
internal
view
returns (bool implemented, uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
implemented :=
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
amount := mul(mload(0x20), implemented)
}
}
/// @dev Returns the total supply of the `token`.
/// Reverts if the token does not exist or does not implement `totalSupply()`.
function totalSupply(address token) internal view returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x18160ddd) // `totalSupply()`.
if iszero(
and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
) {
mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
revert(0x1c, 0x04)
}
result := mload(0x00)
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// If the initial attempt fails, try to use Permit2 to transfer the token.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
if (!trySafeTransferFrom(token, from, to, amount)) {
permit2TransferFrom(token, from, to, amount);
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
/// Reverts upon failure.
function permit2TransferFrom(address token, address from, address to, uint256 amount)
internal
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(add(m, 0x74), shr(96, shl(96, token)))
mstore(add(m, 0x54), amount)
mstore(add(m, 0x34), to)
mstore(add(m, 0x20), shl(96, from))
// `transferFrom(address,address,uint160,address)`.
mstore(m, 0x36c78516000000000000000000000000)
let p := PERMIT2
let exists := eq(chainid(), 1)
if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
if iszero(
and(
call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
)
) {
mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
}
}
}
/// @dev Permit a user to spend a given amount of
/// another user's tokens via native EIP-2612 permit if possible, falling
/// back to Permit2 if native permit fails or is not implemented on the token.
function permit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
for {} shl(96, xor(token, WETH9)) {} {
mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
// Gas stipend to limit gas burn for tokens that don't refund gas when
// an non-existing function is called. 5K should be enough for a SLOAD.
staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
)
) { break }
// After here, we can be sure that token is a contract.
let m := mload(0x40)
mstore(add(m, 0x34), spender)
mstore(add(m, 0x20), shl(96, owner))
mstore(add(m, 0x74), deadline)
if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
mstore(0x14, owner)
mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
mstore(
add(m, 0x94),
lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
)
mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
// `nonces` is already at `add(m, 0x54)`.
// `amount != 0` is already stored at `add(m, 0x94)`.
mstore(add(m, 0xb4), and(0xff, v))
mstore(add(m, 0xd4), r)
mstore(add(m, 0xf4), s)
success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
break
}
mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
mstore(add(m, 0x54), amount)
mstore(add(m, 0x94), and(0xff, v))
mstore(add(m, 0xb4), r)
mstore(add(m, 0xd4), s)
success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
break
}
}
if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
}
/// @dev Simple permit on the Permit2 contract.
function simplePermit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0x927da105) // `allowance(address,address,address)`.
{
let addressMask := shr(96, not(0))
mstore(add(m, 0x20), and(addressMask, owner))
mstore(add(m, 0x40), and(addressMask, token))
mstore(add(m, 0x60), and(addressMask, spender))
mstore(add(m, 0xc0), and(addressMask, spender))
}
let p := mul(PERMIT2, iszero(shr(160, amount)))
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
)
) {
mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(p))), 0x04)
}
mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
// `owner` is already `add(m, 0x20)`.
// `token` is already at `add(m, 0x40)`.
mstore(add(m, 0x60), amount)
mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
// `nonce` is already at `add(m, 0xa0)`.
// `spender` is already at `add(m, 0xc0)`.
mstore(add(m, 0xe0), deadline)
mstore(add(m, 0x100), 0x100) // `signature` offset.
mstore(add(m, 0x120), 0x41) // `signature` length.
mstore(add(m, 0x140), r)
mstore(add(m, 0x160), s)
mstore(add(m, 0x180), shl(248, v))
if iszero( // Revert if token does not have code, or if the call fails.
mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) {
mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
internal
{
/// @solidity memory-safe-assembly
assembly {
let addressMask := shr(96, not(0))
let m := mload(0x40)
mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
mstore(add(m, 0x20), and(addressMask, token))
mstore(add(m, 0x40), and(addressMask, spender))
mstore(add(m, 0x60), and(addressMask, amount))
mstore(add(m, 0x80), and(0xffffffffffff, expiration))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Revokes an approval for `token` and `spender` for `address(this)`.
function permit2Lockdown(address token, address spender) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0xcc53287f) // `Permit2.lockdown`.
mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
mstore(add(m, 0x40), 1) // `approvals.length`.
mstore(add(m, 0x60), shr(96, shl(96, token)))
mstore(add(m, 0x80), shr(96, shl(96, spender)))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
revert(0x1c, 0x04)
}
}
}
}
lib/solady/src/utils/SignatureCheckerLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Signature verification helper that supports both ECDSA signatures from EOAs
/// and ERC1271 signatures from smart contract wallets like Argent and Gnosis safe.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SignatureCheckerLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/SignatureChecker.sol)
///
/// @dev Note:
/// - The signature checking functions use the ecrecover precompile (0x1).
/// - The `bytes memory signature` variants use the identity precompile (0x4)
/// to copy memory internally.
/// - Unlike ECDSA signatures, contract signatures are revocable.
/// - As of Solady version 0.0.134, all `bytes signature` variants accept both
/// regular 65-byte `(r, s, v)` and EIP-2098 `(r, vs)` short form signatures.
/// See: https://eips.ethereum.org/EIPS/eip-2098
/// This is for calldata efficiency on smart accounts prevalent on L2s.
///
/// WARNING! Do NOT use signatures as unique identifiers:
/// - Use a nonce in the digest to prevent replay attacks on the same contract.
/// - Use EIP-712 for the digest to prevent replay attacks across different chains and contracts.
/// EIP-712 also enables readable signing of typed data for better user safety.
/// This implementation does NOT check if a signature is non-malleable.
library SignatureCheckerLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIGNATURE CHECKING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns whether `signature` is valid for `signer` and `hash`.
/// If `signer.code.length == 0`, then validate with `ecrecover`, else
/// it will validate with ERC1271 on `signer`.
function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature)
internal
view
returns (bool isValid)
{
if (signer == address(0)) return isValid;
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
for {} 1 {} {
if iszero(extcodesize(signer)) {
switch mload(signature)
case 64 {
let vs := mload(add(signature, 0x40))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, mload(add(signature, 0x60)))) // `v`.
mstore(0x60, mload(add(signature, 0x40))) // `s`.
}
default { break }
mstore(0x00, hash)
mstore(0x40, mload(add(signature, 0x20))) // `r`.
let recovered := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
isValid := gt(returndatasize(), shl(96, xor(signer, recovered)))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
// Copy the `signature` over.
let n := add(0x20, mload(signature))
let copied := staticcall(gas(), 4, signature, n, add(m, 0x44), n)
isValid := staticcall(gas(), signer, m, add(returndatasize(), 0x44), d, 0x20)
isValid := and(eq(mload(d), f), and(isValid, copied))
break
}
}
}
/// @dev Returns whether `signature` is valid for `signer` and `hash`.
/// If `signer.code.length == 0`, then validate with `ecrecover`, else
/// it will validate with ERC1271 on `signer`.
function isValidSignatureNowCalldata(address signer, bytes32 hash, bytes calldata signature)
internal
view
returns (bool isValid)
{
if (signer == address(0)) return isValid;
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
for {} 1 {} {
if iszero(extcodesize(signer)) {
switch signature.length
case 64 {
let vs := calldataload(add(signature.offset, 0x20))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, calldataload(signature.offset)) // `r`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40)))) // `v`.
calldatacopy(0x40, signature.offset, 0x40) // `r`, `s`.
}
default { break }
mstore(0x00, hash)
let recovered := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
isValid := gt(returndatasize(), shl(96, xor(signer, recovered)))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), signature.length)
// Copy the `signature` over.
calldatacopy(add(m, 0x64), signature.offset, signature.length)
isValid := staticcall(gas(), signer, m, add(signature.length, 0x64), d, 0x20)
isValid := and(eq(mload(d), f), isValid)
break
}
}
}
/// @dev Returns whether the signature (`r`, `vs`) is valid for `signer` and `hash`.
/// If `signer.code.length == 0`, then validate with `ecrecover`, else
/// it will validate with ERC1271 on `signer`.
function isValidSignatureNow(address signer, bytes32 hash, bytes32 r, bytes32 vs)
internal
view
returns (bool isValid)
{
if (signer == address(0)) return isValid;
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
for {} 1 {} {
if iszero(extcodesize(signer)) {
mstore(0x00, hash)
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, r) // `r`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
let recovered := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
isValid := gt(returndatasize(), shl(96, xor(signer, recovered)))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), 65) // Length of the signature.
mstore(add(m, 0x64), r) // `r`.
mstore(add(m, 0x84), shr(1, shl(1, vs))) // `s`.
mstore8(add(m, 0xa4), add(shr(255, vs), 27)) // `v`.
isValid := staticcall(gas(), signer, m, 0xa5, d, 0x20)
isValid := and(eq(mload(d), f), isValid)
break
}
}
}
/// @dev Returns whether the signature (`v`, `r`, `s`) is valid for `signer` and `hash`.
/// If `signer.code.length == 0`, then validate with `ecrecover`, else
/// it will validate with ERC1271 on `signer`.
function isValidSignatureNow(address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s)
internal
view
returns (bool isValid)
{
if (signer == address(0)) return isValid;
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
for {} 1 {} {
if iszero(extcodesize(signer)) {
mstore(0x00, hash)
mstore(0x20, and(v, 0xff)) // `v`.
mstore(0x40, r) // `r`.
mstore(0x60, s) // `s`.
let recovered := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
isValid := gt(returndatasize(), shl(96, xor(signer, recovered)))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), 65) // Length of the signature.
mstore(add(m, 0x64), r) // `r`.
mstore(add(m, 0x84), s) // `s`.
mstore8(add(m, 0xa4), v) // `v`.
isValid := staticcall(gas(), signer, m, 0xa5, d, 0x20)
isValid := and(eq(mload(d), f), isValid)
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC1271 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// Note: These ERC1271 operations do NOT have an ECDSA fallback.
/// @dev Returns whether `signature` is valid for `hash` for an ERC1271 `signer` contract.
function isValidERC1271SignatureNow(address signer, bytes32 hash, bytes memory signature)
internal
view
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
// Copy the `signature` over.
let n := add(0x20, mload(signature))
let copied := staticcall(gas(), 4, signature, n, add(m, 0x44), n)
isValid := staticcall(gas(), signer, m, add(returndatasize(), 0x44), d, 0x20)
isValid := and(eq(mload(d), f), and(isValid, copied))
}
}
/// @dev Returns whether `signature` is valid for `hash` for an ERC1271 `signer` contract.
function isValidERC1271SignatureNowCalldata(
address signer,
bytes32 hash,
bytes calldata signature
) internal view returns (bool isValid) {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), signature.length)
// Copy the `signature` over.
calldatacopy(add(m, 0x64), signature.offset, signature.length)
isValid := staticcall(gas(), signer, m, add(signature.length, 0x64), d, 0x20)
isValid := and(eq(mload(d), f), isValid)
}
}
/// @dev Returns whether the signature (`r`, `vs`) is valid for `hash`
/// for an ERC1271 `signer` contract.
function isValidERC1271SignatureNow(address signer, bytes32 hash, bytes32 r, bytes32 vs)
internal
view
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), 65) // Length of the signature.
mstore(add(m, 0x64), r) // `r`.
mstore(add(m, 0x84), shr(1, shl(1, vs))) // `s`.
mstore8(add(m, 0xa4), add(shr(255, vs), 27)) // `v`.
isValid := staticcall(gas(), signer, m, 0xa5, d, 0x20)
isValid := and(eq(mload(d), f), isValid)
}
}
/// @dev Returns whether the signature (`v`, `r`, `s`) is valid for `hash`
/// for an ERC1271 `signer` contract.
function isValidERC1271SignatureNow(address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s)
internal
view
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), 65) // Length of the signature.
mstore(add(m, 0x64), r) // `r`.
mstore(add(m, 0x84), s) // `s`.
mstore8(add(m, 0xa4), v) // `v`.
isValid := staticcall(gas(), signer, m, 0xa5, d, 0x20)
isValid := and(eq(mload(d), f), isValid)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC6492 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// Note: These ERC6492 operations now include an ECDSA fallback at the very end.
// The calldata variants are excluded for brevity.
/// @dev Returns whether `signature` is valid for `hash`.
/// If the signature is postfixed with the ERC6492 magic number, it will attempt to
/// deploy / prepare the `signer` smart account before doing a regular ERC1271 check.
/// Note: This function is NOT reentrancy safe.
/// The verifier must be deployed.
/// Otherwise, the function will return false if `signer` is not yet deployed / prepared.
/// See: https://gist.github.com/Vectorized/011d6becff6e0a73e42fe100f8d7ef04
/// With a dedicated verifier, this function is safe to use in contracts
/// that have been granted special permissions.
function isValidERC6492SignatureNowAllowSideEffects(
address signer,
bytes32 hash,
bytes memory signature
) internal returns (bool isValid) {
/// @solidity memory-safe-assembly
assembly {
function callIsValidSignature(signer_, hash_, signature_) -> _isValid {
let m_ := mload(0x40)
let f_ := shl(224, 0x1626ba7e)
mstore(m_, f_) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m_, 0x04), hash_)
let d_ := add(m_, 0x24)
mstore(d_, 0x40) // The offset of the `signature` in the calldata.
let n_ := add(0x20, mload(signature_))
let copied_ := staticcall(gas(), 4, signature_, n_, add(m_, 0x44), n_)
_isValid := staticcall(gas(), signer_, m_, add(returndatasize(), 0x44), d_, 0x20)
_isValid := and(eq(mload(d_), f_), and(_isValid, copied_))
}
let noCode := iszero(extcodesize(signer))
let n := mload(signature)
for {} 1 {} {
if iszero(eq(mload(add(signature, n)), mul(0x6492, div(not(isValid), 0xffff)))) {
if iszero(noCode) { isValid := callIsValidSignature(signer, hash, signature) }
break
}
if iszero(noCode) {
let o := add(signature, 0x20) // Signature bytes.
isValid := callIsValidSignature(signer, hash, add(o, mload(add(o, 0x40))))
if isValid { break }
}
let m := mload(0x40)
mstore(m, signer)
mstore(add(m, 0x20), hash)
pop(
call(
gas(), // Remaining gas.
0x0000bc370E4DC924F427d84e2f4B9Ec81626ba7E, // Non-reverting verifier.
0, // Send zero ETH.
m, // Start of memory.
add(returndatasize(), 0x40), // Length of calldata in memory.
staticcall(gas(), 4, add(signature, 0x20), n, add(m, 0x40), n), // 1.
0x00 // Length of returndata to write.
)
)
isValid := returndatasize()
break
}
// Do `ecrecover` fallback if `noCode && !isValid`.
for {} gt(noCode, isValid) {} {
switch n
case 64 {
let vs := mload(add(signature, 0x40))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, mload(add(signature, 0x60)))) // `v`.
mstore(0x60, mload(add(signature, 0x40))) // `s`.
}
default { break }
let m := mload(0x40)
mstore(0x00, hash)
mstore(0x40, mload(add(signature, 0x20))) // `r`.
let recovered := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
isValid := gt(returndatasize(), shl(96, xor(signer, recovered)))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/// @dev Returns whether `signature` is valid for `hash`.
/// If the signature is postfixed with the ERC6492 magic number, it will attempt
/// to use a reverting verifier to deploy / prepare the `signer` smart account
/// and do a `isValidSignature` check via the reverting verifier.
/// Note: This function is reentrancy safe.
/// The reverting verifier must be deployed.
/// Otherwise, the function will return false if `signer` is not yet deployed / prepared.
/// See: https://gist.github.com/Vectorized/846a474c855eee9e441506676800a9ad
function isValidERC6492SignatureNow(address signer, bytes32 hash, bytes memory signature)
internal
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
function callIsValidSignature(signer_, hash_, signature_) -> _isValid {
let m_ := mload(0x40)
let f_ := shl(224, 0x1626ba7e)
mstore(m_, f_) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m_, 0x04), hash_)
let d_ := add(m_, 0x24)
mstore(d_, 0x40) // The offset of the `signature` in the calldata.
let n_ := add(0x20, mload(signature_))
let copied_ := staticcall(gas(), 4, signature_, n_, add(m_, 0x44), n_)
_isValid := staticcall(gas(), signer_, m_, add(returndatasize(), 0x44), d_, 0x20)
_isValid := and(eq(mload(d_), f_), and(_isValid, copied_))
}
let noCode := iszero(extcodesize(signer))
let n := mload(signature)
for {} 1 {} {
if iszero(eq(mload(add(signature, n)), mul(0x6492, div(not(isValid), 0xffff)))) {
if iszero(noCode) { isValid := callIsValidSignature(signer, hash, signature) }
break
}
if iszero(noCode) {
let o := add(signature, 0x20) // Signature bytes.
isValid := callIsValidSignature(signer, hash, add(o, mload(add(o, 0x40))))
if isValid { break }
}
let m := mload(0x40)
mstore(m, signer)
mstore(add(m, 0x20), hash)
let willBeZeroIfRevertingVerifierExists :=
call(
gas(), // Remaining gas.
0x00007bd799e4A591FeA53f8A8a3E9f931626Ba7e, // Reverting verifier.
0, // Send zero ETH.
m, // Start of memory.
add(returndatasize(), 0x40), // Length of calldata in memory.
staticcall(gas(), 4, add(signature, 0x20), n, add(m, 0x40), n), // 1.
0x00 // Length of returndata to write.
)
isValid := gt(returndatasize(), willBeZeroIfRevertingVerifierExists)
break
}
// Do `ecrecover` fallback if `noCode && !isValid`.
for {} gt(noCode, isValid) {} {
switch n
case 64 {
let vs := mload(add(signature, 0x40))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, mload(add(signature, 0x60)))) // `v`.
mstore(0x60, mload(add(signature, 0x40))) // `s`.
}
default { break }
let m := mload(0x40)
mstore(0x00, hash)
mstore(0x40, mload(add(signature, 0x20))) // `r`.
let recovered := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
isValid := gt(returndatasize(), shl(96, xor(signer, recovered)))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HASHING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns an Ethereum Signed Message, created from a `hash`.
/// This produces a hash corresponding to the one signed with the
/// [`eth_sign`](https://eth.wiki/json-rpc/API#eth_sign)
/// JSON-RPC method as part of EIP-191.
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x20, hash) // Store into scratch space for keccak256.
mstore(0x00, "\x00\x00\x00\x00\x19Ethereum Signed Message:\n32") // 28 bytes.
result := keccak256(0x04, 0x3c) // `32 * 2 - (32 - 28) = 60 = 0x3c`.
}
}
/// @dev Returns an Ethereum Signed Message, created from `s`.
/// This produces a hash corresponding to the one signed with the
/// [`eth_sign`](https://eth.wiki/json-rpc/API#eth_sign)
/// JSON-RPC method as part of EIP-191.
/// Note: Supports lengths of `s` up to 999999 bytes.
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let sLength := mload(s)
let o := 0x20
mstore(o, "\x19Ethereum Signed Message:\n") // 26 bytes, zero-right-padded.
mstore(0x00, 0x00)
// Convert the `s.length` to ASCII decimal representation: `base10(s.length)`.
for { let temp := sLength } 1 {} {
o := sub(o, 1)
mstore8(o, add(48, mod(temp, 10)))
temp := div(temp, 10)
if iszero(temp) { break }
}
let n := sub(0x3a, o) // Header length: `26 + 32 - o`.
// Throw an out-of-offset error (consumes all gas) if the header exceeds 32 bytes.
returndatacopy(returndatasize(), returndatasize(), gt(n, 0x20))
mstore(s, or(mload(0x00), mload(n))) // Temporarily store the header.
result := keccak256(add(s, sub(0x20, n)), add(n, sLength))
mstore(s, sLength) // Restore the length.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EMPTY CALLDATA HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns an empty calldata bytes.
function emptySignature() internal pure returns (bytes calldata signature) {
/// @solidity memory-safe-assembly
assembly {
signature.length := 0
}
}
}
src/KeeperPolicyCalls.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {IKeeperPolicy} from "./interfaces/IKeeperPolicy.sol";
/// @dev Fixed returndata buffer and gas stipend bound even a reverting, gas-burning or returndata-bomb policy.
library KeeperPolicyCalls {
uint256 internal constant GAS_LIMIT = 100_000;
uint256 internal constant HARD_MAX_REWARD = 0.311 ether;
uint256 internal constant BURST = 0.622 ether;
uint256 internal constant REFILL_PER_SECOND = uint256(0.05 ether) / 12;
uint256 internal constant MAX_GAS = 6_000_000;
uint256 internal constant OVERHEAD_GAS = 100_000;
uint256 internal constant BASE_GAS = 200_000;
uint256 internal constant PROCESS_GAS = 1_800_000;
uint256 internal constant RECONCILE_GAS = 150_000;
uint256 internal constant SHAPE_GAS = 700_000;
uint256 internal constant PRIZE_GAS = 150_000;
uint256 internal constant PRIORITY_ALLOWANCE = 0.1 gwei;
uint256 internal constant GAS_PRICE_CEILING = 50 gwei;
uint256 internal constant WORK_FEE = 0.00005 ether;
uint256 internal constant BY_VALUE = 0x87f65ed43cb21a90;
error InvalidPolicy();
error PolicyUnavailable();
struct State {
address policy;
address pending;
uint64 activationTime;
uint64 generation;
bool enabled;
uint256 maxReward;
uint256 allowance;
uint64 allowanceTime;
}
struct Reserve {
bool enabled;
uint256 owed;
uint256 target;
uint16[16] have;
uint256 mintFee;
uint256 baseFee;
}
event KeeperPolicyProposed(address indexed policy, uint256 activationTime);
event KeeperPolicyCancelled(address indexed policy);
event KeeperPolicyChanged(address indexed previousPolicy, address indexed newPolicy);
event PaidUpkeepChanged(bool enabled);
event KeeperPaid(address indexed keeper, uint256 amount, uint256 gasUsed);
error PolicyNotReady();
error PaymentUnavailable();
error ReserveNotFunded();
function initialize(State storage s, address policy) public {
s.policy = policy;
s.maxReward = validate(policy);
s.enabled = true;
s.allowance = BURST;
s.allowanceTime = uint64(block.timestamp);
emit KeeperPolicyChanged(address(0), policy);
}
function propose(State storage s, address policy) public {
validate(policy);
s.pending = policy;
s.activationTime = uint64(block.timestamp + 2 days);
emit KeeperPolicyProposed(policy, s.activationTime);
}
function cancel(State storage s) public {
emit KeeperPolicyCancelled(s.pending);
s.pending = address(0);
s.activationTime = 0;
}
function activate(State storage s, uint256 fund, Reserve memory r) public {
if (s.pending == address(0) || block.timestamp < s.activationTime) revert PolicyNotReady();
uint256 bound = validate(s.pending);
uint256 candidate = maintenanceBudget(bound, r);
uint256 previous = maintenanceBudget(s.enabled ? s.maxReward : 0, r);
// A lower bound need not quote less for each job; only immutable maintenance exposure is compared.
if (candidate > previous && fund < candidate) revert ReserveNotFunded();
emit KeeperPolicyChanged(s.policy, s.pending);
s.policy = s.pending;
s.maxReward = bound;
s.enabled = true;
++s.generation;
cancel(s);
emit PaidUpkeepChanged(true);
}
function disable(State storage s, bool value) public {
if (value) revert PolicyNotReady();
s.enabled = false;
++s.generation;
// An already matured proposal must not let a public executor undo the creator's emergency stop.
cancel(s);
emit PaidUpkeepChanged(false);
}
function available(State storage s) public view returns (uint256) {
uint256 elapsed = block.timestamp - s.allowanceTime;
uint256 burst = BURST;
uint256 refill = REFILL_PER_SECOND;
if (elapsed >= burst / refill + 1) return burst;
uint256 amount = s.allowance + elapsed * refill;
return amount > burst ? burst : amount;
}
function pay(State storage s, IKeeperPolicy.Work memory w, uint256 fund) public returns (uint256 amount) {
amount = reward(s.policy, s.maxReward, w);
uint256 balance = available(s);
if (amount > balance || amount > fund) revert PaymentUnavailable();
s.allowance = balance - amount;
s.allowanceTime = uint64(block.timestamp);
if (amount != 0) {
SafeTransferLib.forceSafeTransferETH(msg.sender, amount);
emit KeeperPaid(msg.sender, amount, w.measuredGas);
}
}
/// @dev Actual issued work plus one bounded operating call, independent of inventory restoration and policy quotes.
function maintenanceBudget(uint256 maxReward, Reserve memory r) public pure returns (uint256 need) {
need = r.owed * paymentBound(maxReward, r.baseFee, 1, 1, 0, 0);
if (!r.enabled) return need;
uint256 operating = paymentBound(maxReward, r.baseFee, 0, 5, 5, 5);
uint256 process = paymentBound(maxReward, r.baseFee, 2, 5, 0, 0);
need += operating > process ? operating : process;
}
/// @dev Full withdrawal/opening target. Missing prize capital never enters policy activation funding.
function reserve(uint256 maxReward, Reserve memory r) public pure returns (uint256 need) {
need = maintenanceBudget(maxReward, r);
if (!r.enabled) return need;
uint256 units;
uint256 prizes;
uint256 sizes;
uint256 amounts = 0x9c400fa00c800190014000300022710138803e801f400640032000a00050001;
for (uint256 k; k < 16; ++k) {
uint256 d = (BY_VALUE >> (4 * k)) & 0xF;
uint256 want = (r.target >> (16 * d)) & 0xFFFF;
if (want <= r.have[d]) continue;
uint256 missing = want - r.have[d];
uint256 w = (0x3323232111111111 >> (4 * d)) & 0xF;
uint256 cost = ((amounts >> (16 * d)) & 0xFFFF) * 0.01 ether + w * r.mintFee;
need += missing * cost;
while (missing != 0) {
// Compress all complete same-size batches except the last, which can share its remaining slots.
if (units == 0) {
uint256 perBatch = 5 / w;
uint256 batches = (missing - 1) / perBatch;
if (batches != 0) {
need += batches * paymentBound(maxReward, r.baseFee, 0, 0, perBatch * w, perBatch);
missing -= batches * perBatch;
}
}
uint256 take = (5 - units) / w;
if (take > missing) take = missing;
if (take != 0) {
units += take * w;
prizes += take;
++sizes;
missing -= take;
}
if (missing != 0 || units == 5 || sizes == 4) {
need += paymentBound(maxReward, r.baseFee, 0, 0, units, prizes);
units = 0;
prizes = 0;
sizes = 0;
}
}
}
if (units != 0) need += paymentBound(maxReward, r.baseFee, 0, 0, units, prizes);
}
/// @dev Operation coefficients are immutable payment ceilings, not claims about actual execution gas.
function workGas(uint256 processed, uint256 draws, uint256 units, uint256 prizes) internal pure returns (uint256 gas) {
gas = BASE_GAS + processed * PROCESS_GAS + draws * RECONCILE_GAS + units * SHAPE_GAS + prizes * PRIZE_GAS;
if (gas > MAX_GAS) gas = MAX_GAS;
}
function referencePrice(uint256 baseFee) internal pure returns (uint256 price) {
price = baseFee + PRIORITY_ALLOWANCE;
if (price > GAS_PRICE_CEILING) price = GAS_PRICE_CEILING;
}
function paymentBound(uint256 maxReward, uint256 baseFee, uint256 processed, uint256 draws, uint256 units, uint256 prizes)
public pure returns (uint256)
{
return _bound(maxReward, workGas(processed, draws, units, prizes), referencePrice(baseFee), draws + units);
}
function listingPaymentBound(uint256 maxReward, uint256 draws, uint256 units, uint256 prizes)
public view returns (uint256)
{
uint256 price = referencePrice(block.basefee);
if (price > tx.gasprice) price = tx.gasprice;
return _bound(maxReward, workGas(0, draws, units, prizes), price, draws + units);
}
function _bound(uint256 maxReward, uint256 measured, uint256 price, uint256 serviceUnits) internal pure returns (uint256 amount) {
amount = (measured + OVERHEAD_GAS) * price + serviceUnits * WORK_FEE;
if (amount > maxReward) amount = maxReward;
if (amount > HARD_MAX_REWARD) amount = HARD_MAX_REWARD;
}
function word(address policy, bytes memory input) internal view returns (bool ok, uint256 value) {
assembly ("memory-safe") {
let out := mload(0x40)
ok := staticcall(GAS_LIMIT, policy, add(input, 32), mload(input), out, 32)
ok := and(ok, eq(returndatasize(), 32))
value := mload(out)
}
}
function validate(address policy) public view returns (uint256 bound) {
(bool ok, uint256 v) = word(policy, abi.encodeCall(IKeeperPolicy.interfaceVersion, ()));
if (!ok || v != 1 || policy.code.length == 0) revert InvalidPolicy();
(ok, bound) = word(policy, abi.encodeCall(IKeeperPolicy.maxReward, ()));
if (!ok || bound == 0 || bound > HARD_MAX_REWARD) revert InvalidPolicy();
}
function reward(address policy, uint256 maxReward, IKeeperPolicy.Work memory w) public view returns (uint256 amount) {
(bool ok, uint256 quote) = word(policy, abi.encodeCall(IKeeperPolicy.quoteReward, (w)));
if (!ok) revert PolicyUnavailable();
uint256 price = referencePrice(w.baseFee);
if (price > w.gasPrice) price = w.gasPrice;
uint256 measured = workGas(w.processedDraws, w.reconciledDraws, w.listedShapeUnits, w.listedPrizes);
if (measured > w.measuredGas) measured = w.measuredGas;
uint256 envelope = _bound(maxReward, measured, price, w.reconciledDraws + w.listedShapeUnits);
return quote < envelope ? quote : envelope;
}
function restock(address policy, uint8 d, uint256 units, bool paid, uint256 baseFee) public view returns (uint256) {
(bool ok, uint256 quote) = word(policy, abi.encodeCall(IKeeperPolicy.quoteRestock, (d, units, baseFee)));
// Unpaid callers cannot select cheaper pricing while the creator's chosen policy is healthy.
if (ok && quote <= units * 0.102 ether) return quote;
if (paid) revert PolicyUnavailable();
uint256 price = baseFee + 0.05 gwei;
if (price > 5 gwei) price = 5 gwei;
return units * (900_000 * price + 0.0002 ether);
}
}
src/PoolInventory.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {PoolBalancer} from "./PoolBalancer.sol";
import {KeeperPolicyCalls} from "./KeeperPolicyCalls.sol";
import {IFWAPool, IShapes, IShapePacks, IERC721Min} from "./interfaces/External.sol";
/// @dev Compiler-linked immutable inventory implementation, not a creator-selected policy. Delegatecall preserves
/// the Balancer as NFT owner and FWA operator. There is no configurable execution target or upgrade mechanism.
library PoolInventory {
struct Item {
uint8 kind;
uint8 denom;
uint8 state;
uint104 base; // creator value (curated) or the price less its restocking fees: backing, mint fees, markup (Shape)
uint104 price; // price listed on FWA
}
struct State {
mapping(uint256 => Item) items;
uint256[] activeIds;
mapping(uint256 => uint256) activeIndexPlusOne;
uint16[16] activeShapes;
uint256 listedPrizes;
uint256 shapeStageUpper;
uint256 curatedWitness;
uint256 curatedWitnessSlot;
}
struct Fill {
uint256 plan;
uint256 markup;
uint256 keep;
uint256 maxReward;
uint256 draws;
uint256 fee;
address shapes;
address packs;
address pool;
address policy;
bool paid;
}
uint256 constant MAX_OPS = 5;
uint256 constant DENOMS = 16;
uint256 constant SHAPE_DENOMS = 9;
uint256 constant MAX_RESTOCK_SIZES = 4;
uint8 constant SHAPE = 2;
uint8 constant ACTIVE = 1;
uint256 constant BY_VALUE = 0x87f65ed43cb21a90;
uint256 constant AMOUNTS = 0x9c400fa00c800190014000300022710138803e801f400640032000a00050001;
uint256 constant SHAPES_IN = 0x3323232111111111;
event ShapesMinted(uint8 indexed denom, uint256 firstTokenId, uint256 quantity, uint256 cost);
event ShapeListed(uint256 indexed listingId, uint8 indexed denom, uint256 tokenId, uint256 price);
error InvalidItem();
event ShapesUnlisted(uint256 count, uint256 ethRedeemed);
event CuratedListed(uint256 indexed listingId, address indexed collection, uint256 tokenId, uint256 base, uint256 price);
event CuratedRepriced(uint256 indexed listingId, uint256 base, uint256 price);
event CuratedWithdrawn(uint256 indexed listingId, address indexed to);
event CuratedWitnessRefreshed(uint256 indexed listingId, uint256 slot);
event RefundedRecovered(uint256 indexed listingId, address indexed to, uint256 eth);
event UntrackedNFTRecovered(address indexed collection, uint256 tokenId, address indexed to);
error InvalidBatch();
error InvalidRecipient();
error ValueTooHigh();
error ShapesNotCurated();
error InvalidConfig();
error InvalidPlan();
error ProtectedAsset();
function validateTarget(uint256 plan, uint256 markup) public pure returns (uint256 weight) {
if (markup < 1_000 || markup > 10_000) revert InvalidConfig();
uint256 prizes;
for (uint256 d; d < DENOMS; ++d) {
uint256 n = _count(plan, d);
if (n == 0) continue;
prizes += n;
weight += n * _weight(d);
}
if (prizes == 0 || prizes > 1_000) revert InvalidPlan();
}
function recoverUntracked(address pool, address factory, address collection, uint256 tokenId, address to) public {
if (to == address(0)) revert InvalidRecipient();
if (collection == pool || collection == factory) revert ProtectedAsset();
if (IERC721Min(collection).ownerOf(tokenId) != address(this)) revert ProtectedAsset();
IERC721Min(collection).safeTransferFrom(address(this), to, tokenId);
emit UntrackedNFTRecovered(collection, tokenId, to);
}
function admission(State storage s, IFWAPool pool, address shapes, uint256 mintFeeCap,
uint256 targetWeight, uint256 prizeWeight, uint64 reconciledSequence) public view returns (uint8)
{
if (s.activeIds.length == s.listedPrizes) return 3;
uint256 unsettled = pool.unsettledAcquisitionCount();
if (unsettled >= 5) return 4;
if (IShapes(shapes).mintFee() > mintFeeCap) return 5;
uint256 active = pool.activeListingCount();
// Active Shapes are a subset of tracked Shapes. Otherwise require a fresh identity proof: tracked
// curated includes staging and unreconciled wins. Ambiguity intentionally pauses until public refresh.
if (active <= s.listedPrizes && !_hasCuratedWitness(s, pool)) return 7;
uint256 unavailable = pool.lastIssuedSequence() - reconciledSequence;
uint256 stageUpper = s.shapeStageUpper;
if (stageUpper == 0) {
uint256 lost = unavailable * (1e36 / 0.01 ether);
return prizeWeight < lost || (prizeWeight - lost) * 10_000 < 7_000 * targetWeight ? 6 : 0;
}
uint256 shapeBound = unavailable + stageUpper;
uint256 tracked = s.activeIds.length;
// Earlier reserved batches and the next six staged records activate before the first new selection.
// Inactive records are staged or already won; max(q, C-activation+u) avoids counting a win twice.
uint256 inactive = tracked > active ? tracked - active : 0;
uint256 activation = pool.reservedStagedCount() + 6;
uint256 afterActivation = (inactive > activation ? inactive - activation : 0) + unsettled;
if (afterActivation > unavailable) unavailable = afterActivation;
if (shapeBound < unavailable) unavailable = shapeBound;
uint256 lost = unavailable * (1e36 / 0.01 ether);
if (prizeWeight < lost || (prizeWeight - lost) * 10_000 < 7_000 * targetWeight) return 6;
return 0;
}
function _hasCuratedWitness(State storage s, IFWAPool pool) private view returns (bool) {
uint256 lid = s.curatedWitness;
return lid != 0 && s.activeIndexPlusOne[lid] != 0 && s.items[lid].kind == 1
&& pool.slotToListing(s.curatedWitnessSlot) == lid;
}
/// @dev A caller supplies discovery, never authority. Slot identities are rechecked on every admission.
function refreshCuratedWitness(State storage s, IFWAPool pool, uint256 lid) public returns (bool changed) {
Item storage it = s.items[lid];
if (it.kind != 1 || it.state != ACTIVE || s.activeIndexPlusOne[lid] == 0) revert InvalidItem();
(,,,,,, uint256 slot, uint8 status) = pool.listings(lid);
if (slot == 0 || status != ACTIVE) revert InvalidItem();
// Permissionless callers cannot replace an already valid proof with a less durable candidate.
if (_hasCuratedWitness(s, pool)) return false;
_setCuratedWitness(s, lid, slot);
return true;
}
function _setCuratedWitness(State storage s, uint256 lid, uint256 slot) private {
s.curatedWitness = lid;
s.curatedWitnessSlot = slot;
emit CuratedWitnessRefreshed(lid, slot);
}
function listCurated(State storage s, IFWAPool pool, address shapes, address packs, address source,
PoolBalancer.CuratedInput[] calldata inputs) public returns (uint256[] memory listingIds)
{
uint256 n = inputs.length;
if (n == 0 || n > 20) revert InvalidBatch();
// Clear stale Shape uncertainty before adding curated staging, only with proof all tracked records are active.
if (s.shapeStageUpper != 0 && pool.activeListingCount() == s.activeIds.length) s.shapeStageUpper = 0;
IFWAPool.ListingInput[] memory batch = new IFWAPool.ListingInput[](n);
for (uint256 i; i < n; ++i) {
PoolBalancer.CuratedInput calldata c = inputs[i];
if (c.collection == shapes || c.collection == packs) revert ShapesNotCurated();
IERC721Min token = IERC721Min(c.collection);
token.transferFrom(source, address(this), c.tokenId);
if (token.ownerOf(c.tokenId) != address(this)) revert InvalidItem();
token.approve(address(pool), c.tokenId);
_checkValue(c.base);
batch[i] = IFWAPool.ListingInput(c.collection, c.tokenId, c.base);
}
listingIds = pool.listNFTs(batch);
for (uint256 i; i < n; ++i) {
uint256 lid = listingIds[i];
s.items[lid] = Item(1, 0, ACTIVE, uint104(inputs[i].base), uint104(inputs[i].base));
addActive(s, lid);
emit CuratedListed(lid, inputs[i].collection, inputs[i].tokenId, inputs[i].base, inputs[i].base);
}
if (!_hasCuratedWitness(s, pool)) {
// At most the newly listed batch (20). Discovering other surviving inventory is caller-supplied,
// so neither listing nor the 100k purchase hook scans an uncapped curated inventory.
for (uint256 i; i < n; ++i) {
(,,,,,, uint256 slot, uint8 status) = pool.listings(listingIds[i]);
if (slot != 0 && status == ACTIVE) {
_setCuratedWitness(s, listingIds[i], slot);
break;
}
}
}
}
function updateCurated(State storage s, IFWAPool pool, uint256 lid, uint256 base) public {
Item storage it = s.items[lid];
if (it.kind != 1 || it.state != ACTIVE) revert InvalidItem();
_checkValue(base);
it.base = uint104(base);
if (base != it.price) {
pool.updatePrice(lid, base);
it.price = uint104(base);
}
emit CuratedRepriced(lid, base, base);
}
function withdrawCurated(State storage s, IFWAPool pool, uint256 lid, address to) public {
Item storage it = s.items[lid];
if (it.kind != 1 || it.state != ACTIVE) revert InvalidItem();
if (to == address(0)) revert InvalidRecipient();
removeActive(s, lid);
delete s.items[lid];
pool.withdrawListingTo(lid, to);
emit CuratedWithdrawn(lid, to);
}
function recoverRefunded(State storage s, IFWAPool pool, address shapes, address packs, uint256 lid, address to)
public returns (uint256 eth)
{
Item storage it = s.items[lid];
if (it.state != 2 || to == address(0)) revert InvalidItem();
(address collection,,, uint256 tokenId,,,, uint8 status) = pool.listings(lid);
if (status != 7) revert InvalidItem();
uint8 kind = it.kind;
uint8 d = it.denom;
delete s.items[lid];
pool.recoverRefundedNFT(lid);
if (kind == 1) IERC721Min(collection).safeTransferFrom(address(this), to, tokenId);
else {
uint256 before = address(this).balance;
IShapePacks(d < 9 ? shapes : packs).redeem(tokenId);
eth = address(this).balance - before;
}
emit RefundedRecovered(lid, to, eth);
}
function unlistShapes(State storage s, IFWAPool pool, address shapes, address packs, uint256[] calldata ids)
public returns (uint256 removedWeight)
{
uint256 n = ids.length;
uint256[] memory tokens = new uint256[](n);
uint8[] memory sizes = new uint8[](n);
for (uint256 i; i < n; ++i) {
Item storage it = s.items[ids[i]];
if (it.kind != SHAPE) revert InvalidItem();
removeActive(s, ids[i]);
(,,, tokens[i],,,,) = pool.listings(ids[i]);
sizes[i] = it.denom;
--s.activeShapes[it.denom];
removedWeight += _weight(it.denom);
delete s.items[ids[i]];
}
pool.withdrawListingsTo(ids, address(this));
uint256 before = address(this).balance;
for (uint256 i; i < n; ++i) IShapePacks(sizes[i] < 9 ? shapes : packs).redeem(tokens[i]);
emit ShapesUnlisted(n, address(this).balance - before);
}
function _checkValue(uint256 base) internal pure {
if (base == 0 || base > type(uint104).max) revert ValueTooHigh();
}
function fill(State storage st, Fill memory f) public returns (uint256 used, uint256 listed, uint256 added) {
IFWAPool p = IFWAPool(f.pool);
IShapes SHAPES = IShapes(f.shapes);
IShapePacks PACKS = IShapePacks(f.packs);
uint256 plan = f.plan;
uint256 markup = f.markup;
uint256 keep = f.keep;
uint256 fee = f.fee;
IFWAPool.ListingInput[] memory batch = new IFWAPool.ListingInput[](MAX_OPS);
uint8[] memory sizes = new uint8[](MAX_OPS);
uint256 n;
uint256 restocked; // sizes
for (uint256 k; k < DENOMS; ++k) {
uint256 d = (BY_VALUE >> (4 * k)) & 0xF;
uint256 have = st.activeShapes[d];
uint256 want = _count(plan, d);
if (have >= want) continue;
uint256 w = _shapesIn(d);
uint256 need = want - have;
if (need > (MAX_OPS - used) / w) need = (MAX_OPS - used) / w;
uint256 each = _cost(d, fee);
uint256 bal = address(this).balance;
// Only the candidate work's enforced bound is held, not the policy's unrelated full-call maximum.
while (need != 0) {
uint256 reward = f.paid
? KeeperPolicyCalls.listingPaymentBound(f.maxReward, f.draws, used + need * w, n + need)
: 0;
if (bal >= keep + need * each + reward) break;
--need;
}
if (need == 0) break; // stop at the first size not fully restocked, so restocking stays in value order
uint256 price = _prizeBase(d, fee, markup) + KeeperPolicyCalls.restock(f.policy, uint8(d), w, f.paid, block.basefee);
if (d < SHAPE_DENOMS) {
uint256 first = SHAPES.mintBatch{value: need * each}(_amount(d), need);
emit ShapesMinted(uint8(d), first, need, need * each);
for (uint256 j; j < need; ++j) {
sizes[n] = uint8(d);
batch[n++] = IFWAPool.ListingInput(address(SHAPES), first + j, price);
}
} else {
// One pack per prize, each minting its Shapes inside; the pack token comes to this contract.
uint32[] memory makeup = _makeup(d);
for (uint256 j; j < need; ++j) {
uint256 id = PACKS.createPackTo{value: each}(new uint256[](0), makeup, address(this));
if (j == 0) emit ShapesMinted(uint8(d), id, need, need * each);
sizes[n] = uint8(d);
batch[n++] = IFWAPool.ListingInput(address(PACKS), id, price);
}
}
used += need * w;
if (need < want - have || ++restocked == MAX_RESTOCK_SIZES) break;
}
if (n == 0) return (0, 0, 0);
assembly ("memory-safe") {
mstore(batch, n)
}
uint256[] memory lids = p.listNFTs(batch);
for (uint256 i; i < n; ++i) {
uint8 d = sizes[i];
uint256 base = _prizeBase(d, fee, markup);
st.items[lids[i]] = PoolInventory.Item(SHAPE, d, ACTIVE, uint104(base), uint104(batch[i].price));
addActive(st, lids[i]);
++st.activeShapes[d];
added += _weight(d);
emit ShapeListed(lids[i], d, batch[i].tokenId, batch[i].price);
}
listed = n;
// Every new Shape/pack prize may be staged; activation/removal can only reduce this upper bound.
uint256 stageUpper = st.shapeStageUpper + n;
if (stageUpper > st.listedPrizes) stageUpper = st.listedPrizes;
if (p.activeListingCount() == st.activeIds.length) stageUpper = 0;
st.shapeStageUpper = stageUpper;
}
function missingUnits(State storage s, uint256 plan) public view returns (uint256 units) {
for (uint256 d; d < DENOMS; ++d) {
uint256 want = _count(plan, d);
uint256 have = s.activeShapes[d];
if (want > have) units += (want - have) * _shapesIn(d);
}
}
function addActive(State storage s, uint256 lid) public {
Item storage it = s.items[lid];
if (it.kind == SHAPE) {
++s.listedPrizes;
}
s.activeIds.push(lid);
s.activeIndexPlusOne[lid] = s.activeIds.length;
}
function removeActive(State storage s, uint256 lid) public {
uint256 idx = s.activeIndexPlusOne[lid];
if (idx == 0) revert InvalidItem();
Item storage it = s.items[lid];
if (it.kind == SHAPE) {
--s.listedPrizes;
}
uint256 lastId = s.activeIds[s.activeIds.length - 1];
s.activeIds[idx - 1] = lastId;
s.activeIndexPlusOne[lastId] = idx;
s.activeIds.pop();
delete s.activeIndexPlusOne[lid];
}
function _weight(uint256 d) internal pure returns (uint256) { return 1e36 / _amount(d); }
function _prizeBase(uint256 d, uint256 fee, uint256 markup) internal pure returns (uint256) {
return _cost(d, fee) + _amount(d) * markup / 10_000;
}
function _cost(uint256 d, uint256 fee) internal pure returns (uint256) { return _amount(d) + fee * _shapesIn(d); }
function _count(uint256 plan, uint256 d) internal pure returns (uint256) { return (plan >> (16 * d)) & 0xFFFF; }
function _amount(uint256 d) internal pure returns (uint256) { return ((AMOUNTS >> (16 * d)) & 0xFFFF) * 0.01 ether; }
function _shapesIn(uint256 d) internal pure returns (uint256) { return (SHAPES_IN >> (4 * d)) & 0xF; }
function _makeup(uint256 d) internal pure returns (uint32[] memory m) {
m = new uint32[](SHAPE_DENOMS);
uint256 rest = _amount(d);
for (uint256 i = SHAPE_DENOMS; i != 0;) {
uint256 a = _amount(--i);
m[i] = uint32(rest / a);
rest %= a;
}
}
/// @dev Shapes inside one prize of size `d`, each paying the Shapes mint fee.
}
src/PoolPage.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {LibString} from "solady/utils/LibString.sol";
import {SignatureCheckerLib} from "solady/utils/SignatureCheckerLib.sol";
/// @title PoolPage
/// @notice Builds the digest of FWA's "Publish FWA Pools page" message for one pool. An external library (called by
/// DELEGATECALL, pure) so this rarely used code sits outside PoolBalancer's 24 KB limit.
library PoolPage {
/// @dev Same signature as PoolBalancer.InvalidConfig, so callers of `approvePoolPage` see PoolBalancer's error.
error InvalidConfig();
/// @dev FWA Pools V1 factory, named in FWA's pool-page message next to the V2 PoolFactory.
string internal constant FWA_V1_FACTORY = "0xf5a3a153164791ab579c3d9ba5dbecf7cdfd300c";
/// @notice personal_sign digest of the exact message pools.fwa.fun asks a pool owner to sign. `issuedAt` is the
/// ISO-8601 time the site will submit (24 chars, e.g. 2026-11-10T12:34:56.789Z); `metadataHash` is
/// keccak256 of the page JSON.
function digest(address fwaFactory, address pool, string calldata issuedAt, bytes32 metadataHash)
external
pure
returns (bytes32)
{
bytes calldata t = bytes(issuedAt);
if (t.length != 24) revert InvalidConfig();
for (uint256 i; i < 24; ++i) {
bytes1 c = t[i];
if ((c < "0" || c > "9") && c != "-" && c != ":" && c != "." && c != "T" && c != "Z") revert InvalidConfig();
}
return SignatureCheckerLib.toEthSignedMessageHash(
abi.encodePacked(
"Publish FWA Pools page\nSite: pools.fwa.fun\nChain: 1\nFactories: ",
LibString.toHexString(fwaFactory),
", ",
FWA_V1_FACTORY,
"\nPool: ",
LibString.toHexString(pool),
"\nIssued at: ",
issuedAt,
"\nMetadata hash: ",
LibString.toHexString(uint256(metadataHash), 32)
)
);
}
}
src/interfaces/External.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
/// @dev Subset of the deployed FWA PoolFactory (0x8919814D825a5Af238cC04DE06b1C18c9eaA477C).
interface IFWAPoolFactory {
function implementation() external view returns (address);
function poolImplementation(address pool) external view returns (address);
function createPool(bytes32 userSalt, address expectedImplementation) external returns (address pool);
function edgeBps() external view returns (uint16);
function maxAcquisitionsPerTx() external view returns (uint16);
function maxActivationsPerAcquisition() external view returns (uint16);
function maxStagedListings() external view returns (uint256);
function globalWithdrawOnly() external view returns (bool);
}
/// @dev Subset of the deployed FWA StandardPoolBuyback (0x85Faf92967705dc45535eBCA74D6333F6bCBfEe7).
interface IFWAPool {
struct ListingInput {
address collection;
uint256 tokenId;
uint256 price;
}
// owner inventory
function listNFT(address collection, uint256 tokenId, uint256 price) external returns (uint256 listingId);
function listNFTs(ListingInput[] calldata items) external returns (uint256[] memory listingIds);
function updatePrice(uint256 listingId, uint256 newPrice) external;
function withdrawListingTo(uint256 listingId, address recipient) external;
function withdrawListingsTo(uint256[] calldata listingIds, address recipient) external;
function recoverRefundedNFT(uint256 listingId) external;
function withdrawOwnerProceeds() external returns (uint256 amount);
// owner config
function setBool(uint256 key, bool value) external;
function setPurchaseOperator(address newOperator) external;
function retirePool() external;
// purchases (the Balancer never calls these; players buy on FWA directly)
function acquire(
address purchaser,
uint256 maxAcquisitionFee,
uint256 minWeightedValue,
uint256 maxNegativeSlippageBps,
uint256 expectedInventoryVersion,
uint256 deadline
) external payable returns (uint256 requestId);
function acquireBatch(
address purchaser,
uint256 count,
uint256 maxAcquisitionFee,
uint256 minWeightedValue,
uint256 maxNegativeSlippageBps,
uint256 expectedInventoryVersion,
uint256 deadline
) external payable returns (uint256[] memory requestIds);
function acquireWithToken(
address purchaser,
uint256 count,
uint256 minWeightedValue,
uint256 maxNegativeSlippageBps,
uint256 expectedInventoryVersion,
uint256 expectedOfferVersion,
uint256 deadline
) external payable returns (uint256[] memory requestIds);
function configureTokenOffer(uint256 price, uint256 maxPulls, bool enabled) external;
function processAcquisitions(uint256 maxCount) external returns (uint256 processed);
function activateListings(uint256 maxCount) external;
function quoteAcquisitionPrice(uint256 count) external view returns (uint256 fee, uint256 vrf, uint256 total);
// views
function owner() external view returns (address);
function listings(uint256 listingId)
external
view
returns (
address collection,
address depositor,
address purchaser,
uint256 tokenId,
uint256 weight,
uint256 price,
uint256 slot,
uint8 status
);
function acquisitions(uint256 requestId)
external
view
returns (
address purchaser,
uint256 requestBlock,
uint256 priceEscrowed,
uint256 listingId,
uint8 status,
bool tokenPayment
);
function requestIdAtSequence(uint64 sequence) external view returns (uint256);
function lastIssuedSequence() external view returns (uint64);
function nextSequenceToProcess() external view returns (uint64);
function unsettledAcquisitionCount() external view returns (uint256);
function inventoryVersion() external view returns (uint256);
function totalWeight() external view returns (uint256);
function weightedBackingTotal() external view returns (uint256);
function activeListingCount() external view returns (uint256);
function slotToListing(uint256 slot) external view returns (uint256);
function reservedStagedCount() external view returns (uint256);
function acquisitionFee() external view returns (uint256);
function ownerProceeds() external view returns (uint256);
function purchaseOperator() external view returns (address);
function tokenOfferEnabled() external view returns (bool);
function retired() external view returns (bool);
function localPurchasesEnabled() external view returns (bool);
function vrfServiceFee() external view returns (uint256);
function rawFulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) external;
function retryNFTDelivery(uint256 listingId) external;
function refundFailedDelivery(uint256 listingId) external;
}
/// @dev Subset of the deployed Shapes token (0x6fe9193276bf7abcbee44ab7afd717d637d6faf0).
interface IShapes {
function mintFee() external view returns (uint256);
function mintBatch(uint256 amountWei, uint256 quantity) external payable returns (uint256 firstTokenId);
function redeemBatch(uint256[] calldata tokenIds) external returns (uint256 totalWei);
function denominationAt(uint8 index) external pure returns (uint256);
function denominationCount() external view returns (uint8);
function denomIndexOf(uint256 tokenId) external view returns (uint8);
function backingOf(uint256 tokenId) external view returns (uint256);
function setApprovalForAll(address operator, bool approved) external;
function ownerOf(uint256 tokenId) external view returns (address);
}
interface IERC721Min {
function ownerOf(uint256 tokenId) external view returns (address);
function transferFrom(address from, address to, uint256 tokenId) external;
function safeTransferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
}
interface IENS {
function owner(bytes32 node) external view returns (address);
}
interface IReverseRegistrar {
function setName(string calldata name) external returns (bytes32);
}
/// @dev Draw Packs: an ERC-721 whose token holds Shapes in custody and redeems for exactly their backing. Only what the
/// Balancer calls.
interface IShapePacks {
function createPackTo(uint256[] calldata shapeIds, uint32[] calldata mintCounts, address to)
external
payable
returns (uint256 packId);
function redeem(uint256 packId) external;
function shapes() external view returns (address);
function MIN_PACK_VALUE() external view returns (uint256);
function setApprovalForAll(address operator, bool approved) external;
}
src/interfaces/IKeeperPolicy.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
/// @notice Version 1 of the project's read-only economic quote protocol. Work is counted by PoolBalancer after
/// successful external operations; a policy cannot execute work or decide whether it was useful.
interface IKeeperPolicy {
struct Work {
uint256 measuredGas;
uint256 gasPrice;
uint256 baseFee;
uint256 reconciledDraws;
uint256 listedShapeUnits;
uint256 listedPrizes;
uint256 processedDraws;
}
function interfaceVersion() external view returns (uint256);
function version() external view returns (uint256);
/// @dev PoolBalancer snapshots and enforces this bound; an under-declared quote can never spend above it.
function maxReward() external view returns (uint256);
function quoteReward(Work calldata work) external view returns (uint256);
/// @notice Total surcharge for ONE prize, which may contain several Shapes. Existing prices never change.
function quoteRestock(uint8 denomination, uint256 shapeUnits, uint256 baseFee) external view returns (uint256);
}
Настройки компилятораПоказать
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {
"src/PoolPage.sol": {
"PoolPage": "0x67C828Ad820490C02CDCBbCCc3A303c64207fBcf"
},
"src/PoolInventory.sol": {
"PoolInventory": "0x9154504fB111544725bBb593b813fa106FdcFF9E"
},
"src/KeeperPolicyCalls.sol": {
"KeeperPolicyCalls": "0x1601A841C2C86f6AC574279b87F1168ff284B8fb"
}
},
"optimizer": {
"runs": 50,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/",
"packs/=lib/shape-packs/src/",
"shapes/=lib/shape-packs/lib/shapes/src/",
"@openzeppelin/contracts/=lib/shape-packs/lib/shapes/lib/openzeppelin-contracts/contracts/",
"ladder/=lib/shape-packs/lib/shapes/ladders/mainnet/",
"openzeppelin-contracts/=lib/shape-packs/lib/shapes/lib/openzeppelin-contracts/contracts/",
"shape-packs/=lib/shape-packs/"
]
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.