Verified contractExactAGPL-3.0-only
Swapboard
Address0x000000da7bb4b2a9e3e80e9a4d4157e26ca6189b
- Balance
0 ETH
- Transactions
17
- Compiler
solc 0.8.36
- Same code
Only this contract
Details
- Compiler
- solc 0.8.36+commit.8a079791
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- prague
- Via IR
- yes
- License
- AGPL-3.0-only
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,717,946
- Creation transaction
- 0x201e67f4eb…4e7d05dc90
12 files
- src/Swapboard.solmain81.81 KB
- lib/solady/src/tokens/ERC721.sol40 KB
- lib/solady/src/utils/Base64.sol7.72 KB
- lib/solady/src/utils/FixedPointMathLib.sol55.69 KB
- lib/solady/src/utils/LibBytes.sol38.18 KB
- lib/solady/src/utils/LibString.sol44.25 KB
- lib/solady/src/utils/MetadataReaderLib.sol10.34 KB
- lib/solady/src/utils/Multicallable.sol5.73 KB
- lib/solady/src/utils/ReentrancyGuardTransient.sol4.8 KB
- lib/solady/src/utils/SafeTransferLib.sol32.86 KB
- src/utils/PositionSVG.sol22.27 KB
- src/utils/SwapboardMetadata.sol16.73 KB
src/Swapboard.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.36;
import {PositionSVG} from "./utils/PositionSVG.sol";
import {ERC721} from "../lib/solady/src/tokens/ERC721.sol";
import {SwapboardMetadata} from "./utils/SwapboardMetadata.sol";
import {Multicallable} from "../lib/solady/src/utils/Multicallable.sol";
import {SafeTransferLib} from "../lib/solady/src/utils/SafeTransferLib.sol";
import {FixedPointMathLib} from "../lib/solady/src/utils/FixedPointMathLib.sol";
import {ReentrancyGuardTransient} from "../lib/solady/src/utils/ReentrancyGuardTransient.sol";
/// @title Swapboard
/// @notice Escrowed peer-to-peer orders. Either side may be an ERC-20 or an
/// ERC-721, with optional partial fills, an optional maker-side expiry
/// and an optional named counterparty.
///
/// @dev tokenA is escrowed on creation and returned on cancellation or fill;
/// tokenB is paid by the taker. ERC-721 amounts are token IDs and cannot be
/// partially filled. Expiry is maker-side and inclusive; fill deadlines are
/// taker-side and inclusive. Escrow transfers use exact balance or
/// ownership checks.
///
/// ETH is a boundary concern, not an order type: raw value enters through
/// `createOrderWithEth` / `fillOrderWithEth` and leaves through
/// `fillOrderUnwrap`, wrapped and unwrapped against the immutable canonical
/// WETH at the edge. Orders themselves only ever reference tokens, so
/// settlement keeps one asset model and one set of exact-delta invariants,
/// and permissionless paths like `cancelExpired` never make a value call to
/// arbitrary code. Integrators reading `tokenA`/`tokenB` see WETH where a
/// user deposited ETH; UIs should present that pair as ETH.
///
/// @dev Fungible tokenA transfers are measured on both sides, and direct
/// fungible tokenB payments are measured at the maker. NFT ownership and
/// WETH wrap/unwrap deltas are checked exactly. `counterparty` restricts
/// fills to one caller; recipient only controls delivery. Anyone may sweep
/// expired orders, and typed batch methods are atomic unless prefixed `try`.
/// Rebasing and reflection tokens remain unsupported because pooled escrow
/// balances can change between calls; integrators should allowlist assets.
contract Swapboard is ERC721, ReentrancyGuardTransient, Multicallable {
using SafeTransferLib for address;
/// @dev maker/active/partialFill/expiry/nftA/nftB fill slot 0 exactly.
/// For an NFT side the matching amount is a tokenId, so tokenId 0 is
/// legitimate and the zero-amount check is skipped for that side.
struct Order {
address maker;
bool active;
bool partialFill;
uint64 expiry; // 0 = never expires
bool nftA;
bool nftB;
address counterparty; // 0 = anyone may fill
address tokenA;
uint256 amountA; // tokenId when nftA
address tokenB;
uint256 amountB; // tokenId when nftB
}
struct CreateOrderParams {
address tokenA;
uint256 amountA;
address tokenB;
uint256 amountB;
bool partialFill;
uint64 expiry;
bool nftA;
bool nftB;
address counterparty;
}
struct ReplaceOrderParams {
uint256 orderId;
uint256 amountA;
uint256 amountB;
uint64 expiry;
}
address public immutable weth;
/// @notice Per-board immutable renderer; it has no owner or upgrade path.
SwapboardMetadata public immutable METADATA_RENDERER;
uint256 public nextOrderId;
mapping(uint256 orderId => Order order) public orders;
/// @notice The ask this order was last written against.
/// @dev The live SVG receipt needs a denominator for fill progress, and
/// `amountB` cannot be its own: it is decremented on every partial
/// fill. This is set at creation and reset by `replaceOrder`, which
/// restarts the order's fill progress along with its price. Public
/// because the renderer reads it for itself; see `tokenURI`.
mapping(uint256 orderId => uint256 amount) public initialAmountB;
/// @notice `decimals + 1`, zero for an unavailable/non-standard response.
/// @dev Captured at creation so rendering never depends on token code, and
/// read by the renderer rather than passed to it; see `tokenURI`.
mapping(address token => uint8 snapshot) public tokenDecimals;
/// @notice Optional, sanitised symbol captured at order creation.
/// @dev Read by the renderer rather than passed to it; see `tokenURI`.
mapping(address token => string symbol) public tokenSymbols;
/// @notice Whether this board is escrowing `tokenId` of `collection` for a
/// live order right now.
/// @dev `ownerOf` answers "is the board holding this token", which is NOT
/// the question escrow solvency asks: a token the board is already
/// holding for somebody else's order answers it just as affirmatively
/// as one this call deposited. The push path moves nothing, so
/// `ownerOf` was the only thing standing between a collection that can
/// be induced to call the receiver hook with an arbitrary token id and
/// a second order minted over an existing order's backing - whose
/// cancellation hands the NFT away and leaves the first order
/// permanently unfillable and uncancellable. A collection weird enough
/// to produce the duplicate at all reaches that lock without anyone
/// intending an attack.
///
/// So the board keeps its own record of what it escrows and treats
/// that, not the collection's word, as the authority. Both creation
/// paths consult it: the push path, which has no other backstop, and
/// the pull path, where a collection whose `ownerOf` lies well enough
/// to pass `_moveNFT`'s before/after check twice could otherwise rest
/// two orders on one token.
///
/// A flag rather than the order id: nothing needs to know WHICH order
/// holds it - `orders` already says that - only whether the slot is
/// taken. One cold SSTORE per NFT order, cleared on the close that
/// releases the token: a full fill, or a return of escrow.
mapping(address collection => mapping(uint256 tokenId => bool)) internal escrowedNFT;
/// @notice Whether a closed order was closed BY A FILL that took the whole
/// thing, rather than cancelled.
/// @dev Public because the renderer reads it for itself; see `tokenURI`.
/// `Order` has no spare bit (slot 0 is exactly full), and the
/// distinction cannot be recovered from the legs: a full fill zeroes
/// both, but so does a CANCELLED order escrowing NFT token id 0 against
/// NFT token id 0, which the receipt then drew as FILLED at 100%.
mapping(uint256 id => bool) public settled;
/// @notice Orders soft-frozen against fills and repricing.
/// @dev A position hands over an order's cash flows, but until it is frozen
/// the backing stays mutable by ANYONE: a taker can shrink the claim
/// with a partial fill, or close it out entirely, at any moment. That
/// makes an unfrozen position unsafe to escrow or auction - unlike a
/// Uniswap V3 position, where only the owner or an approved party can
/// reduce it, so no buyer diligence helps because the state can change
/// between simulation and inclusion.
///
/// Freezing is the owner's own act, and only the owner can undo it. An
/// escrow holding a frozen position therefore holds something inert
/// and complete: nobody can alter it while the sale is in flight, and
/// the buyer thaws it once they hold it.
///
/// A soft freeze is not a promise to a THIRD party, because the owner
/// can lift it and cancel; see `frozenUntil` for the binding form.
///
/// A separate mapping rather than a struct field: slot 0 is already
/// exactly full, and ordinary orders should not pay for a feature only
/// traded positions use.
mapping(uint256 orderId => bool) internal _softFrozen;
/// @notice Timestamp until which an order is BOUND: not fillable, not
/// sweepable, and - unlike a soft freeze - not cancellable,
/// repriceable or thawable by its own owner either.
///
/// @dev A soft freeze is only worth what the owner's continued goodwill is
/// worth. Anyone buying a position OFF this board - a signed listing on
/// an ordinary ERC-721 marketplace, an OTC hand-off - commits to a
/// claim the seller can still empty out of from under them: cancel
/// returns the backing, the receipt stays transferable, and the sale
/// settles against a spent ticket. Custody-first escrows are immune
/// (taking the receipt makes the ESCROW the maker), but a generic
/// marketplace never takes custody before the buyer pays.
///
/// A commitment closes that window: while it stands the claim cannot
/// change by any path, including the owner's own. It is also IMMUTABLE
/// while it stands - not shortenable, and not lengthenable either - so
/// the timestamp a buyer reads is the exact end of the window and not
/// merely its floor. An extendable commitment would be a promise the
/// seller could rewrite: commit three days, list the receipt, then
/// front-run the buyer's purchase with a year, and the buyer settles
/// for a position nobody can touch for a year. `MAX_COMMITMENT` bounds
/// one window; unlimited re-extension would have made that bound
/// meaningless.
///
/// It RIDES WITH THE TOKEN. An earlier design cleared it on transfer to
/// a different owner, on the reasoning that a seller's only early exit
/// cost them the thing they had listed, so a stale sale would fail
/// rather than settle on an emptied claim. That reasoning was wrong:
/// ownership is recoverable and escrow is not. Hand the receipt to a
/// second wallet (clearing the commitment), cancel from there (taking
/// the backing), hand it back - three transactions, bundleable ahead of
/// the buyer's purchase, and the buyer pays for a spent ticket. The
/// commitment therefore survives every transfer and lapses only on its
/// own timestamp, which is the guarantee a buyer was reading in the
/// first place.
///
/// Because there is now no early exit at all, the window is CAPPED: an
/// unbounded commitment would be an irreversible burn of the escrow
/// rather than a promise about a sale.
mapping(uint256 orderId => uint64 until) public frozenUntil;
/// @dev The longest a commitment may run from the moment it is made. Long
/// enough to outlast any sale, short enough that a mistake is a wait
/// rather than a loss.
uint64 public constant MAX_COMMITMENT = 365 days;
/// @notice True when `orderId` cannot be filled or repriced right now, by
/// either a soft freeze or a live commitment.
/// @dev Same name and signature as the mapping getter it replaces, so a
/// caller reading `frozen(id)` still gets the question they asked.
///
/// IT IS NOT A GUARANTEE TO A BUYER, and folding both states into one
/// boolean makes that easy to misread. A soft freeze can be lifted by
/// the owner in the same block a marketplace settles, followed by a
/// cancellation or a repricing down to dust. Anyone buying a position
/// off this board must read the exact `frozenUntil` timestamp
/// atomically at purchase and require it to cover the sale window -
/// never this boolean. Note also that a seller with no live commitment
/// can front-run a purchase with a fresh one: the buyer settles on a
/// position that cannot be filled, repriced or cancelled by anyone
/// until it lapses. That griefs rather than steals, and
/// `MAX_COMMITMENT` bounds the wait, but a marketplace flow should
/// pin the exact value it expects. Custody-first escrows - which take
/// the receipt and become the maker - are immune to both and are the
/// recommended path.
function frozen(uint256 orderId) public view returns (bool) {
return _softFrozen[orderId] || block.timestamp < frozenUntil[orderId];
}
event OrderCreated(
uint256 indexed orderId,
address indexed maker,
address tokenA,
uint256 amountA,
address tokenB,
uint256 amountB,
bool partialFill,
uint64 expiry,
bool nftA,
bool nftB,
address counterparty
);
event OrderFilled(
uint256 indexed orderId, address indexed taker, address indexed maker, uint256 amountA, uint256 amountB
);
event OrderPartiallyFilled(
uint256 indexed orderId,
address indexed taker,
address indexed maker,
uint256 amountA,
uint256 amountB,
uint256 remainingA,
uint256 remainingB
);
event OrderReplaced(
uint256 indexed orderId, address indexed maker, uint256 amountA, uint256 amountB, uint64 expiry
);
event OrderFreezeSet(uint256 indexed orderId, bool frozen);
event OrderCommitmentSet(uint256 indexed orderId, uint64 until);
event OrderCanceled(uint256 indexed orderId, address indexed maker);
event OrderExpiredSwept(uint256 indexed orderId, address indexed maker, address indexed caller);
error ZeroETH();
error BadMaker();
error SameToken();
error ZeroAmount();
error ZeroAddress();
error BadRecipient();
error UnexpectedETH();
error LengthMismatch();
error ZeroFillAmount();
error DeadlineExpired();
error NFTNotDivisible();
error DirectNFTTransfer();
error ExpiryInPast(uint64 expiry);
error NotAContract(address token);
error ExpectedERC20(address token);
error OrderFrozen(uint256 orderId);
error OrderExpired(uint256 orderId);
error OrderNotFound(uint256 orderId);
error OrderNotActive(uint256 orderId);
error OrderNotExpired(uint256 orderId);
error NFTNotReplaceable(uint256 orderId);
error LiveClaimNotEscrowable(address token);
error PartialFillNotAllowed(uint256 orderId);
error NotWETH(address expected, address actual);
error CommitmentTooLong(uint64 until, uint64 max);
error CommitmentActive(uint256 orderId, uint64 until);
error ETHAmountMismatch(uint256 required, uint256 sent);
error NFTTransferFailed(address token, uint256 tokenId);
error BalanceMismatch(uint256 expected, uint256 received);
error InsufficientOutput(uint256 minimum, uint256 actual);
error NotMaker(uint256 orderId, address caller, address maker);
error NotCounterparty(uint256 orderId, address caller, address counterparty);
error BalanceDeltaMismatch(address token, address account, uint256 expected, uint256 actual);
/// @dev Use the chain's canonical WETH deployment.
constructor(address _weth) {
if (_weth == address(0)) revert ZeroAddress();
if (_weth.code.length == 0) revert NotAContract(_weth);
weth = _weth;
METADATA_RENDERER = new SwapboardMetadata();
}
// ------------------------------------------------------ POSITION RECEIPTS
/// @dev Marks this collection as a LIVE CLAIM rather than an inert
/// collectible: `bytes4(keccak256("LiveOrderPosition()"))`.
///
/// A position can be filled by anyone at any time, which pays its
/// proceeds to whoever holds it and closes it. That is fine for a
/// wallet and wrong for an escrow: a contract holding the position as
/// inert collateral receives tokens it has no accounting for, and
/// finds the token it was holding is now a spent ticket with no claim
/// left in it - the receipt survives a close, but its value does not.
/// An escrow that cannot recover proceeds should refuse anything
/// declaring this; Swapboard does so at creation, on both legs.
bytes4 internal constant LIVE_ORDER_POSITION = 0x28a93a2e;
/// @dev The ERC-721 interface id: the XOR of the interface's function
/// selectors, as ERC-165 defines it. NOT `keccak256("ERC721")`.
bytes4 internal constant ERC721_INTERFACE = 0x80ac58cd;
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return interfaceId == LIVE_ORDER_POSITION || super.supportsInterface(interfaceId);
}
/// @dev A bounded ERC-165 probe. Anything that does not implement ERC-165
/// simply does not declare the interface, so a failed answer reads as
/// "no" rather than refusing every ordinary token. The word is read
/// directly rather than `abi.decode`d: a noncanonical boolean would
/// make the decoder REVERT, turning a malformed answer into a refusal
/// of the whole order - the opposite of the intended leniency. Only a
/// clean 1 is affirmative.
function _declares(address token, bytes4 interfaceId) internal view returns (bool yes) {
assembly ("memory-safe") {
let p := mload(0x40)
mstore(p, shl(224, 0x01ffc9a7)) // supportsInterface(bytes4)
mstore(add(p, 4), interfaceId)
if staticcall(30000, token, p, 0x24, 0, 0x20) {
yes := and(eq(returndatasize(), 32), eq(mload(0), 1))
}
}
}
/// @dev Refuse a live claim on EITHER leg, for the reason above.
///
/// tokenA is the obvious half: it is held by this board between
/// creation and settlement, and while it sits here anyone may fill the
/// underlying order - paying proceeds to this board, which has no
/// accounting for them, and emptying the very claim backing the
/// escrow.
///
/// tokenB is refused too, and it took an exploit to see why. An order
/// that ASKS for position P commits to P's claim as its price, but
/// settlement can only check that the token id moved - not what it was
/// still worth. The seller cancels P (or reprices it to dust) in the
/// same transaction, hands over the spent ticket, and takes the
/// escrow. Nothing on this board can price a claim whose value its
/// holder controls right up to the moment of delivery, so the trade is
/// refused rather than sold with a warning. A position still trades
/// fine where the buyer takes CUSTODY first - an escrow or auction
/// that holds the receipt becomes the maker, and the seller loses
/// exactly the control this check cannot verify.
///
/// WHAT THIS DOES NOT COVER. It catches contracts that VOLUNTARILY
/// declare the interface, which makes it a defence against accidents
/// between well-behaved boards and nothing more. The hazard it
/// describes is far wider than the set it detects: a Uniswap V3 or V4
/// LP NFT, a vault receipt, a staking or vesting position - any
/// value-bearing NFT - can be emptied by its holder right up to
/// delivery, and none of them declare anything here. A hostile board
/// simply would not declare it, and the 30,000 gas cap means even an
/// honest-looking one can force a `false` by making
/// `supportsInterface` expensive. Makers asking for an NFT as payment
/// must judge that asset themselves; a front end taking a
/// value-bearing NFT as `tokenB` needs an allowlist and a warning, not
/// this check.
function _checkEscrowable(address token) internal view {
if (_declares(token, LIVE_ORDER_POSITION)) revert LiveClaimNotEscrowable(token);
}
/// @dev Refuse an ERC-721 on a leg the caller declared fungible.
///
/// `nftA`/`nftB` are caller-supplied and were taken on trust. ERC-20
/// and ERC-721 share both `balanceOf(address)` and
/// `transferFrom(address,address,uint256)`, so escrowing token id 1 of
/// a collection with `nftA = false` PASSES the exact-delta check: the
/// board's holdings rise by one token, which is exactly the amount
/// asked for. The order then rests as a fungible one, and every exit
/// from it - fill, cancel, sweep, shrink - calls `transfer(address,
/// uint256)`, which no ERC-721 implements. The NFT is locked forever;
/// this board has no rescue path. One staticcall at creation is a
/// cheap price for that.
///
/// It only sees collections that implement ERC-165, so it is an
/// accident guard rather than a guarantee. When it misses, the lock it
/// describes is permanent and this board has no rescue path - which is
/// the other half of why assets belong on an allowlist.
function _checkFungible(address token) internal view {
if (_declares(token, ERC721_INTERFACE)) revert ExpectedERC20(token);
}
function name() public pure override returns (string memory) {
return "Swapboard Position";
}
function symbol() public pure override returns (string memory) {
return "SBPOS";
}
/// @notice Live, self-contained metadata for the order receipt.
/// @dev The image deliberately uses raw base units and shortened asset
/// addresses: those are exact, chain-native facts which need no token
/// metadata call and cannot go stale. WNS is best-effort only.
function tokenURI(uint256 orderId) public view override returns (string memory) {
ownerOf(orderId); // Standard ERC-721 behaviour: nonexistent IDs have no metadata.
// The renderer reads the order for itself through the getters above.
// Assembling its twenty-field parameter struct HERE, and encoding two
// dynamic strings into the call, cost 1,242 bytes of runtime code on
// the one contract in this pair with no EIP-170 headroom to spend. It
// is a view path either way; see `SwapboardMetadata.tokenURI`.
return METADATA_RENDERER.tokenURI(address(this), orderId);
}
function _rememberDecimals(address token) internal {
if (tokenDecimals[token] != 0) return;
(bool known, uint8 decimals) = PositionSVG.readDecimals(token);
if (known) tokenDecimals[token] = decimals + 1;
}
function _rememberSymbol(address token) internal {
if (bytes(tokenSymbols[token]).length == 0) tokenSymbols[token] = PositionSVG.readSymbol(token);
}
/// @dev The transfer that hands control OUT is the one that needs guarding:
/// `safeTransferFrom` calls the recipient AFTER `_afterTokenTransfer`
/// has already made them the maker, inside the sender's transaction,
/// so an unguarded hook could act as maker mid-transfer. Nothing is
/// lost by it - the callee is the legitimate new owner - but it is one
/// fewer way to leave a marketplace holding surprising state.
///
/// The guard goes HERE ONLY, not on `transferFrom` as well. Solady's
/// safe variants reach the transfer through the public, virtual
/// `transferFrom`, so a guard on both would nest on every safe
/// transfer and revert as reentrancy - bricking every push listing and
/// every ERC-721-safe integration. A plain `transferFrom` makes no
/// external call and so has nothing to guard against; settlement
/// caches `maker` before it ever gives anyone control, which is what
/// makes a mid-flight change of owner harmless there.
function safeTransferFrom(address from, address to, uint256 id) public payable override nonReentrant {
super.safeTransferFrom(from, to, id);
}
function safeTransferFrom(address from, address to, uint256 id, bytes calldata data)
public
payable
override
nonReentrant
{
super.safeTransferFrom(from, to, id, data);
}
/// @dev Solady makes the ERC-721 mutators payable for the gas saving, and
/// `receive()`'s WETH-only rule does not apply when calldata selects a
/// payable function - so ETH attached to a transfer or an approval
/// lands here, where there is no rescue path for it. Refuse it.
///
/// Guarding `transferFrom` covers all three transfer entry points:
/// Solady's safe variants reach the move by calling this same function
/// in the SAME frame, where `msg.value` is still whatever the caller
/// attached. This is a value check, not a reentrancy guard - that
/// distinction is what keeps it from bricking safe transfers.
function transferFrom(address from, address to, uint256 id) public payable override {
if (msg.value != 0) revert UnexpectedETH();
super.transferFrom(from, to, id);
}
function approve(address account, uint256 id) public payable override {
if (msg.value != 0) revert UnexpectedETH();
super.approve(account, id);
}
/// @dev Ownership IS makership. Rather than teach settlement to consult
/// `ownerOf`, the stored `maker` is kept in step on every transfer, so
/// payout, cancellation and repricing keep working exactly as before
/// and there is only ever one source of truth. Minting sets it in
/// `_store`; burning is a close, where it must not be cleared because
/// `maker == address(0)` is how a nonexistent order is recognised.
///
/// No separate event: makership changes exactly when the receipt
/// moves, so the ERC-721 `Transfer` log IS the maker-change log, and a
/// second one would be the same fact twice. Indexers should join
/// `Transfer` against order state rather than expect an order event.
function _afterTokenTransfer(address from, address to, uint256 id) internal override {
if (from != address(0) && to != address(0)) {
_checkMaker(to);
orders[id].maker = to;
// `frozenUntil` is deliberately NOT cleared here; see its docs. A
// commitment that ended with the seller's ownership could be voided
// by round-tripping the receipt through a second wallet and
// cancelling from there, which is exactly the move it exists to
// rule out.
}
}
/// @dev Only WETH may send ETH through an ordinary call.
receive() external payable {
if (msg.sender != weth) revert NotWETH(weth, msg.sender);
}
/// @dev The word a push payload must open with before this board reads the
/// rest of it as terms.
///
/// LENGTH ALONE IS NOT CONSENT. A wallet, bridge or marketplace that
/// attaches its own metadata to a `safeTransferFrom` and happens to
/// land on the right size would have it decoded as an order, and a
/// blob whose words happen to fall on a real `tokenB` with a small
/// `amountB` becomes a live order at a price its sender never chose.
/// Most such payloads revert on one of the checks below; "most" is not
/// the standard an irreversible escrow should be held to. A
/// domain-separated prefix makes the intent explicit and sends
/// everything else back to the original refusal.
bytes32 internal constant PUSH_ORDER_MAGIC = keccak256("Swapboard.PushOrder.v1");
/// @notice Terms carried in a pushed NFT's transfer data.
/// @dev Exactly five words, behind `PUSH_ORDER_MAGIC`. `tokenA` is not
/// present: the collection is established by the call itself, not by
/// anything the sender writes.
struct PushOrder {
address tokenB;
uint256 amountB;
uint64 expiry;
bool nftB;
address counterparty;
}
/// @notice Create an order from an NFT pushed with `safeTransferFrom`,
/// carrying its terms in `data`. One transaction, no approval.
///
/// @dev This board previously refused every incoming 721. It accepts one
/// now ONLY when the transfer carries well-formed terms, and an
/// unsolicited push still reverts with the original error - a token
/// sent here by mistake is rejected rather than silently escrowed with
/// no owner.
///
/// THE COLLECTION IS THE CALLER. `tokenA` is `msg.sender`, so the
/// sender cannot name a collection they do not control; the only way
/// to be a collection here is for the collection to make the call.
///
/// OWNERSHIP IS VERIFIED, NOT MOVED. The token is already here by the
/// time this runs, so there is nothing to transfer - and attempting a
/// transfer would be the bug. `ownerOf` establishes that the token
/// arrived at all; `escrowedNFT` establishes that THIS call is what
/// put it here rather than an earlier order, which is the part
/// `ownerOf` alone cannot answer. See that mapping for why the
/// difference matters.
///
/// A fabricated collection can of course report whatever it likes and
/// mint an order backed by its own worthless token. That is not an
/// attack on this board or on anyone's escrow: it is an order nobody
/// has to fill, indistinguishable from listing any other worthless
/// asset, and it is the taker's job to know what they are buying.
///
/// PARTIAL FILLS ARE REFUSED, as for any NFT-sided order: an ERC-721
/// is indivisible and settles only at its full ask.
function onERC721Received(address, address from, uint256 tokenId, bytes calldata data)
external
nonReentrant
returns (bytes4)
{
// No terms means this was not a deliberate order, so keep the old
// behaviour and refuse it.
if (data.length != 192) revert DirectNFTTransfer();
if (bytes32(data[:32]) != PUSH_ORDER_MAGIC) revert DirectNFTTransfer();
PushOrder memory o = abi.decode(data[32:], (PushOrder));
address tokenA = msg.sender;
// This board is itself an ERC-721 now, so a position pushed back here
// would try to escrow the board's own receipt against itself.
if (tokenA == address(this)) revert BadMaker();
// `from` becomes the maker, and a maker is a payout address: the same
// addresses refused at creation are refused here.
_checkMaker(from);
if (tokenA.code.length == 0) revert NotAContract(tokenA);
// A sibling board's position is a live claim, and this leg is escrowed.
_checkEscrowable(tokenA);
if (o.tokenB == address(0)) revert ZeroAddress();
if (o.tokenB.code.length == 0) revert NotAContract(o.tokenB);
// A live claim is no more acceptable as the price here than at creation.
_checkEscrowable(o.tokenB);
if (!o.nftB) _checkFungible(o.tokenB);
// tokenId 0 is a legitimate NFT, so only a fungible side is checked.
if (!o.nftB && o.amountB == 0) revert ZeroAmount();
// Two fungible legs in one token would be a no-op trade; here tokenA is
// always an NFT, so a shared collection is a legitimate 721-for-721
// swap and only the degenerate same-id case needs refusing - which the
// payment leg's ownerOf preflight already does at fill time.
_checkExpiry(o.expiry);
// Not already backing a live order here, and actually present.
if (escrowedNFT[tokenA][tokenId] || IERC721(tokenA).ownerOf(tokenId) != address(this)) {
revert NFTTransferFailed(tokenA, tokenId);
}
_store(from, tokenA, tokenId, o.tokenB, o.amountB, false, o.expiry, true, o.nftB, o.counterparty);
return this.onERC721Received.selector;
}
// ----------------------------------------------------------------- CREATE
function createOrder(
address tokenA,
uint256 amountA,
address tokenB,
uint256 amountB,
bool partialFill,
uint64 expiry,
bool nftA,
bool nftB,
address counterparty
) external nonReentrant returns (uint256 orderId) {
orderId = _createOrder(
msg.sender, tokenA, amountA, tokenB, amountB, partialFill, expiry, nftA, nftB, counterparty
);
}
/// @notice Create a fully funded order owned by `maker`.
/// @dev The caller supplies the escrow; cancellation and payouts go to `maker`.
///
/// MAKERSHIP IS UNSOLICITED HERE. `maker` does not consent, so a
/// position can appear in any wallet, and a contract maker that opts
/// into `acceptsOrderProceeds` will receive `beforeOrderProceeds` /
/// `afterOrderProceeds` for an order it never created, on a `tokenB`
/// and `amountB` the attacker chose. `ownerOf(orderId) == address(this)`
/// passes for that order too, so it is NOT a sufficient check: an
/// integrating escrow or vault must validate `orderId` against its own
/// records of orders it created, and treat anything else as a
/// donation.
function createOrderFor(
address maker,
address tokenA,
uint256 amountA,
address tokenB,
uint256 amountB,
bool partialFill,
uint64 expiry,
bool nftA,
bool nftB,
address counterparty
) external nonReentrant returns (uint256 orderId) {
orderId = _createOrder(maker, tokenA, amountA, tokenB, amountB, partialFill, expiry, nftA, nftB, counterparty);
}
/// @dev Atomic: if any creation reverts, the whole batch reverts.
/// @notice Create several orders in one transaction.
function createOrders(CreateOrderParams[] calldata params)
external
nonReentrant
returns (uint256[] memory orderIds)
{
orderIds = new uint256[](params.length);
for (uint256 i; i < params.length; ++i) {
orderIds[i] = _createOrder(
msg.sender,
params[i].tokenA,
params[i].amountA,
params[i].tokenB,
params[i].amountB,
params[i].partialFill,
params[i].expiry,
params[i].nftA,
params[i].nftB,
params[i].counterparty
);
}
}
/// @dev tokenA is always WETH here, so nftA is necessarily false.
function createOrderWithEth(
address tokenB,
uint256 amountB,
bool partialFill,
uint64 expiry,
bool nftB,
address counterparty
) external payable nonReentrant returns (uint256 orderId) {
orderId = _createOrderWithEth(msg.sender, tokenB, amountB, partialFill, expiry, nftB, counterparty);
}
/// @notice Pay ETH from the caller while crediting the wrapped order to
/// `maker`. The same sponsorship semantics as createOrderFor apply.
function createOrderWithEthFor(
address maker,
address tokenB,
uint256 amountB,
bool partialFill,
uint64 expiry,
bool nftB,
address counterparty
) external payable nonReentrant returns (uint256 orderId) {
orderId = _createOrderWithEth(maker, tokenB, amountB, partialFill, expiry, nftB, counterparty);
}
function _createOrderWithEth(
address maker,
address tokenB,
uint256 amountB,
bool partialFill,
uint64 expiry,
bool nftB,
address counterparty
) internal returns (uint256 orderId) {
_checkMaker(maker);
if (msg.value == 0) revert ZeroETH();
if (tokenB == address(0)) revert ZeroAddress();
if (!nftB && amountB == 0) revert ZeroAmount();
if (nftB && partialFill) revert NFTNotDivisible();
if (tokenB == weth) revert SameToken();
if (tokenB.code.length == 0) revert NotAContract(tokenB);
_checkEscrowable(tokenB);
if (!nftB) _checkFungible(tokenB);
_checkExpiry(expiry);
_wrapETH(msg.value);
orderId = _store(maker, weth, msg.value, tokenB, amountB, partialFill, expiry, false, nftB, counterparty);
}
function _createOrder(
address maker,
address tokenA,
uint256 amountA,
address tokenB,
uint256 amountB,
bool partialFill,
uint64 expiry,
bool nftA,
bool nftB,
address counterparty
) internal returns (uint256 orderId) {
if (tokenA == address(0) || tokenB == address(0)) revert ZeroAddress();
_checkMaker(maker);
// tokenId 0 is a legitimate NFT, so only fungible sides are checked.
if (!nftA && amountA == 0) revert ZeroAmount();
if (!nftB && amountB == 0) revert ZeroAmount();
// An ERC-721 cannot be split, so it cannot rest as a partial order.
if ((nftA || nftB) && partialFill) revert NFTNotDivisible();
// Two fungible legs in the same token are a no-op trade. One collection
// on both sides is not: it is an NFT-for-NFT swap, and the two tokenIds
// are what differ. The degenerate case where they are the same tokenId
// needs no check here - the escrowed token is owned by the board by
// then, so the payment leg's `ownerOf != from` preflight refuses it.
if (tokenA == tokenB && !(nftA || nftB)) revert SameToken();
if (tokenA.code.length == 0) revert NotAContract(tokenA);
// tokenA is escrowed here until settlement, so it must be inert; tokenB
// is the price, and a claim its seller can empty is not a price.
_checkEscrowable(tokenA);
if (tokenB.code.length == 0) revert NotAContract(tokenB);
_checkEscrowable(tokenB);
// The nft flags are the caller's word; a fungible leg has to earn it.
if (!nftA) _checkFungible(tokenA);
if (!nftB) _checkFungible(tokenB);
_checkExpiry(expiry);
if (nftA) {
if (escrowedNFT[tokenA][amountA]) revert NFTTransferFailed(tokenA, amountA);
_moveNFT(tokenA, msg.sender, address(this), amountA);
} else {
// A fee-on-transfer token would leave the escrow short of amountA,
// so what actually arrived is measured rather than assumed - and
// what left the payer with it.
_pullToken(tokenA, address(this), amountA);
}
orderId = _store(maker, tokenA, amountA, tokenB, amountB, partialFill, expiry, nftA, nftB, counterparty);
}
/// @dev Confirm ownership before and after `transferFrom`.
function _moveNFT(address token, address from, address to, uint256 tokenId) internal {
if (IERC721(token).ownerOf(tokenId) != from) revert NFTTransferFailed(token, tokenId);
IERC721(token).transferFrom(from, to, tokenId);
if (IERC721(token).ownerOf(tokenId) != to) revert NFTTransferFailed(token, tokenId);
}
/// @dev An NFT already owned by the maker is treated as returned; otherwise
/// confirm board ownership before transferring it back.
function _returnNFT(address token, address to, uint256 tokenId) internal {
address owner = IERC721(token).ownerOf(tokenId);
if (owner == to) return;
if (owner != address(this)) revert NFTTransferFailed(token, tokenId);
IERC721(token).transferFrom(address(this), to, tokenId);
if (IERC721(token).ownerOf(tokenId) != to) revert NFTTransferFailed(token, tokenId);
}
/// @dev The balance of `account`, where `address(0)` means native ETH. One
/// reader so every leg below measures the same way.
function _balanceOf(address token, address account) internal view returns (uint256) {
return token == address(0) ? account.balance : token.balanceOf(account);
}
/// @dev "This balance moved by exactly `amount`, or revert" - the single
/// form of the check every transfer leg runs. Deltas are measured
/// rather than assumed because a fee-on-transfer token, on either
/// side, would otherwise leave pooled escrow short of what the orders
/// resting against it are owed.
function _expectDelta(address token, address account, uint256 previous, uint256 amount, bool credit) internal view {
uint256 current = _balanceOf(token, account);
uint256 delta = credit ? _increase(previous, current) : _decrease(previous, current);
if (delta != amount) revert BalanceDeltaMismatch(token, account, amount, delta);
}
/// @dev Confirm exact board debit and recipient credit for pooled escrow.
function _sendEscrowToken(address token, address to, uint256 amount) internal {
uint256 boardBefore = token.balanceOf(address(this));
uint256 recipientBefore = token.balanceOf(to);
token.safeTransfer(to, amount);
_expectDelta(token, address(this), boardBefore, amount, false);
_expectDelta(token, to, recipientBefore, amount, true);
}
/// @dev Every fungible pull, measured on BOTH sides: the payer is debited by
/// the nominal amount and the recipient credited by it.
///
/// Measuring only the credit catches a receiver-tax token but not a
/// SENDER-tax one, which debits `amount + fee` and credits exactly
/// `amount` - the payer loses more than the amount they authorised
/// through this board's parameters, and the check waves it through.
/// Both ends are measured so the number in the order is the number
/// that leaves the payer's balance.
///
/// The arrival leg keeps `BalanceMismatch`, which is the error creation
/// and repricing have always reported for a short delivery; a
/// sender-side discrepancy is a `BalanceDeltaMismatch` naming the payer.
///
/// The payer is always `msg.sender` - this board never moves tokens
/// between two third parties.
///
/// A maker filling their OWN fungible order lands here with payer and
/// recipient equal, so the transfer nets to nothing and this reverts
/// with `BalanceMismatch(amount, 0)`. That is the correct outcome -
/// self-filling is a cancellation written the expensive way - but the
/// error names the symptom rather than the cause; front ends should
/// steer a maker to `cancelOrder` instead.
function _pullToken(address token, address to, uint256 amount) internal {
uint256 senderBefore = token.balanceOf(msg.sender);
uint256 recipientBefore = token.balanceOf(to);
token.safeTransferFrom(msg.sender, to, amount);
uint256 received = _increase(recipientBefore, token.balanceOf(to));
if (received != amount) revert BalanceMismatch(amount, received);
_expectDelta(token, msg.sender, senderBefore, amount, false);
}
/// @dev Confirm the exact WETH credit from wrapping.
function _wrapETH(uint256 amount) internal {
uint256 beforeBalance = weth.balanceOf(address(this));
IWETH(weth).deposit{value: amount}();
_expectDelta(weth, address(this), beforeBalance, amount, true);
}
/// @dev Confirm exact WETH debit and native ETH credit.
function _unwrapETH(uint256 amount) internal {
uint256 wethBefore = weth.balanceOf(address(this));
uint256 ethBefore = address(this).balance;
IWETH(weth).withdraw(amount);
_expectDelta(weth, address(this), wethBefore, amount, false);
_expectDelta(address(0), address(this), ethBefore, amount, true);
}
function _increase(uint256 beforeBalance, uint256 afterBalance) internal pure returns (uint256 delta) {
if (afterBalance >= beforeBalance) {
unchecked {
delta = afterBalance - beforeBalance;
}
}
}
function _decrease(uint256 beforeBalance, uint256 afterBalance) internal pure returns (uint256 delta) {
if (beforeBalance >= afterBalance) {
unchecked {
delta = beforeBalance - afterBalance;
}
}
}
/// @dev Maker receives escrow and fill proceeds, so the board and WETH are
/// invalid maker addresses.
function _checkMaker(address maker) internal view {
if (maker == address(0)) revert ZeroAddress();
if (maker == address(this) || maker == weth) revert BadMaker();
}
/// @dev Creation requires a nonzero expiry to be in the future.
function _checkExpiry(uint64 expiry) internal view {
if (expiry != 0 && expiry <= block.timestamp) revert ExpiryInPast(expiry);
}
function _store(
address maker,
address tokenA,
uint256 amountA,
address tokenB,
uint256 amountB,
bool partialFill,
uint64 expiry,
bool nftA,
bool nftB,
address counterparty
) internal returns (uint256 orderId) {
unchecked {
orderId = nextOrderId++;
}
orders[orderId] =
Order(maker, true, partialFill, expiry, nftA, nftB, counterparty, tokenA, amountA, tokenB, amountB);
initialAmountB[orderId] = amountB;
// The board's own record of what it holds, and for whom.
if (nftA) escrowedNFT[tokenA][amountA] = true;
// Both readings, for both legs. A ticker is what a reader recognises and
// a scale is what makes the amount above it parseable; a fungible leg
// used to carry only a truncated address and a decimal count.
if (!nftA) _rememberDecimals(tokenA);
_rememberSymbol(tokenA);
if (!nftB) _rememberDecimals(tokenB);
_rememberSymbol(tokenB);
// The position itself is the receipt. Minted with `_mint`, never
// `_safeMint`: a receiver hook here would hand control to the maker in
// the middle of order creation, which is the callback-mid-settlement
// hazard this board avoids everywhere else.
_mint(maker, orderId);
emit OrderCreated(
orderId, maker, tokenA, amountA, tokenB, amountB, partialFill, expiry, nftA, nftB, counterparty
);
}
// ------------------------------------------------------------------- FILL
/// @param fillAmountB Fungible payment amount; it must be explicit and nonzero.
/// A zero full-fill sentinel is retained only for NFT orders, where an
/// amount can be token ID zero and NFT orders cannot be repriced.
/// @param minAmountA Minimum fungible tokenA output; zero disables the floor.
/// Ignored for NFT tokenA, whose amount is a token ID.
/// @param recipient Where tokenA is delivered. address(0) means the caller.
/// This is a delivery address only - it is NEVER used for
/// authorisation. `counterparty` is still checked against msg.sender,
/// because a caller-supplied recipient could otherwise be set to the
/// intended counterparty and drain every private order.
function fillOrder(uint256 orderId, uint256 deadline, uint256 fillAmountB, uint256 minAmountA, address recipient)
external
nonReentrant
{
_checkDeadline(deadline);
_fill(orderId, fillAmountB, minAmountA, 0, _to(recipient));
}
/// @dev Atomic: if any fill reverts, the whole batch reverts. Each
/// `minAmountsA[i]` protects the corresponding order.
/// @notice Fill several orders atomically; any failure aborts the batch.
/// Use tryFillOrders to skip rather than revert.
function fillOrders(
uint256[] calldata orderIds,
uint256 deadline,
uint256[] calldata fillAmountsB,
uint256[] calldata minAmountsA,
address recipient
) external nonReentrant {
_checkDeadline(deadline);
if (orderIds.length != fillAmountsB.length || orderIds.length != minAmountsA.length) {
revert LengthMismatch();
}
address to = _to(recipient);
for (uint256 i; i < orderIds.length; ++i) {
_fill(orderIds[i], fillAmountsB[i], minAmountsA[i], 0, to);
}
}
/// @dev Skips orders that are inactive, missing, expired, frozen, or
/// reserved for a different counterparty.
///
/// IT DOES NOT MAKE A HOSTILE ORDER SAFE. Every other revert path
/// still aborts the batch, and a maker that opts into proceeds
/// notification gets a full-gas call during settlement whose revert
/// bubbles all the way out - so anyone willing to escrow a little dust
/// can plant an order that kills a router's whole batch. Catching that
/// needs an external self-call per leg, and this contract has no
/// EIP-170 headroom left to buy one; see the size note in
/// `foundry.toml`. Callers that fill orders they did not choose should
/// screen makers themselves, or fill one at a time.
///
/// Minimum-output failures are deliberately NOT skipped either: the
/// floor is the taker's own and silently stepping over it would turn a
/// slippage guarantee into a partial route.
function tryFillOrders(
uint256[] calldata orderIds,
uint256 deadline,
uint256[] calldata fillAmountsB,
uint256[] calldata minAmountsA,
address recipient
) external nonReentrant returns (bool[] memory filled) {
_checkDeadline(deadline);
if (orderIds.length != fillAmountsB.length || orderIds.length != minAmountsA.length) {
revert LengthMismatch();
}
address to = _to(recipient);
filled = new bool[](orderIds.length);
for (uint256 i; i < orderIds.length; ++i) {
Order storage o = orders[orderIds[i]];
address cp = o.counterparty;
// Frozen belongs with the other not-fillable-right-now states: it
// is temporary and outside the taker's control, exactly what this
// variant exists to step over rather than abort on.
if (o.active && !_expired(o.expiry) && !frozen(orderIds[i]) && (cp == address(0) || cp == msg.sender)) {
_fill(orderIds[i], fillAmountsB[i], minAmountsA[i], 0, to);
filled[i] = true;
}
}
}
/// @notice Fill and receive tokenA as ETH rather than WETH. Reverts unless
/// tokenA is WETH; ignored when tokenA is an NFT.
/// @param minAmountA Minimum WETH output; zero disables the floor.
function fillOrderUnwrap(
uint256 orderId,
uint256 deadline,
uint256 fillAmountB,
uint256 minAmountA,
address recipient
) external nonReentrant {
_checkDeadline(deadline);
_fill(orderId, fillAmountB, minAmountA, 1, _to(recipient));
}
/// @dev msg.value is the fill amount and is wrapped before settlement, so a
/// value above the remaining amountB is refused rather than refunded.
///
/// The prepaid path accepts a short payment only for a divisible partial
/// order. NFT-A and all-or-nothing orders must arrive exactly paid. _fill
/// independently rejects those short fills; checking here gives the ETH path
/// its specific ETHAmountMismatch error before wrapping the caller's value.
/// @param minAmountA Minimum fungible tokenA output; zero disables the floor.
/// Ignored for NFT tokenA.
function fillOrderWithEth(uint256 orderId, uint256 deadline, uint256 minAmountA, address recipient)
external
payable
nonReentrant
{
_checkDeadline(deadline);
if (msg.value == 0) revert ZeroETH();
Order storage order = orders[orderId];
if (order.tokenB != weth) revert NotWETH(weth, order.tokenB);
// amountB is a tokenId when nftB, so it is not a price to pay in ETH and
// the wrapped value would be stranded while the 721 leg pulled instead.
if (order.nftB) revert NFTNotDivisible();
uint256 owed = order.amountB;
if (msg.value > owed) revert ETHAmountMismatch(owed, msg.value);
if (msg.value < owed && (order.nftA || !order.partialFill)) {
revert ETHAmountMismatch(owed, msg.value);
}
_wrapETH(msg.value);
_fill(orderId, msg.value, minAmountA, 2, _to(recipient));
}
/// @dev mode bit 0 unwraps tokenA as ETH; mode bit 1 uses pre-wrapped WETH
/// for tokenB. Packing these path flags keeps this settlement routine
/// below the compiler's stack limit after adding the output floor.
function _fill(uint256 orderId, uint256 fillAmountB, uint256 minAmountA, uint256 mode, address to) internal {
(Order storage order, address maker) = _live(orderId);
// Maker-side expiry. Distinct from the `deadline` argument above, which
// guards the taker against a stale mempool transaction.
if (_expired(order.expiry)) revert OrderExpired(orderId);
if (frozen(orderId)) revert OrderFrozen(orderId);
address cp = order.counterparty;
if (cp != address(0) && cp != msg.sender) revert NotCounterparty(orderId, msg.sender, cp);
(uint256 outA, uint256 paidB, bool full) = _applyFill(orderId, order, fillAmountB);
// A taker signs this floor before the transaction enters the public
// mempool. It therefore remains protected if the maker reprices the
// live order before this call executes. NFT token IDs are not amounts,
// so the floor applies only to fungible tokenA legs.
if (!order.nftA && outA < minAmountA) revert InsufficientOutput(minAmountA, outA);
_settleFill(
FillLegs(orderId, order.tokenA, order.tokenB, maker, to, outA, paidB, mode, order.nftA, order.nftB)
);
if (full) {
emit OrderFilled(orderId, msg.sender, maker, outA, paidB);
} else {
emit OrderPartiallyFilled(orderId, msg.sender, maker, outA, paidB, order.amountA, order.amountB);
}
}
/// @dev Refusal codes from `_computeFill`, mapped to this board's errors by
/// settlement and to a zero quote by the view.
uint256 internal constant FILL_OK = 0;
uint256 internal constant FILL_ZERO = 1;
uint256 internal constant FILL_INDIVISIBLE = 2;
/// @dev The fill arithmetic, and the single place it is written. Settlement
/// and `quoteFill` both run it, so a splitter's plan cannot disagree
/// with what the fill actually pays - which is the whole point of
/// quoting on the board rather than rederiving the rounding off chain.
/// It touches no storage: the caller reads the terms and, if it is
/// settling, writes the result back.
function _computeFill(uint256 amountA, uint256 amountB, bool nftA, bool nftB, bool partialFill, uint256 fillAmountB)
internal
pure
returns (uint256 outA, uint256 paidB, bool full, uint256 err)
{
// NFT orders always settle in full. Their amount fields may be token IDs,
// so zero remains the explicit full-fill sentinel for either NFT side.
// Fungible orders must receive an explicit payment amount: resolving zero
// against the live order would let a maker reprice the taker's input after
// the taker signed a transaction.
if (fillAmountB == 0 && !nftA && !nftB) return (0, 0, false, FILL_ZERO);
if (fillAmountB != 0) {
if (nftB && fillAmountB != amountB) return (0, 0, false, FILL_INDIVISIBLE);
if (nftA && fillAmountB < amountB) return (0, 0, false, FILL_INDIVISIBLE);
}
if (nftA || nftB || fillAmountB >= amountB) return (amountA, amountB, true, FILL_OK);
if (!partialFill) return (0, 0, false, FILL_INDIVISIBLE);
// Rounds down, favouring the maker. Full precision so large
// 18-decimal amounts cannot overflow the intermediate product.
outA = FixedPointMathLib.fullMulDiv(fillAmountB, amountA, amountB);
if (outA == 0) return (0, 0, false, FILL_ZERO);
return (outA, fillAmountB, false, FILL_OK);
}
/// @dev Apply fill arithmetic and update the order before any external
/// transfer. Keeping this in its own frame avoids stack pressure in
/// the settlement routine, which also carries the slippage floor.
function _applyFill(uint256 orderId, Order storage order, uint256 fillAmountB)
internal
returns (uint256 outA, uint256 paidB, bool full)
{
uint256 amountA = order.amountA;
uint256 amountB = order.amountB;
uint256 err;
(outA, paidB, full, err) =
_computeFill(amountA, amountB, order.nftA, order.nftB, order.partialFill, fillAmountB);
if (err == FILL_ZERO) revert ZeroFillAmount();
if (err != FILL_OK) revert PartialFillNotAllowed(orderId);
if (full) {
order.active = false;
settled[orderId] = true;
order.amountA = 0;
order.amountB = 0;
// Deliberately NOT burned. A holder may be a contract that reads
// `ownerOf` - an escrow, a marketplace - and burning under it
// leaves that contract pointing at a token which no longer exists,
// with no path to recover whatever it was holding. The receipt
// survives a close as a spent ticket instead; `active` is what says
// whether it still has a claim.
} else {
order.amountA = amountA - outA;
order.amountB = amountB - paidB;
}
}
/// @dev Settlement arguments, grouped only so they occupy one stack slot
/// at the call site. `_fill` carries enough live locals that passing
/// these individually exhausts the stack under via-IR.
struct FillLegs {
uint256 orderId;
address tokenA;
address tokenB;
address maker;
address to;
uint256 outA;
uint256 fillAmountB;
uint256 mode;
bool nftA;
bool nftB;
}
/// @dev Both transfer legs, in their own frame. Ordering and confirmation
/// are unchanged from when this was inline: tokenB reaches the maker
/// first, then tokenA reaches the taker, and every leg is verified
/// rather than assumed.
function _settleFill(FillLegs memory f) internal {
// tokenB to the maker. On the ETH path it is already wrapped and held
// here. The 721 leg is the maker's payment, so it is confirmed rather
// than assumed: an unconfirmed no-op would hand the escrow over for
// nothing.
bool notifyProceeds = _beforeOrderProceeds(f.maker, f.orderId, f.tokenB, f.fillAmountB, f.nftB);
if (f.nftB) _moveNFT(f.tokenB, msg.sender, f.maker, f.fillAmountB);
else if ((f.mode & 2) != 0) _sendEscrowToken(f.tokenB, f.maker, f.fillAmountB);
else _pullToken(f.tokenB, f.maker, f.fillAmountB);
if (notifyProceeds) _afterOrderProceeds(f.maker, f.orderId, f.tokenB, f.fillAmountB, f.nftB);
// tokenA to the taker. Confirmed at both ends too: escrow can go
// missing between creation and fill on a collection that leaves a stale
// approval behind, and the taker has already paid by this point.
if (f.nftA) {
// An NFT leg always settles in full, so the escrow record is
// released here, with the token it tracked.
delete escrowedNFT[f.tokenA][f.outA];
_moveNFT(f.tokenA, address(this), f.to, f.outA);
} else if ((f.mode & 1) != 0) {
if (f.tokenA != weth) revert NotWETH(weth, f.tokenA);
_unwrapETH(f.outA);
f.to.safeTransferETH(f.outA);
} else {
_sendEscrowToken(f.tokenA, f.to, f.outA);
}
}
/// @dev Optional two-phase accounting for a maker that is also an escrow.
/// The bounded static probe preserves ordinary maker compatibility;
/// only an affirmative response opts into the stateful callbacks.
///
/// REVERT DATA IS COPIED WITH A BOUND. A maker that opts in and then
/// reverts takes the fill down either way, so the reason is only ever
/// read by a human - 256 bytes is enough to debug with, and copying
/// more charges the TAKER quadratic memory-expansion gas for a blob the
/// maker chose the size of. Bounding the copy is the part with no
/// honest victim; capping gas would not be, since a callback doing real
/// accounting needs it and a griefer who cannot burn gas can simply
/// revert instead. Dutchboard's `_notifyBeforeProceeds` bounds the same
/// copy for the same reason.
function _beforeOrderProceeds(address maker, uint256 orderId, address token, uint256 amount, bool nft)
internal
returns (bool notify)
{
assembly ("memory-safe") {
let p := mload(0x40)
mstore(p, shl(224, 0x33dbef94)) // acceptsOrderProceeds(uint256)
mstore(add(p, 4), orderId)
let accepted := staticcall(30000, maker, p, 0x24, 0, 0x20)
if and(accepted, eq(returndatasize(), 32)) {
notify := eq(mload(0), 1)
}
if notify {
mstore(p, shl(224, 0x8d27ed3f)) // beforeOrderProceeds(uint256,address,uint256,bool)
mstore(add(p, 4), orderId)
mstore(add(p, 36), token)
mstore(add(p, 68), amount)
mstore(add(p, 100), nft)
if iszero(call(gas(), maker, 0, p, 0x84, 0, 0x20)) {
let n := returndatasize()
if gt(n, 256) { n := 256 }
returndatacopy(p, 0, n)
revert(p, n)
}
notify := and(eq(returndatasize(), 32), eq(mload(0), 1))
}
}
}
function _afterOrderProceeds(address maker, uint256 orderId, address token, uint256 amount, bool nft) internal {
assembly ("memory-safe") {
let p := mload(0x40)
mstore(p, shl(224, 0x2814c622)) // afterOrderProceeds(uint256,address,uint256,bool)
mstore(add(p, 4), orderId)
mstore(add(p, 36), token)
mstore(add(p, 68), amount)
mstore(add(p, 100), nft)
if iszero(call(gas(), maker, 0, p, 0x84, 0, 0)) {
let n := returndatasize()
if gt(n, 256) { n := 256 }
returndatacopy(p, 0, n)
revert(p, n)
}
}
}
// ---------------------------------------------------------------- REPLACE
/// @notice Maker-only repricing and resizing for a live fungible order.
/// @dev Only amounts and expiry change; the order id, pair, permissions and
/// maker remain fixed. NFT orders are not replaceable. Escrow moves only
/// by the amount difference and uses the same exact transfer checks as
/// creation and cancellation. This method is not payable.
function replaceOrder(uint256 orderId, uint256 newAmountA, uint256 newAmountB, uint64 newExpiry)
external
nonReentrant
{
_replace(orderId, newAmountA, newAmountB, newExpiry);
}
/// @notice Reprice several orders atomically.
function replaceOrders(ReplaceOrderParams[] calldata params) external nonReentrant {
for (uint256 i; i < params.length; ++i) {
_replace(params[i].orderId, params[i].amountA, params[i].amountB, params[i].expiry);
}
}
function _replace(uint256 orderId, uint256 newAmountA, uint256 newAmountB, uint64 newExpiry) internal {
(Order storage order, address maker) = _liveOwned(orderId);
if (order.nftA || order.nftB) revert NFTNotReplaceable(orderId);
if (frozen(orderId)) revert OrderFrozen(orderId);
if (newAmountA == 0 || newAmountB == 0) revert ZeroAmount();
_checkExpiry(newExpiry);
address tokenA = order.tokenA;
uint256 amountA = order.amountA;
if (newAmountA > amountA) {
uint256 delta;
unchecked {
delta = newAmountA - amountA;
}
// Effects before the interaction. The exactness check below still
// holds - a mismatch reverts, taking this write with it - so
// ordering costs nothing and removes the need to reason about what
// a token callback could observe. Previously this wrote after the
// pull, safe only because every order-mutating entry point is
// guarded and the ERC-721 methods do not touch amounts.
(order.amountA, order.amountB, order.expiry) = (newAmountA, newAmountB, newExpiry);
initialAmountB[orderId] = newAmountB;
_pullToken(tokenA, address(this), delta);
} else {
uint256 delta;
unchecked {
delta = amountA - newAmountA;
}
(order.amountA, order.amountB, order.expiry) = (newAmountA, newAmountB, newExpiry);
initialAmountB[orderId] = newAmountB;
if (delta != 0) _sendEscrowToken(tokenA, maker, delta);
}
emit OrderReplaced(orderId, maker, newAmountA, newAmountB, newExpiry);
}
// ----------------------------------------------------------------- CANCEL
/// @notice Maker-only. Returns the unfilled escrow and closes the order.
function cancelOrder(uint256 orderId) external nonReentrant {
_cancel(orderId, false);
}
/// @notice Maker-only, all-or-nothing: one bad id aborts the batch.
function cancelOrders(uint256[] calldata orderIds) external nonReentrant {
for (uint256 i; i < orderIds.length; ++i) {
_cancel(orderIds[i], false);
}
}
/// @notice Cancel and take the escrow back as ETH. Requires tokenA = WETH.
function cancelOrderUnwrap(uint256 orderId) external nonReentrant {
_cancel(orderId, true);
}
/// @notice Sweeps expired orders, returning each escrow to its maker.
/// @dev Permissionless: funds go to the maker, so there is nothing to
/// capture. It exists so an expired order's escrow is never stranded behind
/// a maker who stopped watching, and so the book can be kept clean without
/// the maker paying to tidy it.
///
/// A FROZEN order is exempt. The freeze exists so an escrowed position is
/// inert while a sale is in flight, and that guarantee has to hold against
/// every permissionless path, not just fills: a sweep would close the order
/// under the escrow, return the backing to a holder with no accounting for
/// it, and leave the buyer paying for a spent ticket. A soft freeze is the
/// owner's own act and they can still cancel; a commitment lapses on its
/// own timestamp, after which the sweep applies again. Nothing is stranded
/// either way.
function cancelExpired(uint256[] calldata orderIds) external nonReentrant {
for (uint256 i; i < orderIds.length; ++i) {
uint256 orderId = orderIds[i];
(Order storage order, address maker) = _live(orderId);
if (!_expired(order.expiry)) revert OrderNotExpired(orderId);
if (frozen(orderId)) revert OrderFrozen(orderId);
_returnEscrow(order, maker, false);
emit OrderExpiredSwept(orderId, maker, msg.sender);
}
}
/// @notice Sweep variant that skips stale entries instead of reverting the
/// batch.
/// @dev A keeper reads the sweepable set, then submits; anything filled or
/// swept in between would abort an all-or-nothing sweep and clean nothing.
/// Same reasoning as tryFillOrders. Returns which ids were actually swept.
/// A settlement that reverts still aborts the batch - an escrow that cannot
/// be returned (a collection that refuses the transfer) strands the whole
/// sweep. Same EIP-170 reason as tryFillOrders above.
function trySweepExpired(uint256[] calldata orderIds) external nonReentrant returns (bool[] memory swept) {
swept = new bool[](orderIds.length);
for (uint256 i; i < orderIds.length; ++i) {
uint256 orderId = orderIds[i];
Order storage order = orders[orderId];
address maker = order.maker;
if (maker == address(0) || !order.active || !_expired(order.expiry) || frozen(orderId)) continue;
_returnEscrow(order, maker, false);
emit OrderExpiredSwept(orderId, maker, msg.sender);
swept[i] = true;
}
}
/// @notice Owner-only. Freeze an order so its claim cannot change.
/// @dev Freezing is what turns a position into a self-contained asset: no
/// taker can fill it and the owner cannot reprice it, so what a buyer
/// simulates is what they receive. Cancellation stays available,
/// because that is the owner's own escape and cannot surprise anyone
/// else - and an escrow that has TAKEN CUSTODY of the position IS the
/// owner. Selling without custody wants `commitFrozen` instead, which
/// is the same guarantee made to someone who is not yet the owner.
///
/// A live commitment is not lifted by thawing here; it outranks this
/// flag until it lapses.
function setFrozen(uint256 orderId, bool value) external nonReentrant {
_liveOwned(orderId);
_softFrozen[orderId] = value;
emit OrderFreezeSet(orderId, value);
}
/// @notice Owner-only. BIND the order until `until`: no fill, no sweep, no
/// repricing, no cancellation - by anyone, the owner included.
///
/// @dev The promise a soft freeze cannot make. A live commitment cannot be
/// touched at all - not by the owner, not by a later owner - so the
/// `frozenUntil` a buyer verifies is the whole window and not a floor
/// the seller can raise between simulation and settlement. It survives
/// transfer too, so it cannot be voided by handing the receipt to a
/// second wallet and cancelling from there. A new window may only be
/// opened once the previous one has lapsed.
///
/// Pick a window that outlasts the SALE, not the position, and pick it
/// RIGHT THE FIRST TIME: there is no early exit by any path, the
/// owner's included, and no way to lengthen it once made, so whatever
/// is committed here is genuinely immovable for exactly that long.
/// `MAX_COMMITMENT` bounds the damage of getting it wrong.
function commitFrozen(uint256 orderId, uint64 until) external nonReentrant {
_liveOwned(orderId);
uint64 live = frozenUntil[orderId];
if (block.timestamp < live) revert CommitmentActive(orderId, live);
if (until <= block.timestamp) revert ExpiryInPast(until);
uint64 max = uint64(block.timestamp) + MAX_COMMITMENT;
if (until > max) revert CommitmentTooLong(until, max);
frozenUntil[orderId] = until;
emit OrderCommitmentSet(orderId, until);
}
/// @dev The cancellation path's commitment check. Repricing reaches the
/// same rule through `frozen`, which folds in the soft flag as well;
/// cancellation cannot use that helper because a soft freeze must
/// still leave the owner their own escape.
function _checkNotCommitted(uint256 orderId) internal view {
uint64 until = frozenUntil[orderId];
if (block.timestamp < until) revert CommitmentActive(orderId, until);
}
function _cancel(uint256 orderId, bool unwrap) internal {
(Order storage order, address maker) = _liveOwned(orderId);
// A soft freeze leaves this open - it is the owner's own escape. A
// commitment does not: cancelling under a buyer is the exact move it
// exists to rule out.
_checkNotCommitted(orderId);
_returnEscrow(order, maker, unwrap);
emit OrderCanceled(orderId, maker);
}
/// @dev Close the order, then return the remaining escrow. Keeping the
/// last live terms makes the non-fungible receipt a useful terminal
/// record; `active` alone gates every state-changing path.
///
/// The amounts are deliberately NOT zeroed, unlike a full fill. That
/// asymmetry is the only thing distinguishing the two closes: a filled
/// order has both legs at zero. The receipt no longer infers the
/// difference from that: slot 0 is exactly full, so the `settled` flag
/// lives in its own mapping and `SwapboardMetadata` is told outright
/// which kind of close this was. Integrators must read `active`, not
/// `amountA`, to decide whether a claim is live.
function _returnEscrow(Order storage order, address maker, bool unwrap) internal {
address tokenA = order.tokenA;
uint256 amountA = order.amountA;
bool nftA = order.nftA;
order.active = false;
if (nftA) {
delete escrowedNFT[tokenA][amountA];
_returnNFT(tokenA, maker, amountA);
} else if (unwrap) {
if (tokenA != weth) revert NotWETH(weth, tokenA);
_unwrapETH(amountA);
maker.safeTransferETH(amountA);
} else {
_sendEscrowToken(tokenA, maker, amountA);
}
}
// ------------------------------------------------------------------- VIEW
/// @notice Batch read. Unknown ids come back zeroed rather than reverting,
/// so a stale id in a scan does not sink the whole page.
function getOrders(uint256[] calldata orderIds) external view returns (Order[] memory out) {
out = new Order[](orderIds.length);
for (uint256 i; i < orderIds.length; ++i) {
out[i] = orders[orderIds[i]];
}
}
/// @notice Batch read carrying the state that `orders` alone cannot report.
/// @dev `getOrders` returns the packed struct, and `frozen` deliberately
/// lives outside it, so a caller reading only that getter cannot tell a
/// fillable order from a frozen one. A router that plans over the book
/// needs both in the same page or it builds routes whose legs revert;
/// returning them together is what keeps the quote and the fill
/// agreeing. `isExpired` is likewise derived state a caller would
/// otherwise recompute against a stale timestamp.
function getOrdersWithState(uint256[] calldata orderIds)
external
view
returns (Order[] memory out, bool[] memory isFrozen, bool[] memory isExpired)
{
out = new Order[](orderIds.length);
isFrozen = new bool[](orderIds.length);
isExpired = new bool[](orderIds.length);
for (uint256 i; i < orderIds.length; ++i) {
out[i] = orders[orderIds[i]];
isFrozen[i] = frozen(orderIds[i]);
isExpired[i] = _expired(out[i].expiry);
}
}
/// @notice True when `taker` may fill `orderId` right now.
/// @dev Pass address(0) to ask only whether the order is live and public.
/// Frozen is checked here because `_fill` checks it: an answer that
/// omitted it would tell a router an order is fillable and then revert
/// on the leg it planned.
function isFillableBy(uint256 orderId, address taker) public view returns (bool) {
Order storage o = orders[orderId];
if (o.maker == address(0) || !o.active || _expired(o.expiry)) return false;
if (frozen(orderId)) return false;
address cp = o.counterparty;
return cp == address(0) || cp == taker;
}
/// @notice Batch form of `isFillableBy`, for planners paging the book.
function areFillableBy(uint256[] calldata orderIds, address taker) external view returns (bool[] memory out) {
out = new bool[](orderIds.length);
for (uint256 i; i < orderIds.length; ++i) {
out[i] = isFillableBy(orderIds[i], taker);
}
}
// ------------------------------------------------------------- SPLIT QUOTE
/// @notice What paying `fillAmountB` into `orderId` yields right now.
/// @dev The exact arithmetic and refusal set of `_applyFill`, in a view. A
/// splitter carving one swap across several resting orders has to know
/// each leg's output BEFORE it submits, and rederiving the rounding off
/// chain is how a route ends up one wei short of its own floor. Both
/// return zero for anything that would revert - closed, expired,
/// frozen, wrong counterparty is not considered here since it depends
/// on the caller, so pair this with `isFillableBy` for private orders.
///
/// For an NFT-sided order the returned pair is the whole lot, and
/// `outA` is a token ID rather than a quantity: NFT orders settle only
/// in full, which is exactly what makes them indivisible for a splitter.
function quoteFill(uint256 orderId, uint256 fillAmountB) public view returns (uint256 outA, uint256 paidB) {
Order storage o = orders[orderId];
if (o.maker == address(0) || !o.active || _expired(o.expiry) || frozen(orderId)) return (0, 0);
uint256 err;
(outA, paidB,, err) = _computeFill(o.amountA, o.amountB, o.nftA, o.nftB, o.partialFill, fillAmountB);
if (err != FILL_OK) return (0, 0);
}
/// @notice Smallest `fillAmountB` that buys at least `wantA` of tokenA.
/// @dev The exact-output companion to `quoteFill`, and the reason it exists
/// on the board rather than in a router: `_applyFill` rounds the output
/// DOWN, so the input has to round UP or the leg lands just under the
/// amount the route was built around. Feeding the result back through
/// `quoteFill` always yields `outA >= wantA`.
///
/// Returns zero when no input can satisfy the request, and the full ask
/// for an NFT-sided order, which has only one possible payment.
function quoteFillInput(uint256 orderId, uint256 wantA) public view returns (uint256 fillAmountB) {
Order storage o = orders[orderId];
if (o.maker == address(0) || !o.active || _expired(o.expiry) || frozen(orderId)) return 0;
uint256 amountA = o.amountA;
uint256 amountB = o.amountB;
// An NFT leg is all-or-nothing; `wantA` cannot describe a fraction of
// one, and for nftA it is a token ID rather than a quantity.
if (o.nftA || o.nftB) return amountB;
if (wantA == 0 || wantA > amountA) return 0;
if (wantA == amountA) return amountB;
if (!o.partialFill) return 0;
fillAmountB = FixedPointMathLib.fullMulDivUp(wantA, amountB, amountA);
if (fillAmountB > amountB) fillAmountB = amountB;
}
/// @dev address(0) is shorthand for the caller. Two addresses are refused
/// outright: the board itself, where a payout would be stranded in escrow
/// accounting, and WETH, where an unwrapped payout would be re-wrapped to
/// the board and lost. Both are user error rather than attack, but this is
/// an immutable contract and neither mistake is recoverable.
function _to(address recipient) internal view returns (address) {
if (recipient == address(0)) return msg.sender;
if (recipient == address(this) || recipient == weth) revert BadRecipient();
return recipient;
}
/// @dev Every path that acts on an order starts here: it must exist and
/// still be live. `maker == address(0)` is how a nonexistent order is
/// recognised, which is why a close never clears it.
function _live(uint256 orderId) internal view returns (Order storage order, address maker) {
order = orders[orderId];
maker = order.maker;
if (maker == address(0)) revert OrderNotFound(orderId);
if (!order.active) revert OrderNotActive(orderId);
}
/// @dev ...and every owner-only path additionally requires makership.
/// Ownership IS makership, so this is the receipt holder's authority.
function _liveOwned(uint256 orderId) internal view returns (Order storage order, address maker) {
(order, maker) = _live(orderId);
if (msg.sender != maker) revert NotMaker(orderId, msg.sender, maker);
}
function _expired(uint64 expiry) internal view returns (bool) {
return expiry != 0 && block.timestamp > expiry;
}
function _checkDeadline(uint256 deadline) internal view {
if (deadline != 0 && block.timestamp > deadline) revert DeadlineExpired();
}
}
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
interface IERC721 {
function transferFrom(address from, address to, uint256 tokenId) external;
function ownerOf(uint256 tokenId) external view returns (address);
}
lib/solady/src/tokens/ERC721.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple ERC721 implementation with storage hitchhiking.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC721.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC721/ERC721.sol)
///
/// @dev Note:
/// - The ERC721 standard allows for self-approvals.
/// For performance, this implementation WILL NOT revert for such actions.
/// Please add any checks with overrides if desired.
/// - For performance, methods are made payable where permitted by the ERC721 standard.
/// - The `safeTransfer` functions use the identity precompile (0x4)
/// to copy memory internally.
///
/// If you are overriding:
/// - NEVER violate the ERC721 invariant:
/// the balance of an owner MUST always be equal to their number of ownership slots.
/// The transfer functions do not have an underflow guard for user token balances.
/// - Make sure all variables written to storage are properly cleaned
/// (e.g. the bool value for `isApprovedForAll` MUST be either 1 or 0 under the hood).
/// - Check that the overridden function is actually used in the function you want to
/// change the behavior of. Much of the code has been manually inlined for performance.
abstract contract ERC721 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev An account can hold up to 4294967295 tokens.
uint256 internal constant _MAX_ACCOUNT_BALANCE = 0xffffffff;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Only the token owner or an approved account can manage the token.
error NotOwnerNorApproved();
/// @dev The token does not exist.
error TokenDoesNotExist();
/// @dev The token already exists.
error TokenAlreadyExists();
/// @dev Cannot query the balance for the zero address.
error BalanceQueryForZeroAddress();
/// @dev Cannot mint or transfer to the zero address.
error TransferToZeroAddress();
/// @dev The token must be owned by `from`.
error TransferFromIncorrectOwner();
/// @dev The recipient's balance has overflowed.
error AccountBalanceOverflow();
/// @dev Cannot safely transfer to a contract that does not implement
/// the ERC721Receiver interface.
error TransferToNonERC721ReceiverImplementer();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Emitted when token `id` is transferred from `from` to `to`.
event Transfer(address indexed from, address indexed to, uint256 indexed id);
/// @dev Emitted when `owner` enables `account` to manage the `id` token.
event Approval(address indexed owner, address indexed account, uint256 indexed id);
/// @dev Emitted when `owner` enables or disables `operator` to manage all of their tokens.
event ApprovalForAll(address indexed owner, address indexed operator, bool isApproved);
/// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`.
uint256 private constant _TRANSFER_EVENT_SIGNATURE =
0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
/// @dev `keccak256(bytes("Approval(address,address,uint256)"))`.
uint256 private constant _APPROVAL_EVENT_SIGNATURE =
0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;
/// @dev `keccak256(bytes("ApprovalForAll(address,address,bool)"))`.
uint256 private constant _APPROVAL_FOR_ALL_EVENT_SIGNATURE =
0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ownership data slot of `id` is given by:
/// ```
/// mstore(0x00, id)
/// mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
/// let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
/// ```
/// Bits Layout:
/// - [0..159] `addr`
/// - [160..255] `extraData`
///
/// The approved address slot is given by: `add(1, ownershipSlot)`.
///
/// See: https://notes.ethereum.org/%40vbuterin/verkle_tree_eip
///
/// The balance slot of `owner` is given by:
/// ```
/// mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
/// mstore(0x00, owner)
/// let balanceSlot := keccak256(0x0c, 0x1c)
/// ```
/// Bits Layout:
/// - [0..31] `balance`
/// - [32..255] `aux`
///
/// The `operator` approval slot of `owner` is given by:
/// ```
/// mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, operator))
/// mstore(0x00, owner)
/// let operatorApprovalSlot := keccak256(0x0c, 0x30)
/// ```
uint256 private constant _ERC721_MASTER_SLOT_SEED = 0x7d8825530a5a2e7a << 192;
/// @dev Pre-shifted and pre-masked constant.
uint256 private constant _ERC721_MASTER_SLOT_SEED_MASKED = 0x0a5a2e7a00000000;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC721 METADATA */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the token collection name.
function name() public view virtual returns (string memory);
/// @dev Returns the token collection symbol.
function symbol() public view virtual returns (string memory);
/// @dev Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) public view virtual returns (string memory);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC721 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the owner of token `id`.
///
/// Requirements:
/// - Token `id` must exist.
function ownerOf(uint256 id) public view virtual returns (address result) {
result = _ownerOf(id);
/// @solidity memory-safe-assembly
assembly {
if iszero(result) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Returns the number of tokens owned by `owner`.
///
/// Requirements:
/// - `owner` must not be the zero address.
function balanceOf(address owner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
// Revert if the `owner` is the zero address.
if iszero(owner) {
mstore(0x00, 0x8f4eb604) // `BalanceQueryForZeroAddress()`.
revert(0x1c, 0x04)
}
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
mstore(0x00, owner)
result := and(sload(keccak256(0x0c, 0x1c)), _MAX_ACCOUNT_BALANCE)
}
}
/// @dev Returns the account approved to manage token `id`.
///
/// Requirements:
/// - Token `id` must exist.
function getApproved(uint256 id) public view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
if iszero(shl(96, sload(ownershipSlot))) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
result := sload(add(1, ownershipSlot))
}
}
/// @dev Sets `account` as the approved account to manage token `id`.
///
/// Requirements:
/// - Token `id` must exist.
/// - The caller must be the owner of the token,
/// or an approved operator for the token owner.
///
/// Emits an {Approval} event.
function approve(address account, uint256 id) public payable virtual {
_approve(msg.sender, account, id);
}
/// @dev Returns whether `operator` is approved to manage the tokens of `owner`.
function isApprovedForAll(address owner, address operator)
public
view
virtual
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x1c, operator)
mstore(0x08, _ERC721_MASTER_SLOT_SEED_MASKED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x30))
}
}
/// @dev Sets whether `operator` is approved to manage the tokens of the caller.
///
/// Emits an {ApprovalForAll} event.
function setApprovalForAll(address operator, bool isApproved) public virtual {
/// @solidity memory-safe-assembly
assembly {
// Convert to 0 or 1.
isApproved := iszero(iszero(isApproved))
// Update the `isApproved` for (`msg.sender`, `operator`).
mstore(0x1c, operator)
mstore(0x08, _ERC721_MASTER_SLOT_SEED_MASKED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x30), isApproved)
// Emit the {ApprovalForAll} event.
mstore(0x00, isApproved)
// forgefmt: disable-next-item
log3(0x00, 0x20, _APPROVAL_FOR_ALL_EVENT_SIGNATURE, caller(), shr(96, shl(96, operator)))
}
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - The caller must be the owner of the token, or be approved to manage the token.
///
/// Emits a {Transfer} event.
function transferFrom(address from, address to, uint256 id) public payable virtual {
_beforeTokenTransfer(from, to, id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
let bitmaskAddress := shr(96, not(0))
from := and(bitmaskAddress, from)
to := and(bitmaskAddress, to)
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, caller()))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let ownershipPacked := sload(ownershipSlot)
let owner := and(bitmaskAddress, ownershipPacked)
// Revert if the token does not exist, or if `from` is not the owner.
if iszero(mul(owner, eq(owner, from))) {
// `TokenDoesNotExist()`, `TransferFromIncorrectOwner()`.
mstore(shl(2, iszero(owner)), 0xceea21b6a1148100)
revert(0x1c, 0x04)
}
// Load, check, and update the token approval.
{
mstore(0x00, from)
let approvedAddress := sload(add(1, ownershipSlot))
// Revert if the caller is not the owner, nor approved.
if iszero(or(eq(caller(), from), eq(caller(), approvedAddress))) {
if iszero(sload(keccak256(0x0c, 0x30))) {
mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
revert(0x1c, 0x04)
}
}
// Delete the approved address if any.
if approvedAddress { sstore(add(1, ownershipSlot), 0) }
}
// Update with the new owner.
sstore(ownershipSlot, xor(ownershipPacked, xor(from, to)))
// Decrement the balance of `from`.
{
let fromBalanceSlot := keccak256(0x0c, 0x1c)
sstore(fromBalanceSlot, sub(sload(fromBalanceSlot), 1))
}
// Increment the balance of `to`.
{
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x1c)
let toBalanceSlotPacked := add(sload(toBalanceSlot), 1)
// Revert if `to` is the zero address, or if the account balance overflows.
if iszero(mul(to, and(toBalanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
// `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
mstore(shl(2, iszero(to)), 0xea553b3401336cea)
revert(0x1c, 0x04)
}
sstore(toBalanceSlot, toBalanceSlotPacked)
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, from, to, id)
}
_afterTokenTransfer(from, to, id);
}
/// @dev Equivalent to `safeTransferFrom(from, to, id, "")`.
function safeTransferFrom(address from, address to, uint256 id) public payable virtual {
transferFrom(from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, "");
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - The caller must be the owner of the token, or be approved to manage the token.
/// - If `to` refers to a smart contract, it must implement
/// {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
///
/// Emits a {Transfer} event.
function safeTransferFrom(address from, address to, uint256 id, bytes calldata data)
public
payable
virtual
{
transferFrom(from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);
}
/// @dev Returns true if this contract implements the interface defined by `interfaceId`.
/// See: https://eips.ethereum.org/EIPS/eip-165
/// This function call must use less than 30000 gas.
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
let s := shr(224, interfaceId)
// ERC165: 0x01ffc9a7, ERC721: 0x80ac58cd, ERC721Metadata: 0x5b5e139f.
result := or(or(eq(s, 0x01ffc9a7), eq(s, 0x80ac58cd)), eq(s, 0x5b5e139f))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL QUERY FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns if token `id` exists.
function _exists(uint256 id) internal view virtual returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
result := iszero(iszero(shl(96, sload(add(id, add(id, keccak256(0x00, 0x20)))))))
}
}
/// @dev Returns the owner of token `id`.
/// Returns the zero address instead of reverting if the token does not exist.
function _ownerOf(uint256 id) internal view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
result := shr(96, shl(96, sload(add(id, add(id, keccak256(0x00, 0x20))))))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL DATA HITCHHIKING FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// For performance, no events are emitted for the hitchhiking setters.
// Please emit your own events if required.
/// @dev Returns the auxiliary data for `owner`.
/// Minting, transferring, burning the tokens of `owner` will not change the auxiliary data.
/// Auxiliary data can be set for any address, even if it does not have any tokens.
function _getAux(address owner) internal view virtual returns (uint224 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
mstore(0x00, owner)
result := shr(32, sload(keccak256(0x0c, 0x1c)))
}
}
/// @dev Set the auxiliary data for `owner` to `value`.
/// Minting, transferring, burning the tokens of `owner` will not change the auxiliary data.
/// Auxiliary data can be set for any address, even if it does not have any tokens.
function _setAux(address owner, uint224 value) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
mstore(0x00, owner)
let balanceSlot := keccak256(0x0c, 0x1c)
let packed := sload(balanceSlot)
sstore(balanceSlot, xor(packed, shl(32, xor(value, shr(32, packed)))))
}
}
/// @dev Returns the extra data for token `id`.
/// Minting, transferring, burning a token will not change the extra data.
/// The extra data can be set on a non-existent token.
function _getExtraData(uint256 id) internal view virtual returns (uint96 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
result := shr(160, sload(add(id, add(id, keccak256(0x00, 0x20)))))
}
}
/// @dev Sets the extra data for token `id` to `value`.
/// Minting, transferring, burning a token will not change the extra data.
/// The extra data can be set on a non-existent token.
function _setExtraData(uint256 id, uint96 value) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let packed := sload(ownershipSlot)
sstore(ownershipSlot, xor(packed, shl(160, xor(value, shr(160, packed)))))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL MINT FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Mints token `id` to `to`.
///
/// Requirements:
///
/// - Token `id` must not exist.
/// - `to` cannot be the zero address.
///
/// Emits a {Transfer} event.
function _mint(address to, uint256 id) internal virtual {
_beforeTokenTransfer(address(0), to, id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
to := shr(96, shl(96, to))
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let ownershipPacked := sload(ownershipSlot)
// Revert if the token already exists.
if shl(96, ownershipPacked) {
mstore(0x00, 0xc991cbb1) // `TokenAlreadyExists()`.
revert(0x1c, 0x04)
}
// Update with the owner.
sstore(ownershipSlot, or(ownershipPacked, to))
// Increment the balance of the owner.
{
mstore(0x00, to)
let balanceSlot := keccak256(0x0c, 0x1c)
let balanceSlotPacked := add(sload(balanceSlot), 1)
// Revert if `to` is the zero address, or if the account balance overflows.
if iszero(mul(to, and(balanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
// `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
mstore(shl(2, iszero(to)), 0xea553b3401336cea)
revert(0x1c, 0x04)
}
sstore(balanceSlot, balanceSlotPacked)
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, 0, to, id)
}
_afterTokenTransfer(address(0), to, id);
}
/// @dev Mints token `id` to `to`, and updates the extra data for token `id` to `value`.
/// Does NOT check if token `id` already exists (assumes `id` is auto-incrementing).
///
/// Requirements:
///
/// - `to` cannot be the zero address.
///
/// Emits a {Transfer} event.
function _mintAndSetExtraDataUnchecked(address to, uint256 id, uint96 value) internal virtual {
_beforeTokenTransfer(address(0), to, id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
to := shr(96, shl(96, to))
// Update with the owner and extra data.
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
sstore(add(id, add(id, keccak256(0x00, 0x20))), or(shl(160, value), to))
// Increment the balance of the owner.
{
mstore(0x00, to)
let balanceSlot := keccak256(0x0c, 0x1c)
let balanceSlotPacked := add(sload(balanceSlot), 1)
// Revert if `to` is the zero address, or if the account balance overflows.
if iszero(mul(to, and(balanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
// `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
mstore(shl(2, iszero(to)), 0xea553b3401336cea)
revert(0x1c, 0x04)
}
sstore(balanceSlot, balanceSlotPacked)
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, 0, to, id)
}
_afterTokenTransfer(address(0), to, id);
}
/// @dev Equivalent to `_safeMint(to, id, "")`.
function _safeMint(address to, uint256 id) internal virtual {
_safeMint(to, id, "");
}
/// @dev Mints token `id` to `to`.
///
/// Requirements:
///
/// - Token `id` must not exist.
/// - `to` cannot be the zero address.
/// - If `to` refers to a smart contract, it must implement
/// {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
///
/// Emits a {Transfer} event.
function _safeMint(address to, uint256 id, bytes memory data) internal virtual {
_mint(to, id);
if (_hasCode(to)) _checkOnERC721Received(address(0), to, id, data);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL BURN FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `_burn(address(0), id)`.
function _burn(uint256 id) internal virtual {
_burn(address(0), id);
}
/// @dev Destroys token `id`, using `by`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - If `by` is not the zero address,
/// it must be the owner of the token, or be approved to manage the token.
///
/// Emits a {Transfer} event.
function _burn(address by, uint256 id) internal virtual {
address owner = ownerOf(id);
_beforeTokenTransfer(owner, address(0), id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
by := shr(96, shl(96, by))
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let ownershipPacked := sload(ownershipSlot)
// Reload the owner in case it is changed in `_beforeTokenTransfer`.
owner := shr(96, shl(96, ownershipPacked))
// Revert if the token does not exist.
if iszero(owner) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
// Load and check the token approval.
{
mstore(0x00, owner)
let approvedAddress := sload(add(1, ownershipSlot))
// If `by` is not the zero address, do the authorization check.
// Revert if the `by` is not the owner, nor approved.
if iszero(or(iszero(by), or(eq(by, owner), eq(by, approvedAddress)))) {
if iszero(sload(keccak256(0x0c, 0x30))) {
mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
revert(0x1c, 0x04)
}
}
// Delete the approved address if any.
if approvedAddress { sstore(add(1, ownershipSlot), 0) }
}
// Clear the owner.
sstore(ownershipSlot, xor(ownershipPacked, owner))
// Decrement the balance of `owner`.
{
let balanceSlot := keccak256(0x0c, 0x1c)
sstore(balanceSlot, sub(sload(balanceSlot), 1))
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, owner, 0, id)
}
_afterTokenTransfer(owner, address(0), id);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL APPROVAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns whether `account` is the owner of token `id`, or is approved to manage it.
///
/// Requirements:
/// - Token `id` must exist.
function _isApprovedOrOwner(address account, uint256 id)
internal
view
virtual
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
result := 1
// Clear the upper 96 bits.
account := shr(96, shl(96, account))
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, account))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let owner := shr(96, shl(96, sload(ownershipSlot)))
// Revert if the token does not exist.
if iszero(owner) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
// Check if `account` is the `owner`.
if iszero(eq(account, owner)) {
mstore(0x00, owner)
// Check if `account` is approved to manage the token.
if iszero(sload(keccak256(0x0c, 0x30))) {
result := eq(account, sload(add(1, ownershipSlot)))
}
}
}
}
/// @dev Returns the account approved to manage token `id`.
/// Returns the zero address instead of reverting if the token does not exist.
function _getApproved(uint256 id) internal view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
result := sload(add(1, add(id, add(id, keccak256(0x00, 0x20)))))
}
}
/// @dev Equivalent to `_approve(address(0), account, id)`.
function _approve(address account, uint256 id) internal virtual {
_approve(address(0), account, id);
}
/// @dev Sets `account` as the approved account to manage token `id`, using `by`.
///
/// Requirements:
/// - Token `id` must exist.
/// - If `by` is not the zero address, `by` must be the owner
/// or an approved operator for the token owner.
///
/// Emits a {Approval} event.
function _approve(address by, address account, uint256 id) internal virtual {
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
let bitmaskAddress := shr(96, not(0))
account := and(bitmaskAddress, account)
by := and(bitmaskAddress, by)
// Load the owner of the token.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let owner := and(bitmaskAddress, sload(ownershipSlot))
// Revert if the token does not exist.
if iszero(owner) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
// If `by` is not the zero address, do the authorization check.
// Revert if `by` is not the owner, nor approved.
if iszero(or(iszero(by), eq(by, owner))) {
mstore(0x00, owner)
if iszero(sload(keccak256(0x0c, 0x30))) {
mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
revert(0x1c, 0x04)
}
}
// Sets `account` as the approved account to manage `id`.
sstore(add(1, ownershipSlot), account)
// Emit the {Approval} event.
log4(codesize(), 0x00, _APPROVAL_EVENT_SIGNATURE, owner, account, id)
}
}
/// @dev Approve or remove the `operator` as an operator for `by`,
/// without authorization checks.
///
/// Emits an {ApprovalForAll} event.
function _setApprovalForAll(address by, address operator, bool isApproved) internal virtual {
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
by := shr(96, shl(96, by))
operator := shr(96, shl(96, operator))
// Convert to 0 or 1.
isApproved := iszero(iszero(isApproved))
// Update the `isApproved` for (`by`, `operator`).
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, operator))
mstore(0x00, by)
sstore(keccak256(0x0c, 0x30), isApproved)
// Emit the {ApprovalForAll} event.
mstore(0x00, isApproved)
log3(0x00, 0x20, _APPROVAL_FOR_ALL_EVENT_SIGNATURE, by, operator)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL TRANSFER FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `_transfer(address(0), from, to, id)`.
function _transfer(address from, address to, uint256 id) internal virtual {
_transfer(address(0), from, to, id);
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - If `by` is not the zero address,
/// it must be the owner of the token, or be approved to manage the token.
///
/// Emits a {Transfer} event.
function _transfer(address by, address from, address to, uint256 id) internal virtual {
_beforeTokenTransfer(from, to, id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
let bitmaskAddress := shr(96, not(0))
from := and(bitmaskAddress, from)
to := and(bitmaskAddress, to)
by := and(bitmaskAddress, by)
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let ownershipPacked := sload(ownershipSlot)
let owner := and(bitmaskAddress, ownershipPacked)
// Revert if the token does not exist, or if `from` is not the owner.
if iszero(mul(owner, eq(owner, from))) {
// `TokenDoesNotExist()`, `TransferFromIncorrectOwner()`.
mstore(shl(2, iszero(owner)), 0xceea21b6a1148100)
revert(0x1c, 0x04)
}
// Load, check, and update the token approval.
{
mstore(0x00, from)
let approvedAddress := sload(add(1, ownershipSlot))
// If `by` is not the zero address, do the authorization check.
// Revert if the `by` is not the owner, nor approved.
if iszero(or(iszero(by), or(eq(by, from), eq(by, approvedAddress)))) {
if iszero(sload(keccak256(0x0c, 0x30))) {
mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
revert(0x1c, 0x04)
}
}
// Delete the approved address if any.
if approvedAddress { sstore(add(1, ownershipSlot), 0) }
}
// Update with the new owner.
sstore(ownershipSlot, xor(ownershipPacked, xor(from, to)))
// Decrement the balance of `from`.
{
let fromBalanceSlot := keccak256(0x0c, 0x1c)
sstore(fromBalanceSlot, sub(sload(fromBalanceSlot), 1))
}
// Increment the balance of `to`.
{
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x1c)
let toBalanceSlotPacked := add(sload(toBalanceSlot), 1)
// Revert if `to` is the zero address, or if the account balance overflows.
if iszero(mul(to, and(toBalanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
// `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
mstore(shl(2, iszero(to)), 0xea553b3401336cea)
revert(0x1c, 0x04)
}
sstore(toBalanceSlot, toBalanceSlotPacked)
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, from, to, id)
}
_afterTokenTransfer(from, to, id);
}
/// @dev Equivalent to `_safeTransfer(from, to, id, "")`.
function _safeTransfer(address from, address to, uint256 id) internal virtual {
_safeTransfer(from, to, id, "");
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - The caller must be the owner of the token, or be approved to manage the token.
/// - If `to` refers to a smart contract, it must implement
/// {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
///
/// Emits a {Transfer} event.
function _safeTransfer(address from, address to, uint256 id, bytes memory data)
internal
virtual
{
_transfer(address(0), from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);
}
/// @dev Equivalent to `_safeTransfer(by, from, to, id, "")`.
function _safeTransfer(address by, address from, address to, uint256 id) internal virtual {
_safeTransfer(by, from, to, id, "");
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - If `by` is not the zero address,
/// it must be the owner of the token, or be approved to manage the token.
/// - If `to` refers to a smart contract, it must implement
/// {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
///
/// Emits a {Transfer} event.
function _safeTransfer(address by, address from, address to, uint256 id, bytes memory data)
internal
virtual
{
_transfer(by, from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HOOKS FOR OVERRIDING */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Hook that is called before any token transfers, including minting and burning.
function _beforeTokenTransfer(address from, address to, uint256 id) internal virtual {}
/// @dev Hook that is called after any token transfers, including minting and burning.
function _afterTokenTransfer(address from, address to, uint256 id) internal virtual {}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns if `a` has bytecode of non-zero length.
function _hasCode(address a) private view returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := extcodesize(a) // Can handle dirty upper bits.
}
}
/// @dev Perform a call to invoke {IERC721Receiver-onERC721Received} on `to`.
/// Reverts if the target does not support the function correctly.
function _checkOnERC721Received(address from, address to, uint256 id, bytes memory data)
private
{
/// @solidity memory-safe-assembly
assembly {
// Prepare the calldata.
let m := mload(0x40)
let onERC721ReceivedSelector := 0x150b7a02
mstore(m, onERC721ReceivedSelector)
mstore(add(m, 0x20), caller()) // The `operator`, which is always `msg.sender`.
mstore(add(m, 0x40), shr(96, shl(96, from)))
mstore(add(m, 0x60), id)
mstore(add(m, 0x80), 0x80)
let n := mload(data)
mstore(add(m, 0xa0), n)
if n { pop(staticcall(gas(), 4, add(data, 0x20), n, add(m, 0xc0), n)) }
// Revert if the call reverts.
if iszero(call(gas(), to, 0, add(m, 0x1c), add(n, 0xa4), m, 0x20)) {
if returndatasize() {
// Bubble up the revert if the call reverts.
returndatacopy(m, 0x00, returndatasize())
revert(m, returndatasize())
}
}
// Load the returndata and compare it.
if iszero(eq(mload(m), shl(224, onERC721ReceivedSelector))) {
mstore(0x00, 0xd1a57ed6) // `TransferToNonERC721ReceiverImplementer()`.
revert(0x1c, 0x04)
}
}
}
}
lib/solady/src/utils/Base64.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library to encode strings in Base64.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Base64.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Base64.sol)
/// @author Modified from (https://github.com/Brechtpd/base64/blob/main/base64.sol) by Brecht Devos - <[email protected]>.
library Base64 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ENCODING / DECODING */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Encodes `data` using the base64 encoding described in RFC 4648.
/// See: https://datatracker.ietf.org/doc/html/rfc4648
/// @param fileSafe Whether to replace '+' with '-' and '/' with '_'.
/// @param noPadding Whether to strip away the padding.
function encode(bytes memory data, bool fileSafe, bool noPadding)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let dataLength := mload(data)
if dataLength {
// Multiply by 4/3 rounded up.
// The `shl(2, ...)` is equivalent to multiplying by 4.
let encodedLength := shl(2, div(add(dataLength, 2), 3))
// Set `result` to point to the start of the free memory.
result := mload(0x40)
// Store the table into the scratch space.
// Offsetted by -1 byte so that the `mload` will load the character.
// We will rewrite the free memory pointer at `0x40` later with
// the allocated size.
// The magic constant 0x0670 will turn "-_" into "+/".
mstore(0x1f, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
mstore(0x3f, xor("ghijklmnopqrstuvwxyz0123456789-_", mul(iszero(fileSafe), 0x0670)))
// Skip the first slot, which stores the length.
let ptr := add(result, 0x20)
let end := add(ptr, encodedLength)
let dataEnd := add(add(0x20, data), dataLength)
let dataEndValue := mload(dataEnd) // Cache the value at the `dataEnd` slot.
mstore(dataEnd, 0x00) // Zeroize the `dataEnd` slot to clear dirty bits.
// Run over the input, 3 bytes at a time.
for {} 1 {} {
data := add(data, 3) // Advance 3 bytes.
let input := mload(data)
// Write 4 bytes. Optimized for fewer stack operations.
mstore8(0, mload(and(shr(18, input), 0x3F)))
mstore8(1, mload(and(shr(12, input), 0x3F)))
mstore8(2, mload(and(shr(6, input), 0x3F)))
mstore8(3, mload(and(input, 0x3F)))
mstore(ptr, mload(0x00))
ptr := add(ptr, 4) // Advance 4 bytes.
if iszero(lt(ptr, end)) { break }
}
mstore(dataEnd, dataEndValue) // Restore the cached value at `dataEnd`.
mstore(0x40, add(end, 0x20)) // Allocate the memory.
// Equivalent to `o = [0, 2, 1][dataLength % 3]`.
let o := div(2, mod(dataLength, 3))
// Offset `ptr` and pad with '='. We can simply write over the end.
mstore(sub(ptr, o), shl(240, 0x3d3d))
// Set `o` to zero if there is padding.
o := mul(iszero(iszero(noPadding)), o)
mstore(sub(ptr, o), 0) // Zeroize the slot after the string.
mstore(result, sub(encodedLength, o)) // Store the length.
}
}
}
/// @dev Encodes `data` using the base64 encoding described in RFC 4648.
/// Equivalent to `encode(data, false, false)`.
function encode(bytes memory data) internal pure returns (string memory result) {
result = encode(data, false, false);
}
/// @dev Encodes `data` using the base64 encoding described in RFC 4648.
/// Equivalent to `encode(data, fileSafe, false)`.
function encode(bytes memory data, bool fileSafe)
internal
pure
returns (string memory result)
{
result = encode(data, fileSafe, false);
}
/// @dev Decodes base64 encoded `data`.
///
/// Supports:
/// - RFC 4648 (both standard and file-safe mode).
/// - RFC 3501 (63: ',').
///
/// Does not support:
/// - Line breaks.
///
/// Note: For performance reasons,
/// this function will NOT revert on invalid `data` inputs.
/// Outputs for invalid inputs will simply be undefined behaviour.
/// It is the user's responsibility to ensure that the `data`
/// is a valid base64 encoded string.
function decode(string memory data) internal pure returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
let dataLength := mload(data)
if dataLength {
let decodedLength := mul(shr(2, dataLength), 3)
for {} 1 {} {
// If padded.
if iszero(and(dataLength, 3)) {
let t := xor(mload(add(data, dataLength)), 0x3d3d)
// forgefmt: disable-next-item
decodedLength := sub(
decodedLength,
add(iszero(byte(30, t)), iszero(byte(31, t)))
)
break
}
// If non-padded.
decodedLength := add(decodedLength, sub(and(dataLength, 3), 1))
break
}
result := mload(0x40)
// Write the length of the bytes.
mstore(result, decodedLength)
// Skip the first slot, which stores the length.
let ptr := add(result, 0x20)
let end := add(ptr, decodedLength)
// Load the table into the scratch space.
// Constants are optimized for smaller bytecode with zero gas overhead.
// `m` also doubles as the mask of the upper 6 bits.
let m := 0xfc000000fc00686c7074787c8084888c9094989ca0a4a8acb0b4b8bcc0c4c8cc
mstore(0x5b, m)
mstore(0x3b, 0x04080c1014181c2024282c3034383c4044484c5054585c6064)
mstore(0x1a, 0xf8fcf800fcd0d4d8dce0e4e8ecf0f4)
for {} 1 {} {
// Read 4 bytes.
data := add(data, 4)
let input := mload(data)
// Write 3 bytes.
// forgefmt: disable-next-item
mstore(ptr, or(
and(m, mload(byte(28, input))),
shr(6, or(
and(m, mload(byte(29, input))),
shr(6, or(
and(m, mload(byte(30, input))),
shr(6, mload(byte(31, input)))
))
))
))
ptr := add(ptr, 3)
if iszero(lt(ptr, end)) { break }
}
mstore(0x40, add(end, 0x20)) // Allocate the memory.
mstore(end, 0) // Zeroize the slot after the bytes.
mstore(0x60, 0) // Restore the zero slot.
}
}
}
}
lib/solady/src/utils/FixedPointMathLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error ExpOverflow();
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error FactorialOverflow();
/// @dev The operation failed, due to an overflow.
error RPowOverflow();
/// @dev The mantissa is too big to fit.
error MantissaOverflow();
/// @dev The operation failed, due to an multiplication overflow.
error MulWadFailed();
/// @dev The operation failed, due to an multiplication overflow.
error SMulWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error DivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error SDivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error MulDivFailed();
/// @dev The division failed, as the denominator is zero.
error DivFailed();
/// @dev The full precision multiply-divide operation failed, either due
/// to the result being larger than 256 bits, or a division by a zero.
error FullMulDivFailed();
/// @dev The output is undefined, as the input is less-than-or-equal to zero.
error LnWadUndefined();
/// @dev The input outside the acceptable domain.
error OutOfDomain();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The scalar of ETH and most ERC20s.
uint256 internal constant WAD = 1e18;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIMPLIFIED FIXED POINT OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if gt(x, div(not(0), y)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up.
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if iszero(eq(div(z, y), x)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, WAD)
// Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
if iszero(mul(y, eq(sdiv(z, WAD), x))) {
mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up.
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `x` to the power of `y`.
/// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
/// Note: This function is an approximation.
function powWad(int256 x, int256 y) internal pure returns (int256) {
// Using `ln(x)` means `x` must be greater than 0.
return expWad((lnWad(x) * y) / int256(WAD));
}
/// @dev Returns `exp(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function expWad(int256 x) internal pure returns (int256 r) {
unchecked {
// When the result is less than 0.5 we return zero.
// This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
if (x <= -41446531673892822313) return r;
/// @solidity memory-safe-assembly
assembly {
// When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
// an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
if iszero(slt(x, 135305999368893231589)) {
mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
revert(0x1c, 0x04)
}
}
// `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
// for more intermediate precision and a binary basis. This base conversion
// is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
x = (x << 78) / 5 ** 18;
// Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
// of two such that exp(x) = exp(x') * 2**k, where k is an integer.
// Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
x = x - k * 54916777467707473351141471128;
// `k` is in the range `[-61, 195]`.
// Evaluate using a (6, 7)-term rational approximation.
// `p` is made monic, we'll multiply by a scale factor later.
int256 y = x + 1346386616545796478920950773328;
y = ((y * x) >> 96) + 57155421227552351082224309758442;
int256 p = y + x - 94201549194550492254356042504812;
p = ((p * y) >> 96) + 28719021644029726153956944680412240;
p = p * x + (4385272521454847904659076985693276 << 96);
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
int256 q = x - 2855989394907223263936484059900;
q = ((q * x) >> 96) + 50020603652535783019961831881945;
q = ((q * x) >> 96) - 533845033583426703283633433725380;
q = ((q * x) >> 96) + 3604857256930695427073651918091429;
q = ((q * x) >> 96) - 14423608567350463180887372962807573;
q = ((q * x) >> 96) + 26449188498355588339934803723976023;
/// @solidity memory-safe-assembly
assembly {
// Div in assembly because solidity adds a zero check despite the unchecked.
// The q polynomial won't have zeros in the domain as all its roots are complex.
// No scaling is necessary because p is already `2**96` too large.
r := sdiv(p, q)
}
// r should be in the range `(0.09, 0.25) * 2**96`.
// We now need to multiply r by:
// - The scale factor `s ≈ 6.031367120`.
// - The `2**k` factor from the range reduction.
// - The `1e18 / 2**96` factor for base conversion.
// We do this all at once, with an intermediate result in `2**213`
// basis, so the final right shift is always by a positive amount.
r = int256(
(uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
);
}
}
/// @dev Returns `ln(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function lnWad(int256 x) internal pure returns (int256 r) {
/// @solidity memory-safe-assembly
assembly {
// We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
// We do this by multiplying by `2**96 / 10**18`. But since
// `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
// and add `ln(2**96 / 10**18)` at the end.
// Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, 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))))
// We place the check here for more optimal stack operations.
if iszero(sgt(x, 0)) {
mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
revert(0x1c, 0x04)
}
// forgefmt: disable-next-item
r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
// Reduce range of x to (1, 2) * 2**96
// ln(2^k * x) = k * ln(2) + ln(x)
x := shr(159, shl(r, x))
// Evaluate using a (8, 8)-term rational approximation.
// `p` is made monic, we will multiply by a scale factor later.
// forgefmt: disable-next-item
let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
sar(96, mul(add(43456485725739037958740375743393,
sar(96, mul(add(24828157081833163892658089445524,
sar(96, mul(add(3273285459638523848632254066296,
x), x))), x))), x)), 11111509109440967052023855526967)
p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
// `q` is monic by convention.
let q := add(5573035233440673466300451813936, x)
q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
q := add(909429971244387300277376558375, sar(96, mul(x, q)))
// `p / q` is in the range `(0, 0.125) * 2**96`.
// Finalization, we need to:
// - Multiply by the scale factor `s = 5.549…`.
// - Add `ln(2**96 / 10**18)`.
// - Add `k * ln(2)`.
// - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
// The q polynomial is known not to have zeros in the domain.
// No scaling required because p is already `2**96` too large.
p := sdiv(p, q)
// Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
p := mul(1677202110996718588342820967067443963516166, p)
// Add `ln(2) * k * 5**18 * 2**192`.
// forgefmt: disable-next-item
p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
// Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
// Base conversion: mul `2**18 / 2**192`.
r := sar(174, p)
}
}
/// @dev Returns `W_0(x)`, denominated in `WAD`.
/// See: https://en.wikipedia.org/wiki/Lambert_W_function
/// a.k.a. Product log function. This is an approximation of the principal branch.
/// Note: This function is an approximation. Monotonically increasing.
function lambertW0Wad(int256 x) internal pure returns (int256 w) {
// forgefmt: disable-next-item
unchecked {
if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
(int256 wad, int256 p) = (int256(WAD), x);
uint256 c; // Whether we need to avoid catastrophic cancellation.
uint256 i = 4; // Number of iterations.
if (w <= 0x1ffffffffffff) {
if (-0x4000000000000 <= w) {
i = 1; // Inputs near zero only take one step to converge.
} else if (w <= -0x3ffffffffffffff) {
i = 32; // Inputs near `-1/e` take very long to converge.
}
} else if (uint256(w >> 63) == uint256(0)) {
/// @solidity memory-safe-assembly
assembly {
// Inline log2 for more performance, since the range is small.
let v := shr(49, w)
let l := shl(3, lt(0xff, v))
l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
c := gt(l, 60)
i := add(2, add(gt(l, 53), c))
}
} else {
int256 ll = lnWad(w = lnWad(w));
/// @solidity memory-safe-assembly
assembly {
// `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
i := add(3, iszero(shr(68, x)))
c := iszero(shr(143, x))
}
if (c == uint256(0)) {
do { // If `x` is big, use Newton's so that intermediate values won't overflow.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := mul(w, div(e, wad))
w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
}
if (p <= w) break;
p = w;
} while (--i != uint256(0));
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
return w;
}
}
do { // Otherwise, use Halley's for faster convergence.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := add(w, wad)
let s := sub(mul(w, e), mul(x, wad))
w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
}
if (p <= w) break;
p = w;
} while (--i != c);
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
// For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
// R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
if (c == uint256(0)) return w;
int256 t = w | 1;
/// @solidity memory-safe-assembly
assembly {
x := sdiv(mul(x, wad), t)
}
x = (t * (wad + lnWad(x)));
/// @solidity memory-safe-assembly
assembly {
w := sdiv(x, add(wad, t))
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* GENERAL NUMBER UTILITIES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `a * b == x * y`, with full precision.
function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// 512-bit multiply `[p1 p0] = x * y`.
// Compute the product mod `2**256` and mod `2**256 - 1`
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that `product = p1 * 2**256 + p0`.
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`.
for {} 1 {} {
// If overflows.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
/*------------------- 512 by 256 division --------------------*/
// Make division exact by subtracting the remainder from `[p1 p0]`.
let r := mulmod(x, y, d) // Compute remainder using mulmod.
let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
// Make sure `z` is less than `2**256`. Also prevents `d == 0`.
// Placing the check here seems to give more optimal stack operations.
if iszero(gt(d, p1)) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
d := div(d, t) // Divide `d` by `t`, which is a power of two.
// Invert `d mod 2**256`
// Now that `d` is an odd number, it has an inverse
// modulo `2**256` such that `d * inv = 1 mod 2**256`.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, `d * inv = 1 mod 2**4`.
let inv := xor(2, mul(3, d))
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
z :=
mul(
// Divide [p1 p0] by the factors of two.
// Shift in bits from `p1` into `p0`. For this we need
// to flip `t` such that it is `2**256 / t`.
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
)
break
}
z := div(z, d)
break
}
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
/// Performs the full 512 bit calculation regardless.
function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z)))
let t := and(d, sub(0, d))
let r := mulmod(x, y, d)
d := div(d, t)
let inv := xor(2, mul(3, d))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
z :=
mul(
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv)
)
}
}
/// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Uniswap-v3-core under MIT license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
z = fullMulDiv(x, y, d);
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, d) {
z := add(z, 1)
if iszero(z) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
/// Throws if result overflows a uint256.
/// Credit to Philogy under MIT license:
/// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
for {} 1 {} {
if iszero(or(iszero(x), eq(div(z, x), y))) {
let k := and(n, 0xff) // `n`, cleaned.
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
// | p1 | z |
// Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 |
// Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 |
// Check that final `z` doesn't overflow by checking that p1_0 = 0.
if iszero(shr(k, p1)) {
z := add(shl(sub(256, k), p1), shr(k, z))
break
}
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
z := shr(and(n, 0xff), z)
break
}
}
}
/// @dev Returns `floor(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := div(z, d)
}
}
/// @dev Returns `ceil(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(z, d))), div(z, d))
}
}
/// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
/// @solidity memory-safe-assembly
assembly {
let g := n
let r := mod(a, n)
for { let y := 1 } 1 {} {
let q := div(g, r)
let t := g
g := r
r := sub(t, mul(r, q))
let u := x
x := y
y := sub(u, mul(y, q))
if iszero(r) { break }
}
x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
}
}
/// @dev Returns `ceil(x / d)`.
/// Reverts if `d` is zero.
function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
if iszero(d) {
mstore(0x00, 0x65244e4e) // `DivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(x, d))), div(x, d))
}
}
/// @dev Returns `max(0, x - y)`. Alias for `saturatingSub`.
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `max(0, x - y)`.
function saturatingSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x + y)`.
function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(0, lt(add(x, y), x)), add(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x * y)`.
function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `x != 0 ? x : y`, without branching.
function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != bytes32(0) ? x : y`, without branching.
function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != address(0) ? x : y`, without branching.
function coalesce(address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(shl(96, x))))
}
}
/// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
/// Reverts if the computation overflows.
function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
if x {
z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
let half := shr(1, b) // Divide `b` by 2.
// Divide `y` by 2 every iteration.
for { y := shr(1, y) } y { y := shr(1, y) } {
let xx := mul(x, x) // Store x squared.
let xxRound := add(xx, half) // Round to the nearest number.
// Revert if `xx + half` overflowed, or if `x ** 2` overflows.
if or(lt(xxRound, xx), shr(128, x)) {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
x := div(xxRound, b) // Set `x` to scaled `xxRound`.
// If `y` is odd:
if and(y, 1) {
let zx := mul(z, x) // Compute `z * x`.
let zxRound := add(zx, half) // Round to the nearest number.
// If `z * x` overflowed or `zx + half` overflowed:
if or(xor(div(zx, x), z), lt(zxRound, zx)) {
// Revert if `x` is non-zero.
if x {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
}
z := div(zxRound, b) // Return properly scaled `zxRound`.
}
}
}
}
}
/// @dev Returns the square root of `x`, rounded down.
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
// but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffffff, shr(r, x))))
z := shl(shr(1, r), z)
// Goal was to get `z*z*y` within a small factor of `x`. More iterations could
// get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
// We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
// That's not possible if `x < 256` but we can just verify those cases exhaustively.
// Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
// Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
// Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
// For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
// is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
// with largest error when `s = 1` and when `s = 256` or `1/256`.
// Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
// Then we can estimate `sqrt(y)` using
// `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
// There is no overflow risk here since `y < 2**136` after the first branch above.
z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If `x+1` is a perfect square, the Babylonian method cycles between
// `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
z := sub(z, lt(div(x, z), z))
}
}
/// @dev Returns the cube root of `x`, rounded down.
/// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
/// https://github.com/pcaversaccio/snekmate/blob/main/src/snekmate/utils/math.vy
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, 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))))
// Makeshift lookup table to nudge the approximate log2 result.
z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
// Newton-Raphson's.
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
// Round down.
z := sub(z, lt(div(x, mul(z, z)), z))
}
}
/// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
function sqrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
z = (1 + sqrt(x)) * 10 ** 9;
z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
}
/// @solidity memory-safe-assembly
assembly {
z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
}
}
/// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
z = (1 + cbrt(x)) * 10 ** 12;
z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
}
/// @solidity memory-safe-assembly
assembly {
let p := x
for {} 1 {} {
if iszero(shr(229, p)) {
if iszero(shr(199, p)) {
p := mul(p, 100000000000000000) // 10 ** 17.
break
}
p := mul(p, 100000000) // 10 ** 8.
break
}
if iszero(shr(249, p)) { p := mul(p, 100) }
break
}
let t := mulmod(mul(z, z), z, p)
z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
}
}
/// @dev Returns `sqrt(x * y)`. Also called the geometric mean.
function mulSqrt(uint256 x, uint256 y) internal pure returns (uint256 z) {
if (x == y) return x;
uint256 p = rawMul(x, y);
if (y == rawDiv(p, x)) return sqrt(p);
for (z = saturatingMul(rawAdd(sqrt(x), 1), rawAdd(sqrt(y), 1));; z = avg(z, p)) {
if ((p = fullMulDivUnchecked(x, y, z)) >= z) break;
}
}
/// @dev Returns the factorial of `x`.
function factorial(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := 1
if iszero(lt(x, 58)) {
mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
revert(0x1c, 0x04)
}
for {} x { x := sub(x, 1) } { z := mul(z, x) }
}
}
/// @dev Returns the log2 of `x`.
/// Equivalent to computing the index of the most significant bit (MSB) of `x`.
/// Returns 0 if `x` is zero.
function log2(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, 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
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000))
}
}
/// @dev Returns the log2 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log2Up(uint256 x) internal pure returns (uint256 r) {
r = log2(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(r, 1), x))
}
}
/// @dev Returns the log10 of `x`.
/// Returns 0 if `x` is zero.
function log10(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(x, 100000000000000000000000000000000000000)) {
x := div(x, 100000000000000000000000000000000000000)
r := 38
}
if iszero(lt(x, 100000000000000000000)) {
x := div(x, 100000000000000000000)
r := add(r, 20)
}
if iszero(lt(x, 10000000000)) {
x := div(x, 10000000000)
r := add(r, 10)
}
if iszero(lt(x, 100000)) {
x := div(x, 100000)
r := add(r, 5)
}
r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
}
}
/// @dev Returns the log10 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log10Up(uint256 x) internal pure returns (uint256 r) {
r = log10(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(exp(10, r), x))
}
}
/// @dev Returns the log256 of `x`.
/// Returns 0 if `x` is zero.
function log256(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, 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(shr(3, r), lt(0xff, shr(r, x)))
}
}
/// @dev Returns the log256 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log256Up(uint256 x) internal pure returns (uint256 r) {
r = log256(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(shl(3, r), 1), x))
}
}
/// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
/// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
/// @solidity memory-safe-assembly
assembly {
mantissa := x
if mantissa {
if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
mantissa := div(mantissa, 1000000000000000000000000000000000)
exponent := 33
}
if iszero(mod(mantissa, 10000000000000000000)) {
mantissa := div(mantissa, 10000000000000000000)
exponent := add(exponent, 19)
}
if iszero(mod(mantissa, 1000000000000)) {
mantissa := div(mantissa, 1000000000000)
exponent := add(exponent, 12)
}
if iszero(mod(mantissa, 1000000)) {
mantissa := div(mantissa, 1000000)
exponent := add(exponent, 6)
}
if iszero(mod(mantissa, 10000)) {
mantissa := div(mantissa, 10000)
exponent := add(exponent, 4)
}
if iszero(mod(mantissa, 100)) {
mantissa := div(mantissa, 100)
exponent := add(exponent, 2)
}
if iszero(mod(mantissa, 10)) {
mantissa := div(mantissa, 10)
exponent := add(exponent, 1)
}
}
}
}
/// @dev Convenience function for packing `x` into a smaller number using `sci`.
/// The `mantissa` will be in bits [7..255] (the upper 249 bits).
/// The `exponent` will be in bits [0..6] (the lower 7 bits).
/// Use `SafeCastLib` to safely ensure that the `packed` number is small
/// enough to fit in the desired unsigned integer type:
/// ```
/// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
/// ```
function packSci(uint256 x) internal pure returns (uint256 packed) {
(x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
/// @solidity memory-safe-assembly
assembly {
if shr(249, x) {
mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
revert(0x1c, 0x04)
}
packed := or(shl(7, x), packed)
}
}
/// @dev Convenience function for unpacking a packed number from `packSci`.
function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
unchecked {
unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards zero.
function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = (x & y) + ((x ^ y) >> 1);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
function avg(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
/// @dev Returns the absolute value of `x`.
function abs(int256 x) internal pure returns (uint256 z) {
unchecked {
z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(int256 x, int256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), slt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), gt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), sgt(y, x)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(uint256 x, uint256 minValue, uint256 maxValue)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
}
}
/// @dev Returns greatest common divisor of `x` and `y`.
function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
for { z := x } y {} {
let t := y
y := mod(z, y)
z := t
}
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
internal
pure
returns (uint256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
unchecked {
if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
return a - fullMulDiv(a - b, t - begin, end - begin);
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
internal
pure
returns (int256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
// forgefmt: disable-next-item
unchecked {
if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
uint256(t - begin), uint256(end - begin)));
return int256(uint256(a) - fullMulDiv(uint256(a - b),
uint256(t - begin), uint256(end - begin)));
}
}
/// @dev Returns if `x` is an even number. Some people may need this.
function isEven(uint256 x) internal pure returns (bool) {
return x & uint256(1) == uint256(0);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RAW NUMBER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(x, y)
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mod(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := smod(x, y)
}
}
/// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := addmod(x, y, d)
}
}
/// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mulmod(x, y, d)
}
}
}
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/MetadataReaderLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for reading contract metadata robustly.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/MetadataReaderLib.sol)
library MetadataReaderLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Default gas stipend for contract reads. High enough for most practical use cases
/// (able to SLOAD about 1000 bytes of data), but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev Default string byte length limit.
uint256 internal constant STRING_LIMIT_DEFAULT = 1000;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* METADATA READING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// Best-effort string reading operations.
// Should NOT revert as long as sufficient gas is provided.
//
// Performs the following in order:
// 1. Returns the empty string for the following cases:
// - Reverts.
// - No returndata (e.g. function returns nothing, EOA).
// - Returns empty string.
// 2. Attempts to `abi.decode` the returndata into a string.
// 3. With any remaining gas, scans the returndata from start to end for the
// null byte '\0', to interpret the returndata as a null-terminated string.
/// @dev Equivalent to `readString(abi.encodeWithSignature("name()"))`.
function readName(address target) internal view returns (string memory) {
return _string(target, _ptr(0x06fdde03), STRING_LIMIT_DEFAULT, GAS_STIPEND_NO_GRIEF);
}
/// @dev Equivalent to `readString(abi.encodeWithSignature("name()"), limit)`.
function readName(address target, uint256 limit) internal view returns (string memory) {
return _string(target, _ptr(0x06fdde03), limit, GAS_STIPEND_NO_GRIEF);
}
/// @dev Equivalent to `readString(abi.encodeWithSignature("name()"), limit, gasStipend)`.
function readName(address target, uint256 limit, uint256 gasStipend)
internal
view
returns (string memory)
{
return _string(target, _ptr(0x06fdde03), limit, gasStipend);
}
/// @dev Equivalent to `readString(abi.encodeWithSignature("symbol()"))`.
function readSymbol(address target) internal view returns (string memory) {
return _string(target, _ptr(0x95d89b41), STRING_LIMIT_DEFAULT, GAS_STIPEND_NO_GRIEF);
}
/// @dev Equivalent to `readString(abi.encodeWithSignature("symbol()"), limit)`.
function readSymbol(address target, uint256 limit) internal view returns (string memory) {
return _string(target, _ptr(0x95d89b41), limit, GAS_STIPEND_NO_GRIEF);
}
/// @dev Equivalent to `readString(abi.encodeWithSignature("symbol()"), limit, gasStipend)`.
function readSymbol(address target, uint256 limit, uint256 gasStipend)
internal
view
returns (string memory)
{
return _string(target, _ptr(0x95d89b41), limit, gasStipend);
}
/// @dev Performs a best-effort string query on `target` with `data` as the calldata.
/// The string will be truncated to `STRING_LIMIT_DEFAULT` (1000) bytes.
function readString(address target, bytes memory data) internal view returns (string memory) {
return _string(target, _ptr(data), STRING_LIMIT_DEFAULT, GAS_STIPEND_NO_GRIEF);
}
/// @dev Performs a best-effort string query on `target` with `data` as the calldata.
/// The string will be truncated to `limit` bytes.
function readString(address target, bytes memory data, uint256 limit)
internal
view
returns (string memory)
{
return _string(target, _ptr(data), limit, GAS_STIPEND_NO_GRIEF);
}
/// @dev Performs a best-effort string query on `target` with `data` as the calldata.
/// The string will be truncated to `limit` bytes.
function readString(address target, bytes memory data, uint256 limit, uint256 gasStipend)
internal
view
returns (string memory)
{
return _string(target, _ptr(data), limit, gasStipend);
}
// Best-effort unsigned integer reading operations.
// Should NOT revert as long as sufficient gas is provided.
//
// Performs the following in order:
// 1. Attempts to `abi.decode` the result into a uint256
// (equivalent across all Solidity uint types, downcast as needed).
// 2. Returns zero for the following cases:
// - Reverts.
// - No returndata (e.g. function returns nothing, EOA).
// - Returns zero.
// - `abi.decode` failure.
/// @dev Equivalent to `uint8(readUint(abi.encodeWithSignature("decimals()")))`.
function readDecimals(address target) internal view returns (uint8) {
return uint8(_uint(target, _ptr(0x313ce567), GAS_STIPEND_NO_GRIEF));
}
/// @dev Equivalent to `uint8(readUint(abi.encodeWithSignature("decimals()"), gasStipend))`.
function readDecimals(address target, uint256 gasStipend) internal view returns (uint8) {
return uint8(_uint(target, _ptr(0x313ce567), gasStipend));
}
/// @dev Performs a best-effort uint query on `target` with `data` as the calldata.
function readUint(address target, bytes memory data) internal view returns (uint256) {
return _uint(target, _ptr(data), GAS_STIPEND_NO_GRIEF);
}
/// @dev Performs a best-effort uint query on `target` with `data` as the calldata.
function readUint(address target, bytes memory data, uint256 gasStipend)
internal
view
returns (uint256)
{
return _uint(target, _ptr(data), gasStipend);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Attempts to read and return a string at `target`.
function _string(address target, bytes32 ptr, uint256 limit, uint256 gasStipend)
private
view
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
function min(x_, y_) -> _z {
_z := xor(x_, mul(xor(x_, y_), lt(y_, x_)))
}
for {} staticcall(gasStipend, target, add(ptr, 0x20), mload(ptr), 0x00, 0x20) {} {
let m := mload(0x40) // Grab the free memory pointer.
let s := add(0x20, m) // Start of the string's bytes in memory.
// Attempt to `abi.decode` if the returndatasize is greater or equal to 64.
if iszero(lt(returndatasize(), 0x40)) {
let o := mload(0x00) // Load the string's offset in the returndata.
// If the string's offset is within bounds.
if iszero(gt(o, sub(returndatasize(), 0x20))) {
returndatacopy(m, o, 0x20) // Copy the string's length.
// If the full string's end is within bounds.
// Note: If the full string doesn't fit, the `abi.decode` must be aborted
// for compliance purposes, regardless if the truncated string can fit.
if iszero(gt(mload(m), sub(returndatasize(), add(o, 0x20)))) {
let n := min(mload(m), limit) // Truncate if needed.
mstore(m, n) // Overwrite the length.
returndatacopy(s, add(o, 0x20), n) // Copy the string's bytes.
mstore(add(s, n), 0) // Zeroize the slot after the string.
mstore(0x40, add(0x20, add(s, n))) // Allocate memory for the string.
result := m
break
}
}
}
// Try interpreting as a null-terminated string.
let n := min(returndatasize(), limit) // Truncate if needed.
returndatacopy(s, 0, n) // Copy the string's bytes.
mstore8(add(s, n), 0) // Place a '\0' at the end.
let i := s // Pointer to the next byte to scan.
for {} byte(0, mload(i)) { i := add(i, 1) } {} // Scan for '\0'.
mstore(m, sub(i, s)) // Store the string's length.
mstore(i, 0) // Zeroize the slot after the string.
mstore(0x40, add(0x20, i)) // Allocate memory for the string.
result := m
break
}
}
}
/// @dev Attempts to read and return a uint at `target`.
function _uint(address target, bytes32 ptr, uint256 gasStipend)
private
view
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
result :=
mul(
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gasStipend, target, add(ptr, 0x20), mload(ptr), 0x20, 0x20)
)
)
}
}
/// @dev Casts the function selector `s` into a pointer.
function _ptr(uint256 s) private pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
// Layout the calldata in the scratch space for temporary usage.
mstore(0x04, s) // Store the function selector.
mstore(result, 4) // Store the length.
}
}
/// @dev Casts the `data` into a pointer.
function _ptr(bytes memory data) private pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := data
}
}
}
lib/solady/src/utils/Multicallable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Contract that enables a single call to call multiple methods on itself.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Multicallable.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Multicallable.sol)
///
/// WARNING:
/// This implementation is NOT to be used with ERC2771 out-of-the-box.
/// https://blog.openzeppelin.com/arbitrary-address-spoofing-vulnerability-erc2771context-multicall-public-disclosure
/// This also applies to potentially other ERCs / patterns appending to the back of calldata.
///
/// We do NOT have a check for ERC2771, as we do not inherit from OpenZeppelin's context.
/// Moreover, it is infeasible and inefficient for us to add checks and mitigations
/// for all possible ERC / patterns appending to the back of calldata.
///
/// We would highly recommend using an alternative pattern such as
/// https://github.com/Vectorized/multicaller
/// which is more flexible, futureproof, and safer by default.
abstract contract Multicallable {
/// @dev Apply `delegatecall` with the current contract to each calldata in `data`,
/// and store the `abi.encode` formatted results of each `delegatecall` into `results`.
/// If any of the `delegatecall`s reverts, the entire context is reverted,
/// and the error is bubbled up.
///
/// By default, this function directly returns the results and terminates the call context.
/// If you need to add before and after actions to the multicall, please override this function.
function multicall(bytes[] calldata data) public payable virtual returns (bytes[] memory) {
// Revert if `msg.value` is non-zero by default to guard against double-spending.
// (See: https://www.paradigm.xyz/2021/08/two-rights-might-make-a-wrong)
//
// If you really need to pass in a `msg.value`, then you will have to
// override this function and add in any relevant before and after checks.
if (msg.value != 0) revert();
// `_multicallDirectReturn` returns the results directly and terminates the call context.
_multicallDirectReturn(_multicall(data));
}
/// @dev The inner logic of `multicall`.
/// This function is included so that you can override `multicall`
/// to add before and after actions, and use the `_multicallDirectReturn` function.
function _multicall(bytes[] calldata data) internal virtual returns (bytes32 results) {
/// @solidity memory-safe-assembly
assembly {
results := mload(0x40)
mstore(results, 0x20)
mstore(add(0x20, results), data.length)
let c := add(0x40, results)
let s := c
let end := shl(5, data.length)
calldatacopy(c, data.offset, end)
end := add(c, end)
let m := end
if data.length {
for {} 1 {} {
let o := add(data.offset, mload(c))
calldatacopy(m, add(o, 0x20), calldataload(o))
// forgefmt: disable-next-item
if iszero(delegatecall(gas(), address(), m, calldataload(o), codesize(), 0x00)) {
// Bubble up the revert if the delegatecall reverts.
returndatacopy(results, 0x00, returndatasize())
revert(results, returndatasize())
}
mstore(c, sub(m, s))
c := add(0x20, c)
// Append the `returndatasize()`, and the return data.
mstore(m, returndatasize())
let b := add(m, 0x20)
returndatacopy(b, 0x00, returndatasize())
// Advance `m` by `returndatasize() + 0x20`,
// rounded up to the next multiple of 32.
m := and(add(add(b, returndatasize()), 0x1f), 0xffffffffffffffe0)
mstore(add(b, returndatasize()), 0) // Zeroize the slot after the returndata.
if iszero(lt(c, end)) { break }
}
}
mstore(0x40, m) // Allocate memory.
results := or(shl(64, sub(m, results)), results) // Pack the bytes length into `results`.
}
}
/// @dev Decodes the `results` into an array of bytes.
/// This can be useful if you need to access the results or re-encode it.
function _multicallResultsToBytesArray(bytes32 results)
internal
pure
virtual
returns (bytes[] memory decoded)
{
/// @solidity memory-safe-assembly
assembly {
decoded := mload(0x40)
let c := and(0xffffffffffffffff, results) // Extract the offset.
mstore(decoded, mload(add(c, 0x20))) // Store the length.
let o := add(decoded, 0x20) // Start of elements in `decoded`.
let end := add(o, shl(5, mload(decoded)))
mstore(0x40, end) // Allocate memory.
let s := add(c, 0x40) // Start of elements in `results`.
let d := sub(s, o) // Difference between input and output pointers.
for {} iszero(eq(o, end)) { o := add(o, 0x20) } { mstore(o, add(mload(add(d, o)), s)) }
}
}
/// @dev Directly returns the `results` and terminates the current call context.
/// `results` must be from `_multicall`, else behavior is undefined.
function _multicallDirectReturn(bytes32 results) internal pure virtual {
/// @solidity memory-safe-assembly
assembly {
return(and(0xffffffffffffffff, results), shr(64, results))
}
}
}
lib/solady/src/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Reentrancy guard mixin (transient storage variant).
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuardTransient.sol)
///
/// @dev Note: This implementation utilizes the `TSTORE` and `TLOAD` opcodes.
/// Please ensure that the chain you are deploying on supports them.
abstract contract ReentrancyGuardTransient {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unauthorized reentrant call.
error Reentrancy();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to: `uint32(bytes4(keccak256("Reentrancy()"))) | 1 << 71`.
/// 9 bytes is large enough to avoid collisions in practice,
/// but not too large to result in excessive bytecode bloat.
uint256 private constant _REENTRANCY_GUARD_SLOT = 0x8000000000ab143c06;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* REENTRANCY GUARD */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Guards a function from reentrancy.
modifier nonReentrant() virtual {
if (_useTransientReentrancyGuardOnlyOnMainnet()) {
uint256 s = _REENTRANCY_GUARD_SLOT;
if (block.chainid == 1) {
/// @solidity memory-safe-assembly
assembly {
if tload(s) {
mstore(0x00, s) // `Reentrancy()`.
revert(0x1c, 0x04)
}
tstore(s, address())
}
} else {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(s), address()) {
mstore(0x00, s) // `Reentrancy()`.
revert(0x1c, 0x04)
}
sstore(s, address())
}
}
} else {
/// @solidity memory-safe-assembly
assembly {
if tload(_REENTRANCY_GUARD_SLOT) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
tstore(_REENTRANCY_GUARD_SLOT, address())
}
}
_;
if (_useTransientReentrancyGuardOnlyOnMainnet()) {
uint256 s = _REENTRANCY_GUARD_SLOT;
if (block.chainid == 1) {
/// @solidity memory-safe-assembly
assembly {
tstore(s, 0)
}
} else {
/// @solidity memory-safe-assembly
assembly {
sstore(s, s)
}
}
} else {
/// @solidity memory-safe-assembly
assembly {
tstore(_REENTRANCY_GUARD_SLOT, 0)
}
}
}
/// @dev Guards a view function from read-only reentrancy.
modifier nonReadReentrant() virtual {
if (_useTransientReentrancyGuardOnlyOnMainnet()) {
uint256 s = _REENTRANCY_GUARD_SLOT;
if (block.chainid == 1) {
/// @solidity memory-safe-assembly
assembly {
if tload(s) {
mstore(0x00, s) // `Reentrancy()`.
revert(0x1c, 0x04)
}
}
} else {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(s), address()) {
mstore(0x00, s) // `Reentrancy()`.
revert(0x1c, 0x04)
}
}
}
} else {
/// @solidity memory-safe-assembly
assembly {
if tload(_REENTRANCY_GUARD_SLOT) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
}
}
_;
}
/// @dev For widespread compatibility with L2s.
/// Only Ethereum mainnet is expensive anyways.
function _useTransientReentrancyGuardOnlyOnMainnet() internal view virtual returns (bool) {
return true;
}
}
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)
}
}
}
}
src/utils/PositionSVG.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.36;
import {Base64} from "../../lib/solady/src/utils/Base64.sol";
import {LibString} from "../../lib/solady/src/utils/LibString.sol";
import {MetadataReaderLib} from "../../lib/solady/src/utils/MetadataReaderLib.sol";
/// @notice Small helpers for self-contained live-position metadata.
/// @dev The WNS answer is deliberately treated as untrusted display text. SVG
/// metadata is consumed by wallets and marketplaces, so only a compact
/// ASCII subset is admitted rather than interpolating arbitrary XML.
library PositionSVG {
address internal constant WNS = 0x0000000000696760E15f265e828DB644A0c242EB;
bytes4 internal constant REVERSE_RESOLVE = 0x9af8b7aa; // reverseResolve(address)
function dataURI(string memory mime, string memory body) internal pure returns (string memory) {
return string.concat("data:", mime, ";base64,", Base64.encode(bytes(body)));
}
/// @dev The shared card chrome. Every board renders into the same 720x420
/// frame so a wallet showing positions from all three reads as one
/// family, and so the geometry is fixed once rather than three times.
/// No width or height attribute: the card scales to whatever box it is
/// given, from a list thumbnail up to a full screen.
string internal constant OPEN =
"<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 720 420'><rect width='720' height='420' fill='#000'/>";
/// @dev The frame and its two rules. Callers open their own stroked group so
/// board-specific geometry (a curve, a fill bar) joins the same group.
string internal constant FRAME =
"<g fill='none' stroke='#fff' stroke-width='2'><rect x='18' y='18' width='684' height='384'/><path d='M18 88h684M18 326h684";
string internal constant TEXT = "</g><g fill='#fff' font-family='Helvetica,Arial,sans-serif'>";
/// @dev Every label on a card is drawn in this grey and every value in white.
/// The cards used to separate the two with a double space, which SVG's
/// default whitespace handling COLLAPSES - so "MAKER 0x12..." shipped
/// as "MAKER 0x12..." and a row of same-size, same-colour text ran
/// together with nothing marking where the question ended and the
/// answer began. Colour does that job in a way whitespace cannot.
string internal constant MUTED = "#8b939e";
/// @dev Column headings. Smaller, tracked out and muted, so the 22px figure
/// under a heading is unmistakably the subject and the heading is
/// unmistakably a label - at 12px against a 13px value line they
/// competed.
string internal constant LABEL =
"<text font-size='11' letter-spacing='.09em' fill='#8b939e' ";
/// @dev Axis captions sitting either side of the schedule curve. The left one
/// opens at the margin, the right one is anchored to it, so a wide
/// number grows inward instead of off the card.
string internal constant AXIS_L = "<text font-size='12' x='32' ";
string internal constant AXIS_R = "<text font-size='12' text-anchor='end' x='688' ";
/// @dev An inline label preceding a value on the same line. See `MUTED`.
function key(string memory label) internal pure returns (string memory) {
return string.concat("<tspan fill='", MUTED, "'>", label, "</tspan> ");
}
string internal constant CLOSE = "</g></svg>";
/// @dev The full schedule, drawn faint, with the shape itself put in
/// `<defs>` so the trace can be drawn over it.
///
/// The shape used to be a rendered `<path opacity='.3'>` that the
/// trace referenced with `<use opacity='1'>`. A `<use>` clones the
/// referenced element WITH its own presentation attributes, and those
/// win over the ones on the `<use>` - so the accent trace inherited
/// the .3 and every card drew the elapsed part of its schedule at the
/// same weight as the part still to come. The state colour was there;
/// it was three-tenths visible. Defining the geometry unstyled and
/// giving each instance its own weight is what the two-`<use>` shape
/// was for in the first place.
/// The id carries the position number because a card is not always
/// rendered alone. As an `<img src=data:...>` - what a wallet does -
/// each SVG is its own document and any id is safe; inlined into a
/// marketplace's page, two cards sharing `id='c'` mean the second
/// one's `<use>` resolves to the FIRST one's geometry and draws
/// somebody else's schedule.
function baseline(string memory path, uint256 curveEnd, string memory id)
internal
pure
returns (string memory)
{
return string.concat(
"<defs><path id='",
id,
"' d='",
path,
LibString.toString(curveEnd),
"' pathLength='100'/></defs>",
use_(id, "opacity='.3'")
);
}
/// @dev One instance of the shared geometry. Both `href` and the legacy
/// `xlink:href` are written because renderers in the wild honour
/// different ones.
function use_(string memory id, string memory attrs) internal pure returns (string memory) {
return string.concat("<use href='#", id, "' xlink:href='#", id, "' ", attrs, "/>");
}
/// @dev The point the traced schedule has reached, marked on the curve.
/// The curve's whole job is to say where the listing is in its
/// schedule, and until now it said it only as a length of coloured
/// line - readable next to the baseline it is drawn over, and at a
/// thumbnail's size not readable at all. A filled head reads as a
/// position at any scale, which is what a percentage in the row above
/// already gives a reader who is willing to stop and parse it.
///
/// Both boards' control point sits at the midpoint's x, so the head's
/// x is exactly `32 + 656t` on either curve and only the y differs.
function head(uint256 y, uint256 progress, string memory accent)
internal
pure
returns (string memory)
{
return string.concat(
"<circle r='4' stroke='none' fill='",
accent,
"' cx='",
LibString.toString(32 + (656 * progress) / 10_000),
"' cy='",
LibString.toString(y),
"'/>"
);
}
/// @dev The status palette, defined once for the whole family. These strings
/// are read at a thumbnail's size, where the colour lands before the
/// word does, so the same state must be the same colour on all three
/// boards - EXPIRED was previously amber on two of them and red on the
/// third, while that same amber meant FLOOR on the third.
string internal constant LIVE = "#43d69b"; // still actionable
string internal constant FILLED = "#6fa8ff"; // completed in full
string internal constant CLOSED = "#969da7"; // ended without settling
string internal constant FROZEN = "#c69cff"; // claim suspended
string internal constant EXPIRED = "#ff8f8f"; // deadline passed
string internal constant RESTING = "#ffb55b"; // schedule exhausted, still takeable
string internal constant FREE = "#5ee6d2"; // decayed to nothing
/// @dev Deliberately a muted blue rather than `FILLED`'s saturated one. The
/// two were the same value, so "has not started" and "completely done"
/// - the two states furthest apart in meaning - were indistinguishable
/// until you read the word.
string internal constant PENDING = "#8fa4c4"; // window has not opened
/// @dev The identity line under a leg's amount. A symbol alone is
/// attacker-chosen and a bare address is unreadable, so the card
/// carries both: the ticker to recognise, the address to verify.
/// Written `SYM / 0x1234...cdef / 18 DEC` - the standard's name is
/// dropped because the decimal basis already implies fungibility and
/// the token's own traits state it exactly.
function legLabel(address token, string memory symbol, uint8 snapshot, bool isNFT)
internal
pure
returns (string memory line)
{
line = shortAddress(token);
// A fungible leg needs its scale stated or the amount above it cannot be
// read. An NFT leg does not: the figure above it already reads "TOKEN
// #1" / "BUNDLE 3" / "NFT x2", so a trailing "/ NFT" only repeats it -
// and repeated it twice over for a collection whose ticker is "NFT".
if (!isNFT) line = string.concat(line, " / ", decimalsLabel(snapshot));
else if (bytes(symbol).length == 0) line = string.concat(line, " / NFT");
if (bytes(symbol).length != 0) line = string.concat(symbol, " / ", line);
}
/// @dev The quote leg of a priced board. Native ETH is its own identity and
/// needs no address or scale beside it; anything else is a token and is
/// written exactly like a lot leg.
function quoteLine(address quote, string memory symbol, uint8 snapshot)
internal
pure
returns (string memory)
{
if (quote == address(0)) return "ETH";
return legLabel(quote, symbol, snapshot, false);
}
/// @dev Basis points as a percentage with the hundredths padded: 1005 is
/// 10.05%, not 10.5%. Shared because an unpadded split is wrong twice
/// over - it misreports the number and, where the same value drives a
/// `stroke-dasharray`, it draws the wrong length of curve.
function percent(uint256 bps) internal pure returns (string memory) {
uint256 fraction = bps % 100;
return string.concat(
LibString.toString(bps / 100), ".", fraction < 10 ? "0" : "", LibString.toString(fraction)
);
}
/// @dev Timestamps are shown as raw unix seconds on purpose: they are exact,
/// chain-native, locale-free, and need no calendar arithmetic onchain.
function timestamp(uint256 unixTime) internal pure returns (string memory) {
return unixTime == 0 ? "NEVER" : string.concat("UNIX ", LibString.toString(unixTime));
}
/// @dev The decimal basis on its own, for a quote leg. `assetType` asserts a
/// token standard as well, which is wrong for a quote: what a reader
/// needs there is only the scale the price is written in.
function decimalsLabel(uint8 snapshot) internal pure returns (string memory) {
return snapshot == 0 ? "RAW" : string.concat(LibString.toString(snapshot - 1), " DEC");
}
/// @dev The zero address is native ETH on every board that accepts it.
function quoteLabel(address quote) internal pure returns (string memory) {
return quote == address(0) ? "ETH" : shortAddress(quote);
}
function shortAddress(address account) internal pure returns (string memory) {
bytes memory full = bytes(LibString.toHexString(account));
bytes memory result = new bytes(13); // 0x1234...cdef
result[0] = full[0];
result[1] = full[1];
for (uint256 i; i < 4; ++i) {
result[2 + i] = full[2 + i];
result[9 + i] = full[38 + i];
}
result[6] = ".";
result[7] = ".";
result[8] = ".";
return string(result);
}
/// @notice A WNS name when configured, otherwise a stable short address.
/// @dev Bound both gas and returned bytes so tokenURI remains reliable even
/// when queried on a chain where WNS is unavailable.
function makerLabel(address maker) internal view returns (string memory) {
(bool ok, bytes memory response) = WNS.staticcall{gas: 35_000}(
abi.encodeWithSelector(REVERSE_RESOLVE, maker)
);
if (!ok || response.length < 96) return shortAddress(maker);
// Follow the ABI head rather than assuming it sits at 0x20. A
// conformant encoder is free to pad it, and reading the length from a
// fixed word then misparses a perfectly valid answer as garbage.
uint256 offset;
assembly ("memory-safe") {
offset := mload(add(response, 0x20))
}
if (offset > response.length - 64) return shortAddress(maker);
uint256 length;
assembly ("memory-safe") {
length := mload(add(add(response, 0x20), offset))
}
if (length == 0 || length > 28 || response.length - 32 - offset < length) {
return shortAddress(maker);
}
// `offset` counts from the start of the returndata to the LENGTH word,
// so the characters begin one word after it.
string memory name = _safeText(response, offset + 32, length);
if (bytes(name).length == 0) return shortAddress(maker);
return name;
}
/// @dev Best-effort ERC-20/721 `symbol()` snapshot. The same strict text
/// policy as reverse WNS keeps a nonstandard collection from adding
/// markup to a card, and no read is made while metadata is rendered.
function readSymbol(address token) internal view returns (string memory) {
bytes memory symbol = bytes(MetadataReaderLib.readSymbol(token, 12, 15_000));
return _safeText(symbol, 0, symbol.length);
}
function _safeText(bytes memory source, uint256 start, uint256 length) private pure returns (string memory) {
bytes memory text = new bytes(length);
uint256 kept;
for (uint256 i; i < length; ++i) {
bytes1 c = source[start + i];
// Names are labels, not markup. Keep the terminal card legible and
// XML-safe even if a resolver returns an unexpected value.
// `<` and `&` are the only printable ASCII characters that can
// create XML markup/entities in element text.
// A space is not markup, and excluding it turned "Wrapped Ether"
// into "WrappedEther". The range starts at 0x20 rather than 0x21
// for that one character; the guard is otherwise unchanged, and
// deliberately no wider, because this runs inside the boards - both
// of which are within a few hundred bytes of EIP-170.
if (c >= 0x20 && c <= 0x7e && c != "<" && c != "&") {
text[kept++] = c;
}
}
assembly ("memory-safe") {
mstore(text, kept)
}
return string(text);
}
/// @dev Read a conventional ERC-20 decimals value without ever making a
/// position renderer depend on an untrusted token at display time.
/// The caller snapshots the result at creation; 36 is deliberately
/// conservative for a compact, exact decimal display.
function readDecimals(address token) internal view returns (bool known, uint8 decimals) {
(bool ok, bytes memory response) = token.staticcall{gas: 15_000}(abi.encodeWithSelector(0x313ce567));
if (!ok || response.length != 32) return (false, 0);
uint256 value;
assembly ("memory-safe") {
value := mload(add(response, 0x20))
}
if (value > 36) return (false, 0);
return (true, uint8(value));
}
/// @dev The widest number an amount slot can hold at its display size.
/// Anything longer is compacted rather than allowed to run off the
/// edge of the image, which is what keeps a card readable at any
/// scale for tokens of any denomination.
uint256 internal constant MAX_WIDTH = 18;
/// @dev `snapshot` is `decimals + 1`; zero is the explicit raw fallback.
/// Magnitude is never sacrificed: a number too wide for the slot is
/// shown in scientific notation rather than cut short.
function amount(uint256 value, uint8 snapshot, bool isNFT) internal pure returns (string memory) {
if (isNFT) return string.concat("TOKEN #", _shortId(value));
// Zero is zero at every scale. Without this an emptied leg on a filled
// order renders through the tiny-value path as "0e-18".
if (value == 0) return "0";
bytes memory raw = bytes(LibString.toString(value));
uint256 decimals = snapshot == 0 ? 0 : snapshot - 1;
uint256 n = raw.length;
if (n > decimals) {
uint256 whole = n - decimals;
if (whole > MAX_WIDTH) return _scientific(raw, whole - 1, false);
uint256 end = n;
while (end > whole && raw[end - 1] == "0") --end;
// The whole part is kept intact and whatever the slot has left over
// is spent on the fraction, so a wide number loses precision rather
// than magnitude. The second strip removes zeros the cut exposed.
if (end + 1 > MAX_WIDTH) end = MAX_WIDTH - 1;
while (end > whole && raw[end - 1] == "0") --end;
if (end <= whole) return string(_copy(raw, 0, whole));
bytes memory decimalOut = new bytes(end + 1);
for (uint256 i; i < whole; ++i) decimalOut[i] = raw[i];
decimalOut[whole] = ".";
for (uint256 i = whole; i < end; ++i) decimalOut[i + 1] = raw[i];
return string(decimalOut);
}
uint256 zeroes = decimals - n;
// Write the value out whenever five significant places survive the
// leading zeros, and state it in scientific notation when they do not -
// below that, `d.ddddeK` carries strictly more of the number than a
// string of zeros with two digits on the end.
//
// The test used to be `decimals + 2 > MAX_WIDTH`, which asks about the
// TOKEN's scale and never about the value: on any token with seventeen
// decimals or more it was true unconditionally, so half an ETH rendered
// "5e-1" in the largest slot on the card.
if (zeroes + 7 > MAX_WIDTH) return _scientific(raw, zeroes + 1, true);
// The leading zeros of the fraction, written out. A fresh `bytes` is
// zero-BYTES, not zero-DIGITS: skipping straight to the significant
// digits left NUL bytes in the gap, which is not a character XML admits
// at all - so the whole card stopped being a well-formed document - and
// read as though the zeros were not there, printing 0.012345 as
// "0.<NUL>12345". Ten times the real value, on any token with sixteen
// decimals or fewer holding a value one or two places below its first
// significant digit. 0.012345 USDC is exactly that.
// Trailing zeros carry no information and the whole-number branch above
// already drops them, so a card could otherwise show "1.5" beside
// "0.010000" for the same reason. The LEADING count is fixed by the
// original digit count and does not move; only the tail shrinks, and
// never past the last significant digit.
while (n > 1 && raw[n - 1] == "0") --n;
// Whatever the slot has left after the leading zeros is spent on
// significant digits - the same trade the whole-number branch makes,
// losing precision rather than magnitude. The second strip removes
// zeros the cut exposed.
uint256 room = MAX_WIDTH - 2 - zeroes;
if (n > room) n = room;
while (n > 1 && raw[n - 1] == "0") --n;
bytes memory fractionalOut = new bytes(2 + zeroes + n);
fractionalOut[0] = "0";
fractionalOut[1] = ".";
for (uint256 i; i < zeroes; ++i) fractionalOut[2 + i] = "0";
for (uint256 i; i < n; ++i) fractionalOut[2 + zeroes + i] = raw[i];
return string(fractionalOut);
}
/// @dev `d.dddde±K` from the decimal digits of `raw`, to at most five
/// significant figures. Used at both ends of the range: values too
/// wide for the slot and values too small to write out in full.
function _scientific(bytes memory raw, uint256 exponent, bool negative)
private
pure
returns (string memory)
{
uint256 significant = raw.length;
while (significant > 1 && raw[significant - 1] == "0") --significant;
if (significant > 5) significant = 5;
while (significant > 1 && raw[significant - 1] == "0") --significant;
bytes memory exp = bytes(LibString.toString(exponent));
bytes memory out = new bytes(significant + (significant > 1 ? 3 : 2) + exp.length);
out[0] = raw[0];
uint256 cursor = 1;
if (significant > 1) {
out[cursor++] = ".";
for (uint256 i = 1; i < significant; ++i) out[cursor++] = raw[i];
}
out[cursor++] = "e";
out[cursor++] = negative ? bytes1("-") : bytes1("+");
for (uint256 i; i < exp.length; ++i) out[cursor++] = exp[i];
return string(out);
}
/// @dev Token ids are arbitrary 256-bit words and are routinely hashes, so
/// a long one is elided in the middle the way an address is rather
/// than left to overrun the card.
function _shortId(uint256 id) internal pure returns (string memory) {
bytes memory raw = bytes(LibString.toString(id));
if (raw.length <= 12) return string(raw);
bytes memory out = new bytes(12);
for (uint256 i; i < 6; ++i) out[i] = raw[i];
out[6] = ".";
out[7] = ".";
for (uint256 i; i < 4; ++i) out[8 + i] = raw[raw.length - 4 + i];
return string(out);
}
function assetType(uint8 snapshot, bool isNFT) internal pure returns (string memory) {
if (isNFT) return "NFT";
if (snapshot == 0) return "ERC20 / RAW";
return string.concat("ERC20 / ", LibString.toString(snapshot - 1), " DEC");
}
function _copy(bytes memory input, uint256 start, uint256 end) private pure returns (bytes memory out) {
out = new bytes(end - start);
for (uint256 i; i < out.length; ++i) out[i] = input[start + i];
}
}
src/utils/SwapboardMetadata.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.36;
import {LibString} from "../../lib/solady/src/utils/LibString.sol";
import {PositionSVG} from "./PositionSVG.sol";
/// @notice Immutable renderer deployed by each Swapboard instance.
/// @dev Keeping presentation code separate lets the position board remain
/// deployable under EIP-170 without making metadata upgradeable. The card
/// shares `PositionSVG`'s 720x420 chrome with Dutchboard and Floorboard so
/// a wallet holding receipts from all three shows one family.
contract SwapboardMetadata {
struct RenderParams {
uint256 id;
address maker;
address tokenA;
address tokenB;
uint256 amountA;
uint256 amountB;
uint256 initialAmountB;
uint64 expiry;
uint8 decimalsA;
uint8 decimalsB;
string symbolA;
string symbolB;
uint64 frozenUntil;
address counterparty; // zero when the order is open to anyone
bool active;
bool settled; // closed by a fill that took the whole order
bool partialFill;
bool nftA;
bool nftB;
bool frozen;
bool restricted;
}
/// @notice Render the receipt for `id` on `board`.
/// @dev The board used to assemble `RenderParams` itself and pass the whole
/// struct across. That cost it 1,242 bytes of runtime code - the
/// twenty-field build plus the encoder for two dynamic strings - on a
/// contract with no EIP-170 headroom left, to save this one, which has
/// thousands. So the reading moved here: the board exposes its
/// snapshots as getters and this contract does the assembly.
///
/// It is a view path reached through `eth_call`, so the extra
/// staticcalls cost nothing anyone pays for, and `RenderParams` stays
/// the shape every helper below is written against.
function tokenURI(address board, uint256 id) external view returns (string memory) {
ISwapboard b = ISwapboard(board);
RenderParams memory q;
q.id = id;
(
q.maker,
q.active,
q.partialFill,
q.expiry,
q.nftA,
q.nftB,
q.counterparty,
q.tokenA,
q.amountA,
q.tokenB,
q.amountB
) = b.orders(id);
q.initialAmountB = b.initialAmountB(id);
// An NFT leg's amount is a token id, not a quantity, so it carries no
// scale - the same substitution the board made before this moved.
if (!q.nftA) q.decimalsA = b.tokenDecimals(q.tokenA);
if (!q.nftB) q.decimalsB = b.tokenDecimals(q.tokenB);
q.symbolA = b.tokenSymbols(q.tokenA);
q.symbolB = b.tokenSymbols(q.tokenB);
q.frozenUntil = b.frozenUntil(id);
q.settled = b.settled(id);
q.frozen = b.frozen(id);
q.restricted = q.counterparty != address(0);
return _render(q);
}
function _render(RenderParams memory p) internal view returns (string memory) {
(string memory status, string memory accent) = _state(p);
uint256 progress = _progress(p);
string memory svg = string.concat(
PositionSVG.OPEN,
PositionSVG.FRAME,
// The divider between the two legs, and the fill bar, drawn in the
// same stroked group as the frame. The divider stops at 230, clear
// of the full-width rows below it: a long TERMS string used to run
// straight through it.
//
// The bar sits in the 258-298 band, centred on the same 278 the
// sibling boards' schedule curve is centred on. It used to float at
// 272 with its caption immediately above and forty dead pixels
// below, which made the one board without a curve read as the one
// board that ran out of things to say.
"M360 112v100'/><rect x='32' y='270' width='656' height='16'/><rect x='32' y='270' width='",
LibString.toString((656 * progress) / 10_000),
"' height='16' fill='",
accent,
"' stroke='none'/>",
PositionSVG.TEXT,
"<text x='32' y='55' font-size='25' font-weight='700'>SWAPBOARD / POSITION #",
LibString.toString(p.id),
"</text><text x='32' y='77' font-size='12'><tspan fill='#8b939e'>ESCROW RECEIPT //</tspan> <tspan fill='",
accent,
"' font-weight='700'>",
status,
"</tspan></text>",
_legs(p),
_unitPrice(p),
_rows(p, accent, progress),
_ledger(p),
_footer(p),
PositionSVG.CLOSE
);
return PositionSVG.dataURI(
"application/json",
string.concat(
'{"name":"Swapboard Position #',
LibString.toString(p.id),
'","description":"A live escrowed order on Swapboard. The holder of this receipt is the maker: they own the escrow, its proceeds, and the right to reprice or cancel.","image":"',
PositionSVG.dataURI("image/svg+xml", svg),
'","attributes":[{"trait_type":"Board","value":"Swapboard"},{"trait_type":"Status","value":"',
status,
'"},{"trait_type":"Escrow","value":"',
p.nftA ? "ERC721" : "ERC20",
'"},{"trait_type":"Request","value":"',
p.nftB ? "ERC721" : "ERC20",
'"},{"trait_type":"Fill","value":"',
p.partialFill ? "Partial" : "All or nothing",
'"},{"trait_type":"Access","value":"',
p.restricted ? "Private" : "Public",
'"},{"display_type":"number","trait_type":"Filled %","value":',
PositionSVG.percent(progress),
"}",
_expiryAttribute(p.expiry),
"]}"
)
);
}
/// @dev Split out to keep `tokenURI`'s frame under the stack limit.
/// @dev A closed order keeps its last live terms in storage, so the headings
/// say so. Reading "ESCROW 10" off a cancelled receipt whose escrow went
/// back to the maker is the one way these numbers can mislead.
function _legs(RenderParams memory p) private pure returns (string memory) {
return string.concat(
PositionSVG.LABEL,
"x='32' y='132'>",
p.active ? "ESCROW" : "ESCROW AT CLOSE",
"</text><text x='32' y='168' font-size='22'>",
PositionSVG.amount(p.amountA, p.decimalsA, p.nftA),
"</text><text x='32' y='192' font-size='12'>",
PositionSVG.legLabel(p.tokenA, p.symbolA, p.decimalsA, p.nftA),
"</text>",
PositionSVG.LABEL,
"x='384' y='132'>",
p.active ? "REQUEST" : "REQUEST AT CLOSE",
"</text><text x='384' y='168' font-size='22'>",
PositionSVG.amount(p.amountB, p.decimalsB, p.nftB),
"</text><text x='384' y='192' font-size='12'>",
PositionSVG.legLabel(p.tokenB, p.symbolB, p.decimalsB, p.nftB),
"</text>"
);
}
/// @dev The terms row and the bar's caption. Split out with `_footer` to
/// keep `tokenURI`'s frame under the stack limit - it went one slot over
/// when the labels gained their tspans.
function _rows(RenderParams memory p, string memory accent, uint256 progress)
private
view
returns (string memory)
{
return string.concat(
"<text x='32' y='230' font-size='12'>",
PositionSVG.key("TERMS"),
_tags(p),
"</text>",
"<text x='32' y='248' font-size='12'>",
PositionSVG.key("FILL PROGRESS"),
"<tspan fill='",
accent,
"' font-weight='700'>",
PositionSVG.percent(progress),
"%</tspan></text>"
);
}
/// @dev The footer band runs 326-402 and held two lines hugging its top
/// edge. Centred, they read as belonging to the band rather than
/// hanging off the rule above it.
function _footer(RenderParams memory p) private view returns (string memory) {
return string.concat(
"<text x='32' y='358' font-size='12'>",
PositionSVG.key("MAKER"),
PositionSVG.makerLabel(p.maker),
"</text><text x='32' y='382' font-size='12'>",
PositionSVG.key("EXPIRY"),
PositionSVG.timestamp(p.expiry),
"</text>",
_reserved(p)
);
}
/// @dev The fill bar in words, on the row the sibling boards close their
/// schedule band with. Swapboard is the one board with no curve, and
/// its lower half ended at the bar with the whole 286-326 strip empty
/// while Dutchboard and Floorboard carried captions down to 316.
///
/// PAID and the original ask are the two facts the bar is drawn from
/// that are NOT already on the card. What is left to pay is deliberately
/// absent: it is `amountB`, which is the REQUEST figure in the hero slot
/// directly above, so naming it here restated a number verbatim instead
/// of adding one.
function _ledger(RenderParams memory p) private pure returns (string memory) {
if (p.nftB || p.initialAmountB == 0 || p.amountB > p.initialAmountB) return "";
return string.concat(
PositionSVG.AXIS_L,
"y='316'>",
PositionSVG.key("PAID"),
PositionSVG.amount(p.initialAmountB - p.amountB, p.decimalsB, false),
"</text>",
PositionSVG.AXIS_R,
"y='316'>",
PositionSVG.key("REQUESTED AT OPEN"),
PositionSVG.amount(p.initialAmountB, p.decimalsB, false),
"</text>"
);
}
/// @dev What one whole unit of the escrowed asset is being asked for, in the
/// request asset. Both sibling boards put a price in their largest slot;
/// a swap order's price is the entire point of it, and until now it was
/// the one fact a reader had to work out for themselves - across two
/// different decimal bases, from two raw amounts. Sits under the request
/// leg because that is what it is denominated in.
///
/// A partial fill scales both legs together, so this holds for the life
/// of the order and only a reprice moves it.
function _unitPrice(RenderParams memory p) private pure returns (string memory) {
if (p.nftA || p.nftB || p.amountA == 0 || p.amountB == 0) return "";
// `decimalsA` is a snapshot: decimals + 1, with zero meaning raw units.
uint256 scale = 10 ** (p.decimalsA == 0 ? 0 : p.decimalsA - 1);
// Checked rather than assumed. An immutable renderer must never be the
// reason a receipt reverts instead of drawing, however odd the pair.
if (p.amountB > type(uint256).max / scale) return "";
uint256 rate = (p.amountB * scale) / p.amountA;
// Below one base unit per whole unit there is no price left to show, and
// "UNIT PRICE 0" would state something false about a live order.
if (rate == 0) return "";
return string.concat(
"<text x='384' y='210' font-size='12'>", PositionSVG.key("UNIT PRICE"), "",
PositionSVG.amount(rate, p.decimalsB, false),
"</text>"
);
}
/// @dev Who is allowed to take this order, stated on every card rather than
/// only on private ones. "PRIVATE" in the terms told the holder that
/// somebody else held the only right to fill without telling them who -
/// the one fact that decides what the position is worth to them - and a
/// public order said nothing at all, leaving the reader to infer it from
/// an absence. Sits beside MAKER: the two are the same kind of fact.
function _reserved(RenderParams memory p) private pure returns (string memory) {
return string.concat(
"<text text-anchor='end' x='688' y='358' font-size='12'>",
PositionSVG.key("TAKER"),
p.counterparty == address(0) ? "ANYONE" : PositionSVG.shortAddress(p.counterparty),
"</text>"
);
}
/// @dev An ERC-721 expiry is a real terminal state, so a zero timestamp has
/// to read as "never" rather than as an epoch date. Emitted only when
/// set so a perpetual order carries no misleading date trait.
function _expiryAttribute(uint64 expiry) private pure returns (string memory) {
if (expiry == 0) return "";
return string.concat(
',{"display_type":"date","trait_type":"Expiry","value":', LibString.toString(expiry), "}"
);
}
/// @dev The one headline state. Everything a state can coincide with -
/// private, frozen, divisible - is a tag rather than a status, so no
/// combination of them can hide another.
function _state(RenderParams memory p) private view returns (string memory, string memory) {
// The board says whether the close was a settlement. It used to be
// inferred from both legs reading zero, which is exactly what a
// CANCELLED order escrowing NFT token id 0 against NFT token id 0 also
// reads as - that receipt claimed FILLED, and its bar claimed 100%.
if (!p.active) {
return p.settled ? ("FILLED", PositionSVG.FILLED) : ("CLOSED", PositionSVG.CLOSED);
}
// FROZEN outranks EXPIRED, matching Dutchboard: an order that is both
// used to draw a different headline and a different accent on the two
// boards, which is exactly the family consistency the shared palette
// exists to hold. A suspended claim is the fact the holder can act on.
if (p.frozen) return ("FROZEN", PositionSVG.FROZEN);
if (p.expiry != 0 && p.expiry < block.timestamp) return ("EXPIRED", PositionSVG.EXPIRED);
return ("OPEN", PositionSVG.LIVE);
}
/// @dev The order's remaining terms, in the space a status line cannot
/// carry: divisibility, and whether the claim is merely soft-frozen or
/// bound until a timestamp nobody - the owner included - can shorten.
///
/// Access is deliberately NOT here. It used to append "/ PRIVATE", but
/// the footer now names the taker outright on every card, so the tag
/// said the same thing a second time and less precisely. This line is
/// about how the order fills; that one is about who may fill it.
function _tags(RenderParams memory p) private view returns (string memory tags) {
tags = p.partialFill ? "PARTIAL FILL" : "ALL OR NOTHING";
if (p.frozenUntil > block.timestamp) {
tags = string.concat(tags, " / BOUND UNIX ", LibString.toString(p.frozenUntil));
} else if (p.frozen) {
tags = string.concat(tags, " / FROZEN");
}
}
/// @dev How much of the current ask has been paid, in basis points.
function _progress(RenderParams memory p) private pure returns (uint256) {
// A settled order is complete whatever its legs read. A cancelled one
// keeps whatever it managed to fill first, which is the honest number.
if (p.settled) return 10_000;
// An NFT leg has no ratio to measure - and its amount is a token id
// rather than a quantity - so it reads as untouched unless settled.
if (p.nftA || p.nftB) return 0;
// A reprice rebases `initialAmountB`, so `amountB` is never above it in
// practice. Clamped anyway: an immutable renderer must not be the reason
// a receipt becomes unreadable if the board ever writes them out of step.
if (p.initialAmountB == 0 || p.amountB >= p.initialAmountB) return 0;
return ((p.initialAmountB - p.amountB) * 10_000) / p.initialAmountB;
}
}
interface ISwapboard {
function orders(uint256)
external
view
returns (address, bool, bool, uint64, bool, bool, address, address, uint256, address, uint256);
function initialAmountB(uint256) external view returns (uint256);
function tokenDecimals(address) external view returns (uint8);
function tokenSymbols(address) external view returns (string memory);
function settled(uint256) external view returns (bool);
function frozenUntil(uint256) external view returns (uint64);
function frozen(uint256) external view returns (bool);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.