Verified contractPartialMIT
CovenantNotes
Address0x7798ee1c7f63df202eb4f9f17706b3aaac75853a
- Balance
0 ETH
- Transactions
23
- 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
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,785,647
- Creation transaction
- 0xec841d3fa4…a2111b22b9
7 files
src/CovenantNotes.sol
// SPDX-License-Identifier: MIT
// Landing: https://covenanthook.com/
// DApp: https://app.covenanthook.com/
// Documentation: https://gitbook.covenanthook.com/
// X: https://x.com/covenantv4
// Telegram: https://t.me/covenanthook
pragma solidity ^0.8.36;
import {ERC721} from "solady/src/tokens/ERC721.sol";
import {Base64} from "solady/src/utils/Base64.sol";
import {LibString} from "solady/src/utils/LibString.sol";
import {ICovenantERC20} from "./interfaces/ICovenantERC20.sol";
import {CovenantSocials} from "./base/CovenantSocials.sol";
/// @notice Optional art source for bond metadata. Kept as a separate contract so that
/// artwork can be added after launch without the bond contract — which is
/// immutable — having to know anything about it in advance.
interface ICovenantBondRenderer {
function imageURI(uint256 tokenId) external view returns (string memory);
}
/// @title CovenantNotes
/// @notice Bond positions, held as ERC-721 tokens.
///
/// A holder commits tokens to open a bond, or receives one automatically from the
/// retention on a sell. Committed tokens are NOT destroyed: they join this
/// contract's pool and become part of what it can pay out. Every bond earns a
/// 10%/day base rate, rising by +0.25 point per compound (at most one bonus per
/// 6h window). A committed bond carries a +5 point boost on top — 15%/day at
/// birth — forfeited, per bond and for good, the moment its holder sells or
/// transfers a single token. The effective rate is capped at 20%/day. Claiming
/// does not reset the rate, and a commit-origin bond also exempts its owner's
/// router sells from the retention entirely (no skim, no new bond).
///
/// @dev Why an NFT, from day one:
///
/// Positions must eventually be transferable and tradeable. Whether a position is
/// "a row keyed by address" or "an object with an owner" is a storage decision, and
/// changing it later would force a migration. Keying by token id now means the v2
/// unlock is a single switch — no migration, no user action, no second pool. (That
/// switch is reversible; see `setTransfersEnabled`, which spells out what it costs.)
///
/// It also removes a whole class of bug: with one bond per address, moving a
/// position into an address that already held one would silently overwrite it while
/// the global counters kept counting the destroyed value.
///
/// Other things worth knowing:
///
/// * `principal` is a YIELD BASIS, not a balance. Compounding raises it without
/// moving tokens, so the sum of all principals is not backed one-for-one. That is
/// intended: payouts are capped by what this contract holds and stop when it is
/// empty — first come, first served.
///
/// * Accrual is O(1) per position: computed from elapsed time on the position
/// itself, never by iterating holders.
///
/// * The contract accepts tokens from any source (the reserve deposited at deploy,
/// sell-side retention, plain transfers). Anything that lands here is payable as
/// rewards.
contract CovenantNotes is ERC721, CovenantSocials {
using LibString for uint256;
// ------------------------------------------------------------------ parameters --
uint256 public constant BPS = 10_000;
uint256 public constant BASE_RATE_BPS = 1_000; // 10%/day — every bond's stored base
/// @dev The commit boost. NEVER folded into the stored rate: it is added at read
/// time while it is alive, so forfeiting it costs one per-wallet timestamp
/// write instead of a loop over positions — a loop that dust-bond spam
/// (`openBondFrom` mints to any actor) would turn into a gas bomb.
uint256 public constant BOOST_BPS = 500; // +5 points while the commit boost is alive
uint256 public constant MAX_RATE_BPS = 2_000; // 20%/day — cap on the EFFECTIVE rate
uint256 public constant RATE_STEP_BPS = 25; // +0.25 point per compound
/// @dev EVERY bond, sell-side or commit, grants its FIRST holder a lifetime
/// retention-exemption allowance of EXEMPT_CAP_MULTIPLE x the principal it
/// opened with. Struck once at `_open` and never revised: not by compounding,
/// not by a transfer, not by a marketplace sale.
///
/// Cumulative on purpose. A per-sale check would let a whale with a dust bond
/// salami-slice any volume through it, which is the exact abuse the cap exists
/// to stop. Fixing it at the OPENING principal closes the other half: accrued
/// rewards cannot be compounded into fresh retention-free volume, and a bond
/// cannot be passed around to mint an allowance at each stop.
uint256 public constant EXEMPT_CAP_MULTIPLE = 5;
uint256 public constant MIN_COMMIT_BPS = 2_000; // a voluntary bond takes 20%..100%
/// @dev Absolute floor on a voluntary commitment, alongside the percentage one. The
/// percentage alone is measured on `balanceOf(msg.sender)` at call time — a
/// figure the caller sets freely by moving tokens to a second address first — so
/// on its own it is a two-transaction speed bump, and below a 4-wei balance it
/// rounds to zero and admits 1-wei bonds. Since a bond is an NFT that can be
/// pushed onto a stranger, dust bonds are also how you spam somebody's position
/// list. This floor cannot be dodged by splitting a balance.
uint256 public constant MIN_COMMIT_ABS = 1e18;
/// @dev Longest image string a renderer may contribute to `tokenURI`.
uint256 internal constant MAX_IMAGE_URI_BYTES = 8_192;
/// @notice Length of one bonus window: at most one +0.25 rate step per window.
/// @dev A constructor parameter rather than a constant, for the same reason the
/// launch tax is: the mechanism cannot be tested at its production cadence.
/// PRODUCTION IS 6 HOURS; testnet deployments shorten it (60s) so the whole
/// ladder is exercisable in minutes instead of weeks. Immutable, so a deployment
/// states its cadence once and can never quietly change it. Kept SHOUTING_CASE
/// so the getter's ABI matches what the constant exposed.
uint256 public immutable BONUS_COOLDOWN;
ICovenantERC20 public immutable token;
address public immutable deployer;
/// @notice How a bond came to exist. Permanent, and it survives transfers: the
/// origin is what carries the retention exemption — the boost does not.
enum Origin {
Sell,
Commit
}
/// @dev Field widths are chosen so the rate, the clocks and the boost state share
/// ONE storage slot: 32 + 64 + 64 + 8 + 64 + 8 = 240 bits. Giving any of them a
/// full word of its own would cost an extra slot to read and write on every
/// single compound.
struct Bond {
uint256 principal; // yield basis
uint256 pending; // accrued, unclaimed
uint32 rateBps; // STORED daily rate: base + compound steps, BASE_RATE..MAX_RATE
uint64 lastAccrual;
uint64 lastBonusAt;
Origin origin;
uint64 ownedSince; // protocolNow() at the last real change of hands
bool boostDead; // sticky: once the boost is forfeited it never comes back
}
mapping(uint256 => Bond) internal _bonds;
uint256 public nextTokenId = 1; // id 0 is never minted, so 0 means "no bond"
/// @dev Contract allowed to open sell-side bonds (the hook). Wired once.
address public retentionSource;
/// @dev Contract allowed to catch up positions IT HOLDS in escrow (the bond market).
/// Wired once, same shape as `retentionSource`. Left unset — which is the v1
/// state — `compoundEscrowed` can never be reached.
address public custodian;
/// @notice The instant a wallet last SENT tokens anywhere — a sell, a transfer, one
/// single wei: the token reports every outbound move through `onTokenDebit`.
/// A commit bond's boost is alive only while its beneficial owner has not
/// moved a token since acquiring the position.
mapping(address => uint64) public lastStripAt;
/// @dev Beneficial owner of a position while the custodian holds it in escrow.
/// Written when a bond moves INTO the custodian, cleared on the way out. It is
/// what keeps the boost — and the retention exemption — attached to the seller
/// rather than to the market contract.
mapping(uint256 => address) public escrowSeller;
/// @notice How many commit-origin bonds a wallet beneficially owns (escrowed
/// listings included).
mapping(address => uint32) public commitBondCountOf;
/// @notice Sum of the commit-origin principals a wallet beneficially owns. The base
/// of the retention-exemption allowance: it grows with commits and with
/// compounding, moves on a sale, and stays with the seller through escrow.
mapping(address => uint256) public commitPrincipalOf;
/// @notice Exempt-sale volume a wallet has consumed, lifetime. Compared against
/// `exemptGrantedOf` to price the next sale.
mapping(address => uint256) public exemptUsedOf;
/// @notice Retention-free selling volume a wallet has been GRANTED, lifetime.
/// EXEMPT_CAP_MULTIPLE x the opening principal of every bond the wallet was
/// the FIRST to receive, sell-side and commit alike.
/// @dev The grant is struck once, at `_open`, and never moves again. Not on compound
/// (the principal grows, the grant does not), not on transfer, not on a
/// marketplace sale. That is the whole anti-abuse property, and it is a
/// structural one rather than a patched one:
///
/// - Hopping a bond to a fresh wallet grants that wallet nothing, because a
/// grant is born with the bond and belongs to whoever first held it. This is
/// what audit V13 finding 1 exploited, back when the base was the CURRENT
/// principal and moved with the position.
/// - Buying a bond on the marketplace buys no allowance either, for the same
/// reason. The buyer gets the yield, not the exemption.
/// - Compounding cannot manufacture allowance out of accrued rewards.
///
/// So a wallet's ceiling is exactly five times what it ever put in, whether it
/// put it in deliberately or had it retained on a sell.
mapping(address => uint256) public exemptGrantedOf;
/// @notice Transfers are locked until this is flipped. REVERSIBLE: `setTransfersEnabled`
/// takes a bool, so the same key that opens transfers can close them again.
/// Treat it as a trusted-role power, never as a guarantee — while it is off,
/// positions cannot change hands at all.
bool public transfersEnabled;
/// @notice Emergency stop: bonds can still be CREATED, but not claimed, compounded,
/// merged or moved — and they earn NOTHING while it lasts. Trading through the
/// hook is unaffected.
bool public emergency;
/// @notice Extra daily rate, in basis points, granted by the deployer to EVERY bond —
/// those already open included. Zero at deployment.
///
/// @dev Read-time, exactly like the commit boost: nothing is written into positions,
/// so one call reaches every bond at once. There is no loop to run and no bond
/// left behind.
///
/// Deliberately UNCAPPED (user decision, 2026-08-12). The stored ladder still
/// stops at MAX_RATE_BPS and compounding is untouched; this sits on top of that
/// result. The floor is what stays guaranteed: this value only ever ADDS, and a
/// stored rate is never below BASE_RATE_BPS, so no setting can take a bond under
/// 10%/day.
///
/// Two things this costs, and both belong in the documentation rather than in a
/// comment nobody reads. First, it is a TRUSTED-ROLE power: the same key that
/// raises the rate can lower it back to zero-boost, so yields are no longer a
/// property of the code alone. Second, accrual is lazy — a position is settled
/// only when it is touched — so a change applies to time ALREADY ELAPSED since
/// each bond's last touch. That exposure is bounded by the one-window accrual
/// cap, never more, and it cannot be avoided: settling every bond on change
/// would be an unbounded loop.
///
/// A mistake here is recoverable: the setter neither reads nor writes accrual, so
/// even a value that made accrual overflow could be set back down.
uint256 public globalBoostBps;
/// @notice A FLOOR under every bond's effective rate, in bps per day. Zero disables
/// it, which is the deploy state.
/// @dev The instant lever, and the counterpart of `globalBoostBps`. The grant ADDS a
/// fixed number of points to each bond, so it preserves the spread between a
/// fresh position and one that has been compounded for a week. This LIFTS every
/// bond to the same number, whatever its ladder, the moment it is set: existing
/// positions and ones opened afterwards alike, with nothing to claim or compound
/// first. Applied last in `_effectiveRate`, so it overrides MAX_RATE_BPS too.
///
/// What that costs, stated plainly because it is not obvious: while a floor
/// above the earned cap is on, the ladder stops being visible. Everyone reads
/// the floor, so compounding still grows principal but no longer moves the rate
/// anybody sees. Lower or clear the floor and every ladder is exactly where its
/// holder left it, because this reads the stored rate rather than writing it.
///
/// Uncapped and immediate, like the grant. Paying a higher rate out of a finite
/// reserve empties it proportionally faster, for every position at once.
uint256 public rateFloorBps;
/// @dev The protocol clock, which STOPS during an emergency. Every deadline in this
/// contract — accrual, the harvest window, the bonus cooldown, the escrow stamp —
/// is measured on it rather than on `block.timestamp`.
///
/// Freezing the clock is what makes "earns nothing while paused" true. Blocking
/// the harvest alone would not: time would keep running underneath, and the first
/// claim after the pause would still pay a full window for a period the protocol
/// was shut. It also protects the holder in the other direction — a pause does not
/// eat the window progress they had already accumulated.
uint64 internal _pausedAt; // clock instant the pause began
uint64 internal _pausedTotal; // real seconds spent paused, cumulative
/// @notice The protocol clock. Frozen while `emergency` is on. Front-ends must compare
/// bond timestamps against THIS, never against the block timestamp, or every
/// countdown drifts by the length of the pause.
function protocolNow() public view returns (uint64) {
if (emergency) return _pausedAt;
return uint64(block.timestamp - _pausedTotal);
}
/// @notice Optional artwork source. Zero address means no image — which is the v1
/// state on purpose.
/// @dev This contract is immutable, so `tokenURI` can never gain an image field
/// later. The only way to add art after launch is to leave a pointer now. It is
/// deliberately narrow: a renderer can influence the image string and nothing
/// else — never a balance, a rate, or an owner. Once the art is final,
/// `freezeRenderer` makes it permanent, so holders end up with the same
/// guarantee as if it had been hardcoded.
address public renderer;
bool public rendererFrozen;
// Per-owner index, so the app can list positions without an indexer.
mapping(address => uint256[]) internal _ownedTokens;
mapping(uint256 => uint256) internal _ownedIndex;
uint256 public totalPrincipal;
uint256 public totalCommitted;
uint256 public totalPaidOut;
// ---------------------------------------------------------------------- events --
/// @dev `rateBps` is the EFFECTIVE entry rate (base + boost for a commit bond) —
/// the number a holder actually sees, not the stored ladder value.
event BondOpened(
uint256 indexed tokenId, address indexed owner, uint256 amount, uint256 rateBps, uint8 origin
);
/// @dev Emitted once per bond, when a forfeited boost is materialised into it.
event BoostDied(uint256 indexed tokenId);
/// @dev An exempt sale was recorded against the seller's lifetime allowance.
event ExemptionConsumed(address indexed seller, uint256 amount);
/// @dev A new bond granted its FIRST holder retention-free selling volume. Emitted
/// once per bond, at its opening, and never again: the grant does not follow the
/// position to a later owner.
event ExemptionGranted(address indexed wallet, uint256 indexed tokenId, uint256 amount);
event Compounded(uint256 indexed tokenId, uint256 amount, uint256 principal, uint256 rateBps);
event Claimed(uint256 indexed tokenId, address indexed to, uint256 amount, uint256 stillPending);
event Merged(uint256 indexed survivorId, uint256[] absorbed, uint256 principal, uint256 rateBps);
event PoolExhausted(uint256 indexed tokenId, uint256 requested, uint256 paid);
event TransfersSet(bool enabled);
event EmergencySet(bool on);
event CustodianSet(address indexed custodian);
event RetentionSourceSet(address indexed source);
event RendererSet(address indexed renderer);
event RendererFrozen(address indexed renderer);
event GlobalBoostSet(uint256 bps);
event RateFloorSet(uint256 bps);
// ---------------------------------------------------------------------- errors --
error ZeroAddress();
error ZeroAmount();
error CommitTooSmall(uint256 amount, uint256 minimum);
error CommitExceedsBalance(uint256 amount, uint256 balance);
// NOTE: `NotOwnerNorApproved` is inherited from Solady's ERC721 — do not redeclare it.
error NothingPending();
/// @param readyAt The instant the current window closes and harvesting reopens.
error WindowNotElapsed(uint64 readyAt);
error TransferFailed();
error Unauthorized();
error AlreadyInitialized();
error TransfersLocked();
error EmergencyStop();
error NothingToMerge();
error DuplicateToken();
error OriginMismatch();
error BoostMismatch();
error RendererIsFrozen();
error NotAContract();
error BadCooldown();
constructor(ICovenantERC20 _token, uint256 _bonusCooldown) {
if (address(_token) == address(0)) revert ZeroAddress();
// Zero would grant a step every block; anything above 30 days is a unit mistake
// (minutes/ms instead of seconds) that would freeze the ladder for everyone.
if (_bonusCooldown == 0 || _bonusCooldown > 30 days) revert BadCooldown();
token = _token;
deployer = msg.sender;
BONUS_COOLDOWN = _bonusCooldown;
}
// -------------------------------------------------------------------- ERC-721 --
function name() public pure override returns (string memory) {
return "Covenant Bond";
}
function symbol() public pure override returns (string memory) {
return "C4-BOND";
}
/// @notice Fully on-chain metadata. It has to be right the first time: the contract
/// is immutable, so a placeholder here could never be replaced later.
function tokenURI(uint256 id) public view override returns (string memory) {
ownerOf(id); // reverts if the id does not exist
Bond storage n = _bonds[id];
string memory json = string.concat(
'{"name":"Covenant Bond #',
id.toString(),
'","description":"A Covenant position earning a daily reward. The principal is a yield basis, not a withdrawable balance: it is never returned."',
_imageField(id),
',"attributes":[',
'{"trait_type":"Principal","value":',
n.principal.toString(),
'},{"trait_type":"Daily rate (bps)","value":',
_effectiveRate(id, n).toString(),
'},{"trait_type":"Origin","value":"',
n.origin == Origin.Commit ? "commit" : "sell",
'"},{"trait_type":"Boost","value":"',
_boostAlive(id, n) ? "active" : "none",
'"},{"trait_type":"Pending","value":',
pendingOf(id).toString(),
'},{"trait_type":"At cap","value":"',
_effectiveRate(id, n) >= MAX_RATE_BPS ? "yes" : "no",
'"}]}'
);
return string.concat("data:application/json;base64,", Base64.encode(bytes(json)));
}
/// @dev Returns `,"image":"..."` when a renderer is set, or an empty string when it
/// is not — which is the v1 state. A renderer that reverts, or that is not a
/// contract, degrades to "no image" instead of bricking `tokenURI`: metadata
/// must never be able to make a position unreadable.
function _imageField(uint256 id) internal view returns (string memory) {
address r = renderer;
// The code check is not redundant with try/catch: on an address with no code,
// Solidity reverts on its own extcodesize check BEFORE the call, and try/catch
// does not catch that. Without this line, pointing the renderer at a wallet by
// mistake would make every position's metadata unreadable.
if (r == address(0) || r.code.length == 0) return "";
try ICovenantBondRenderer(r).imageURI(id) returns (string memory uri) {
if (bytes(uri).length == 0) return "";
// The string is spliced raw between two quotes, so a renderer that returned a
// quote or a backslash could close the image field early and append fields of
// its own -- rewriting the whole metadata object a marketplace displays. The
// renderer is allowed to influence the image and nothing else, so anything
// that could break out of it degrades to "no image".
if (!_isQuoteSafe(uri)) return "";
return string.concat(',"image":"', uri, '"');
} catch {
// Explicit, though falling off the end would return the same empty string --
// which is why a mutation campaign reports this line as unkillable. Written
// out because "a renderer that reverts yields no image" is a guarantee, and a
// guarantee should be visible rather than inferred from a default.
return "";
}
}
/// @dev True when `s` contains no character that can terminate or escape a JSON
/// string literal. Also bounds the length: the whole point of the try/catch above
/// is that metadata can never make a position unreadable, and an unbounded return
/// would defeat it by running an on-chain reader out of gas.
function _isQuoteSafe(string memory s) internal pure returns (bool) {
bytes memory b = bytes(s);
if (b.length > MAX_IMAGE_URI_BYTES) return false;
for (uint256 i; i < b.length; ++i) {
bytes1 c = b[i];
if (c == '"' || c == "\\" || c < 0x20) return false;
}
return true;
}
/// @notice Points metadata at an artwork source. No image at all until this is set.
function setRenderer(address newRenderer) external {
if (msg.sender != deployer) revert Unauthorized();
if (rendererFrozen) revert RendererIsFrozen();
renderer = newRenderer;
emit RendererSet(newRenderer);
}
/// @notice Makes the artwork permanent. Irreversible.
function freezeRenderer() external {
if (msg.sender != deployer) revert Unauthorized();
if (rendererFrozen) revert RendererIsFrozen();
rendererFrozen = true;
emit RendererFrozen(renderer);
}
/// @dev The transfer lock, and the accrual settlement that must happen with it.
/// Minting (from == 0) and burning (to == 0) stay allowed: burning is how
/// `merge` consolidates a holder's own positions.
///
/// Settling HERE rather than in `_afterTokenTransfer` is deliberate. Solady runs
/// the after-hook before the ERC-721 receiver check, so by the time
/// `onERC721Received` fires ownership has already moved — a contract recipient
/// could re-enter `compound`/`claim` as the new owner. Pinning the accrual
/// before any ownership change closes that window, and it also makes the amount
/// handed over deterministic rather than block-dependent.
function _beforeTokenTransfer(address from, address to, uint256 id) internal override {
if (from != address(0) && to != address(0)) {
// Minting (from == 0) stays allowed on purpose: a sell must keep working.
_requireNotPaused();
// Locked, with ONE exception: the custodian may always hand a position back.
// Without it, re-locking while bonds sit in market escrow would strand them
// there — their owners could neither sell nor retrieve their own property.
// Buying stays blocked, because the market refuses to sell while locked; what
// remains open is `cancel`, i.e. taking your bond home.
if (!transfersEnabled && (custodian == address(0) || from != custodian)) {
revert TransfersLocked();
}
// Settling here also materialises a forfeited boost (`_syncBoost`) BEFORE
// `_afterTokenTransfer` restamps `ownedSince` — the ordering that makes
// shuffling a bond between wallets useless as a resurrection trick.
_settle(id, _bonds[id]);
}
}
/// @dev Keeps the per-owner index in step — written once so it is already correct
/// when transfers unlock in v2 — and, since the boost model, also maintains the
/// ownership stamp, the escrow seller record and the commit-bond count.
///
/// `ownedSince` restamps on every REAL change of hands: mint, plain transfer,
/// and a market sale leaving the custodian. It deliberately does NOT move when a
/// bond enters escrow or comes home from a cancel — custody is not ownership,
/// and restamping on the way back would hand every seller a fresh boost clock
/// for the price of a listing fee.
///
/// The commit count follows the BENEFICIAL owner: a wallet whose only commit
/// bond sits listed keeps its retention exemption, exactly as it keeps the
/// boost. The count moves on a sale, not on custody.
function _afterTokenTransfer(address from, address to, uint256 id) internal override {
if (from != address(0)) {
uint256[] storage owned = _ownedTokens[from];
uint256 i = _ownedIndex[id];
uint256 last = owned.length - 1;
if (i != last) {
uint256 moved = owned[last];
owned[i] = moved;
_ownedIndex[moved] = i;
}
owned.pop();
}
if (to != address(0)) {
_ownedIndex[id] = _ownedTokens[to].length;
_ownedTokens[to].push(id);
}
// NOTE for `merge`: the absorbed bond must still exist here (burn before delete),
// or the commit count below would read a zeroed origin and drift.
Bond storage n = _bonds[id];
bool isCommit = n.origin == Origin.Commit;
address c = custodian;
if (from == address(0)) {
// Mint: the first real acquisition.
n.ownedSince = protocolNow();
if (isCommit) {
commitBondCountOf[to]++;
commitPrincipalOf[to] += n.principal;
}
} else if (to == address(0)) {
// Burn (merge absorbing a position).
if (isCommit) {
commitBondCountOf[from]--;
commitPrincipalOf[from] -= n.principal;
}
} else if (c != address(0) && to == c) {
// Into escrow: remember who it really belongs to, move nothing else.
escrowSeller[id] = from;
} else if (c != address(0) && from == c) {
address seller = escrowSeller[id];
if (to != seller) {
// Sale out of escrow: the buyer starts a fresh ownership clock.
n.ownedSince = protocolNow();
if (isCommit) {
commitBondCountOf[seller]--;
commitBondCountOf[to]++;
commitPrincipalOf[seller] -= n.principal;
commitPrincipalOf[to] += n.principal;
}
}
// Cancel (to == seller): the position comes home unchanged — a strip that
// happened while it sat listed was already materialised by `_settle`.
delete escrowSeller[id];
} else {
// Plain transfer.
n.ownedSince = protocolNow();
if (isCommit) {
commitBondCountOf[from]--;
commitBondCountOf[to]++;
commitPrincipalOf[from] -= n.principal;
commitPrincipalOf[to] += n.principal;
}
}
}
// ---------------------------------------------------------------------- wiring --
/// @notice One-time wiring of the contract allowed to open sell-side bonds.
/// @dev Required to be a contract, like the custodian: `openBondFrom` books principal
/// without pulling any tokens, trusting the caller to have sent them first. An
/// EOA wired here by a slip of the keyboard could mint unbacked bonds at will.
function initRetentionSource(address source) external {
if (msg.sender != deployer) revert Unauthorized();
if (source == address(0)) revert ZeroAddress();
if (source.code.length == 0) revert NotAContract();
if (retentionSource != address(0)) revert AlreadyInitialized();
retentionSource = source;
emit RetentionSourceSet(source);
}
/// @notice Wires the escrow custodian. One-time and deployer-only, like the retention
/// source. Never called on v1, where no marketplace exists.
/// @dev Required to be a contract: an EOA custodian could hold bonds and grant itself
/// rate steps without any of the escrow constraints that justify the catch-up.
function initCustodian(address c) external {
if (msg.sender != deployer) revert Unauthorized();
if (c == address(0)) revert ZeroAddress();
if (c.code.length == 0) revert NotAContract();
if (custodian != address(0)) revert AlreadyInitialized();
custodian = c;
emit CustodianSet(c);
}
/// @notice Called by the token on EVERY outbound transfer: `from` just moved tokens.
/// This is the whole strip mechanism — one timestamp write.
/// @dev Sits on the hot path of every single C4 transfer, so it must never be able
/// to brick one: a single storage write, no loops, no external calls, and the
/// only revert is the caller gate, which cannot fire when the token calls.
///
/// O(1) on purpose. Sweeping the wallet's positions here instead would let
/// anyone gas-bomb a holder — `openBondFrom` mints to any actor, so a stranger
/// can grow somebody's position list at will — and every transfer of the victim
/// would then pay for the sweep. The per-bond consequence is materialised lazily
/// by `_syncBoost` the next time each position is touched.
///
/// Runs during an emergency too, on the frozen clock: ERC-20 transfers are
/// outside this contract's control, so the forfeit they trigger must keep being
/// recorded even while everything else is paused.
function onTokenDebit(address from, uint256 amount) external {
if (msg.sender != address(token)) revert Unauthorized();
lastStripAt[from] = protocolNow();
_addDebited(from, amount);
}
// --------------------------------------------------- the same-transaction tally --
//
// How much a wallet has sent out DURING THE CURRENT TRANSACTION, kept in transient
// storage (EIP-1153): written by `onTokenDebit`, spent by `consumeExemption`, and
// wiped by the EVM when the transaction ends. Nothing to reset, nothing to leak into
// the next block.
//
// Its whole purpose is to answer one question the hook cannot otherwise answer on a
// route that vouches for nobody: "are the tokens being sold coming out of the wallet
// whose allowance is about to be spent?". Before this existed, the exemption trusted
// `tx.origin`, and `tx.origin` says "this address started the transaction", not "this
// address is selling" — so any code running inside someone's transaction could sell
// ITS OWN tokens against THEIR allowance (audit V13 finding 2). A debit cannot be
// borrowed: it only exists because that wallet's balance actually went down.
//
// Slot: keccak256(wallet, DEBITED_SEED). Hashing rather than using the address as the
// slot directly keeps this namespace from ever colliding with another transient use.
uint256 private constant DEBITED_SEED = uint256(keccak256("covenant.debited.tx"));
function _debitedSlot(address who) private pure returns (bytes32) {
return keccak256(abi.encode(who, DEBITED_SEED));
}
/// @dev Saturating on purpose. An overflow here would revert a plain token transfer,
/// which is the one thing this path must never do — and a wallet that has moved
/// 2^256 tokens in one transaction is past every allowance anyway.
function _addDebited(address who, uint256 amount) private {
bytes32 slot = _debitedSlot(who);
assembly ("memory-safe") {
let current := tload(slot)
let next := add(current, amount)
if lt(next, current) { next := not(0) }
tstore(slot, next)
}
}
/// @notice How much `who` has sent out so far in this transaction. Always zero at the
/// start of one, so a stale value can never grant anything.
function debitedThisTx(address who) external view returns (uint256 amount) {
bytes32 slot = _debitedSlot(who);
assembly ("memory-safe") {
amount := tload(slot)
}
}
/// @dev Spends the proof so it justifies exactly one exemption. Without this, a single
/// debit could be waved at the hook over and over inside one transaction, and a
/// contract routing somebody's sale could drain their whole lifetime quota with
/// it. Clamped at zero rather than checked: this runs inside a sell, and a revert
/// here would block the sale itself.
function _spendDebited(address who, uint256 amount) private {
bytes32 slot = _debitedSlot(who);
assembly ("memory-safe") {
let current := tload(slot)
switch gt(current, amount)
case 1 { tstore(slot, sub(current, amount)) }
default { tstore(slot, 0) }
}
}
/// @notice Opens or closes bond transfers. Deployer-only, and REVERSIBLE since
/// 2026-08-05 (user decision): what was a one-way unlock is now a switch.
/// @dev Be clear about what this costs. Before, "there is no re-lock" was a
/// guarantee holders could verify by reading the code. It no longer holds: the
/// deployer can freeze every position's transferability at any moment, which
/// also freezes the marketplace, since every listing, purchase and cancellation
/// moves the token. Whoever holds this key must be trusted accordingly, and the
/// documentation must say so rather than imply the old promise.
function setTransfersEnabled(bool enabled) external {
if (msg.sender != deployer) revert Unauthorized();
transfersEnabled = enabled;
emit TransfersSet(enabled);
}
/// @notice Sets the extra daily rate granted to every bond, open ones included.
/// Deployer-only, reversible, and effective the instant it lands.
/// @param bps Extra basis points per day. `0` restores the plain schedule.
/// @dev Uncapped by decision, so read `globalBoostBps` for what that costs before
/// touching this. Nothing is settled here: accrual stays lazy, and each bond
/// picks the new rate up on its next touch, for at most one window of elapsed
/// time. Setting the same value twice is a no-op rather than a revert — this is a
/// knob, and refusing an idempotent call would only make automation brittle.
function setGlobalBoost(uint256 bps) external {
if (msg.sender != deployer) revert Unauthorized();
if (bps == globalBoostBps) return;
globalBoostBps = bps;
emit GlobalBoostSet(bps);
}
/// @notice Lifts EVERY bond to at least `bps` per day, at once. Zero clears it.
/// @dev Deployer-only, uncapped, immediate, reversible: the same shape as the grant,
/// and the same trust model. It differs from `setGlobalBoost` in what it does to
/// the spread between positions. A grant adds points to each bond and preserves
/// the ladder's ordering; a floor collapses it, because every bond below the
/// floor reads the floor.
///
/// It writes no position. `_effectiveRate` reads this at call time, which is why
/// it reaches bonds opened long ago and bonds opened after it in the same breath,
/// and why clearing it puts every ladder back exactly where its holder left it.
///
/// Accrual already banked is untouched: a change prices the time since each
/// position was last settled, capped at one window, like every other rate change.
///
/// TRUSTED-ROLE power, and the documentation must say so. It is also the fastest
/// way to empty a finite reserve, since it applies to every position at once.
function setRateFloor(uint256 bps) external {
if (msg.sender != deployer) revert Unauthorized();
if (bps == rateFloorBps) return;
rateFloorBps = bps;
emit RateFloorSet(bps);
}
/// @notice Emergency stop. Halts everything a bond can DO — claiming, compounding,
/// merging, transferring, and therefore every marketplace operation, since
/// each one moves the token.
///
/// @dev Deliberately does NOT stop bond creation: `openBond` and `openBondFrom` keep
/// working, so the pool keeps trading. A sell mints a bond through the hook, and
/// blocking that would block selling itself — turning a circuit breaker into a
/// trap where holders cannot exit.
///
/// The cost, stated plainly: while this is on, holders cannot withdraw rewards
/// they have already earned. Nothing is lost — accrual is settled on the way out
/// and resumes — but the funds are unreachable until the deployer turns it off.
/// If that key is lost while the switch is on, they stay unreachable. This is a
/// trusted role, not a trustless mechanism, and it should be documented as one.
function setEmergency(bool on) external {
if (msg.sender != deployer) revert Unauthorized();
if (on == emergency) return;
if (on) {
_pausedAt = uint64(block.timestamp - _pausedTotal);
} else {
// Real time here, NOT protocolNow(): the clock is still frozen at this point,
// so reading it would measure the pause as zero and credit the whole outage.
_pausedTotal = uint64(block.timestamp) - _pausedAt;
}
emergency = on;
emit EmergencySet(on);
}
/// @dev Guard for every bond action that is not creation.
function _requireNotPaused() internal view {
if (emergency) revert EmergencyStop();
}
// ----------------------------------------------------------------------- views --
function bondOf(uint256 tokenId) external view returns (Bond memory) {
ownerOf(tokenId);
return _bonds[tokenId];
}
/// @notice Every position held by `owner`, so the app needs no indexer.
/// @dev UNBOUNDED. A bond can be transferred to anyone without their consent, so the
/// length of this array is not something its owner controls: somebody willing to
/// pay the gas can push arbitrarily many positions onto a stranger. Callers that
/// must not fail — the app, an integrator — should page through `tokensOfSlice`
/// instead and treat this one as a convenience for small holders.
function tokensOf(address owner) external view returns (uint256[] memory) {
return _ownedTokens[owner];
}
/// @notice How many positions `owner` holds. Read this first, then page.
function balanceOfBonds(address owner) external view returns (uint256) {
return _ownedTokens[owner].length;
}
/// @notice A window of `owner`'s positions: up to `limit` ids starting at `offset`.
/// Returns a shorter array at the end of the list, and an empty one past it.
function tokensOfSlice(address owner, uint256 offset, uint256 limit)
external
view
returns (uint256[] memory ids)
{
uint256[] storage all = _ownedTokens[owner];
uint256 total = all.length;
if (offset >= total) return new uint256[](0);
uint256 end = offset + limit;
if (end > total) end = total;
ids = new uint256[](end - offset);
for (uint256 i; i < ids.length; ++i) {
ids[i] = all[offset + i];
}
}
/// @notice Tokens available to pay rewards right now.
function rewardPool() public view returns (uint256) {
return token.balanceOf(address(this));
}
/// @notice Accrued-but-unclaimed rewards. Rewards are WINDOWED: at most one bonus
/// window of elapsed time counts — showing up each window harvests
/// everything, staying away forfeits the excess. The same figure applies to a
/// position sitting in market escrow: custody says who may act on a bond, not
/// what it earns.
function pendingOf(uint256 tokenId) public view returns (uint256) {
return _bonds[tokenId].pending + _accruedFor(tokenId, _bonds[tokenId], BONUS_COOLDOWN);
}
/// @notice STORED daily rate of a position, in bps: base + compound steps, boost
/// excluded (1000 = 10%/day). The figure a position actually earns is
/// `effectiveRateOf`.
/// @dev Reverts on a non-existent id rather than returning a default, so "no bond"
/// can never be mistaken for "a bond at the entry rate".
function rateOf(uint256 tokenId) external view returns (uint256) {
ownerOf(tokenId);
return _bonds[tokenId].rateBps;
}
/// @notice The daily rate a position earns right now: the stored ladder plus the
/// commit boost while it is alive, capped at MAX_RATE_BPS.
function effectiveRateOf(uint256 tokenId) external view returns (uint256) {
ownerOf(tokenId);
return _effectiveRate(tokenId, _bonds[tokenId]);
}
/// @notice True while `wallet` beneficially owns at least one commit-origin bond.
/// Display-level: what actually prices a sale is `exemptAllowanceOf`.
function hasCommitBond(address wallet) external view returns (bool) {
return commitBondCountOf[wallet] != 0;
}
/// @notice How much MORE a wallet can sell retention-free: everything its bonds
/// granted it at their opening, minus everything its exempt sales have
/// consumed. Opening another bond raises it; nothing else does, and nothing
/// lowers it but spending it.
function exemptAllowanceOf(address wallet) external view returns (uint256) {
uint256 granted = exemptGrantedOf[wallet];
uint256 used = exemptUsedOf[wallet];
return used >= granted ? 0 : granted - used;
}
/// @notice Records an exempt sale against the seller's lifetime allowance.
/// @dev Retention-source only: the hook grants the exemption and burns the allowance
/// in the same transaction, against the same storage, so the two can never
/// disagree. Anyone else calling this could only grief allowances — hence the
/// gate.
function consumeExemption(address seller, uint256 amount) external {
if (msg.sender != retentionSource) revert Unauthorized();
exemptUsedOf[seller] += amount;
// Spend the same-transaction proof alongside the lifetime quota, whichever anchor
// justified this sale. On the router path there is a debit too — the seller hands
// the tokens to the router — so spending it there costs nothing and keeps one
// debit from justifying a second, unvouched sale later in the same transaction.
_spendDebited(seller, amount);
emit ExemptionConsumed(seller, amount);
}
/// @dev Who the position really belongs to: its owner, unless the custodian holds it
/// in escrow — then the seller recorded on the way in. Custody says who may act
/// on a bond, never who it earns for.
function _beneficialOwner(uint256 tokenId) internal view returns (address owner) {
owner = ownerOf(tokenId);
if (owner == custodian && custodian != address(0)) {
address seller = escrowSeller[tokenId];
if (seller != address(0)) owner = seller;
}
}
/// @dev The boost lives while three things hold: the bond is commit-origin, it was
/// never caught being held through a strip (`boostDead`), and its beneficial
/// owner has not moved a single token since acquiring it. STRICT comparison on
/// purpose: acquiring and stripping in the same second resolves to "dead", so
/// committing and dumping inside one block can never keep the boost — while a
/// fresh commit one second after a sell is boosted, as it should be.
function _boostAlive(uint256 tokenId, Bond storage n) internal view returns (bool) {
return n.origin == Origin.Commit && !n.boostDead
&& lastStripAt[_beneficialOwner(tokenId)] < n.ownedSince;
}
/// @dev Effective rate = stored ladder + live boost, clamped to the cap, plus the
/// deployer's global boost. The clamp is load-bearing: a stripped bond can climb
/// its STORED rate all the way to MAX_RATE_BPS, and nothing EARNED may push the
/// effective rate past it.
///
/// `globalBoostBps` is added AFTER that clamp, on purpose. It is a grant, not a
/// reward: keeping it outside leaves the earned part — ladder plus commit boost —
/// governed by exactly the same cap as before, so raising or clearing the grant
/// never changes what compounding is worth. It is also why the grant can only
/// push the rate up, never down.
function _effectiveRate(uint256 tokenId, Bond storage n) internal view returns (uint256 rate) {
rate = uint256(n.rateBps);
if (_boostAlive(tokenId, n)) {
rate += BOOST_BPS;
if (rate > MAX_RATE_BPS) rate = MAX_RATE_BPS;
}
rate += globalBoostBps;
// Last, so it wins over the earned cap as well as over the ladder: a floor is a
// promise about what every bond pays, and one that some positions were exempt
// from would not be one.
if (rate < rateFloorBps) rate = rateFloorBps;
}
/// @dev Materialises a forfeited boost into the position, permanently. Without this,
/// the `ownedSince` restamp on a transfer would resurrect the boost: a stripped
/// holder could hand the bond to themselves — or bounce it off a second wallet —
/// and come back boosted. Run by every settle, so it always executes BEFORE the
/// transfer hooks restamp `ownedSince`; that ordering is what makes the shuffle
/// useless.
function _syncBoost(uint256 tokenId, Bond storage n) internal {
if (
n.origin == Origin.Commit && !n.boostDead
&& lastStripAt[_beneficialOwner(tokenId)] >= n.ownedSince
) {
n.boostDead = true;
emit BoostDied(tokenId);
}
}
/// @dev Owner-path accrual: at most ONE bonus window of elapsed time counts.
/// Rewards are windowed by design (user decision 2026-08-04) — the pot does not
/// stockpile while nobody shows up. Whatever ran past the window is forfeited at
/// the next touch, not deferred: `lastAccrual` jumps to now regardless, so the
/// uncounted time can never be recovered later.
function _accrued(uint256 tokenId, Bond storage n) internal view returns (uint256) {
return _accruedFor(tokenId, n, BONUS_COOLDOWN);
}
/// @dev `cap == 0` would count the full elapsed time. NOTHING passes zero any more:
/// escrow custody used to, and that exemption turned out to be the whole
/// windowed model's back door (see `_catchUp`). The parameter survives only
/// because the cap is a value rather than a constant here; every caller passes
/// BONUS_COOLDOWN.
///
/// The whole capped span is priced at the effective rate AS OF NOW — no
/// piecewise split at the strip instant. Mid-span the rate can only fall (a
/// strip), never rise (gaining the boost requires an `ownedSince` restamp,
/// which always settles first), so this never over-credits. The cost lands on
/// the seller: the un-harvested window is re-priced without the boost, at most
/// BOOST_BPS × one window ≈ 1.25% of principal. Harvest before you sell.
function _accruedFor(uint256 tokenId, Bond storage n, uint256 cap)
internal
view
returns (uint256)
{
if (n.principal == 0 || n.lastAccrual == 0) return 0;
uint256 elapsed = protocolNow() - n.lastAccrual;
if (elapsed == 0) return 0;
if (cap != 0 && elapsed > cap) elapsed = cap;
return n.principal * _effectiveRate(tokenId, n) * elapsed / (1 days * BPS);
}
function _settle(uint256 tokenId, Bond storage n) internal {
_syncBoost(tokenId, n);
n.pending += _accrued(tokenId, n);
n.lastAccrual = protocolNow();
}
/// @dev Harvesting happens ONCE PER WINDOW, never between two. Rewards are capped at
/// one window of accrual anyway, so an early call could only ever collect a
/// fraction — and, for `compound`, pay a fee to skip the rate bonus. Refusing it
/// outright makes the cadence a rule of the protocol instead of a habit the
/// interface hopes for, and makes every harvest worth exactly one window.
///
/// Measured from `lastAccrual`, which every settle updates — so opening,
/// receiving a transfer or merging all start a fresh window. The custodian
/// catch-up (`compoundEscrowed`) does NOT pass through here: an escrowed
/// position's owner cannot act, so gating it would punish them for it.
function _requireWindowElapsed(Bond storage n) internal view {
uint256 readyAt = uint256(n.lastAccrual) + BONUS_COOLDOWN;
if (protocolNow() < readyAt) revert WindowNotElapsed(uint64(readyAt));
}
function _authorized(uint256 tokenId) internal view {
if (!_isApprovedOrOwner(msg.sender, tokenId)) revert NotOwnerNorApproved();
}
// -------------------------------------------------------------------- opening --
/// @notice Opens a bond by committing tokens. Each call mints a NEW position: since
/// positions are transferable objects, growing one in place would be the
/// wrong shape. Use `merge` to consolidate.
/// @dev The commitment must be at least 20% of the caller's balance and at most all
/// of it — a bond is a real commitment, not dust.
function openBond(uint256 amount) external returns (uint256 tokenId) {
if (amount == 0) revert ZeroAmount();
uint256 balance = token.balanceOf(msg.sender);
if (amount > balance) revert CommitExceedsBalance(amount, balance);
uint256 minimum = balance * MIN_COMMIT_BPS / BPS;
if (minimum < MIN_COMMIT_ABS) minimum = MIN_COMMIT_ABS;
if (amount < minimum) revert CommitTooSmall(amount, minimum);
tokenId = _open(msg.sender, amount, Origin.Commit);
// Committed tokens join the reward pool (they are not destroyed).
if (!token.transferFrom(msg.sender, address(this), amount)) revert TransferFailed();
}
/// @notice Opens a bond on behalf of a seller, from the sell-side retention. The
/// tokens must already have been sent to this contract.
/// @dev Restricted to the wired retention source. The 20% floor does not apply: the
/// size is decided by the trade, not by the holder.
function openBondFrom(address owner, uint256 amount) external returns (uint256 tokenId) {
if (msg.sender != retentionSource) revert Unauthorized();
if (owner == address(0)) revert ZeroAddress();
if (amount == 0) revert ZeroAmount();
tokenId = _open(owner, amount, Origin.Sell);
}
function _open(address owner, uint256 amount, Origin origin) internal returns (uint256 tokenId) {
tokenId = nextTokenId++;
Bond storage n = _bonds[tokenId];
n.principal = amount;
n.rateBps = uint32(BASE_RATE_BPS);
n.lastAccrual = protocolNow();
n.lastBonusAt = protocolNow();
n.origin = origin;
// `ownedSince` and the commit count are stamped by `_afterTokenTransfer` on the
// mint below, which reads the origin set above.
totalPrincipal += amount;
totalCommitted += amount;
// The retention-free grant, struck once and only here. `owner` is the first
// holder by construction: this is the mint. Every later hop leaves it alone.
exemptGrantedOf[owner] += amount * EXEMPT_CAP_MULTIPLE;
emit ExemptionGranted(owner, tokenId, amount * EXEMPT_CAP_MULTIPLE);
_mint(owner, tokenId);
// The event carries the EFFECTIVE entry rate — the number the holder sees.
uint256 entry = origin == Origin.Commit ? BASE_RATE_BPS + BOOST_BPS : BASE_RATE_BPS;
emit BondOpened(tokenId, owner, amount, entry, uint8(origin));
}
// ------------------------------------------------------------------ lifecycle --
/// @notice Rolls accrued rewards into the principal and, at most once per 6h, raises
/// the daily rate by 0.25 point (effective rate capped at 20%/day).
/// @dev No token moves: the rewards are already held here, so this is pure
/// bookkeeping.
function compound(uint256 tokenId) external returns (uint256 rolled) {
_requireNotPaused();
_authorized(tokenId);
Bond storage n = _bonds[tokenId];
_requireWindowElapsed(n);
rolled = _rollPrincipal(tokenId, n);
if (rolled == 0) revert NothingPending();
// ONE step per call, and the clock restarts HERE rather than advancing by whole
// windows. Both details matter:
//
// * banking several windows at once would make the rate a function of elapsed
// time instead of a reward for showing up, which is the entire point of the
// 6h cadence;
// * carrying the remainder instead of resetting would let a bond neglected for
// a month bank 120 windows and then claim them one call at a time WITHIN A
// SINGLE BLOCK, climbing the whole ladder at once. The reset is what makes
// the cooldown a real wait.
//
// `compoundEscrowed` below is the one exception, and only for positions whose
// owner is structurally unable to call this function.
//
// The condition below can never actually refuse on this path: `lastAccrual` is
// never behind `lastBonusAt` anywhere in the contract, and `_requireWindowElapsed`
// above already demanded a full window on it. So the check is redundant here, and
// a mutation campaign correctly reports both it and the write as unkillable. Kept
// anyway: the redundancy is what stops the two clocks drifting apart if the
// harvest gate ever changes, and it is one SSTORE on a slot this function is
// already writing.
if (protocolNow() >= uint256(n.lastBonusAt) + BONUS_COOLDOWN) {
// The cap is on the EFFECTIVE rate: while the boost is alive the stored
// ladder stops BOOST_BPS short of it, and that headroom reopens if the boost
// is ever forfeited. The stored rate itself never goes down.
uint256 ceiling = MAX_RATE_BPS - (_boostAlive(tokenId, n) ? BOOST_BPS : 0);
uint256 next = uint256(n.rateBps) + RATE_STEP_BPS;
n.rateBps = uint32(next > ceiling ? ceiling : next);
n.lastBonusAt = protocolNow();
}
emit Compounded(tokenId, rolled, n.principal, n.rateBps);
}
/// @notice Compounds a position held in escrow by the custodian: ONE window and one
/// ladder step per call, exactly `compound`'s rule. (Escrow used to bank
/// every elapsed window — `_catchUp` explains why that exception is gone.)
///
/// @dev Exists because an escrowed position's owner structurally cannot call
/// `compound` — the market keeps listed positions ticking by calling this as it
/// sweeps.
///
/// The authorisation is deliberately two conditions, not one: the caller must BE
/// the custodian AND must currently HOLD the position. The second is what stops
/// this from being a privilege — the custodian can never raise the rate of a bond
/// it is not itself holding, so it cannot favour anyone. With `custodian` left
/// unset the function is unreachable, which is the v1 state.
///
/// Unlike `compound` it does NOT revert when nothing has accrued: it is called in
/// a loop over listed positions, and one idle bond must not abort the sweep.
/// @return rolled Rewards folded into the principal.
/// @return rateBps The resulting daily rate. Returned rather than left to be read
/// back: the caller needs it for its own event, and a second call to
/// `rateOf` would cost another CALL plus a storage read for a value
/// this function already has in hand.
function compoundEscrowed(uint256 tokenId) external returns (uint256 rolled, uint256 rateBps) {
_requireNotPaused();
address c = custodian;
if (c == address(0) || msg.sender != c || ownerOf(tokenId) != c) revert Unauthorized();
return _catchUp(tokenId);
}
/// @notice Catches up several escrowed positions in one call.
/// @dev Purely a gas shape: the custodian slot is read once instead of once per
/// position, and — far more importantly — the market crosses the contract
/// boundary once instead of once per bond. The ownership check stays per-token,
/// because that check is what stops the role from becoming a privilege.
///
/// Deliberately NOT bounded here. The bound belongs to the caller, which knows
/// how many listings it is willing to service; capping it here would only move
/// the same limit somewhere harder to see.
function compoundEscrowedMany(uint256[] calldata tokenIds) external returns (uint256 totalRolled) {
_requireNotPaused();
address c = custodian;
if (c == address(0) || msg.sender != c) revert Unauthorized();
uint256 len = tokenIds.length;
for (uint256 i = 0; i < len;) {
uint256 id = tokenIds[i];
if (ownerOf(id) != c) revert Unauthorized();
(uint256 rolled,) = _catchUp(id);
totalRolled += rolled;
unchecked {
++i;
}
}
}
/// @dev Escrow time earns EXACTLY what owner-held time earns: one window per touch,
/// one ladder step per window, remainder dropped. Custody is a guarantee about
/// who can act on a position, never a better rate.
///
/// It used to be the one uncapped span, on the reasoning that an escrowed owner
/// cannot show up and should not be punished for it. That reasoning is sound and
/// the mechanism was not: the owner chooses when to enter escrow and when to
/// leave it. Listing at a price nobody will pay — and no on-chain rule can tell
/// an honest ask from an absurd one — turned "cannot show up" into "need not show
/// up", and the whole windowed model with it. A position parked for a month and
/// cancelled collected the entire month plus a maxed ladder, for the price of two
/// transactions, while everyone who actually showed up every six hours collected
/// less. The listing fee could not deter it (it is a share of a price the parker
/// picks, and rounds to zero below 100 wei), and the permissionless maintenance
/// calls meant third parties paid the gas to keep the position compounding.
///
/// So the exception is gone. A seller who lists and cancels forfeits the windows
/// they were away for, exactly like a holder who went on holiday — the same rule
/// the entire product is built on. What custody still buys the buyer is the thing
/// it was introduced for: while a bond is listed its seller cannot claim it out
/// from under them.
function _catchUp(uint256 tokenId) internal returns (uint256 rolled, uint256 rateBps) {
Bond storage n = _bonds[tokenId];
// One harvest per WINDOW, not one per call. Removing the uncapped span bounded
// what a single touch pays; it left the NUMBER of touches free, and this path is
// permissionless, so a listed position could be poked as often as anyone cared to
// pay gas for. Compounding the same elapsed time in smaller, more frequent steps
// earns strictly more, so parking an unbuyable ask beat honest holding again — by
// a different route than the one that was closed, and one no test caught because
// every one of them measured a single call.
//
// Measured on `lastBonusAt`, the COMPOUNDING clock, and deliberately not on
// `lastAccrual`: every transfer settles the position and restamps `lastAccrual`,
// so gating on that would let the act of entering escrow swallow a window the
// position had already earned.
//
// Returns instead of reverting: `compoundEscrowedMany` walks a batch, and a
// position that is simply not due yet must not abort the whole sweep — nor, by
// extension, the sale or cancellation that triggered it.
if (protocolNow() < uint256(n.lastBonusAt) + BONUS_COOLDOWN) return (0, n.rateBps);
rolled = _rollPrincipal(tokenId, n);
// One step, and the clock restarts here — `compound`'s rule, for the same reason:
// carrying the remainder would let a neglected position climb the whole ladder in
// a single block by way of repeated calls. Unconditional now that the gate above
// governs the cadence on this path.
//
// The cap is on the EFFECTIVE rate: while the boost is alive the stored ladder
// stops BOOST_BPS short of it, and that headroom reopens if the boost is ever
// forfeited. The stored rate itself never goes down.
uint256 ceiling = MAX_RATE_BPS - (_boostAlive(tokenId, n) ? BOOST_BPS : 0);
uint256 next = uint256(n.rateBps) + RATE_STEP_BPS;
n.rateBps = uint32(next > ceiling ? ceiling : next);
n.lastBonusAt = protocolNow();
rateBps = n.rateBps;
emit Compounded(tokenId, rolled, n.principal, rateBps);
}
/// @dev Settles accrual and folds it into the principal. Shared by both compound
/// paths; the rate ladder is deliberately NOT handled here, because that is the
/// only thing the two paths do differently.
///
/// The span is capped at one window for every caller, with no way to ask for
/// more. This used to take a `custody` flag that selected an uncapped span for
/// the escrow path; the flag is gone rather than merely unused, so no future
/// caller can reopen the hole it turned out to be (see `_catchUp`).
function _rollPrincipal(uint256 tokenId, Bond storage n) internal returns (uint256 rolled) {
_syncBoost(tokenId, n);
n.pending += _accruedFor(tokenId, n, BONUS_COOLDOWN);
n.lastAccrual = protocolNow();
rolled = n.pending;
if (rolled == 0) return 0;
n.pending = 0;
n.principal += rolled;
totalPrincipal += rolled;
// Compounding grows the exemption base too: the allowance follows the CURRENT
// commit principal, and the beneficial owner is who it belongs to in escrow.
if (n.origin == Origin.Commit) {
commitPrincipalOf[_beneficialOwner(tokenId)] += rolled;
}
}
/// @notice Withdraws accrued rewards to the position's owner. The rate is NOT reset.
/// @dev Pays what the pool can cover; the remainder stays pending. `PoolExhausted`
/// makes the shortfall visible on-chain instead of looking like a quiet
/// zero-yield period.
function claim(uint256 tokenId) external returns (uint256 paid) {
_requireNotPaused();
_authorized(tokenId);
address owner = ownerOf(tokenId);
Bond storage n = _bonds[tokenId];
_requireWindowElapsed(n);
_settle(tokenId, n);
uint256 owed = n.pending;
if (owed == 0) revert NothingPending();
uint256 pool = rewardPool();
paid = owed > pool ? pool : owed;
if (paid == 0) {
emit PoolExhausted(tokenId, owed, 0);
return 0;
}
n.pending = owed - paid;
totalPaidOut += paid;
if (paid < owed) emit PoolExhausted(tokenId, owed, paid);
if (!token.transfer(owner, paid)) revert TransferFailed();
emit Claimed(tokenId, owner, paid, n.pending);
}
/// @notice Consolidates several of your positions into the first one. Without this,
/// ten sells leave ten positions to compound separately.
/// @dev The surviving rate is the amount-weighted average, so merging can never hand
/// out a better rate than the parts deserve — a large low-rate position merged
/// with a dust high-rate one barely moves. The bonus clock takes the LATER of
/// the two, so merging never grants a free step.
///
/// Deliberately does NOT touch `totalPrincipal` or `totalCommitted`: no tokens
/// enter, positions are only regrouped.
function merge(uint256[] calldata tokenIds) external returns (uint256 survivorId) {
_requireNotPaused();
if (tokenIds.length < 2) revert NothingToMerge();
survivorId = tokenIds[0];
_authorized(survivorId);
// Every position merged must already belong to the same wallet. Authorisation
// alone is not enough: an operator approved on two different owners' bonds could
// otherwise fold one into the other, and merging BURNS the absorbed token. That
// turns an approval — which normally moves a position, leaving something to trace
// and hand back — into an irreversible destruction of one.
address owner = ownerOf(survivorId);
Bond storage s = _bonds[survivorId];
_settle(survivorId, s);
bool survivorBoost = _boostAlive(survivorId, s);
uint256 survivorPrincipalBefore = s.principal;
uint256 principal = s.principal;
uint256 weighted = s.principal * uint256(s.rateBps);
uint256 pending = s.pending;
uint64 bonusAt = s.lastBonusAt;
uint256[] memory absorbed = new uint256[](tokenIds.length - 1);
for (uint256 i = 1; i < tokenIds.length; i++) {
uint256 id = tokenIds[i];
if (id == survivorId) revert DuplicateToken();
_authorized(id);
if (ownerOf(id) != owner) revert Unauthorized();
Bond storage o = _bonds[id];
_settle(id, o);
// Same origin and same boost state, or the weighted average would launder
// value across the boundary: folding a live-boost position into a dead one
// silently destroys its boost, and the other direction would smuggle boosted
// principal into a position the strip can no longer reach.
if (o.origin != s.origin) revert OriginMismatch();
if (_boostAlive(id, o) != survivorBoost) revert BoostMismatch();
principal += o.principal;
weighted += o.principal * uint256(o.rateBps);
pending += o.pending;
if (o.lastBonusAt > bonusAt) bonusAt = o.lastBonusAt;
// Burn BEFORE delete: the burn's `_afterTokenTransfer` reads the position's
// origin to keep `commitBondCountOf` honest, so the struct must still exist.
_burn(id);
delete _bonds[id];
absorbed[i - 1] = id;
}
s.principal = principal;
s.pending = pending;
if (principal != 0) s.rateBps = uint32(weighted / principal);
s.lastAccrual = protocolNow();
s.lastBonusAt = bonusAt;
// The burns above subtracted every absorbed principal from the owner's commit
// aggregate; the survivor just grew by exactly that much. Net effect: conserved.
if (s.origin == Origin.Commit) {
commitPrincipalOf[owner] += principal - survivorPrincipalBefore;
}
emit Merged(survivorId, absorbed, principal, s.rateBps);
}
}
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/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 {} // Scan for '\0'.
byte(n, s) { n := add(n, 1) } {}
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 {} // Scan for '\0'.
byte(result, s) { result := add(result, 1) } {}
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))),
shr(shl(3, add(aLen, 1)), mload(add(b, 0x1f)))
),
// `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)))
}
}
}
src/base/CovenantSocials.sol
// SPDX-License-Identifier: MIT
// Landing: https://covenanthook.com/
// DApp: https://app.covenanthook.com/
// Documentation: https://gitbook.covenanthook.com/
// X: https://x.com/covenantv4
// Telegram: https://t.me/covenanthook
pragma solidity ^0.8.36;
/// @title CovenantSocials
/// @notice The project's official links, carried on-chain by every deployed Covenant
/// contract. Each `public constant` compiles into a getter, so any explorer's
/// Read tab answers with the canonical URLs straight from the bytecode — the
/// links survive even if every website and mirror goes down.
/// @dev Inherited by all five deployable contracts (token, bonds, vault, hook, router).
/// Constants only: no storage slots, no constructor, nothing to wire.
abstract contract CovenantSocials {
string public constant LANDING = "https://covenanthook.com/";
string public constant DAPP = "https://app.covenanthook.com/";
string public constant DOCUMENTATION = "https://gitbook.covenanthook.com/";
string public constant X = "https://x.com/covenantv4";
string public constant TELEGRAM = "https://t.me/covenanthook";
}
src/interfaces/ICovenantERC20.sol
// SPDX-License-Identifier: MIT
// Landing: https://covenanthook.com/
// DApp: https://app.covenanthook.com/
// Documentation: https://gitbook.covenanthook.com/
// X: https://x.com/covenantv4
// Telegram: https://t.me/covenanthook
pragma solidity ^0.8.36;
/// @notice Minimal ERC-20 surface used by the bond contracts. Shared so the vault and
/// the distributor speak the same type (a per-file copy would make them
/// incompatible at the call site).
interface ICovenantERC20 {
function balanceOf(address) external view returns (uint256);
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@uniswap/v4-periphery/=lib/v4-periphery/",
"@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
"v4-periphery/=lib/v4-periphery/",
"v4-core/=lib/v4-periphery/lib/v4-core/",
"permit2/=lib/v4-periphery/lib/permit2/",
"solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
"@openzeppelin/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"forge-std/=lib/v4-periphery/lib/v4-core/lib/forge-std/src/",
"ds-test/=lib/v4-periphery/lib/v4-core/lib/forge-std/lib/ds-test/src/",
"forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"solady/=lib/solady/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.