Verified contractPartialMIT
Abnormies
Address0xfa3bb476e170ff090e2b40ab266eb310cc3e4b1d
- Balance
0 ETH
- Transactions
3,665
- Compiler
solc 0.8.33
- Same code
Only this contract
Details
- Compiler
- solc 0.8.33+commit.64118f21
- Language
- solidity
- Optimization
- Yes, 10,000 runs
- EVM version
- prague
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,202,779
- Creation transaction
- 0xbbef32af19…a138608c09
38 files
- src/Abnormies.solmain31.77 KB
- lib/creator-token-standards/lib/PermitC/src/Constants.sol3.54 KB
- lib/creator-token-standards/lib/openzeppelin-contracts/contracts/access/Ownable.sol2.62 KB
- lib/creator-token-standards/lib/openzeppelin-contracts/contracts/interfaces/IERC2981.sol888 B
- lib/creator-token-standards/lib/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol17.31 KB
- lib/creator-token-standards/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol4.98 KB
- lib/creator-token-standards/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol987 B
- lib/creator-token-standards/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol761 B
- lib/creator-token-standards/lib/openzeppelin-contracts/contracts/token/common/ERC2981.sol4.1 KB
- lib/creator-token-standards/lib/openzeppelin-contracts/contracts/utils/Address.sol9.16 KB
- lib/creator-token-standards/lib/openzeppelin-contracts/contracts/utils/Context.sol844 B
- lib/creator-token-standards/lib/openzeppelin-contracts/contracts/utils/Strings.sol2.25 KB
- lib/creator-token-standards/lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol9.3 KB
- lib/creator-token-standards/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol987 B
- lib/creator-token-standards/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol853 B
- lib/creator-token-standards/lib/openzeppelin-contracts/contracts/utils/math/Math.sol12.51 KB
- lib/creator-token-standards/src/access/OwnableBasic.sol320 B
- lib/creator-token-standards/src/access/OwnablePermissions.sol230 B
- lib/creator-token-standards/src/erc721c/ERC721C.sol6.58 KB
- lib/creator-token-standards/src/interfaces/ICreatorToken.sol422 B
- lib/creator-token-standards/src/interfaces/ICreatorTokenLegacy.sol313 B
- lib/creator-token-standards/src/interfaces/ITransferValidator.sol1.09 KB
- lib/creator-token-standards/src/interfaces/ITransferValidatorSetTokenType.sol187 B
- lib/creator-token-standards/src/programmable-royalties/BasicRoyalties.sol1.54 KB
- lib/creator-token-standards/src/token/erc721/ERC721OpenZeppelin.sol1.7 KB
- lib/creator-token-standards/src/utils/AutomaticValidatorTransferApproval.sol1.39 KB
- lib/creator-token-standards/src/utils/CreatorTokenBase.sol8.25 KB
- lib/creator-token-standards/src/utils/TransferValidation.sol6.45 KB
- lib/solady/src/utils/Base64.sol7.72 KB
- lib/solady/src/utils/DynamicBufferLib.sol43.74 KB
- lib/solady/src/utils/LibBytes.sol38.18 KB
- lib/solady/src/utils/LibString.sol44.25 KB
- src/AbnormiesRenderer.sol17.64 KB
- src/interfaces/IAbnormies.sol1.18 KB
- src/interfaces/IAdapter8004.sol342 B
- src/interfaces/IDelegateRegistry.sol887 B
- src/interfaces/INormies.sol152 B
- src/interfaces/INormiesCanvasStorage.sol168 B
src/Abnormies.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
import {OwnableBasic} from "@limitbreak/creator-token-standards/access/OwnableBasic.sol";
import {OwnablePermissions} from "@limitbreak/creator-token-standards/access/OwnablePermissions.sol";
import {ERC721C} from "@limitbreak/creator-token-standards/erc721c/ERC721C.sol";
import {ERC721OpenZeppelin} from "@limitbreak/creator-token-standards/token/erc721/ERC721OpenZeppelin.sol";
import {BasicRoyalties} from "@limitbreak/creator-token-standards/programmable-royalties/BasicRoyalties.sol";
import {ERC2981} from "@openzeppelin/contracts/token/common/ERC2981.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {AbnormiesRenderer} from "./AbnormiesRenderer.sol";
import {INormies} from "./interfaces/INormies.sol";
import {INormiesCanvasStorage} from "./interfaces/INormiesCanvasStorage.sol";
import {IAdapter8004, TokenStandard} from "./interfaces/IAdapter8004.sol";
import {IDelegateRegistry} from "./interfaces/IDelegateRegistry.sol";
contract Abnormies is OwnableBasic, ERC721C, BasicRoyalties {
uint96 public constant ROYALTY_FEE_NUMERATOR = 250;
uint64 public constant PHASE_1_DURATION = 2 days;
uint64 public constant FALLBACK_REVEAL_DELAY = 14 days;
uint256 public constant MAX_SUPPLY = 10_000;
uint256 public constant MINT_PRICE = 0.005 ether;
uint256 public constant PHASE2_MAX_PER_CALL = 50;
// Seal-then-commit-then-reveal. Receipts are frozen first (sealed); only afterwards is a fixed
// window of future block hashes — unknown and unchosen at seal time — mixed into the reveal
// seed. Because the seal happens before the entropy blocks exist, no one can simulate future
// receipts' outcomes while Phase 2 is still open. REVEAL_DELAY_BLOCKS gaps the seal from the
// first entropy block so the seal-tx proposer cannot also be the first entropy proposer.
// Mixing REVEAL_BLOCK_COUNT consecutive blockhashes removes any single intermediate
// proposer's influence, but does NOT fully eliminate proposer bias: the proposer of the last
// entropy block can compute the resulting seed before publishing and withhold that block for
// one conditional reroll, at the cost of forfeiting its MEV. The manipulation surface is
// therefore ~(proposer share) x (block MEV) per reveal — a single reroll attempt — not
// (proposer share)^N. That residual bias is acceptable for this project at 0.005 ETH/mint and
// a ~30 ETH pot. REVEAL_EXPIRY_BLOCKS keeps the whole window inside the 256-block blockhash
// horizon; past it, reveal() can no longer read the hashes and reseal() restarts from the
// current block.
uint256 public constant REVEAL_DELAY_BLOCKS = 8;
uint256 public constant REVEAL_BLOCK_COUNT = 4;
uint256 public constant REVEAL_EXPIRY_BLOCKS = 240;
address public constant NORMIES = 0x9Eb6E2025B64f340691e424b7fe7022fFDE12438;
address public constant NORMIES_CANVAS_STORAGE = 0xC255BE0983776BAB027a156681b6925cde47B2D1;
address public constant ADAPTER8004 = 0xde152AfB7db5373F34876E1499fbD893A82dD336;
// delegate.xyz v2 registry. Same address across mainnet, Sepolia, and all major L2s.
address public constant DELEGATE_REGISTRY = 0x00000000000000447e69651d841bD8D104Bed493;
bytes32 public immutable SNAPSHOT_ROOT;
AbnormiesRenderer public immutable renderer;
uint64 public immutable deployedAt;
address public immutable treasury;
struct Receipt {
address claimant;
uint16 normieId;
bool fromPhase1;
bool snapshotCustomized;
bool resolved;
uint16 abnormieId;
}
struct AbnormieState {
uint16 seedNormieId;
uint64 staticAt;
address frozenBy;
uint8 freezeAction;
bool seedDeadAtFreeze;
uint32 pairedAtCascadeIndex;
uint32 staticAtCascadeIndex;
uint16 cirrusCountAtFreeze;
bool seedCustomizedAtFreeze;
uint64 seedDeadAtBlockAtFreeze;
bool paired;
}
struct Cascade {
uint64 blockNumber;
uint16 burnedTokenId;
uint16 freezeTargetTokenId;
uint8 action;
uint8 thunderSize;
}
Receipt[] public receipts;
mapping(uint256 => bool) public claimed;
mapping(uint256 => AbnormieState) public abnormieState;
mapping(uint256 => address) public lastObservedSeedOwner;
mapping(uint256 => uint16) public cirrusCount;
mapping(uint256 => bool) public seedCustomized;
mapping(uint256 => bool) public seedBurned;
mapping(uint256 => uint64) public seedDeadAtBlock;
mapping(uint256 => bool) public seedAwakened;
mapping(uint256 => uint256) public boundAgentId;
Cascade[] public cascadeLog;
uint16 public firstStaticTokenId;
bool public firstStaticSet;
uint256[MAX_SUPPLY] private _unclaimedIds;
uint256 public unclaimedCount = MAX_SUPPLY;
uint8 public phase;
uint64 public phase1ClosedAt;
uint64 public sealedAtBlock;
bool public isSealed;
uint256 public revealSeed;
bool public revealed;
uint256 public nextResolveIndex;
uint256 public phase1ReceiptCount;
uint256 public phase2ReceiptCount;
uint256 public phase2RemainingSlots;
mapping(uint256 => uint256) private _phase2NormiePool;
uint256 public phase2NormiePoolSize;
event Phase1Claimed(address indexed claimant, uint256 indexed normieId, bool customized);
event Phase1Closed(uint256 receiptCount);
event Sealed(uint64 sealedAtBlock, uint256 receiptCount);
event Resealed(uint64 sealedAtBlock);
event Revealed(uint256 seed, uint256 blockNumber);
event AbnormiePaired(uint256 indexed abnormieId, uint256 indexed normieId, address indexed claimant);
event CirrusObserved(uint256 indexed normieId, address indexed newOwner, uint16 cirrusCount);
event SeedCustomized(uint256 indexed normieId);
event SeedBurned(uint256 indexed normieId);
event SeedAwakened(uint256 indexed normieId, uint256 indexed agentId);
event Thundered(
uint256 indexed burnedTokenId, uint256 indexed freezeTargetTokenId, address indexed burner, uint256 cascadeIndex
);
event Lightninged(
uint256 indexed burnedTokenId, uint256 indexed freezeTargetTokenId, address indexed burner, uint256 cascadeIndex
);
event AbnormieFrozen(uint256 indexed tokenId, address indexed by, uint8 action, uint64 atBlock, bool firstStatic);
event Phase2Minted(address indexed claimant, uint256 firstReceiptIndex, uint256 count);
event AirdropMinted(address indexed recipient, uint256 count, uint256 startReceiptIndex, uint256 endReceiptIndex);
event TreasuryWithdrawal(address indexed treasury, uint256 amount);
error NotOwner();
error InvalidTreasury();
error WithdrawalFailed();
error PhaseNotOpen();
error Phase1Ended();
error Phase1NotEnded();
error LengthMismatch();
error InvalidProof();
error InvalidDelegation();
error AlreadyClaimed(uint256 normieId);
error OutOfRangeNormieId(uint256 normieId);
error ResolveBeforeReveal();
error FallbackRevealTooEarly();
error PhaseSealed();
error NotSealed();
error AlreadyRevealed();
error RevealBlocksNotReady(uint256 needBlock);
error BlockhashUnavailable(uint256 blockNumber);
error RevealExpired();
error CannotReseal();
error EmptyRange();
error AlreadyAwakened();
error WrongBindingStandard();
error WrongBindingContract();
error WrongBindingTokenId();
error NotActive(uint256 tokenId);
error SelfFreezeForbidden();
error SeedStillLiving();
error SeedNotCustomized();
error SeedDead();
error WrongMintPrice();
error MaxPerCallExceeded();
error SoldOut();
error InvalidRecipient();
constructor(bytes32 snapshotRoot, address royaltyReceiver, address treasury_, address renderer_)
ERC721OpenZeppelin("Abnormies", "ABNORMIES")
BasicRoyalties(royaltyReceiver, ROYALTY_FEE_NUMERATOR)
{
if (treasury_ == address(0)) revert InvalidTreasury();
SNAPSHOT_ROOT = snapshotRoot;
treasury = treasury_;
renderer = AbnormiesRenderer(renderer_);
deployedAt = uint64(block.timestamp);
}
function withdraw() external {
uint256 balance = address(this).balance;
if (balance == 0) return;
(bool ok,) = treasury.call{value: balance}("");
if (!ok) revert WithdrawalFailed();
emit TreasuryWithdrawal(treasury, balance);
}
// -----------------------------------------------------------------------
// Phase 1: claim + close
// -----------------------------------------------------------------------
/// @notice Create Phase 1 receipts for claimed Normies, each proven against the snapshot root.
/// @dev Two paths, selected by `vault`:
/// - Direct (`vault == address(0)`): `claimant = msg.sender`. Each leaf is verified against
/// `msg.sender` and receipts are credited to `msg.sender`.
/// - Delegated (`vault != address(0)`): the caller must be an authorized delegate for
/// `vault` per delegate.xyz v2 — `checkDelegateForContract(msg.sender, vault, this, 0)`,
/// where `rights == bytes32(0)` matches both an "all" delegation and one scoped to this
/// contract. On success `claimant = vault`: leaves are verified against `vault` and
/// receipts are credited to `vault`, letting a hot wallet claim for the cold vault that
/// actually held the Normies at snapshot. Reverts `InvalidDelegation` if not authorized.
function claim(
uint256[] calldata normieIds,
bool[] calldata customizedFlags,
bytes32[][] calldata proofs,
address vault
) external {
if (phase != 0) revert PhaseNotOpen();
if (block.timestamp >= deployedAt + PHASE_1_DURATION) revert Phase1Ended();
uint256 n = normieIds.length;
if (customizedFlags.length != n || proofs.length != n) revert LengthMismatch();
// Resolve the address the receipts are credited to and proven against.
address claimant = msg.sender;
if (vault != address(0)) {
if (!IDelegateRegistry(DELEGATE_REGISTRY)
.checkDelegateForContract(msg.sender, vault, address(this), bytes32(0))) {
revert InvalidDelegation();
}
claimant = vault;
}
for (uint256 i = 0; i < n;) {
uint256 normieId = normieIds[i];
bool customized = customizedFlags[i];
// Guard against a malformed snapshot root carrying an out-of-range id. The valid
// Normie range is 0..MAX_SUPPLY-1; anything at MAX_SUPPLY or above can never pair and
// would overflow the uint16 receipt field.
require(normieId < MAX_SUPPLY, OutOfRangeNormieId(normieId));
if (claimed[normieId]) revert AlreadyClaimed(normieId);
// Double-hashed leaf encoding matches OpenZeppelin's StandardMerkleTree (used by
// `snapshot/build.ts`). The outer keccak protects against second-preimage attacks on
// intermediate tree nodes; the inner keccak is the leaf-value commitment that the
// proof verifies against.
bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(normieId, claimant, customized))));
if (!MerkleProof.verify(proofs[i], SNAPSHOT_ROOT, leaf)) revert InvalidProof();
claimed[normieId] = true;
receipts.push(
Receipt({
claimant: claimant,
normieId: uint16(normieId),
fromPhase1: true,
snapshotCustomized: customized,
resolved: false,
abnormieId: 0
})
);
phase1ReceiptCount += 1;
emit Phase1Claimed(claimant, normieId, customized);
unchecked {
++i;
}
}
}
function closePhase1() external {
if (phase != 0) revert PhaseNotOpen();
if (block.timestamp < deployedAt + PHASE_1_DURATION) revert Phase1NotEnded();
phase = 1;
phase1ClosedAt = uint64(block.timestamp);
phase2RemainingSlots = MAX_SUPPLY - phase1ReceiptCount;
phase2NormiePoolSize = MAX_SUPPLY;
// No entropy is committed here. Phase 2 stays open and receipts accumulate; the commitment
// to randomness happens only at seal time, so no one can simulate outcomes for receipts
// that don't exist yet.
emit Phase1Closed(phase1ReceiptCount);
}
// -----------------------------------------------------------------------
// Phase 2: paid mints, owner airdrops, reveal, resolve
// -----------------------------------------------------------------------
function mintPhase2(uint256 count) external payable {
if (phase != 1 || revealed) revert PhaseNotOpen();
if (isSealed) revert PhaseSealed();
if (count == 0 || count > PHASE2_MAX_PER_CALL) revert MaxPerCallExceeded();
if (msg.value != count * MINT_PRICE) revert WrongMintPrice();
if (phase2RemainingSlots < count) revert SoldOut();
uint256 start = receipts.length;
phase2RemainingSlots -= count;
for (uint256 i = 0; i < count;) {
receipts.push(
Receipt({
claimant: msg.sender,
normieId: 0,
fromPhase1: false,
snapshotCustomized: false,
resolved: false,
abnormieId: 0
})
);
unchecked {
++i;
}
}
phase2ReceiptCount += count;
emit Phase2Minted(msg.sender, start, count);
_maybeAutoSeal();
}
function airdrop(address recipient, uint256 count) external {
_requireCallerIsContractOwner();
if (phase != 1 || revealed) revert PhaseNotOpen();
if (isSealed) revert PhaseSealed();
if (recipient == address(0)) revert InvalidRecipient();
if (count == 0 || count > PHASE2_MAX_PER_CALL) revert MaxPerCallExceeded();
if (phase2RemainingSlots < count) revert SoldOut();
uint256 start = receipts.length;
phase2RemainingSlots -= count;
for (uint256 i = 0; i < count;) {
receipts.push(
Receipt({
claimant: recipient,
normieId: 0,
fromPhase1: false,
snapshotCustomized: false,
resolved: false,
abnormieId: 0
})
);
unchecked {
++i;
}
}
phase2ReceiptCount += count;
emit AirdropMinted(recipient, count, start, receipts.length);
_maybeAutoSeal();
}
/// @notice Permissionless seal trigger for the fallback path. Freezes the receipt list so the
/// reveal window can begin. Auto-seal already fires inline when supply is exhausted via
/// mint/airdrop; this is the safety net if Phase 2 stalls below capacity — callable
/// once `phase1ClosedAt + FALLBACK_REVEAL_DELAY` has elapsed. Any remaining Phase 2
/// slots are stranded: after seal, no further mints or airdrops are accepted.
function sealForReveal() external {
if (isSealed) revert PhaseSealed();
if (phase != 1 || revealed) revert PhaseNotOpen();
bool soldOut = phase2RemainingSlots == 0;
bool late = block.timestamp >= uint256(phase1ClosedAt) + FALLBACK_REVEAL_DELAY;
if (!soldOut && !late) revert FallbackRevealTooEarly();
_seal();
}
/// @notice Permissionless reveal. Mixes the hashes of REVEAL_BLOCK_COUNT consecutive blocks
/// starting at `sealedAtBlock + REVEAL_DELAY_BLOCKS` into the seed. Callable once all
/// those blocks are mined (and far enough back that they're stable) but before the
/// blockhash window expires. Past expiry, reseal() must restart the window first.
function reveal() external {
if (!isSealed) revert NotSealed();
if (revealed) revert AlreadyRevealed();
uint256 firstBlock = uint256(sealedAtBlock) + REVEAL_DELAY_BLOCKS;
uint256 readyBlock = firstBlock + REVEAL_BLOCK_COUNT;
if (block.number <= readyBlock) revert RevealBlocksNotReady(readyBlock);
if (block.number > uint256(sealedAtBlock) + REVEAL_EXPIRY_BLOCKS) revert RevealExpired();
bytes32 seed;
for (uint256 i = 0; i < REVEAL_BLOCK_COUNT;) {
uint256 target = firstBlock + i;
bytes32 h = blockhash(target);
if (h == bytes32(0)) revert BlockhashUnavailable(target);
seed = keccak256(abi.encode(seed, h));
unchecked {
++i;
}
}
revealSeed = uint256(seed);
revealed = true;
phase = 2;
emit Revealed(revealSeed, block.number);
}
/// @notice Restart the reveal window when the prior seal aged out of the 256-block blockhash
/// horizon (the practical case being the 14-day fallback, where the entropy blocks are
/// long unreadable by the time anyone calls reveal). Only moves `sealedAtBlock`; the
/// frozen receipt list is untouched.
function reseal() external {
if (!isSealed) revert NotSealed();
if (revealed) revert AlreadyRevealed();
if (block.number <= uint256(sealedAtBlock) + REVEAL_EXPIRY_BLOCKS) revert CannotReseal();
sealedAtBlock = uint64(block.number);
emit Resealed(sealedAtBlock);
}
function _maybeAutoSeal() internal {
if (isSealed || revealed) return;
if (phase != 1) return;
if (phase2RemainingSlots != 0) return;
_seal();
}
function _seal() internal {
isSealed = true;
sealedAtBlock = uint64(block.number);
emit Sealed(sealedAtBlock, receipts.length);
}
function resolveReceipts(uint256 count) external {
if (!revealed) revert ResolveBeforeReveal();
if (count == 0) return;
uint256 receiptCount = receipts.length;
uint256 start = nextResolveIndex;
if (start >= receiptCount) return;
uint256 remaining = receiptCount - start;
if (count > remaining) count = remaining;
uint256 end = start + count;
for (uint256 i = start; i < end;) {
Receipt storage r = receipts[i];
if (!r.resolved) {
uint256 abnormieId = _pickAndPop(uint256(keccak256(abi.encode(revealSeed, i))) % unclaimedCount);
uint256 normieId = r.fromPhase1
? uint256(r.normieId)
: _pickNormieIdForPhase2(uint256(keccak256(abi.encode(revealSeed, i, "norm"))));
r.abnormieId = uint16(abnormieId);
r.normieId = uint16(normieId);
r.resolved = true;
_mint(r.claimant, abnormieId);
AbnormieState storage st = abnormieState[abnormieId];
st.seedNormieId = uint16(normieId);
st.pairedAtCascadeIndex = uint32(cascadeLog.length);
st.paired = true;
if (r.fromPhase1) {
lastObservedSeedOwner[normieId] = r.claimant;
if (r.snapshotCustomized) {
seedCustomized[normieId] = true;
}
} else {
_snapshotSeedAtPairing(normieId);
}
emit AbnormiePaired(abnormieId, normieId, r.claimant);
}
unchecked {
++i;
}
}
nextResolveIndex = end;
}
function _pickAndPop(uint256 index) internal returns (uint256 abnormieId) {
uint256 lastIndex = unclaimedCount - 1;
uint256 picked = _unclaimedIds[index];
abnormieId = picked == 0 ? index + 1 : picked;
if (index != lastIndex) {
uint256 lastStored = _unclaimedIds[lastIndex];
_unclaimedIds[index] = lastStored == 0 ? lastIndex + 1 : lastStored;
}
unclaimedCount = lastIndex;
}
function _pickNormieIdForPhase2(uint256 seedBase) internal returns (uint256 normieId) {
// Pool spans Normie ids 0..MAX_SUPPLY-1 inclusive (matches the live Normies token range:
// 0 exists, 9999 exists, 10000 does not). Slot encoding stores (candidate + 1) so a
// raw 0 in the mapping unambiguously means "uninitialised; natural value = r" rather
// than the literal candidate 0.
uint256 attempt = 0;
while (true) {
uint256 size = phase2NormiePoolSize;
uint256 r = uint256(keccak256(abi.encode(seedBase, attempt))) % size;
uint256 stored = _phase2NormiePool[r];
uint256 candidate = stored == 0 ? r : stored - 1;
uint256 lastIdx = size - 1;
if (r != lastIdx) {
uint256 lastStored = _phase2NormiePool[lastIdx];
uint256 lastCandidate = lastStored == 0 ? lastIdx : lastStored - 1;
_phase2NormiePool[r] = lastCandidate + 1;
}
phase2NormiePoolSize = lastIdx;
if (claimed[candidate]) {
unchecked {
++attempt;
}
continue;
}
claimed[candidate] = true;
return candidate;
}
}
function _snapshotSeedAtPairing(uint256 normieId) internal {
try INormiesCanvasStorage(NORMIES_CANVAS_STORAGE).isTransformed(normieId) returns (bool transformed) {
if (transformed) {
seedCustomized[normieId] = true;
}
} catch {}
try INormies(NORMIES).ownerOf(normieId) returns (address o) {
if (o == address(0)) {
_markSeedBurned(normieId);
} else {
lastObservedSeedOwner[normieId] = o;
}
} catch {
_markSeedBurned(normieId);
}
}
function _markSeedBurned(uint256 normieId) internal {
if (seedBurned[normieId]) return;
seedBurned[normieId] = true;
seedDeadAtBlock[normieId] = uint64(block.number);
emit SeedBurned(normieId);
}
// -----------------------------------------------------------------------
// Pokes
// -----------------------------------------------------------------------
function pokeSeed(uint256 normieId) external {
_pokeSeed(normieId);
}
function pokeMany(uint256[] calldata normieIds) external {
uint256 n = normieIds.length;
for (uint256 i = 0; i < n;) {
_pokeSeed(normieIds[i]);
unchecked {
++i;
}
}
}
function pokeAwakening(uint256 normieId, uint256 agentId) external {
if (seedAwakened[normieId]) revert AlreadyAwakened();
IAdapter8004.Binding memory binding = IAdapter8004(ADAPTER8004).bindingOf(agentId);
if (binding.standard != TokenStandard.ERC721) revert WrongBindingStandard();
if (binding.tokenContract != NORMIES) revert WrongBindingContract();
if (binding.tokenId != normieId) revert WrongBindingTokenId();
seedAwakened[normieId] = true;
boundAgentId[normieId] = agentId;
emit SeedAwakened(normieId, agentId);
}
function _pokeSeed(uint256 normieId) internal {
if (seedBurned[normieId]) {
return;
}
address currentOwner;
try INormies(NORMIES).ownerOf(normieId) returns (address o) {
currentOwner = o;
} catch {
_markSeedBurned(normieId);
return;
}
if (currentOwner == address(0)) {
_markSeedBurned(normieId);
return;
}
address last = lastObservedSeedOwner[normieId];
if (last == address(0)) {
lastObservedSeedOwner[normieId] = currentOwner;
} else if (currentOwner != last) {
uint16 current = cirrusCount[normieId];
uint16 next = current;
if (current < type(uint16).max) {
next = current + 1;
cirrusCount[normieId] = next;
}
lastObservedSeedOwner[normieId] = currentOwner;
emit CirrusObserved(normieId, currentOwner, next);
}
if (!seedCustomized[normieId]) {
try INormiesCanvasStorage(NORMIES_CANVAS_STORAGE).isTransformed(normieId) returns (bool transformed) {
if (transformed) {
seedCustomized[normieId] = true;
emit SeedCustomized(normieId);
}
} catch {}
}
}
// -----------------------------------------------------------------------
// Actions
// -----------------------------------------------------------------------
function thunder(uint256 burnTokenId, uint256 freezeTargetTokenId) external {
if (phase < 2) revert PhaseNotOpen();
if (ownerOf(burnTokenId) != msg.sender) revert NotOwner();
AbnormieState storage burnState = abnormieState[burnTokenId];
if (burnState.staticAt != 0) revert NotActive(burnTokenId);
uint256 seedId = burnState.seedNormieId;
if (!seedBurned[seedId]) {
_pokeSeed(seedId);
}
if (!seedBurned[seedId]) revert SeedStillLiving();
_requireFreezeTargetEligible(freezeTargetTokenId);
uint256 cascadeIndex = _freezeAndCascade(burnTokenId, freezeTargetTokenId, 1);
emit Thundered(burnTokenId, freezeTargetTokenId, msg.sender, cascadeIndex);
}
function lightning(uint256 burnTokenId, uint256 freezeTargetTokenId) external {
if (phase < 2) revert PhaseNotOpen();
if (ownerOf(burnTokenId) != msg.sender) revert NotOwner();
AbnormieState storage burnState = abnormieState[burnTokenId];
if (burnState.staticAt != 0) revert NotActive(burnTokenId);
uint256 seedId = burnState.seedNormieId;
_pokeSeed(seedId);
if (seedBurned[seedId]) revert SeedDead();
if (!seedCustomized[seedId]) revert SeedNotCustomized();
_requireFreezeTargetEligible(freezeTargetTokenId);
uint256 cascadeIndex = _freezeAndCascade(burnTokenId, freezeTargetTokenId, 2);
emit Lightninged(burnTokenId, freezeTargetTokenId, msg.sender, cascadeIndex);
}
function _requireFreezeTargetEligible(uint256 freezeTargetTokenId) internal view {
address freezeOwner = ownerOf(freezeTargetTokenId);
if (freezeOwner == msg.sender) revert SelfFreezeForbidden();
if (abnormieState[freezeTargetTokenId].staticAt != 0) revert NotActive(freezeTargetTokenId);
}
function _freezeAndCascade(uint256 burnTokenId, uint256 freezeTargetTokenId, uint8 action)
internal
returns (uint256 cascadeIndex)
{
AbnormieState storage targetState = abnormieState[freezeTargetTokenId];
uint256 targetSeedId = targetState.seedNormieId;
uint64 atBlock = uint64(block.number);
_pokeSeed(targetSeedId);
targetState.staticAt = atBlock;
targetState.frozenBy = msg.sender;
targetState.freezeAction = action;
targetState.seedDeadAtFreeze = seedBurned[targetSeedId];
targetState.cirrusCountAtFreeze = cirrusCount[targetSeedId];
targetState.seedCustomizedAtFreeze = seedCustomized[targetSeedId];
targetState.seedDeadAtBlockAtFreeze = seedDeadAtBlock[targetSeedId];
targetState.staticAtCascadeIndex = uint32(cascadeLog.length);
bool firstStatic = !firstStaticSet;
if (firstStatic) {
firstStaticTokenId = uint16(freezeTargetTokenId);
firstStaticSet = true;
}
emit AbnormieFrozen(freezeTargetTokenId, msg.sender, action, atBlock, firstStatic);
cascadeLog.push(
Cascade({
blockNumber: atBlock,
burnedTokenId: uint16(burnTokenId),
freezeTargetTokenId: uint16(freezeTargetTokenId),
action: action,
thunderSize: 0
})
);
cascadeIndex = cascadeLog.length - 1;
_burn(burnTokenId);
}
function cascadeLogLength() external view returns (uint256) {
return cascadeLog.length;
}
function getAllCascades() external view returns (Cascade[] memory) {
return cascadeLog;
}
function getCascade(uint256 index) external view returns (Cascade memory) {
return cascadeLog[index];
}
function getAbnormieState(uint256 abnormieId) external view returns (AbnormieState memory) {
return abnormieState[abnormieId];
}
function getSeedState(uint256 normieId)
external
view
returns (address lastOwner, uint16 cirrus, bool customized, bool burned, bool awakened, uint256 boundAgent)
{
return (
lastObservedSeedOwner[normieId],
cirrusCount[normieId],
seedCustomized[normieId],
seedBurned[normieId],
seedAwakened[normieId],
boundAgentId[normieId]
);
}
// -----------------------------------------------------------------------
// Hooks + utility
// -----------------------------------------------------------------------
function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize)
internal
virtual
override
{
super._beforeTokenTransfer(from, to, firstTokenId, batchSize);
if (from == address(0)) return;
for (uint256 i = 0; i < batchSize;) {
uint256 tokenId = firstTokenId + i;
// Gate on `paired`, not `seedNormieId != 0`: an Abnormie legitimately paired with
// Normie 0 has seedNormieId == 0 and must still auto-poke its seed on transfer.
AbnormieState storage state = abnormieState[tokenId];
if (state.paired) {
_pokeSeed(state.seedNormieId);
}
unchecked {
++i;
}
}
}
function receiptsLength() external view returns (uint256) {
return receipts.length;
}
function receiptAt(uint256 index)
external
view
returns (
address claimant,
uint16 normieId,
bool fromPhase1,
bool snapshotCustomized,
bool resolved,
uint16 abnormieId
)
{
Receipt storage r = receipts[index];
return (r.claimant, r.normieId, r.fromPhase1, r.snapshotCustomized, r.resolved, r.abnormieId);
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
_requireMinted(tokenId);
return renderer.tokenURI(tokenId);
}
function setRoyaltyInfo(address receiver, uint96 feeNumerator) external {
_requireCallerIsContractOwner();
_setDefaultRoyalty(receiver, feeNumerator);
}
function _requireCallerIsContractOwner() internal view virtual override(OwnableBasic, OwnablePermissions) {
if (msg.sender != owner()) revert NotOwner();
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721C, ERC2981) returns (bool) {
return ERC721C.supportsInterface(interfaceId) || ERC2981.supportsInterface(interfaceId);
}
}
lib/creator-token-standards/lib/PermitC/src/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @dev Constant bytes32 value of 0x000...000
bytes32 constant ZERO_BYTES32 = bytes32(0);
/// @dev Constant value of 0
uint256 constant ZERO = 0;
/// @dev Constant value of 1
uint256 constant ONE = 1;
/// @dev Constant value representing an open order in storage
uint8 constant ORDER_STATE_OPEN = 0;
/// @dev Constant value representing a filled order in storage
uint8 constant ORDER_STATE_FILLED = 1;
/// @dev Constant value representing a cancelled order in storage
uint8 constant ORDER_STATE_CANCELLED = 2;
/// @dev Constant value representing the ERC721 token type for signatures and transfer hooks
uint256 constant TOKEN_TYPE_ERC721 = 721;
/// @dev Constant value representing the ERC1155 token type for signatures and transfer hooks
uint256 constant TOKEN_TYPE_ERC1155 = 1155;
/// @dev Constant value representing the ERC20 token type for signatures and transfer hooks
uint256 constant TOKEN_TYPE_ERC20 = 20;
/// @dev Constant value to mask the upper bits of a signature that uses a packed `vs` value to extract `s`
bytes32 constant UPPER_BIT_MASK = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/// @dev EIP-712 typehash used for validating signature based stored approvals
bytes32 constant UPDATE_APPROVAL_TYPEHASH =
keccak256("UpdateApprovalBySignature(uint256 tokenType,address token,uint256 id,uint256 amount,uint256 nonce,address operator,uint256 approvalExpiration,uint256 sigDeadline,uint256 masterNonce)");
/// @dev EIP-712 typehash used for validating a single use permit without additional data
bytes32 constant SINGLE_USE_PERMIT_TYPEHASH =
keccak256("PermitTransferFrom(uint256 tokenType,address token,uint256 id,uint256 amount,uint256 nonce,address operator,uint256 expiration,uint256 masterNonce)");
/// @dev EIP-712 typehash used for validating a single use permit with additional data
string constant SINGLE_USE_PERMIT_TRANSFER_ADVANCED_TYPEHASH_STUB =
"PermitTransferFromWithAdditionalData(uint256 tokenType,address token,uint256 id,uint256 amount,uint256 nonce,address operator,uint256 expiration,uint256 masterNonce,";
/// @dev EIP-712 typehash used for validating an order permit that updates storage as it fills
string constant PERMIT_ORDER_ADVANCED_TYPEHASH_STUB =
"PermitOrderWithAdditionalData(uint256 tokenType,address token,uint256 id,uint256 amount,uint256 salt,address operator,uint256 expiration,uint256 masterNonce,";
/// @dev Pausable flag for stored approval transfers of ERC721 assets
uint256 constant PAUSABLE_APPROVAL_TRANSFER_FROM_ERC721 = 1 << 0;
/// @dev Pausable flag for stored approval transfers of ERC1155 assets
uint256 constant PAUSABLE_APPROVAL_TRANSFER_FROM_ERC1155 = 1 << 1;
/// @dev Pausable flag for stored approval transfers of ERC20 assets
uint256 constant PAUSABLE_APPROVAL_TRANSFER_FROM_ERC20 = 1 << 2;
/// @dev Pausable flag for single use permit transfers of ERC721 assets
uint256 constant PAUSABLE_PERMITTED_TRANSFER_FROM_ERC721 = 1 << 3;
/// @dev Pausable flag for single use permit transfers of ERC1155 assets
uint256 constant PAUSABLE_PERMITTED_TRANSFER_FROM_ERC1155 = 1 << 4;
/// @dev Pausable flag for single use permit transfers of ERC20 assets
uint256 constant PAUSABLE_PERMITTED_TRANSFER_FROM_ERC20 = 1 << 5;
/// @dev Pausable flag for order fill transfers of ERC1155 assets
uint256 constant PAUSABLE_ORDER_TRANSFER_FROM_ERC1155 = 1 << 6;
/// @dev Pausable flag for order fill transfers of ERC20 assets
uint256 constant PAUSABLE_ORDER_TRANSFER_FROM_ERC20 = 1 << 7;lib/creator-token-standards/lib/openzeppelin-contracts/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/creator-token-standards/lib/openzeppelin-contracts/contracts/interfaces/IERC2981.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
lib/creator-token-standards/lib/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.2) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: address zero is not a valid owner");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _ownerOf(tokenId);
require(owner != address(0), "ERC721: invalid token ID");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
_requireMinted(tokenId);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not token owner or approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
_requireMinted(tokenId);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
_safeTransfer(from, to, tokenId, data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - 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 tokenId,
bytes memory data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
*/
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
return _owners[tokenId];
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _ownerOf(tokenId) != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - 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 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId, 1);
// Check that tokenId was not minted by `_beforeTokenTransfer` hook
require(!_exists(tokenId), "ERC721: token already minted");
unchecked {
// Will not overflow unless all 2**256 token ids are minted to the same owner.
// Given that tokens are minted one by one, it is impossible in practice that
// this ever happens. Might change if we allow batch minting.
// The ERC fails to describe this case.
_balances[to] += 1;
}
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId, 1);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
* This is an internal function that does not check if the sender is authorized to operate on the token.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId, 1);
// Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
owner = ERC721.ownerOf(tokenId);
// Clear approvals
delete _tokenApprovals[tokenId];
unchecked {
// Cannot overflow, as that would require more tokens to be burned/transferred
// out than the owner initially received through minting and transferring in.
_balances[owner] -= 1;
}
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId, 1);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId, 1);
// Check that tokenId was not transferred by `_beforeTokenTransfer` hook
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
// Clear approvals from the previous owner
delete _tokenApprovals[tokenId];
unchecked {
// `_balances[from]` cannot overflow for the same reason as described in `_burn`:
// `from`'s balance is the number of token held, which is at least one before the current
// transfer.
// `_balances[to]` could overflow in the conditions described in `_mint`. That would require
// all 2**256 token ids to be minted, which in practice is impossible.
_balances[from] -= 1;
_balances[to] += 1;
}
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` has not been minted yet.
*/
function _requireMinted(uint256 tokenId) internal view virtual {
require(_exists(tokenId), "ERC721: invalid token ID");
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
/// @solidity memory-safe-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
* used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
* - When `from` is zero, the tokens will be minted for `to`.
* - When `to` is zero, ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
* - `batchSize` is non-zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
) internal virtual {}
/**
* @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
* used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
* - When `from` is zero, the tokens were minted for `to`.
* - When `to` is zero, ``from``'s tokens were burned.
* - `from` and `to` are never both zero.
* - `batchSize` is non-zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
) internal virtual {}
/**
* @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
*
* WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant
* being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such
* that `ownerOf(tokenId)` is `a`.
*/
// solhint-disable-next-line func-name-mixedcase
function __unsafe_increaseBalance(address account, uint256 amount) internal {
_balances[account] += amount;
}
}
lib/creator-token-standards/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - 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 tokenId,
bytes calldata data
) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - 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 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
lib/creator-token-standards/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
lib/creator-token-standards/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
lib/creator-token-standards/lib/openzeppelin-contracts/contracts/token/common/ERC2981.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/common/ERC2981.sol)
pragma solidity ^0.8.0;
import "../../interfaces/IERC2981.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
*
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
* specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
*
* Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
* fee is specified in basis points by default.
*
* IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
* https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
* voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
*
* _Available since v4.5._
*/
abstract contract ERC2981 is IERC2981, ERC165 {
struct RoyaltyInfo {
address receiver;
uint96 royaltyFraction;
}
RoyaltyInfo private _defaultRoyaltyInfo;
mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @inheritdoc IERC2981
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view virtual override returns (address, uint256) {
RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
if (royalty.receiver == address(0)) {
royalty = _defaultRoyaltyInfo;
}
uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
return (royalty.receiver, royaltyAmount);
}
/**
* @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
* fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
* override.
*/
function _feeDenominator() internal pure virtual returns (uint96) {
return 10000;
}
/**
* @dev Sets the royalty information that all ids in this contract will default to.
*
* Requirements:
*
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: invalid receiver");
_defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Removes default royalty information.
*/
function _deleteDefaultRoyalty() internal virtual {
delete _defaultRoyaltyInfo;
}
/**
* @dev Sets the royalty information for a specific token id, overriding the global default.
*
* Requirements:
*
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setTokenRoyalty(
uint256 tokenId,
address receiver,
uint96 feeNumerator
) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: Invalid parameters");
_tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Resets royalty information for the token id back to the global default.
*/
function _resetTokenRoyalty(uint256 tokenId) internal virtual {
delete _tokenRoyaltyInfo[tokenId];
}
}
lib/creator-token-standards/lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
lib/creator-token-standards/lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
lib/creator-token-standards/lib/openzeppelin-contracts/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}
lib/creator-token-standards/lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The tree and the proofs can be generated using our
* https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
* You will find a quickstart guide in the readme.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the merkle tree could be reinterpreted as a leaf value.
* OpenZeppelin's JavaScript library generates merkle trees that are safe
* against this attack out of the box.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Calldata version of {verify}
*
* _Available since v4.7._
*/
function verifyCalldata(
bytes32[] calldata proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Calldata version of {processProof}
*
* _Available since v4.7._
*/
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
*
* _Available since v4.7._
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Calldata version of {multiProofVerify}
*
* CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
*
* _Available since v4.7._
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* _Available since v4.7._
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the merkle tree.
uint256 leavesLen = leaves.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value for the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
return hashes[totalHashes - 1];
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Calldata version of {processMultiProof}.
*
* CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
*
* _Available since v4.7._
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the merkle tree.
uint256 leavesLen = leaves.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value for the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
return hashes[totalHashes - 1];
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
lib/creator-token-standards/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/creator-token-standards/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/creator-token-standards/lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10**64) {
value /= 10**64;
result += 64;
}
if (value >= 10**32) {
value /= 10**32;
result += 32;
}
if (value >= 10**16) {
value /= 10**16;
result += 16;
}
if (value >= 10**8) {
value /= 10**8;
result += 8;
}
if (value >= 10**4) {
value /= 10**4;
result += 4;
}
if (value >= 10**2) {
value /= 10**2;
result += 2;
}
if (value >= 10**1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
}
}
}
lib/creator-token-standards/src/access/OwnableBasic.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./OwnablePermissions.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
abstract contract OwnableBasic is OwnablePermissions, Ownable {
function _requireCallerIsContractOwner() internal view virtual override {
_checkOwner();
}
}
lib/creator-token-standards/src/access/OwnablePermissions.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/Context.sol";
abstract contract OwnablePermissions is Context {
function _requireCallerIsContractOwner() internal view virtual;
}
lib/creator-token-standards/src/erc721c/ERC721C.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../utils/AutomaticValidatorTransferApproval.sol";
import "../utils/CreatorTokenBase.sol";
import "../token/erc721/ERC721OpenZeppelin.sol";
import "../interfaces/ITransferValidatorSetTokenType.sol";
import {TOKEN_TYPE_ERC721} from "@limitbreak/permit-c/Constants.sol";
/**
* @title ERC721C
* @author Limit Break, Inc.
* @notice Extends OpenZeppelin's ERC721 implementation with Creator Token functionality, which
* allows the contract owner to update the transfer validation logic by managing a security policy in
* an external transfer validation security policy registry. See {CreatorTokenTransferValidator}.
*/
abstract contract ERC721C is ERC721OpenZeppelin, CreatorTokenBase, AutomaticValidatorTransferApproval {
/**
* @notice Overrides behavior of isApprovedFor all such that if an operator is not explicitly approved
* for all, the contract owner can optionally auto-approve the 721-C transfer validator for transfers.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool isApproved) {
isApproved = super.isApprovedForAll(owner, operator);
if (!isApproved) {
if (autoApproveTransfersFromValidator) {
isApproved = operator == address(getTransferValidator());
}
}
}
/**
* @notice Indicates whether the contract implements the specified interface.
* @dev Overrides supportsInterface in ERC165.
* @param interfaceId The interface id
* @return true if the contract implements the specified interface, false otherwise
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(ICreatorToken).interfaceId ||
interfaceId == type(ICreatorTokenLegacy).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @notice Returns the function selector for the transfer validator's validation function to be called
* @notice for transaction simulation.
*/
function getTransferValidationFunction() external pure returns (bytes4 functionSignature, bool isViewFunction) {
functionSignature = bytes4(keccak256("validateTransfer(address,address,address,uint256)"));
isViewFunction = true;
}
/// @dev Ties the open-zeppelin _beforeTokenTransfer hook to more granular transfer validation logic
function _beforeTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize) internal virtual override {
for (uint256 i = 0; i < batchSize;) {
_validateBeforeTransfer(from, to, firstTokenId + i);
unchecked {
++i;
}
}
}
/// @dev Ties the open-zeppelin _afterTokenTransfer hook to more granular transfer validation logic
function _afterTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize) internal virtual override {
for (uint256 i = 0; i < batchSize;) {
_validateAfterTransfer(from, to, firstTokenId + i);
unchecked {
++i;
}
}
}
function _tokenType() internal pure override returns(uint16) {
return uint16(TOKEN_TYPE_ERC721);
}
}
/**
* @title ERC721CInitializable
* @author Limit Break, Inc.
* @notice Initializable implementation of ERC721C to allow for EIP-1167 proxy clones.
*/
abstract contract ERC721CInitializable is ERC721OpenZeppelinInitializable, CreatorTokenBase, AutomaticValidatorTransferApproval {
function initializeERC721(string memory name_, string memory symbol_) public override {
super.initializeERC721(name_, symbol_);
_emitDefaultTransferValidator();
_registerTokenType(getTransferValidator());
}
/**
* @notice Overrides behavior of isApprovedFor all such that if an operator is not explicitly approved
* for all, the contract owner can optionally auto-approve the 721-C transfer validator for transfers.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool isApproved) {
isApproved = super.isApprovedForAll(owner, operator);
if (!isApproved) {
if (autoApproveTransfersFromValidator) {
isApproved = operator == address(getTransferValidator());
}
}
}
/**
* @notice Indicates whether the contract implements the specified interface.
* @dev Overrides supportsInterface in ERC165.
* @param interfaceId The interface id
* @return true if the contract implements the specified interface, false otherwise
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(ICreatorToken).interfaceId ||
interfaceId == type(ICreatorTokenLegacy).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @notice Returns the function selector for the transfer validator's validation function to be called
* @notice for transaction simulation.
*/
function getTransferValidationFunction() external pure returns (bytes4 functionSignature, bool isViewFunction) {
functionSignature = bytes4(keccak256("validateTransfer(address,address,address,uint256)"));
isViewFunction = true;
}
/// @dev Ties the open-zeppelin _beforeTokenTransfer hook to more granular transfer validation logic
function _beforeTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize) internal virtual override {
for (uint256 i = 0; i < batchSize;) {
_validateBeforeTransfer(from, to, firstTokenId + i);
unchecked {
++i;
}
}
}
/// @dev Ties the open-zeppelin _afterTokenTransfer hook to more granular transfer validation logic
function _afterTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize) internal virtual override {
for (uint256 i = 0; i < batchSize;) {
_validateAfterTransfer(from, to, firstTokenId + i);
unchecked {
++i;
}
}
}
function _tokenType() internal pure override returns(uint16) {
return uint16(TOKEN_TYPE_ERC721);
}
}lib/creator-token-standards/src/interfaces/ICreatorToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ICreatorToken {
event TransferValidatorUpdated(address oldValidator, address newValidator);
function getTransferValidator() external view returns (address validator);
function setTransferValidator(address validator) external;
function getTransferValidationFunction() external view returns (bytes4 functionSignature, bool isViewFunction);
}lib/creator-token-standards/src/interfaces/ICreatorTokenLegacy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ICreatorTokenLegacy {
event TransferValidatorUpdated(address oldValidator, address newValidator);
function getTransferValidator() external view returns (address validator);
function setTransferValidator(address validator) external;
}
lib/creator-token-standards/src/interfaces/ITransferValidator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ITransferValidator {
function applyCollectionTransferPolicy(address caller, address from, address to) external view;
function validateTransfer(address caller, address from, address to) external view;
function validateTransfer(address caller, address from, address to, uint256 tokenId) external view;
function validateTransfer(address caller, address from, address to, uint256 tokenId, uint256 amount) external;
function beforeAuthorizedTransfer(address operator, address token, uint256 tokenId) external;
function afterAuthorizedTransfer(address token, uint256 tokenId) external;
function beforeAuthorizedTransfer(address operator, address token) external;
function afterAuthorizedTransfer(address token) external;
function beforeAuthorizedTransfer(address token, uint256 tokenId) external;
function beforeAuthorizedTransferWithAmount(address token, uint256 tokenId, uint256 amount) external;
function afterAuthorizedTransferWithAmount(address token, uint256 tokenId) external;
}lib/creator-token-standards/src/interfaces/ITransferValidatorSetTokenType.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ITransferValidatorSetTokenType {
function setTokenTypeOfCollection(address collection, uint16 tokenType) external;
}lib/creator-token-standards/src/programmable-royalties/BasicRoyalties.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/common/ERC2981.sol";
/**
* @title BasicRoyaltiesBase
* @author Limit Break, Inc.
* @dev Base functionality of an NFT mix-in contract implementing the most basic form of programmable royalties.
*/
abstract contract BasicRoyaltiesBase is ERC2981 {
event DefaultRoyaltySet(address indexed receiver, uint96 feeNumerator);
event TokenRoyaltySet(uint256 indexed tokenId, address indexed receiver, uint96 feeNumerator);
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual override {
super._setDefaultRoyalty(receiver, feeNumerator);
emit DefaultRoyaltySet(receiver, feeNumerator);
}
function _setTokenRoyalty(uint256 tokenId, address receiver, uint96 feeNumerator) internal virtual override {
super._setTokenRoyalty(tokenId, receiver, feeNumerator);
emit TokenRoyaltySet(tokenId, receiver, feeNumerator);
}
}
/**
* @title BasicRoyalties
* @author Limit Break, Inc.
* @notice Constructable BasicRoyalties Contract implementation.
*/
abstract contract BasicRoyalties is BasicRoyaltiesBase {
constructor(address receiver, uint96 feeNumerator) {
_setDefaultRoyalty(receiver, feeNumerator);
}
}
/**
* @title BasicRoyaltiesInitializable
* @author Limit Break, Inc.
* @notice Initializable BasicRoyalties Contract implementation to allow for EIP-1167 clones.
*/
abstract contract BasicRoyaltiesInitializable is BasicRoyaltiesBase {}lib/creator-token-standards/src/token/erc721/ERC721OpenZeppelin.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../../access/OwnablePermissions.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
abstract contract ERC721OpenZeppelinBase is ERC721 {
// Token name
string internal _contractName;
// Token symbol
string internal _contractSymbol;
function name() public view virtual override returns (string memory) {
return _contractName;
}
function symbol() public view virtual override returns (string memory) {
return _contractSymbol;
}
function _setNameAndSymbol(string memory name_, string memory symbol_) internal {
_contractName = name_;
_contractSymbol = symbol_;
}
}
abstract contract ERC721OpenZeppelin is ERC721OpenZeppelinBase {
constructor(string memory name_, string memory symbol_) ERC721("", "") {
_setNameAndSymbol(name_, symbol_);
}
}
abstract contract ERC721OpenZeppelinInitializable is OwnablePermissions, ERC721OpenZeppelinBase {
error ERC721OpenZeppelinInitializable__AlreadyInitializedERC721();
/// @notice Specifies whether or not the contract is initialized
bool private _erc721Initialized;
/// @dev Initializes parameters of ERC721 tokens.
/// These cannot be set in the constructor because this contract is optionally compatible with EIP-1167.
function initializeERC721(string memory name_, string memory symbol_) public virtual {
_requireCallerIsContractOwner();
if(_erc721Initialized) {
revert ERC721OpenZeppelinInitializable__AlreadyInitializedERC721();
}
_erc721Initialized = true;
_setNameAndSymbol(name_, symbol_);
}
}
lib/creator-token-standards/src/utils/AutomaticValidatorTransferApproval.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../access/OwnablePermissions.sol";
/**
* @title AutomaticValidatorTransferApproval
* @author Limit Break, Inc.
* @notice Base contract mix-in that provides boilerplate code giving the contract owner the
* option to automatically approve a 721-C transfer validator implementation for transfers.
*/
abstract contract AutomaticValidatorTransferApproval is OwnablePermissions {
/// @dev Emitted when the automatic approval flag is modified by the creator.
event AutomaticApprovalOfTransferValidatorSet(bool autoApproved);
/// @dev If true, the collection's transfer validator is automatically approved to transfer holder's tokens.
bool public autoApproveTransfersFromValidator;
/**
* @notice Sets if the transfer validator is automatically approved as an operator for all token owners.
*
* @dev Throws when the caller is not the contract owner.
*
* @param autoApprove If true, the collection's transfer validator will be automatically approved to
* transfer holder's tokens.
*/
function setAutomaticApprovalOfTransfersFromValidator(bool autoApprove) external {
_requireCallerIsContractOwner();
autoApproveTransfersFromValidator = autoApprove;
emit AutomaticApprovalOfTransferValidatorSet(autoApprove);
}
}lib/creator-token-standards/src/utils/CreatorTokenBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../access/OwnablePermissions.sol";
import "../interfaces/ICreatorToken.sol";
import "../interfaces/ICreatorTokenLegacy.sol";
import "../interfaces/ITransferValidator.sol";
import "./TransferValidation.sol";
import "../interfaces/ITransferValidatorSetTokenType.sol";
/**
* @title CreatorTokenBase
* @author Limit Break, Inc.
* @notice CreatorTokenBaseV3 is an abstract contract that provides basic functionality for managing token
* transfer policies through an implementation of ICreatorTokenTransferValidator/ICreatorTokenTransferValidatorV2/ICreatorTokenTransferValidatorV3.
* This contract is intended to be used as a base for creator-specific token contracts, enabling customizable transfer
* restrictions and security policies.
*
* <h4>Features:</h4>
* <ul>Ownable: This contract can have an owner who can set and update the transfer validator.</ul>
* <ul>TransferValidation: Implements the basic token transfer validation interface.</ul>
*
* <h4>Benefits:</h4>
* <ul>Provides a flexible and modular way to implement custom token transfer restrictions and security policies.</ul>
* <ul>Allows creators to enforce policies such as account and codehash blacklists, whitelists, and graylists.</ul>
* <ul>Can be easily integrated into other token contracts as a base contract.</ul>
*
* <h4>Intended Usage:</h4>
* <ul>Use as a base contract for creator token implementations that require advanced transfer restrictions and
* security policies.</ul>
* <ul>Set and update the ICreatorTokenTransferValidator implementation contract to enforce desired policies for the
* creator token.</ul>
*
* <h4>Compatibility:</h4>
* <ul>Backward and Forward Compatible - V1/V2/V3 Creator Token Base will work with V1/V2/V3 Transfer Validators.</ul>
*/
abstract contract CreatorTokenBase is OwnablePermissions, TransferValidation, ICreatorToken {
/// @dev Thrown when setting a transfer validator address that has no deployed code.
error CreatorTokenBase__InvalidTransferValidatorContract();
/// @dev The default transfer validator that will be used if no transfer validator has been set by the creator.
address public constant DEFAULT_TRANSFER_VALIDATOR = address(0x721C008fdff27BF06E7E123956E2Fe03B63342e3);
/// @dev Used to determine if the default transfer validator is applied.
/// @dev Set to true when the creator sets a transfer validator address.
bool private isValidatorInitialized;
/// @dev Address of the transfer validator to apply to transactions.
address private transferValidator;
constructor() {
_emitDefaultTransferValidator();
_registerTokenType(DEFAULT_TRANSFER_VALIDATOR);
}
/**
* @notice Sets the transfer validator for the token contract.
*
* @dev Throws when provided validator contract is not the zero address and does not have code.
* @dev Throws when the caller is not the contract owner.
*
* @dev <h4>Postconditions:</h4>
* 1. The transferValidator address is updated.
* 2. The `TransferValidatorUpdated` event is emitted.
*
* @param transferValidator_ The address of the transfer validator contract.
*/
function setTransferValidator(address transferValidator_) public {
_requireCallerIsContractOwner();
bool isValidTransferValidator = transferValidator_.code.length > 0;
if(transferValidator_ != address(0) && !isValidTransferValidator) {
revert CreatorTokenBase__InvalidTransferValidatorContract();
}
emit TransferValidatorUpdated(address(getTransferValidator()), transferValidator_);
isValidatorInitialized = true;
transferValidator = transferValidator_;
_registerTokenType(transferValidator_);
}
/**
* @notice Returns the transfer validator contract address for this token contract.
*/
function getTransferValidator() public view override returns (address validator) {
validator = transferValidator;
if (validator == address(0)) {
if (!isValidatorInitialized) {
validator = DEFAULT_TRANSFER_VALIDATOR;
}
}
}
/**
* @dev Pre-validates a token transfer, reverting if the transfer is not allowed by this token's security policy.
* Inheriting contracts are responsible for overriding the _beforeTokenTransfer function, or its equivalent
* and calling _validateBeforeTransfer so that checks can be properly applied during token transfers.
*
* @dev Be aware that if the msg.sender is the transfer validator, the transfer is automatically permitted, as the
* transfer validator is expected to pre-validate the transfer.
*
* @dev Throws when the transfer doesn't comply with the collection's transfer policy, if the transferValidator is
* set to a non-zero address.
*
* @param caller The address of the caller.
* @param from The address of the sender.
* @param to The address of the receiver.
* @param tokenId The token id being transferred.
*/
function _preValidateTransfer(
address caller,
address from,
address to,
uint256 tokenId,
uint256 /*value*/) internal virtual override {
address validator = getTransferValidator();
if (validator != address(0)) {
if (msg.sender == validator) {
return;
}
ITransferValidator(validator).validateTransfer(caller, from, to, tokenId);
}
}
/**
* @dev Pre-validates a token transfer, reverting if the transfer is not allowed by this token's security policy.
* Inheriting contracts are responsible for overriding the _beforeTokenTransfer function, or its equivalent
* and calling _validateBeforeTransfer so that checks can be properly applied during token transfers.
*
* @dev Be aware that if the msg.sender is the transfer validator, the transfer is automatically permitted, as the
* transfer validator is expected to pre-validate the transfer.
*
* @dev Used for ERC20 and ERC1155 token transfers which have an amount value to validate in the transfer validator.
* @dev The `tokenId` for ERC20 tokens should be set to `0`.
*
* @dev Throws when the transfer doesn't comply with the collection's transfer policy, if the transferValidator is
* set to a non-zero address.
*
* @param caller The address of the caller.
* @param from The address of the sender.
* @param to The address of the receiver.
* @param tokenId The token id being transferred.
* @param amount The amount of token being transferred.
*/
function _preValidateTransfer(
address caller,
address from,
address to,
uint256 tokenId,
uint256 amount,
uint256 /*value*/) internal virtual override {
address validator = getTransferValidator();
if (validator != address(0)) {
if (msg.sender == validator) {
return;
}
ITransferValidator(validator).validateTransfer(caller, from, to, tokenId, amount);
}
}
function _tokenType() internal virtual pure returns(uint16);
function _registerTokenType(address validator) internal {
if (validator != address(0)) {
uint256 validatorCodeSize;
assembly {
validatorCodeSize := extcodesize(validator)
}
if(validatorCodeSize > 0) {
try ITransferValidatorSetTokenType(validator).setTokenTypeOfCollection(address(this), _tokenType()) {
} catch { }
}
}
}
/**
* @dev Used during contract deployment for constructable and cloneable creator tokens
* @dev to emit the `TransferValidatorUpdated` event signaling the validator for the contract
* @dev is the default transfer validator.
*/
function _emitDefaultTransferValidator() internal {
emit TransferValidatorUpdated(address(0), DEFAULT_TRANSFER_VALIDATOR);
}
}
lib/creator-token-standards/src/utils/TransferValidation.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @title TransferValidation
* @author Limit Break, Inc.
* @notice A mix-in that can be combined with ERC-721 contracts to provide more granular hooks.
* Openzeppelin's ERC721 contract only provides hooks for before and after transfer. This allows
* developers to validate or customize transfers within the context of a mint, a burn, or a transfer.
*/
abstract contract TransferValidation is Context {
/// @dev Thrown when the from and to address are both the zero address.
error ShouldNotMintToBurnAddress();
/*************************************************************************/
/* Transfers Without Amounts */
/*************************************************************************/
/// @dev Inheriting contracts should call this function in the _beforeTokenTransfer function to get more granular hooks.
function _validateBeforeTransfer(address from, address to, uint256 tokenId) internal virtual {
bool fromZeroAddress = from == address(0);
bool toZeroAddress = to == address(0);
if(fromZeroAddress && toZeroAddress) {
revert ShouldNotMintToBurnAddress();
} else if(fromZeroAddress) {
_preValidateMint(_msgSender(), to, tokenId, msg.value);
} else if(toZeroAddress) {
_preValidateBurn(_msgSender(), from, tokenId, msg.value);
} else {
_preValidateTransfer(_msgSender(), from, to, tokenId, msg.value);
}
}
/// @dev Inheriting contracts should call this function in the _afterTokenTransfer function to get more granular hooks.
function _validateAfterTransfer(address from, address to, uint256 tokenId) internal virtual {
bool fromZeroAddress = from == address(0);
bool toZeroAddress = to == address(0);
if(fromZeroAddress && toZeroAddress) {
revert ShouldNotMintToBurnAddress();
} else if(fromZeroAddress) {
_postValidateMint(_msgSender(), to, tokenId, msg.value);
} else if(toZeroAddress) {
_postValidateBurn(_msgSender(), from, tokenId, msg.value);
} else {
_postValidateTransfer(_msgSender(), from, to, tokenId, msg.value);
}
}
/// @dev Optional validation hook that fires before a mint
function _preValidateMint(address caller, address to, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a mint
function _postValidateMint(address caller, address to, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires before a burn
function _preValidateBurn(address caller, address from, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a burn
function _postValidateBurn(address caller, address from, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires before a transfer
function _preValidateTransfer(address caller, address from, address to, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a transfer
function _postValidateTransfer(address caller, address from, address to, uint256 tokenId, uint256 value) internal virtual {}
/*************************************************************************/
/* Transfers With Amounts */
/*************************************************************************/
/// @dev Inheriting contracts should call this function in the _beforeTokenTransfer function to get more granular hooks.
function _validateBeforeTransfer(address from, address to, uint256 tokenId, uint256 amount) internal virtual {
bool fromZeroAddress = from == address(0);
bool toZeroAddress = to == address(0);
if(fromZeroAddress && toZeroAddress) {
revert ShouldNotMintToBurnAddress();
} else if(fromZeroAddress) {
_preValidateMint(_msgSender(), to, tokenId, amount, msg.value);
} else if(toZeroAddress) {
_preValidateBurn(_msgSender(), from, tokenId, amount, msg.value);
} else {
_preValidateTransfer(_msgSender(), from, to, tokenId, amount, msg.value);
}
}
/// @dev Inheriting contracts should call this function in the _afterTokenTransfer function to get more granular hooks.
function _validateAfterTransfer(address from, address to, uint256 tokenId, uint256 amount) internal virtual {
bool fromZeroAddress = from == address(0);
bool toZeroAddress = to == address(0);
if(fromZeroAddress && toZeroAddress) {
revert ShouldNotMintToBurnAddress();
} else if(fromZeroAddress) {
_postValidateMint(_msgSender(), to, tokenId, amount, msg.value);
} else if(toZeroAddress) {
_postValidateBurn(_msgSender(), from, tokenId, amount, msg.value);
} else {
_postValidateTransfer(_msgSender(), from, to, tokenId, amount, msg.value);
}
}
/// @dev Optional validation hook that fires before a mint
function _preValidateMint(address caller, address to, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a mint
function _postValidateMint(address caller, address to, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires before a burn
function _preValidateBurn(address caller, address from, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a burn
function _postValidateBurn(address caller, address from, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires before a transfer
function _preValidateTransfer(address caller, address from, address to, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a transfer
function _postValidateTransfer(address caller, address from, address to, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
}
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/DynamicBufferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for buffers with automatic capacity resizing.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/DynamicBufferLib.sol)
/// @author Modified from cozyco (https://github.com/samkingco/cozyco/blob/main/contracts/utils/DynamicBuffer.sol)
library DynamicBufferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Type to represent a dynamic buffer in memory.
/// You can directly assign to `data`, and the `p` function will
/// take care of the memory allocation.
struct DynamicBuffer {
bytes data;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// Some of these functions return the same buffer for function chaining.
// e.g. `buffer.p("1").p("2")`.
/// @dev Shorthand for `buffer.data.length`.
function length(DynamicBuffer memory buffer) internal pure returns (uint256) {
return buffer.data.length;
}
/// @dev Reserves at least `minimum` amount of contiguous memory.
function reserve(DynamicBuffer memory buffer, uint256 minimum)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = buffer;
uint256 n = buffer.data.length;
if (minimum > n) {
uint256 i = 0x40;
do {} while ((i <<= 1) < minimum);
bytes memory data;
/// @solidity memory-safe-assembly
assembly {
data := 0x01
mstore(data, sub(i, n))
}
result = p(result, data);
}
}
/// @dev Clears the buffer without deallocating the memory.
function clear(DynamicBuffer memory buffer)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
/// @solidity memory-safe-assembly
assembly {
mstore(mload(buffer), 0)
}
result = buffer;
}
/// @dev Returns a string pointing to the underlying bytes data.
/// Note: The string WILL change if the buffer is updated.
function s(DynamicBuffer memory buffer) internal pure returns (string memory) {
return string(buffer.data);
}
/// @dev Appends `data` to `buffer`.
function p(DynamicBuffer memory buffer, bytes memory data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = buffer;
if (data.length == uint256(0)) return result;
/// @solidity memory-safe-assembly
assembly {
let w := not(0x1f)
let bufData := mload(buffer)
let bufDataLen := mload(bufData)
let newBufDataLen := add(mload(data), bufDataLen)
// Some random prime number to multiply `cap`, so that
// we know that the `cap` is for a dynamic buffer.
// Selected to be larger than any memory pointer realistically.
let prime := 1621250193422201
let cap := mload(add(bufData, w)) // `mload(sub(bufData, 0x20))`.
// Extract `cap`, initializing it to zero if it is not a multiple of `prime`.
cap := mul(div(cap, prime), iszero(mod(cap, prime)))
// Expand / Reallocate memory if required.
// Note that we need to allocate an extra word for the length, and
// and another extra word as a safety word (giving a total of 0x40 bytes).
// Without the safety word, the backwards copying can cause a buffer overflow.
for {} iszero(lt(newBufDataLen, cap)) {} {
// Approximately more than double the capacity to ensure more than enough space.
let newCap := and(add(cap, add(or(cap, newBufDataLen), 0x20)), w)
// If the memory is contiguous, we can simply expand it.
if iszero(or(xor(mload(0x40), add(bufData, add(0x40, cap))), iszero(cap))) {
// Store `cap * prime` in the word before the length.
mstore(add(bufData, w), mul(prime, newCap))
mstore(0x40, add(bufData, add(0x40, newCap))) // Expand the memory allocation.
break
}
// Set the `newBufData` to point to the word after `cap`.
let newBufData := add(mload(0x40), 0x20)
mstore(0x40, add(newBufData, add(0x40, newCap))) // Reallocate the memory.
mstore(buffer, newBufData) // Store the `newBufData`.
// Copy `bufData` one word at a time, backwards.
for { let o := and(add(bufDataLen, 0x20), w) } 1 {} {
mstore(add(newBufData, o), mload(add(bufData, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
// Store `cap * prime` in the word before the length.
mstore(add(newBufData, w), mul(prime, newCap))
bufData := newBufData // Assign `newBufData` to `bufData`.
break
}
// If it's a reserve operation, set the variables to skip the appending.
if eq(data, 0x01) {
mstore(data, 0x00)
newBufDataLen := bufDataLen
}
// Copy `data` one word at a time, backwards.
for { let o := and(add(mload(data), 0x20), w) } 1 {} {
mstore(add(add(bufData, bufDataLen), o), mload(add(data, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
mstore(add(add(bufData, 0x20), newBufDataLen), 0) // Zeroize the word after the buffer.
mstore(bufData, newBufDataLen) // Store the length.
}
}
/// @dev Appends `data0`, `data1` to `buffer`.
function p(DynamicBuffer memory buffer, bytes memory data0, bytes memory data1)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(p(buffer, data0), data1);
}
/// @dev Appends `data0` .. `data2` to `buffer`.
function p(
DynamicBuffer memory buffer,
bytes memory data0,
bytes memory data1,
bytes memory data2
) internal pure returns (DynamicBuffer memory result) {
_deallocate(result);
result = p(p(p(buffer, data0), data1), data2);
}
/// @dev Appends `data0` .. `data3` to `buffer`.
function p(
DynamicBuffer memory buffer,
bytes memory data0,
bytes memory data1,
bytes memory data2,
bytes memory data3
) internal pure returns (DynamicBuffer memory result) {
_deallocate(result);
result = p(p(p(p(buffer, data0), data1), data2), data3);
}
/// @dev Appends `data0` .. `data4` to `buffer`.
function p(
DynamicBuffer memory buffer,
bytes memory data0,
bytes memory data1,
bytes memory data2,
bytes memory data3,
bytes memory data4
) internal pure returns (DynamicBuffer memory result) {
_deallocate(result);
result = p(p(p(p(p(buffer, data0), data1), data2), data3), data4);
}
/// @dev Appends `data0` .. `data5` to `buffer`.
function p(
DynamicBuffer memory buffer,
bytes memory data0,
bytes memory data1,
bytes memory data2,
bytes memory data3,
bytes memory data4,
bytes memory data5
) internal pure returns (DynamicBuffer memory result) {
_deallocate(result);
result = p(p(p(p(p(p(buffer, data0), data1), data2), data3), data4), data5);
}
/// @dev Appends `data0` .. `data6` to `buffer`.
function p(
DynamicBuffer memory buffer,
bytes memory data0,
bytes memory data1,
bytes memory data2,
bytes memory data3,
bytes memory data4,
bytes memory data5,
bytes memory data6
) internal pure returns (DynamicBuffer memory result) {
_deallocate(result);
result = p(p(p(p(p(p(p(buffer, data0), data1), data2), data3), data4), data5), data6);
}
/// @dev Appends `abi.encodePacked(bool(data))` to buffer.
function pBool(DynamicBuffer memory buffer, bool data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
uint256 casted;
/// @solidity memory-safe-assembly
assembly {
casted := iszero(iszero(data))
}
result = p(buffer, _single(casted, 1));
}
/// @dev Appends `abi.encodePacked(address(data))` to buffer.
function pAddress(DynamicBuffer memory buffer, address data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(uint256(uint160(data)), 20));
}
/// @dev Appends `abi.encodePacked(uint8(data))` to buffer.
function pUint8(DynamicBuffer memory buffer, uint8 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 1));
}
/// @dev Appends `abi.encodePacked(uint16(data))` to buffer.
function pUint16(DynamicBuffer memory buffer, uint16 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 2));
}
/// @dev Appends `abi.encodePacked(uint24(data))` to buffer.
function pUint24(DynamicBuffer memory buffer, uint24 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 3));
}
/// @dev Appends `abi.encodePacked(uint32(data))` to buffer.
function pUint32(DynamicBuffer memory buffer, uint32 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 4));
}
/// @dev Appends `abi.encodePacked(uint40(data))` to buffer.
function pUint40(DynamicBuffer memory buffer, uint40 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 5));
}
/// @dev Appends `abi.encodePacked(uint48(data))` to buffer.
function pUint48(DynamicBuffer memory buffer, uint48 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 6));
}
/// @dev Appends `abi.encodePacked(uint56(data))` to buffer.
function pUint56(DynamicBuffer memory buffer, uint56 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 7));
}
/// @dev Appends `abi.encodePacked(uint64(data))` to buffer.
function pUint64(DynamicBuffer memory buffer, uint64 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 8));
}
/// @dev Appends `abi.encodePacked(uint72(data))` to buffer.
function pUint72(DynamicBuffer memory buffer, uint72 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 9));
}
/// @dev Appends `abi.encodePacked(uint80(data))` to buffer.
function pUint80(DynamicBuffer memory buffer, uint80 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 10));
}
/// @dev Appends `abi.encodePacked(uint88(data))` to buffer.
function pUint88(DynamicBuffer memory buffer, uint88 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 11));
}
/// @dev Appends `abi.encodePacked(uint96(data))` to buffer.
function pUint96(DynamicBuffer memory buffer, uint96 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 12));
}
/// @dev Appends `abi.encodePacked(uint104(data))` to buffer.
function pUint104(DynamicBuffer memory buffer, uint104 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 13));
}
/// @dev Appends `abi.encodePacked(uint112(data))` to buffer.
function pUint112(DynamicBuffer memory buffer, uint112 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 14));
}
/// @dev Appends `abi.encodePacked(uint120(data))` to buffer.
function pUint120(DynamicBuffer memory buffer, uint120 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 15));
}
/// @dev Appends `abi.encodePacked(uint128(data))` to buffer.
function pUint128(DynamicBuffer memory buffer, uint128 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 16));
}
/// @dev Appends `abi.encodePacked(uint136(data))` to buffer.
function pUint136(DynamicBuffer memory buffer, uint136 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 17));
}
/// @dev Appends `abi.encodePacked(uint144(data))` to buffer.
function pUint144(DynamicBuffer memory buffer, uint144 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 18));
}
/// @dev Appends `abi.encodePacked(uint152(data))` to buffer.
function pUint152(DynamicBuffer memory buffer, uint152 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 19));
}
/// @dev Appends `abi.encodePacked(uint160(data))` to buffer.
function pUint160(DynamicBuffer memory buffer, uint160 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 20));
}
/// @dev Appends `abi.encodePacked(uint168(data))` to buffer.
function pUint168(DynamicBuffer memory buffer, uint168 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 21));
}
/// @dev Appends `abi.encodePacked(uint176(data))` to buffer.
function pUint176(DynamicBuffer memory buffer, uint176 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 22));
}
/// @dev Appends `abi.encodePacked(uint184(data))` to buffer.
function pUint184(DynamicBuffer memory buffer, uint184 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 23));
}
/// @dev Appends `abi.encodePacked(uint192(data))` to buffer.
function pUint192(DynamicBuffer memory buffer, uint192 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 24));
}
/// @dev Appends `abi.encodePacked(uint200(data))` to buffer.
function pUint200(DynamicBuffer memory buffer, uint200 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 25));
}
/// @dev Appends `abi.encodePacked(uint208(data))` to buffer.
function pUint208(DynamicBuffer memory buffer, uint208 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 26));
}
/// @dev Appends `abi.encodePacked(uint216(data))` to buffer.
function pUint216(DynamicBuffer memory buffer, uint216 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 27));
}
/// @dev Appends `abi.encodePacked(uint224(data))` to buffer.
function pUint224(DynamicBuffer memory buffer, uint224 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 28));
}
/// @dev Appends `abi.encodePacked(uint232(data))` to buffer.
function pUint232(DynamicBuffer memory buffer, uint232 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 29));
}
/// @dev Appends `abi.encodePacked(uint240(data))` to buffer.
function pUint240(DynamicBuffer memory buffer, uint240 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 30));
}
/// @dev Appends `abi.encodePacked(uint248(data))` to buffer.
function pUint248(DynamicBuffer memory buffer, uint248 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 31));
}
/// @dev Appends `abi.encodePacked(uint256(data))` to buffer.
function pUint256(DynamicBuffer memory buffer, uint256 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 32));
}
/// @dev Appends `abi.encodePacked(bytes1(data))` to buffer.
function pBytes1(DynamicBuffer memory buffer, bytes1 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 1));
}
/// @dev Appends `abi.encodePacked(bytes2(data))` to buffer.
function pBytes2(DynamicBuffer memory buffer, bytes2 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 2));
}
/// @dev Appends `abi.encodePacked(bytes3(data))` to buffer.
function pBytes3(DynamicBuffer memory buffer, bytes3 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 3));
}
/// @dev Appends `abi.encodePacked(bytes4(data))` to buffer.
function pBytes4(DynamicBuffer memory buffer, bytes4 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 4));
}
/// @dev Appends `abi.encodePacked(bytes5(data))` to buffer.
function pBytes5(DynamicBuffer memory buffer, bytes5 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 5));
}
/// @dev Appends `abi.encodePacked(bytes6(data))` to buffer.
function pBytes6(DynamicBuffer memory buffer, bytes6 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 6));
}
/// @dev Appends `abi.encodePacked(bytes7(data))` to buffer.
function pBytes7(DynamicBuffer memory buffer, bytes7 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 7));
}
/// @dev Appends `abi.encodePacked(bytes8(data))` to buffer.
function pBytes8(DynamicBuffer memory buffer, bytes8 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 8));
}
/// @dev Appends `abi.encodePacked(bytes9(data))` to buffer.
function pBytes9(DynamicBuffer memory buffer, bytes9 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 9));
}
/// @dev Appends `abi.encodePacked(bytes10(data))` to buffer.
function pBytes10(DynamicBuffer memory buffer, bytes10 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 10));
}
/// @dev Appends `abi.encodePacked(bytes11(data))` to buffer.
function pBytes11(DynamicBuffer memory buffer, bytes11 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 11));
}
/// @dev Appends `abi.encodePacked(bytes12(data))` to buffer.
function pBytes12(DynamicBuffer memory buffer, bytes12 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 12));
}
/// @dev Appends `abi.encodePacked(bytes13(data))` to buffer.
function pBytes13(DynamicBuffer memory buffer, bytes13 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 13));
}
/// @dev Appends `abi.encodePacked(bytes14(data))` to buffer.
function pBytes14(DynamicBuffer memory buffer, bytes14 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 14));
}
/// @dev Appends `abi.encodePacked(bytes15(data))` to buffer.
function pBytes15(DynamicBuffer memory buffer, bytes15 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 15));
}
/// @dev Appends `abi.encodePacked(bytes16(data))` to buffer.
function pBytes16(DynamicBuffer memory buffer, bytes16 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 16));
}
/// @dev Appends `abi.encodePacked(bytes17(data))` to buffer.
function pBytes17(DynamicBuffer memory buffer, bytes17 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 17));
}
/// @dev Appends `abi.encodePacked(bytes18(data))` to buffer.
function pBytes18(DynamicBuffer memory buffer, bytes18 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 18));
}
/// @dev Appends `abi.encodePacked(bytes19(data))` to buffer.
function pBytes19(DynamicBuffer memory buffer, bytes19 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 19));
}
/// @dev Appends `abi.encodePacked(bytes20(data))` to buffer.
function pBytes20(DynamicBuffer memory buffer, bytes20 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 20));
}
/// @dev Appends `abi.encodePacked(bytes21(data))` to buffer.
function pBytes21(DynamicBuffer memory buffer, bytes21 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 21));
}
/// @dev Appends `abi.encodePacked(bytes22(data))` to buffer.
function pBytes22(DynamicBuffer memory buffer, bytes22 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 22));
}
/// @dev Appends `abi.encodePacked(bytes23(data))` to buffer.
function pBytes23(DynamicBuffer memory buffer, bytes23 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 23));
}
/// @dev Appends `abi.encodePacked(bytes24(data))` to buffer.
function pBytes24(DynamicBuffer memory buffer, bytes24 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 24));
}
/// @dev Appends `abi.encodePacked(bytes25(data))` to buffer.
function pBytes25(DynamicBuffer memory buffer, bytes25 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 25));
}
/// @dev Appends `abi.encodePacked(bytes26(data))` to buffer.
function pBytes26(DynamicBuffer memory buffer, bytes26 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 26));
}
/// @dev Appends `abi.encodePacked(bytes27(data))` to buffer.
function pBytes27(DynamicBuffer memory buffer, bytes27 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 27));
}
/// @dev Appends `abi.encodePacked(bytes28(data))` to buffer.
function pBytes28(DynamicBuffer memory buffer, bytes28 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 28));
}
/// @dev Appends `abi.encodePacked(bytes29(data))` to buffer.
function pBytes29(DynamicBuffer memory buffer, bytes29 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 29));
}
/// @dev Appends `abi.encodePacked(bytes30(data))` to buffer.
function pBytes30(DynamicBuffer memory buffer, bytes30 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 30));
}
/// @dev Appends `abi.encodePacked(bytes31(data))` to buffer.
function pBytes31(DynamicBuffer memory buffer, bytes31 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 31));
}
/// @dev Appends `abi.encodePacked(bytes32(data))` to buffer.
function pBytes32(DynamicBuffer memory buffer, bytes32 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 32));
}
/// @dev Shorthand for returning a new buffer.
function p() internal pure returns (DynamicBuffer memory result) {}
/// @dev Shorthand for `p(p(), data)`.
function p(bytes memory data) internal pure returns (DynamicBuffer memory result) {
p(result, data);
}
/// @dev Shorthand for `p(p(), data0, data1)`.
function p(bytes memory data0, bytes memory data1)
internal
pure
returns (DynamicBuffer memory result)
{
p(p(result, data0), data1);
}
/// @dev Shorthand for `p(p(), data0, .., data2)`.
function p(bytes memory data0, bytes memory data1, bytes memory data2)
internal
pure
returns (DynamicBuffer memory result)
{
p(p(p(result, data0), data1), data2);
}
/// @dev Shorthand for `p(p(), data0, .., data3)`.
function p(bytes memory data0, bytes memory data1, bytes memory data2, bytes memory data3)
internal
pure
returns (DynamicBuffer memory result)
{
p(p(p(p(result, data0), data1), data2), data3);
}
/// @dev Shorthand for `p(p(), data0, .., data4)`.
function p(
bytes memory data0,
bytes memory data1,
bytes memory data2,
bytes memory data3,
bytes memory data4
) internal pure returns (DynamicBuffer memory result) {
p(p(p(p(p(result, data0), data1), data2), data3), data4);
}
/// @dev Shorthand for `p(p(), data0, .., data5)`.
function p(
bytes memory data0,
bytes memory data1,
bytes memory data2,
bytes memory data3,
bytes memory data4,
bytes memory data5
) internal pure returns (DynamicBuffer memory result) {
p(p(p(p(p(p(result, data0), data1), data2), data3), data4), data5);
}
/// @dev Shorthand for `p(p(), data0, .., data6)`.
function p(
bytes memory data0,
bytes memory data1,
bytes memory data2,
bytes memory data3,
bytes memory data4,
bytes memory data5,
bytes memory data6
) internal pure returns (DynamicBuffer memory result) {
p(p(p(p(p(p(p(result, data0), data1), data2), data3), data4), data5), data6);
}
/// @dev Shorthand for `pBool(p(), data)`.
function pBool(bool data) internal pure returns (DynamicBuffer memory result) {
pBool(result, data);
}
/// @dev Shorthand for `pAddress(p(), data)`.
function pAddress(address data) internal pure returns (DynamicBuffer memory result) {
pAddress(result, data);
}
/// @dev Shorthand for `pUint8(p(), data)`.
function pUint8(uint8 data) internal pure returns (DynamicBuffer memory result) {
pUint8(result, data);
}
/// @dev Shorthand for `pUint16(p(), data)`.
function pUint16(uint16 data) internal pure returns (DynamicBuffer memory result) {
pUint16(result, data);
}
/// @dev Shorthand for `pUint24(p(), data)`.
function pUint24(uint24 data) internal pure returns (DynamicBuffer memory result) {
pUint24(result, data);
}
/// @dev Shorthand for `pUint32(p(), data)`.
function pUint32(uint32 data) internal pure returns (DynamicBuffer memory result) {
pUint32(result, data);
}
/// @dev Shorthand for `pUint40(p(), data)`.
function pUint40(uint40 data) internal pure returns (DynamicBuffer memory result) {
pUint40(result, data);
}
/// @dev Shorthand for `pUint48(p(), data)`.
function pUint48(uint48 data) internal pure returns (DynamicBuffer memory result) {
pUint48(result, data);
}
/// @dev Shorthand for `pUint56(p(), data)`.
function pUint56(uint56 data) internal pure returns (DynamicBuffer memory result) {
pUint56(result, data);
}
/// @dev Shorthand for `pUint64(p(), data)`.
function pUint64(uint64 data) internal pure returns (DynamicBuffer memory result) {
pUint64(result, data);
}
/// @dev Shorthand for `pUint72(p(), data)`.
function pUint72(uint72 data) internal pure returns (DynamicBuffer memory result) {
pUint72(result, data);
}
/// @dev Shorthand for `pUint80(p(), data)`.
function pUint80(uint80 data) internal pure returns (DynamicBuffer memory result) {
pUint80(result, data);
}
/// @dev Shorthand for `pUint88(p(), data)`.
function pUint88(uint88 data) internal pure returns (DynamicBuffer memory result) {
pUint88(result, data);
}
/// @dev Shorthand for `pUint96(p(), data)`.
function pUint96(uint96 data) internal pure returns (DynamicBuffer memory result) {
pUint96(result, data);
}
/// @dev Shorthand for `pUint104(p(), data)`.
function pUint104(uint104 data) internal pure returns (DynamicBuffer memory result) {
pUint104(result, data);
}
/// @dev Shorthand for `pUint112(p(), data)`.
function pUint112(uint112 data) internal pure returns (DynamicBuffer memory result) {
pUint112(result, data);
}
/// @dev Shorthand for `pUint120(p(), data)`.
function pUint120(uint120 data) internal pure returns (DynamicBuffer memory result) {
pUint120(result, data);
}
/// @dev Shorthand for `pUint128(p(), data)`.
function pUint128(uint128 data) internal pure returns (DynamicBuffer memory result) {
pUint128(result, data);
}
/// @dev Shorthand for `pUint136(p(), data)`.
function pUint136(uint136 data) internal pure returns (DynamicBuffer memory result) {
pUint136(result, data);
}
/// @dev Shorthand for `pUint144(p(), data)`.
function pUint144(uint144 data) internal pure returns (DynamicBuffer memory result) {
pUint144(result, data);
}
/// @dev Shorthand for `pUint152(p(), data)`.
function pUint152(uint152 data) internal pure returns (DynamicBuffer memory result) {
pUint152(result, data);
}
/// @dev Shorthand for `pUint160(p(), data)`.
function pUint160(uint160 data) internal pure returns (DynamicBuffer memory result) {
pUint160(result, data);
}
/// @dev Shorthand for `pUint168(p(), data)`.
function pUint168(uint168 data) internal pure returns (DynamicBuffer memory result) {
pUint168(result, data);
}
/// @dev Shorthand for `pUint176(p(), data)`.
function pUint176(uint176 data) internal pure returns (DynamicBuffer memory result) {
pUint176(result, data);
}
/// @dev Shorthand for `pUint184(p(), data)`.
function pUint184(uint184 data) internal pure returns (DynamicBuffer memory result) {
pUint184(result, data);
}
/// @dev Shorthand for `pUint192(p(), data)`.
function pUint192(uint192 data) internal pure returns (DynamicBuffer memory result) {
pUint192(result, data);
}
/// @dev Shorthand for `pUint200(p(), data)`.
function pUint200(uint200 data) internal pure returns (DynamicBuffer memory result) {
pUint200(result, data);
}
/// @dev Shorthand for `pUint208(p(), data)`.
function pUint208(uint208 data) internal pure returns (DynamicBuffer memory result) {
pUint208(result, data);
}
/// @dev Shorthand for `pUint216(p(), data)`.
function pUint216(uint216 data) internal pure returns (DynamicBuffer memory result) {
pUint216(result, data);
}
/// @dev Shorthand for `pUint224(p(), data)`.
function pUint224(uint224 data) internal pure returns (DynamicBuffer memory result) {
pUint224(result, data);
}
/// @dev Shorthand for `pUint232(p(), data)`.
function pUint232(uint232 data) internal pure returns (DynamicBuffer memory result) {
pUint232(result, data);
}
/// @dev Shorthand for `pUint240(p(), data)`.
function pUint240(uint240 data) internal pure returns (DynamicBuffer memory result) {
pUint240(result, data);
}
/// @dev Shorthand for `pUint248(p(), data)`.
function pUint248(uint248 data) internal pure returns (DynamicBuffer memory result) {
pUint248(result, data);
}
/// @dev Shorthand for `pUint256(p(), data)`.
function pUint256(uint256 data) internal pure returns (DynamicBuffer memory result) {
pUint256(result, data);
}
/// @dev Shorthand for `pBytes1(p(), data)`.
function pBytes1(bytes1 data) internal pure returns (DynamicBuffer memory result) {
pBytes1(result, data);
}
/// @dev Shorthand for `pBytes2(p(), data)`.
function pBytes2(bytes2 data) internal pure returns (DynamicBuffer memory result) {
pBytes2(result, data);
}
/// @dev Shorthand for `pBytes3(p(), data)`.
function pBytes3(bytes3 data) internal pure returns (DynamicBuffer memory result) {
pBytes3(result, data);
}
/// @dev Shorthand for `pBytes4(p(), data)`.
function pBytes4(bytes4 data) internal pure returns (DynamicBuffer memory result) {
pBytes4(result, data);
}
/// @dev Shorthand for `pBytes5(p(), data)`.
function pBytes5(bytes5 data) internal pure returns (DynamicBuffer memory result) {
pBytes5(result, data);
}
/// @dev Shorthand for `pBytes6(p(), data)`.
function pBytes6(bytes6 data) internal pure returns (DynamicBuffer memory result) {
pBytes6(result, data);
}
/// @dev Shorthand for `pBytes7(p(), data)`.
function pBytes7(bytes7 data) internal pure returns (DynamicBuffer memory result) {
pBytes7(result, data);
}
/// @dev Shorthand for `pBytes8(p(), data)`.
function pBytes8(bytes8 data) internal pure returns (DynamicBuffer memory result) {
pBytes8(result, data);
}
/// @dev Shorthand for `pBytes9(p(), data)`.
function pBytes9(bytes9 data) internal pure returns (DynamicBuffer memory result) {
pBytes9(result, data);
}
/// @dev Shorthand for `pBytes10(p(), data)`.
function pBytes10(bytes10 data) internal pure returns (DynamicBuffer memory result) {
pBytes10(result, data);
}
/// @dev Shorthand for `pBytes11(p(), data)`.
function pBytes11(bytes11 data) internal pure returns (DynamicBuffer memory result) {
pBytes11(result, data);
}
/// @dev Shorthand for `pBytes12(p(), data)`.
function pBytes12(bytes12 data) internal pure returns (DynamicBuffer memory result) {
pBytes12(result, data);
}
/// @dev Shorthand for `pBytes13(p(), data)`.
function pBytes13(bytes13 data) internal pure returns (DynamicBuffer memory result) {
pBytes13(result, data);
}
/// @dev Shorthand for `pBytes14(p(), data)`.
function pBytes14(bytes14 data) internal pure returns (DynamicBuffer memory result) {
pBytes14(result, data);
}
/// @dev Shorthand for `pBytes15(p(), data)`.
function pBytes15(bytes15 data) internal pure returns (DynamicBuffer memory result) {
pBytes15(result, data);
}
/// @dev Shorthand for `pBytes16(p(), data)`.
function pBytes16(bytes16 data) internal pure returns (DynamicBuffer memory result) {
pBytes16(result, data);
}
/// @dev Shorthand for `pBytes17(p(), data)`.
function pBytes17(bytes17 data) internal pure returns (DynamicBuffer memory result) {
pBytes17(result, data);
}
/// @dev Shorthand for `pBytes18(p(), data)`.
function pBytes18(bytes18 data) internal pure returns (DynamicBuffer memory result) {
pBytes18(result, data);
}
/// @dev Shorthand for `pBytes19(p(), data)`.
function pBytes19(bytes19 data) internal pure returns (DynamicBuffer memory result) {
pBytes19(result, data);
}
/// @dev Shorthand for `pBytes20(p(), data)`.
function pBytes20(bytes20 data) internal pure returns (DynamicBuffer memory result) {
pBytes20(result, data);
}
/// @dev Shorthand for `pBytes21(p(), data)`.
function pBytes21(bytes21 data) internal pure returns (DynamicBuffer memory result) {
pBytes21(result, data);
}
/// @dev Shorthand for `pBytes22(p(), data)`.
function pBytes22(bytes22 data) internal pure returns (DynamicBuffer memory result) {
pBytes22(result, data);
}
/// @dev Shorthand for `pBytes23(p(), data)`.
function pBytes23(bytes23 data) internal pure returns (DynamicBuffer memory result) {
pBytes23(result, data);
}
/// @dev Shorthand for `pBytes24(p(), data)`.
function pBytes24(bytes24 data) internal pure returns (DynamicBuffer memory result) {
pBytes24(result, data);
}
/// @dev Shorthand for `pBytes25(p(), data)`.
function pBytes25(bytes25 data) internal pure returns (DynamicBuffer memory result) {
pBytes25(result, data);
}
/// @dev Shorthand for `pBytes26(p(), data)`.
function pBytes26(bytes26 data) internal pure returns (DynamicBuffer memory result) {
pBytes26(result, data);
}
/// @dev Shorthand for `pBytes27(p(), data)`.
function pBytes27(bytes27 data) internal pure returns (DynamicBuffer memory result) {
pBytes27(result, data);
}
/// @dev Shorthand for `pBytes28(p(), data)`.
function pBytes28(bytes28 data) internal pure returns (DynamicBuffer memory result) {
pBytes28(result, data);
}
/// @dev Shorthand for `pBytes29(p(), data)`.
function pBytes29(bytes29 data) internal pure returns (DynamicBuffer memory result) {
pBytes29(result, data);
}
/// @dev Shorthand for `pBytes30(p(), data)`.
function pBytes30(bytes30 data) internal pure returns (DynamicBuffer memory result) {
pBytes30(result, data);
}
/// @dev Shorthand for `pBytes31(p(), data)`.
function pBytes31(bytes31 data) internal pure returns (DynamicBuffer memory result) {
pBytes31(result, data);
}
/// @dev Shorthand for `pBytes32(p(), data)`.
function pBytes32(bytes32 data) internal pure returns (DynamicBuffer memory result) {
pBytes32(result, data);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Helper for deallocating an automatically allocated `buffer` pointer.
function _deallocate(DynamicBuffer memory result) private pure {
/// @solidity memory-safe-assembly
assembly {
mstore(0x40, result) // Deallocate, as we have already allocated.
}
}
/// @dev Returns a temporary bytes string of length `n` for `data`.
function _single(uint256 data, uint256 n) private pure returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := 0x00
mstore(n, data)
mstore(result, n)
}
}
/// @dev Returns a temporary bytes string of length `n` for `data`.
function _single(bytes32 data, uint256 n) private pure returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := 0x00
mstore(0x20, data)
mstore(result, n)
}
}
}
lib/solady/src/utils/LibBytes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for byte related operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibBytes.sol)
library LibBytes {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Goated bytes storage struct that totally MOGs, no cap, fr.
/// Uses less gas and bytecode than Solidity's native bytes storage. It's meta af.
/// Packs length with the first 31 bytes if <255 bytes, so it’s mad tight.
struct BytesStorage {
bytes32 _spacer;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the bytes.
uint256 internal constant NOT_FOUND = type(uint256).max;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTE STORAGE OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sets the value of the bytes storage `$` to `s`.
function set(BytesStorage storage $, bytes memory s) internal {
/// @solidity memory-safe-assembly
assembly {
let n := mload(s)
let packed := or(0xff, shl(8, n))
for { let i := 0 } 1 {} {
if iszero(gt(n, 0xfe)) {
i := 0x1f
packed := or(n, shl(8, mload(add(s, i))))
if iszero(gt(n, i)) { break }
}
let o := add(s, 0x20)
mstore(0x00, $.slot)
for { let p := keccak256(0x00, 0x20) } 1 {} {
sstore(add(p, shr(5, i)), mload(add(o, i)))
i := add(i, 0x20)
if iszero(lt(i, n)) { break }
}
break
}
sstore($.slot, packed)
}
}
/// @dev Sets the value of the bytes storage `$` to `s`.
function setCalldata(BytesStorage storage $, bytes calldata s) internal {
/// @solidity memory-safe-assembly
assembly {
let packed := or(0xff, shl(8, s.length))
for { let i := 0 } 1 {} {
if iszero(gt(s.length, 0xfe)) {
i := 0x1f
packed := or(s.length, shl(8, shr(8, calldataload(s.offset))))
if iszero(gt(s.length, i)) { break }
}
mstore(0x00, $.slot)
for { let p := keccak256(0x00, 0x20) } 1 {} {
sstore(add(p, shr(5, i)), calldataload(add(s.offset, i)))
i := add(i, 0x20)
if iszero(lt(i, s.length)) { break }
}
break
}
sstore($.slot, packed)
}
}
/// @dev Sets the value of the bytes storage `$` to the empty bytes.
function clear(BytesStorage storage $) internal {
delete $._spacer;
}
/// @dev Returns whether the value stored is `$` is the empty bytes "".
function isEmpty(BytesStorage storage $) internal view returns (bool) {
return uint256($._spacer) & 0xff == uint256(0);
}
/// @dev Returns the length of the value stored in `$`.
function length(BytesStorage storage $) internal view returns (uint256 result) {
result = uint256($._spacer);
/// @solidity memory-safe-assembly
assembly {
let n := and(0xff, result)
result := or(mul(shr(8, result), eq(0xff, n)), mul(n, iszero(eq(0xff, n))))
}
}
/// @dev Returns the value stored in `$`.
function get(BytesStorage storage $) internal view returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let o := add(result, 0x20)
let packed := sload($.slot)
let n := shr(8, packed)
for { let i := 0 } 1 {} {
if iszero(eq(or(packed, 0xff), packed)) {
mstore(o, packed)
n := and(0xff, packed)
i := 0x1f
if iszero(gt(n, i)) { break }
}
mstore(0x00, $.slot)
for { let p := keccak256(0x00, 0x20) } 1 {} {
mstore(add(o, i), sload(add(p, shr(5, i))))
i := add(i, 0x20)
if iszero(lt(i, n)) { break }
}
break
}
mstore(result, n) // Store the length of the memory.
mstore(add(o, n), 0) // Zeroize the slot after the bytes.
mstore(0x40, add(add(o, n), 0x20)) // Allocate memory.
}
}
/// @dev Returns the uint8 at index `i`. If out-of-bounds, returns 0.
function uint8At(BytesStorage storage $, uint256 i) internal view returns (uint8 result) {
/// @solidity memory-safe-assembly
assembly {
for { let packed := sload($.slot) } 1 {} {
if iszero(eq(or(packed, 0xff), packed)) {
if iszero(gt(i, 0x1e)) {
result := byte(i, packed)
break
}
if iszero(gt(i, and(0xff, packed))) {
mstore(0x00, $.slot)
let j := sub(i, 0x1f)
result := byte(and(j, 0x1f), sload(add(keccak256(0x00, 0x20), shr(5, j))))
}
break
}
if iszero(gt(i, shr(8, packed))) {
mstore(0x00, $.slot)
result := byte(and(i, 0x1f), sload(add(keccak256(0x00, 0x20), shr(5, i))))
}
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTES OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `subject` all occurrences of `needle` replaced with `replacement`.
function replace(bytes memory subject, bytes memory needle, bytes memory replacement)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let needleLen := mload(needle)
let replacementLen := mload(replacement)
let d := sub(result, subject) // Memory difference.
let i := add(subject, 0x20) // Subject bytes pointer.
mstore(0x00, add(i, mload(subject))) // End of subject.
if iszero(gt(needleLen, mload(subject))) {
let subjectSearchEnd := add(sub(mload(0x00), needleLen), 1)
let h := 0 // The hash of `needle`.
if iszero(lt(needleLen, 0x20)) { h := keccak256(add(needle, 0x20), needleLen) }
let s := mload(add(needle, 0x20))
for { let m := shl(3, sub(0x20, and(needleLen, 0x1f))) } 1 {} {
let t := mload(i)
// Whether the first `needleLen % 32` bytes of `subject` and `needle` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(i, needleLen), h)) {
mstore(add(i, d), t)
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
// Copy the `replacement` one word at a time.
for { let j := 0 } 1 {} {
mstore(add(add(i, d), j), mload(add(add(replacement, 0x20), j)))
j := add(j, 0x20)
if iszero(lt(j, replacementLen)) { break }
}
d := sub(add(d, replacementLen), needleLen)
if needleLen {
i := add(i, needleLen)
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
mstore(add(i, d), t)
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
}
}
let end := mload(0x00)
let n := add(sub(d, add(result, 0x20)), end)
// Copy the rest of the bytes one word at a time.
for {} lt(i, end) { i := add(i, 0x20) } { mstore(add(i, d), mload(i)) }
let o := add(i, d)
mstore(o, 0) // Zeroize the slot after the bytes.
mstore(0x40, add(o, 0x20)) // Allocate memory.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(bytes memory subject, bytes memory needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
result := not(0) // Initialize to `NOT_FOUND`.
for { let subjectLen := mload(subject) } 1 {} {
if iszero(mload(needle)) {
result := from
if iszero(gt(from, subjectLen)) { break }
result := subjectLen
break
}
let needleLen := mload(needle)
let subjectStart := add(subject, 0x20)
subject := add(subjectStart, from)
let end := add(sub(add(subjectStart, subjectLen), needleLen), 1)
let m := shl(3, sub(0x20, and(needleLen, 0x1f)))
let s := mload(add(needle, 0x20))
if iszero(and(lt(subject, end), lt(from, subjectLen))) { break }
if iszero(lt(needleLen, 0x20)) {
for { let h := keccak256(add(needle, 0x20), needleLen) } 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
if eq(keccak256(subject, needleLen), h) {
result := sub(subject, subjectStart)
break
}
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
for {} 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
result := sub(subject, subjectStart)
break
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right, starting from `from`. Optimized for byte needles.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOfByte(bytes memory subject, bytes1 needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
result := not(0) // Initialize to `NOT_FOUND`.
if gt(mload(subject), from) {
let start := add(subject, 0x20)
let end := add(start, mload(subject))
let m := div(not(0), 255) // `0x0101 ... `.
let h := mul(byte(0, needle), m) // Replicating needle mask.
m := not(shl(7, m)) // `0x7f7f ... `.
for { let i := add(start, from) } 1 {} {
let c := xor(mload(i), h) // Load 32-byte chunk and xor with mask.
c := not(or(or(add(and(c, m), m), c), m)) // Each needle byte will be `0x80`.
if c {
c := and(not(shr(shl(3, sub(end, i)), not(0))), c) // Truncate bytes past the end.
if c {
let r := shl(7, lt(0x8421084210842108cc6318c6db6d54be, c)) // Save bytecode.
r := or(shl(6, lt(0xffffffffffffffff, shr(r, c))), r)
// forgefmt: disable-next-item
result := add(sub(i, start), shr(3, xor(byte(and(0x1f, shr(byte(24,
mul(0x02040810204081, shr(r, c))), 0x8421084210842108cc6318c6db6d54be)),
0xc0c8c8d0c8e8d0d8c8e8e0e8d0d8e0f0c8d0e8d0e0e0d8f0d0d0e0d8f8f8f8f8), r)))
break
}
}
i := add(i, 0x20)
if iszero(lt(i, end)) { break }
}
}
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right. Optimized for byte needles.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOfByte(bytes memory subject, bytes1 needle)
internal
pure
returns (uint256 result)
{
return indexOfByte(subject, needle, 0);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(bytes memory subject, bytes memory needle) internal pure returns (uint256) {
return indexOf(subject, needle, 0);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(bytes memory subject, bytes memory needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
for {} 1 {} {
result := not(0) // Initialize to `NOT_FOUND`.
let needleLen := mload(needle)
if gt(needleLen, mload(subject)) { break }
let w := result
let fromMax := sub(mload(subject), needleLen)
if iszero(gt(fromMax, from)) { from := fromMax }
let end := add(add(subject, 0x20), w)
subject := add(add(subject, 0x20), from)
if iszero(gt(subject, end)) { break }
// As this function is not too often used,
// we shall simply use keccak256 for smaller bytecode size.
for { let h := keccak256(add(needle, 0x20), needleLen) } 1 {} {
if eq(keccak256(subject, needleLen), h) {
result := sub(subject, add(end, 1))
break
}
subject := add(subject, w) // `sub(subject, 1)`.
if iszero(gt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(bytes memory subject, bytes memory needle)
internal
pure
returns (uint256)
{
return lastIndexOf(subject, needle, type(uint256).max);
}
/// @dev Returns true if `needle` is found in `subject`, false otherwise.
function contains(bytes memory subject, bytes memory needle) internal pure returns (bool) {
return indexOf(subject, needle) != NOT_FOUND;
}
/// @dev Returns whether `subject` starts with `needle`.
function startsWith(bytes memory subject, bytes memory needle)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(needle)
// Just using keccak256 directly is actually cheaper.
let t := eq(keccak256(add(subject, 0x20), n), keccak256(add(needle, 0x20), n))
result := lt(gt(n, mload(subject)), t)
}
}
/// @dev Returns whether `subject` ends with `needle`.
function endsWith(bytes memory subject, bytes memory needle)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(needle)
let notInRange := gt(n, mload(subject))
// `subject + 0x20 + max(subject.length - needle.length, 0)`.
let t := add(add(subject, 0x20), mul(iszero(notInRange), sub(mload(subject), n)))
// Just using keccak256 directly is actually cheaper.
result := gt(eq(keccak256(t, n), keccak256(add(needle, 0x20), n)), notInRange)
}
}
/// @dev Returns `subject` repeated `times`.
function repeat(bytes memory subject, uint256 times)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
let l := mload(subject) // Subject length.
if iszero(or(iszero(times), iszero(l))) {
result := mload(0x40)
subject := add(subject, 0x20)
let o := add(result, 0x20)
for {} 1 {} {
// Copy the `subject` one word at a time.
for { let j := 0 } 1 {} {
mstore(add(o, j), mload(add(subject, j)))
j := add(j, 0x20)
if iszero(lt(j, l)) { break }
}
o := add(o, l)
times := sub(times, 1)
if iszero(times) { break }
}
mstore(o, 0) // Zeroize the slot after the bytes.
mstore(0x40, add(o, 0x20)) // Allocate memory.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets.
function slice(bytes memory subject, uint256 start, uint256 end)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
let l := mload(subject) // Subject length.
if iszero(gt(l, end)) { end := l }
if iszero(gt(l, start)) { start := l }
if lt(start, end) {
result := mload(0x40)
let n := sub(end, start)
let i := add(subject, start)
let w := not(0x1f)
// Copy the `subject` one word at a time, backwards.
for { let j := and(add(n, 0x1f), w) } 1 {} {
mstore(add(result, j), mload(add(i, j)))
j := add(j, w) // `sub(j, 0x20)`.
if iszero(j) { break }
}
let o := add(add(result, 0x20), n)
mstore(o, 0) // Zeroize the slot after the bytes.
mstore(0x40, add(o, 0x20)) // Allocate memory.
mstore(result, n) // Store the length.
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the bytes.
/// `start` is a byte offset.
function slice(bytes memory subject, uint256 start)
internal
pure
returns (bytes memory result)
{
result = slice(subject, start, type(uint256).max);
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets. Faster than Solidity's native slicing.
function sliceCalldata(bytes calldata subject, uint256 start, uint256 end)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
end := xor(end, mul(xor(end, subject.length), lt(subject.length, end)))
start := xor(start, mul(xor(start, subject.length), lt(subject.length, start)))
result.offset := add(subject.offset, start)
result.length := mul(lt(start, end), sub(end, start))
}
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the bytes.
/// `start` is a byte offset. Faster than Solidity's native slicing.
function sliceCalldata(bytes calldata subject, uint256 start)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
start := xor(start, mul(xor(start, subject.length), lt(subject.length, start)))
result.offset := add(subject.offset, start)
result.length := mul(lt(start, subject.length), sub(subject.length, start))
}
}
/// @dev Reduces the size of `subject` to `n`.
/// If `n` is greater than the size of `subject`, this will be a no-op.
function truncate(bytes memory subject, uint256 n)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := subject
mstore(mul(lt(n, mload(result)), result), n)
}
}
/// @dev Returns a copy of `subject`, with the length reduced to `n`.
/// If `n` is greater than the size of `subject`, this will be a no-op.
function truncatedCalldata(bytes calldata subject, uint256 n)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
result.offset := subject.offset
result.length := xor(n, mul(xor(n, subject.length), lt(subject.length, n)))
}
}
/// @dev Returns all the indices of `needle` in `subject`.
/// The indices are byte offsets.
function indicesOf(bytes memory subject, bytes memory needle)
internal
pure
returns (uint256[] memory result)
{
/// @solidity memory-safe-assembly
assembly {
let searchLen := mload(needle)
if iszero(gt(searchLen, mload(subject))) {
result := mload(0x40)
let i := add(subject, 0x20)
let o := add(result, 0x20)
let subjectSearchEnd := add(sub(add(i, mload(subject)), searchLen), 1)
let h := 0 // The hash of `needle`.
if iszero(lt(searchLen, 0x20)) { h := keccak256(add(needle, 0x20), searchLen) }
let s := mload(add(needle, 0x20))
for { let m := shl(3, sub(0x20, and(searchLen, 0x1f))) } 1 {} {
let t := mload(i)
// Whether the first `searchLen % 32` bytes of `subject` and `needle` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(i, searchLen), h)) {
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
mstore(o, sub(i, add(subject, 0x20))) // Append to `result`.
o := add(o, 0x20)
i := add(i, searchLen) // Advance `i` by `searchLen`.
if searchLen {
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
}
mstore(result, shr(5, sub(o, add(result, 0x20)))) // Store the length of `result`.
// Allocate memory for result.
// We allocate one more word, so this array can be recycled for {split}.
mstore(0x40, add(o, 0x20))
}
}
}
/// @dev Returns an arrays of bytess based on the `delimiter` inside of the `subject` bytes.
function split(bytes memory subject, bytes memory delimiter)
internal
pure
returns (bytes[] memory result)
{
uint256[] memory indices = indicesOf(subject, delimiter);
/// @solidity memory-safe-assembly
assembly {
let w := not(0x1f)
let indexPtr := add(indices, 0x20)
let indicesEnd := add(indexPtr, shl(5, add(mload(indices), 1)))
mstore(add(indicesEnd, w), mload(subject))
mstore(indices, add(mload(indices), 1))
for { let prevIndex := 0 } 1 {} {
let index := mload(indexPtr)
mstore(indexPtr, 0x60)
if iszero(eq(index, prevIndex)) {
let element := mload(0x40)
let l := sub(index, prevIndex)
mstore(element, l) // Store the length of the element.
// Copy the `subject` one word at a time, backwards.
for { let o := and(add(l, 0x1f), w) } 1 {} {
mstore(add(element, o), mload(add(add(subject, prevIndex), o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
mstore(add(add(element, 0x20), l), 0) // Zeroize the slot after the bytes.
// Allocate memory for the length and the bytes, rounded up to a multiple of 32.
mstore(0x40, add(element, and(add(l, 0x3f), w)))
mstore(indexPtr, element) // Store the `element` into the array.
}
prevIndex := add(index, mload(delimiter))
indexPtr := add(indexPtr, 0x20)
if iszero(lt(indexPtr, indicesEnd)) { break }
}
result := indices
if iszero(mload(delimiter)) {
result := add(indices, 0x20)
mstore(result, sub(mload(indices), 2))
}
}
}
/// @dev Returns a concatenated bytes of `a` and `b`.
/// Cheaper than `bytes.concat()` and does not de-align the free memory pointer.
function concat(bytes memory a, bytes memory b) internal pure returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let w := not(0x1f)
let aLen := mload(a)
// Copy `a` one word at a time, backwards.
for { let o := and(add(aLen, 0x20), w) } 1 {} {
mstore(add(result, o), mload(add(a, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let bLen := mload(b)
let output := add(result, aLen)
// Copy `b` one word at a time, backwards.
for { let o := and(add(bLen, 0x20), w) } 1 {} {
mstore(add(output, o), mload(add(b, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let totalLen := add(aLen, bLen)
let last := add(add(result, 0x20), totalLen)
mstore(last, 0) // Zeroize the slot after the bytes.
mstore(result, totalLen) // Store the length.
mstore(0x40, add(last, 0x20)) // Allocate memory.
}
}
/// @dev Returns whether `a` equals `b`.
function eq(bytes memory a, bytes memory b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
}
}
/// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small bytes.
function eqs(bytes memory a, bytes32 b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
// These should be evaluated on compile time, as far as possible.
let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
let x := not(or(m, or(b, add(m, and(b, m)))))
let r := shl(7, iszero(iszero(shr(128, x))))
r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
}
}
/// @dev Returns 0 if `a == b`, -1 if `a < b`, +1 if `a > b`.
/// If `a` == b[:a.length]`, and `a.length < b.length`, returns -1.
function cmp(bytes memory a, bytes memory b) internal pure returns (int256 result) {
/// @solidity memory-safe-assembly
assembly {
let aLen := mload(a)
let bLen := mload(b)
let n := and(xor(aLen, mul(xor(aLen, bLen), lt(bLen, aLen))), not(0x1f))
if n {
for { let i := 0x20 } 1 {} {
let x := mload(add(a, i))
let y := mload(add(b, i))
if iszero(or(xor(x, y), eq(i, n))) {
i := add(i, 0x20)
continue
}
result := sub(gt(x, y), lt(x, y))
break
}
}
// forgefmt: disable-next-item
if iszero(result) {
let l := 0x201f1e1d1c1b1a191817161514131211100f0e0d0c0b0a090807060504030201
let x := and(mload(add(add(a, 0x20), n)), shl(shl(3, byte(sub(aLen, n), l)), not(0)))
let y := and(mload(add(add(b, 0x20), n)), shl(shl(3, byte(sub(bLen, n), l)), not(0)))
result := sub(gt(x, y), lt(x, y))
if iszero(result) { result := sub(gt(aLen, bLen), lt(aLen, bLen)) }
}
}
}
/// @dev Directly returns `a` without copying.
function directReturn(bytes memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
// Assumes that the bytes does not start from the scratch space.
let retStart := sub(a, 0x20)
let retUnpaddedSize := add(mload(a), 0x40)
// Right pad with zeroes. Just in case the bytes is produced
// by a method that doesn't zero right pad.
mstore(add(retStart, retUnpaddedSize), 0)
mstore(retStart, 0x20) // Store the return offset.
// End the transaction, returning the bytes.
return(retStart, and(not(0x1f), add(0x1f, retUnpaddedSize)))
}
}
/// @dev Directly returns `a` with minimal copying.
function directReturn(bytes[] memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
let n := mload(a) // `a.length`.
let o := add(a, 0x20) // Start of elements in `a`.
let u := a // Highest memory slot.
let w := not(0x1f)
for { let i := 0 } iszero(eq(i, n)) { i := add(i, 1) } {
let c := add(o, shl(5, i)) // Location of pointer to `a[i]`.
let s := mload(c) // `a[i]`.
let l := mload(s) // `a[i].length`.
let r := and(l, 0x1f) // `a[i].length % 32`.
let z := add(0x20, and(l, w)) // Offset of last word in `a[i]` from `s`.
// If `s` comes before `o`, or `s` is not zero right padded.
if iszero(lt(lt(s, o), or(iszero(r), iszero(shl(shl(3, r), mload(add(s, z))))))) {
let m := mload(0x40)
mstore(m, l) // Copy `a[i].length`.
for {} 1 {} {
mstore(add(m, z), mload(add(s, z))) // Copy `a[i]`, backwards.
z := add(z, w) // `sub(z, 0x20)`.
if iszero(z) { break }
}
let e := add(add(m, 0x20), l)
mstore(e, 0) // Zeroize the slot after the copied bytes.
mstore(0x40, add(e, 0x20)) // Allocate memory.
s := m
}
mstore(c, sub(s, o)) // Convert to calldata offset.
let t := add(l, add(s, 0x20))
if iszero(lt(t, u)) { u := t }
}
let retStart := add(a, w) // Assumes `a` doesn't start from scratch space.
mstore(retStart, 0x20) // Store the return offset.
return(retStart, add(0x40, sub(u, retStart))) // End the transaction.
}
}
/// @dev Returns the word at `offset`, without any bounds checks.
function load(bytes memory a, uint256 offset) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(a, 0x20), offset))
}
}
/// @dev Returns the word at `offset`, without any bounds checks.
function loadCalldata(bytes calldata a, uint256 offset)
internal
pure
returns (bytes32 result)
{
/// @solidity memory-safe-assembly
assembly {
result := calldataload(add(a.offset, offset))
}
}
/// @dev Returns a slice representing a static struct in the calldata. Performs bounds checks.
function staticStructInCalldata(bytes calldata a, uint256 offset)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
let l := sub(a.length, 0x20)
result.offset := add(a.offset, offset)
result.length := sub(a.length, offset)
if or(shr(64, or(l, a.offset)), gt(offset, l)) { revert(l, 0x00) }
}
}
/// @dev Returns a slice representing a dynamic struct in the calldata. Performs bounds checks.
function dynamicStructInCalldata(bytes calldata a, uint256 offset)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
let l := sub(a.length, 0x20)
let s := calldataload(add(a.offset, offset)) // Relative offset of `result` from `a.offset`.
result.offset := add(a.offset, s)
result.length := sub(a.length, s)
if or(shr(64, or(s, or(l, a.offset))), gt(offset, l)) { revert(l, 0x00) }
}
}
/// @dev Returns bytes in calldata. Performs bounds checks.
function bytesInCalldata(bytes calldata a, uint256 offset)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
let l := sub(a.length, 0x20)
let s := calldataload(add(a.offset, offset)) // Relative offset of `result` from `a.offset`.
result.offset := add(add(a.offset, s), 0x20)
result.length := calldataload(add(a.offset, s))
// forgefmt: disable-next-item
if or(shr(64, or(result.length, or(s, or(l, a.offset)))),
or(gt(add(s, result.length), l), gt(offset, l))) { revert(l, 0x00) }
}
}
/// @dev Checks if `x` is in `a`. Assumes `a` has been checked.
function checkInCalldata(bytes calldata x, bytes calldata a) internal pure {
/// @solidity memory-safe-assembly
assembly {
if or(
or(lt(x.offset, a.offset), gt(add(x.offset, x.length), add(a.length, a.offset))),
shr(64, or(x.length, x.offset))
) { revert(0x00, 0x00) }
}
}
/// @dev Checks if `x` is in `a`. Assumes `a` has been checked.
function checkInCalldata(bytes[] calldata x, bytes calldata a) internal pure {
/// @solidity memory-safe-assembly
assembly {
let e := sub(add(a.length, a.offset), 0x20)
if or(lt(x.offset, a.offset), shr(64, x.offset)) { revert(0x00, 0x00) }
for { let i := 0 } iszero(eq(x.length, i)) { i := add(i, 1) } {
let o := calldataload(add(x.offset, shl(5, i)))
let t := add(o, x.offset)
let l := calldataload(t)
if or(shr(64, or(l, o)), gt(add(t, l), e)) { revert(0x00, 0x00) }
}
}
}
/// @dev Returns empty calldata bytes. For silencing the compiler.
function emptyCalldata() internal pure returns (bytes calldata result) {
/// @solidity memory-safe-assembly
assembly {
result.length := 0
}
}
/// @dev Returns the most significant 20 bytes as an address.
function msbToAddress(bytes32 x) internal pure returns (address) {
return address(bytes20(x));
}
/// @dev Returns the least significant 20 bytes as an address.
function lsbToAddress(bytes32 x) internal pure returns (address) {
return address(uint160(uint256(x)));
}
}
lib/solady/src/utils/LibString.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {LibBytes} from "./LibBytes.sol";
/// @notice Library for converting numbers into strings and other string operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibString.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol)
///
/// @dev Note:
/// For performance and bytecode compactness, most of the string operations are restricted to
/// byte strings (7-bit ASCII), except where otherwise specified.
/// Usage of byte string operations on charsets with runes spanning two or more bytes
/// can lead to undefined behavior.
library LibString {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Goated string storage struct that totally MOGs, no cap, fr.
/// Uses less gas and bytecode than Solidity's native string storage. It's meta af.
/// Packs length with the first 31 bytes if <255 bytes, so it’s mad tight.
struct StringStorage {
bytes32 _spacer;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The length of the output is too small to contain all the hex digits.
error HexLengthInsufficient();
/// @dev The length of the string is more than 32 bytes.
error TooBigForSmallString();
/// @dev The input string must be a 7-bit ASCII.
error StringNot7BitASCII();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the string.
uint256 internal constant NOT_FOUND = type(uint256).max;
/// @dev Lookup for '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant ALPHANUMERIC_7_BIT_ASCII = 0x7fffffe07fffffe03ff000000000000;
/// @dev Lookup for 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant LETTERS_7_BIT_ASCII = 0x7fffffe07fffffe0000000000000000;
/// @dev Lookup for 'abcdefghijklmnopqrstuvwxyz'.
uint128 internal constant LOWERCASE_7_BIT_ASCII = 0x7fffffe000000000000000000000000;
/// @dev Lookup for 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant UPPERCASE_7_BIT_ASCII = 0x7fffffe0000000000000000;
/// @dev Lookup for '0123456789'.
uint128 internal constant DIGITS_7_BIT_ASCII = 0x3ff000000000000;
/// @dev Lookup for '0123456789abcdefABCDEF'.
uint128 internal constant HEXDIGITS_7_BIT_ASCII = 0x7e0000007e03ff000000000000;
/// @dev Lookup for '01234567'.
uint128 internal constant OCTDIGITS_7_BIT_ASCII = 0xff000000000000;
/// @dev Lookup for '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'.
uint128 internal constant PRINTABLE_7_BIT_ASCII = 0x7fffffffffffffffffffffff00003e00;
/// @dev Lookup for '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'.
uint128 internal constant PUNCTUATION_7_BIT_ASCII = 0x78000001f8000001fc00fffe00000000;
/// @dev Lookup for ' \t\n\r\x0b\x0c'.
uint128 internal constant WHITESPACE_7_BIT_ASCII = 0x100003e00;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRING STORAGE OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sets the value of the string storage `$` to `s`.
function set(StringStorage storage $, string memory s) internal {
LibBytes.set(bytesStorage($), bytes(s));
}
/// @dev Sets the value of the string storage `$` to `s`.
function setCalldata(StringStorage storage $, string calldata s) internal {
LibBytes.setCalldata(bytesStorage($), bytes(s));
}
/// @dev Sets the value of the string storage `$` to the empty string.
function clear(StringStorage storage $) internal {
delete $._spacer;
}
/// @dev Returns whether the value stored is `$` is the empty string "".
function isEmpty(StringStorage storage $) internal view returns (bool) {
return uint256($._spacer) & 0xff == uint256(0);
}
/// @dev Returns the length of the value stored in `$`.
function length(StringStorage storage $) internal view returns (uint256) {
return LibBytes.length(bytesStorage($));
}
/// @dev Returns the value stored in `$`.
function get(StringStorage storage $) internal view returns (string memory) {
return string(LibBytes.get(bytesStorage($)));
}
/// @dev Returns the uint8 at index `i`. If out-of-bounds, returns 0.
function uint8At(StringStorage storage $, uint256 i) internal view returns (uint8) {
return LibBytes.uint8At(bytesStorage($), i);
}
/// @dev Helper to cast `$` to a `BytesStorage`.
function bytesStorage(StringStorage storage $)
internal
pure
returns (LibBytes.BytesStorage storage casted)
{
/// @solidity memory-safe-assembly
assembly {
casted.slot := $.slot
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the base 10 decimal representation of `value`.
function toString(uint256 value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits.
result := add(mload(0x40), 0x80)
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end of the memory to calculate the length later.
let w := not(0) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
result := add(result, w) // `sub(result, 1)`.
// Store the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(result, add(48, mod(temp, 10)))
temp := div(temp, 10) // Keep dividing `temp` until zero.
if iszero(temp) { break }
}
let n := sub(end, result)
result := sub(result, 0x20) // Move the pointer 32 bytes back to make room for the length.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the base 10 decimal representation of `value`.
function toString(int256 value) internal pure returns (string memory result) {
if (value >= 0) return toString(uint256(value));
unchecked {
result = toString(~uint256(value) + 1);
}
/// @solidity memory-safe-assembly
assembly {
// We still have some spare memory space on the left,
// as we have allocated 3 words (96 bytes) for up to 78 digits.
let n := mload(result) // Load the string length.
mstore(result, 0x2d) // Store the '-' character.
result := sub(result, 1) // Move back the string pointer by a byte.
mstore(result, add(n, 1)) // Update the string length.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HEXADECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `byteCount` bytes.
/// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
/// giving a total length of `byteCount * 2 + 2` bytes.
/// Reverts if `byteCount` is too small for the output to contain all the digits.
function toHexString(uint256 value, uint256 byteCount)
internal
pure
returns (string memory result)
{
result = toHexStringNoPrefix(value, byteCount);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `byteCount` bytes.
/// The output is not prefixed with "0x" and is encoded using 2 hexadecimal digits per byte,
/// giving a total length of `byteCount * 2` bytes.
/// Reverts if `byteCount` is too small for the output to contain all the digits.
function toHexStringNoPrefix(uint256 value, uint256 byteCount)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, `byteCount * 2` bytes
// for the digits, 0x02 bytes for the prefix, and 0x20 bytes for the length.
// We add 0x20 to the total and round down to a multiple of 0x20.
// (0x20 + 0x20 + 0x02 + 0x20) = 0x62.
result := add(mload(0x40), and(add(shl(1, byteCount), 0x42), not(0x1f)))
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end to calculate the length later.
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let start := sub(result, add(byteCount, byteCount))
let w := not(1) // Tsk.
let temp := value
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for {} 1 {} {
result := add(result, w) // `sub(result, 2)`.
mstore8(add(result, 1), mload(and(temp, 15)))
mstore8(result, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(xor(result, start)) { break }
}
if temp {
mstore(0x00, 0x2194895a) // `HexLengthInsufficient()`.
revert(0x1c, 0x04)
}
let n := sub(end, result)
result := sub(result, 0x20)
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2 + 2` bytes.
function toHexString(uint256 value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x".
/// The output excludes leading "0" from the `toHexString` output.
/// `0x00: "0x0", 0x01: "0x1", 0x12: "0x12", 0x123: "0x123"`.
function toMinimalHexString(uint256 value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(result, 0x20))), 0x30) // Whether leading zero is present.
let n := add(mload(result), 2) // Compute the length.
mstore(add(result, o), 0x3078) // Store the "0x" prefix, accounting for leading zero.
result := sub(add(result, o), 2) // Move the pointer, accounting for leading zero.
mstore(result, sub(n, o)) // Store the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output excludes leading "0" from the `toHexStringNoPrefix` output.
/// `0x00: "0", 0x01: "1", 0x12: "12", 0x123: "123"`.
function toMinimalHexStringNoPrefix(uint256 value)
internal
pure
returns (string memory result)
{
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(result, 0x20))), 0x30) // Whether leading zero is present.
let n := mload(result) // Get the length.
result := add(result, o) // Move the pointer, accounting for leading zero.
mstore(result, sub(n, o)) // Store the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2` bytes.
function toHexStringNoPrefix(uint256 value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x40 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x40) is 0xa0.
result := add(mload(0x40), 0x80)
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end to calculate the length later.
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
let w := not(1) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
result := add(result, w) // `sub(result, 2)`.
mstore8(add(result, 1), mload(and(temp, 15)))
mstore8(result, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(temp) { break }
}
let n := sub(end, result)
result := sub(result, 0x20)
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x", encoded using 2 hexadecimal digits per byte,
/// and the alphabets are capitalized conditionally according to
/// https://eips.ethereum.org/EIPS/eip-55
function toHexStringChecksummed(address value) internal pure returns (string memory result) {
result = toHexString(value);
/// @solidity memory-safe-assembly
assembly {
let mask := shl(6, div(not(0), 255)) // `0b010000000100000000 ...`
let o := add(result, 0x22)
let hashed := and(keccak256(o, 40), mul(34, mask)) // `0b10001000 ... `
let t := shl(240, 136) // `0b10001000 << 240`
for { let i := 0 } 1 {} {
mstore(add(i, i), mul(t, byte(i, hashed)))
i := add(i, 1)
if eq(i, 20) { break }
}
mstore(o, xor(mload(o), shr(1, and(mload(0x00), and(mload(o), mask)))))
o := add(o, 0x20)
mstore(o, xor(mload(o), shr(1, and(mload(0x20), and(mload(o), mask)))))
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
function toHexString(address value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(address value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
// Allocate memory.
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x28 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x28) is 0x80.
mstore(0x40, add(result, 0x80))
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
result := add(result, 2)
mstore(result, 40) // Store the length.
let o := add(result, 0x20)
mstore(add(o, 40), 0) // Zeroize the slot after the string.
value := shl(96, value)
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let i := 0 } 1 {} {
let p := add(o, add(i, i))
let temp := byte(i, value)
mstore8(add(p, 1), mload(and(temp, 15)))
mstore8(p, mload(shr(4, temp)))
i := add(i, 1)
if eq(i, 20) { break }
}
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexString(bytes memory raw) internal pure returns (string memory result) {
result = toHexStringNoPrefix(raw);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(bytes memory raw) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(raw)
result := add(mload(0x40), 2) // Skip 2 bytes for the optional prefix.
mstore(result, add(n, n)) // Store the length of the output.
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
let o := add(result, 0x20)
let end := add(raw, n)
for {} iszero(eq(raw, end)) {} {
raw := add(raw, 1)
mstore8(add(o, 1), mload(and(mload(raw), 15)))
mstore8(o, mload(and(shr(4, mload(raw)), 15)))
o := add(o, 2)
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RUNE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the number of UTF characters in the string.
function runeCount(string memory s) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
if mload(s) {
mstore(0x00, div(not(0), 255))
mstore(0x20, 0x0202020202020202020202020202020202020202020202020303030304040506)
let o := add(s, 0x20)
let end := add(o, mload(s))
for { result := 1 } 1 { result := add(result, 1) } {
o := add(o, byte(0, mload(shr(250, mload(o)))))
if iszero(lt(o, end)) { break }
}
}
}
}
/// @dev Returns if this string is a 7-bit ASCII string.
/// (i.e. all characters codes are in [0..127])
function is7BitASCII(string memory s) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
let mask := shl(7, div(not(0), 255))
let n := mload(s)
if n {
let o := add(s, 0x20)
let end := add(o, n)
let last := mload(end)
mstore(end, 0)
for {} 1 {} {
if and(mask, mload(o)) {
result := 0
break
}
o := add(o, 0x20)
if iszero(lt(o, end)) { break }
}
mstore(end, last)
}
}
}
/// @dev Returns if this string is a 7-bit ASCII string,
/// AND all characters are in the `allowed` lookup.
/// Note: If `s` is empty, returns true regardless of `allowed`.
function is7BitASCII(string memory s, uint128 allowed) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
if mload(s) {
let allowed_ := shr(128, shl(128, allowed))
let o := add(s, 0x20)
for { let end := add(o, mload(s)) } 1 {} {
result := and(result, shr(byte(0, mload(o)), allowed_))
o := add(o, 1)
if iszero(and(result, lt(o, end))) { break }
}
}
}
}
/// @dev Converts the bytes in the 7-bit ASCII string `s` to
/// an allowed lookup for use in `is7BitASCII(s, allowed)`.
/// To save runtime gas, you can cache the result in an immutable variable.
function to7BitASCIIAllowedLookup(string memory s) internal pure returns (uint128 result) {
/// @solidity memory-safe-assembly
assembly {
if mload(s) {
let o := add(s, 0x20)
for { let end := add(o, mload(s)) } 1 {} {
result := or(result, shl(byte(0, mload(o)), 1))
o := add(o, 1)
if iszero(lt(o, end)) { break }
}
if shr(128, result) {
mstore(0x00, 0xc9807e0d) // `StringNot7BitASCII()`.
revert(0x1c, 0x04)
}
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// For performance and bytecode compactness, byte string operations are restricted
// to 7-bit ASCII strings. All offsets are byte offsets, not UTF character offsets.
// Usage of byte string operations on charsets with runes spanning two or more bytes
// can lead to undefined behavior.
/// @dev Returns `subject` all occurrences of `needle` replaced with `replacement`.
function replace(string memory subject, string memory needle, string memory replacement)
internal
pure
returns (string memory)
{
return string(LibBytes.replace(bytes(subject), bytes(needle), bytes(replacement)));
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(string memory subject, string memory needle, uint256 from)
internal
pure
returns (uint256)
{
return LibBytes.indexOf(bytes(subject), bytes(needle), from);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(string memory subject, string memory needle) internal pure returns (uint256) {
return LibBytes.indexOf(bytes(subject), bytes(needle), 0);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(string memory subject, string memory needle, uint256 from)
internal
pure
returns (uint256)
{
return LibBytes.lastIndexOf(bytes(subject), bytes(needle), from);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(string memory subject, string memory needle)
internal
pure
returns (uint256)
{
return LibBytes.lastIndexOf(bytes(subject), bytes(needle), type(uint256).max);
}
/// @dev Returns true if `needle` is found in `subject`, false otherwise.
function contains(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.contains(bytes(subject), bytes(needle));
}
/// @dev Returns whether `subject` starts with `needle`.
function startsWith(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.startsWith(bytes(subject), bytes(needle));
}
/// @dev Returns whether `subject` ends with `needle`.
function endsWith(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.endsWith(bytes(subject), bytes(needle));
}
/// @dev Returns `subject` repeated `times`.
function repeat(string memory subject, uint256 times) internal pure returns (string memory) {
return string(LibBytes.repeat(bytes(subject), times));
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets.
function slice(string memory subject, uint256 start, uint256 end)
internal
pure
returns (string memory)
{
return string(LibBytes.slice(bytes(subject), start, end));
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the string.
/// `start` is a byte offset.
function slice(string memory subject, uint256 start) internal pure returns (string memory) {
return string(LibBytes.slice(bytes(subject), start, type(uint256).max));
}
/// @dev Returns all the indices of `needle` in `subject`.
/// The indices are byte offsets.
function indicesOf(string memory subject, string memory needle)
internal
pure
returns (uint256[] memory)
{
return LibBytes.indicesOf(bytes(subject), bytes(needle));
}
/// @dev Returns an arrays of strings based on the `delimiter` inside of the `subject` string.
function split(string memory subject, string memory delimiter)
internal
pure
returns (string[] memory result)
{
bytes[] memory a = LibBytes.split(bytes(subject), bytes(delimiter));
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Returns a concatenated string of `a` and `b`.
/// Cheaper than `string.concat()` and does not de-align the free memory pointer.
function concat(string memory a, string memory b) internal pure returns (string memory) {
return string(LibBytes.concat(bytes(a), bytes(b)));
}
/// @dev Returns a copy of the string in either lowercase or UPPERCASE.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function toCase(string memory subject, bool toUpper)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(subject)
if n {
result := mload(0x40)
let o := add(result, 0x20)
let d := sub(subject, result)
let flags := shl(add(70, shl(5, toUpper)), 0x3ffffff)
for { let end := add(o, n) } 1 {} {
let b := byte(0, mload(add(d, o)))
mstore8(o, xor(and(shr(b, flags), 0x20), b))
o := add(o, 1)
if eq(o, end) { break }
}
mstore(result, n) // Store the length.
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
}
/// @dev Returns a string from a small bytes32 string.
/// `s` must be null-terminated, or behavior will be undefined.
function fromSmallString(bytes32 s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let n := 0
for {} byte(n, s) { n := add(n, 1) } {} // Scan for '\0'.
mstore(result, n) // Store the length.
let o := add(result, 0x20)
mstore(o, s) // Store the bytes of the string.
mstore(add(o, n), 0) // Zeroize the slot after the string.
mstore(0x40, add(result, 0x40)) // Allocate memory.
}
}
/// @dev Returns the small string, with all bytes after the first null byte zeroized.
function normalizeSmallString(bytes32 s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
for {} byte(result, s) { result := add(result, 1) } {} // Scan for '\0'.
mstore(0x00, s)
mstore(result, 0x00)
result := mload(0x00)
}
}
/// @dev Returns the string as a normalized null-terminated small string.
function toSmallString(string memory s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(s)
if iszero(lt(result, 33)) {
mstore(0x00, 0xec92f9a3) // `TooBigForSmallString()`.
revert(0x1c, 0x04)
}
result := shl(shl(3, sub(32, result)), mload(add(s, result)))
}
}
/// @dev Returns a lowercased copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function lower(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, false);
}
/// @dev Returns an UPPERCASED copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function upper(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, true);
}
/// @dev Escapes the string to be used within HTML tags.
function escapeHTML(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let end := add(s, mload(s))
let o := add(result, 0x20)
// Store the bytes of the packed offsets and strides into the scratch space.
// `packed = (stride << 5) | offset`. Max offset is 20. Max stride is 6.
mstore(0x1f, 0x900094)
mstore(0x08, 0xc0000000a6ab)
// Store ""&'<>" into the scratch space.
mstore(0x00, shl(64, 0x2671756f743b26616d703b262333393b266c743b2667743b))
for {} iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
// Not in `["\"","'","&","<",">"]`.
if iszero(and(shl(c, 1), 0x500000c400000000)) {
mstore8(o, c)
o := add(o, 1)
continue
}
let t := shr(248, mload(c))
mstore(o, mload(and(t, 0x1f)))
o := add(o, shr(5, t))
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
/// If `addDoubleQuotes` is true, the result will be enclosed in double-quotes.
function escapeJSON(string memory s, bool addDoubleQuotes)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let o := add(result, 0x20)
if addDoubleQuotes {
mstore8(o, 34)
o := add(1, o)
}
// Store "\\u0000" in scratch space.
// Store "0123456789abcdef" in scratch space.
// Also, store `{0x08:"b", 0x09:"t", 0x0a:"n", 0x0c:"f", 0x0d:"r"}`.
// into the scratch space.
mstore(0x15, 0x5c75303030303031323334353637383961626364656662746e006672)
// Bitmask for detecting `["\"","\\"]`.
let e := or(shl(0x22, 1), shl(0x5c, 1))
for { let end := add(s, mload(s)) } iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
if iszero(lt(c, 0x20)) {
if iszero(and(shl(c, 1), e)) {
// Not in `["\"","\\"]`.
mstore8(o, c)
o := add(o, 1)
continue
}
mstore8(o, 0x5c) // "\\".
mstore8(add(o, 1), c)
o := add(o, 2)
continue
}
if iszero(and(shl(c, 1), 0x3700)) {
// Not in `["\b","\t","\n","\f","\d"]`.
mstore8(0x1d, mload(shr(4, c))) // Hex value.
mstore8(0x1e, mload(and(c, 15))) // Hex value.
mstore(o, mload(0x19)) // "\\u00XX".
o := add(o, 6)
continue
}
mstore8(o, 0x5c) // "\\".
mstore8(add(o, 1), mload(add(c, 8)))
o := add(o, 2)
}
if addDoubleQuotes {
mstore8(o, 34)
o := add(1, o)
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
function escapeJSON(string memory s) internal pure returns (string memory result) {
result = escapeJSON(s, false);
}
/// @dev Encodes `s` so that it can be safely used in a URI,
/// just like `encodeURIComponent` in JavaScript.
/// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
/// See: https://datatracker.ietf.org/doc/html/rfc2396
/// See: https://datatracker.ietf.org/doc/html/rfc3986
function encodeURIComponent(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
// Store "0123456789ABCDEF" in scratch space.
// Uppercased to be consistent with JavaScript's implementation.
mstore(0x0f, 0x30313233343536373839414243444546)
let o := add(result, 0x20)
for { let end := add(s, mload(s)) } iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
// If not in `[0-9A-Z-a-z-_.!~*'()]`.
if iszero(and(1, shr(c, 0x47fffffe87fffffe03ff678200000000))) {
mstore8(o, 0x25) // '%'.
mstore8(add(o, 1), mload(and(shr(4, c), 15)))
mstore8(add(o, 2), mload(and(c, 15)))
o := add(o, 3)
continue
}
mstore8(o, c)
o := add(o, 1)
}
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Returns whether `a` equals `b`.
function eq(string memory a, string memory b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
}
}
/// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small string.
function eqs(string memory a, bytes32 b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
// These should be evaluated on compile time, as far as possible.
let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
let x := not(or(m, or(b, add(m, and(b, m)))))
let r := shl(7, iszero(iszero(shr(128, x))))
r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
}
}
/// @dev Returns 0 if `a == b`, -1 if `a < b`, +1 if `a > b`.
/// If `a` == b[:a.length]`, and `a.length < b.length`, returns -1.
function cmp(string memory a, string memory b) internal pure returns (int256) {
return LibBytes.cmp(bytes(a), bytes(b));
}
/// @dev Packs a single string with its length into a single word.
/// Returns `bytes32(0)` if the length is zero or greater than 31.
function packOne(string memory a) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
// We don't need to zero right pad the string,
// since this is our own custom non-standard packing scheme.
result :=
mul(
// Load the length and the bytes.
mload(add(a, 0x1f)),
// `length != 0 && length < 32`. Abuses underflow.
// Assumes that the length is valid and within the block gas limit.
lt(sub(mload(a), 1), 0x1f)
)
}
}
/// @dev Unpacks a string packed using {packOne}.
/// Returns the empty string if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packOne}, the output behavior is undefined.
function unpackOne(bytes32 packed) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40) // Grab the free memory pointer.
mstore(0x40, add(result, 0x40)) // Allocate 2 words (1 for the length, 1 for the bytes).
mstore(result, 0) // Zeroize the length slot.
mstore(add(result, 0x1f), packed) // Store the length and bytes.
mstore(add(add(result, 0x20), mload(result)), 0) // Right pad with zeroes.
}
}
/// @dev Packs two strings with their lengths into a single word.
/// Returns `bytes32(0)` if combined length is zero or greater than 30.
function packTwo(string memory a, string memory b) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let aLen := mload(a)
// We don't need to zero right pad the strings,
// since this is our own custom non-standard packing scheme.
result :=
mul(
or( // Load the length and the bytes of `a` and `b`.
shl(shl(3, sub(0x1f, aLen)), mload(add(a, aLen))), mload(sub(add(b, 0x1e), aLen))),
// `totalLen != 0 && totalLen < 31`. Abuses underflow.
// Assumes that the lengths are valid and within the block gas limit.
lt(sub(add(aLen, mload(b)), 1), 0x1e)
)
}
}
/// @dev Unpacks strings packed using {packTwo}.
/// Returns the empty strings if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packTwo}, the output behavior is undefined.
function unpackTwo(bytes32 packed)
internal
pure
returns (string memory resultA, string memory resultB)
{
/// @solidity memory-safe-assembly
assembly {
resultA := mload(0x40) // Grab the free memory pointer.
resultB := add(resultA, 0x40)
// Allocate 2 words for each string (1 for the length, 1 for the byte). Total 4 words.
mstore(0x40, add(resultB, 0x40))
// Zeroize the length slots.
mstore(resultA, 0)
mstore(resultB, 0)
// Store the lengths and bytes.
mstore(add(resultA, 0x1f), packed)
mstore(add(resultB, 0x1f), mload(add(add(resultA, 0x20), mload(resultA))))
// Right pad with zeroes.
mstore(add(add(resultA, 0x20), mload(resultA)), 0)
mstore(add(add(resultB, 0x20), mload(resultB)), 0)
}
}
/// @dev Directly returns `a` without copying.
function directReturn(string memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
// Assumes that the string does not start from the scratch space.
let retStart := sub(a, 0x20)
let retUnpaddedSize := add(mload(a), 0x40)
// Right pad with zeroes. Just in case the string is produced
// by a method that doesn't zero right pad.
mstore(add(retStart, retUnpaddedSize), 0)
mstore(retStart, 0x20) // Store the return offset.
// End the transaction, returning the string.
return(retStart, and(not(0x1f), add(0x1f, retUnpaddedSize)))
}
}
}
src/AbnormiesRenderer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
import {DynamicBufferLib} from "solady/utils/DynamicBufferLib.sol";
import {Base64} from "solady/utils/Base64.sol";
import {LibString} from "solady/utils/LibString.sol";
import {IAbnormies, AbnormieState, Cascade} from "./interfaces/IAbnormies.sol";
import {INormies} from "./interfaces/INormies.sol";
contract AbnormiesRenderer {
using DynamicBufferLib for DynamicBufferLib.DynamicBuffer;
uint256 public constant CANVAS_SIZE = 1600;
uint256 public constant CANVAS_WIDTH = 40;
bytes6 internal constant COLOR_SKY = "e3e5e4";
bytes6 internal constant COLOR_CIRRUS = "b0b1b0";
bytes6 internal constant COLOR_ALTOCUMULUS = "7c7d7e";
bytes6 internal constant COLOR_NIMBOSTRATUS = "48494b";
address public immutable abnormiesContract;
address public immutable normiesContract;
error TokenDoesNotExist(uint256 tokenId);
constructor(address abnormiesContract_, address normiesContract_) {
abnormiesContract = abnormiesContract_;
normiesContract = normiesContract_;
}
// ---------------------------------------------------------------------
// Public entry points
// ---------------------------------------------------------------------
function tokenURI(uint256 abnormieId) external view returns (string memory) {
(
uint8[1600] memory canvas,
uint16 lightningCount,
uint16 thunderCount,
bool inverted,
uint16 effectiveCirrus,
bool effectiveCustomized,
bool effectiveDead
) = _render(abnormieId);
AbnormieState memory s = IAbnormies(abnormiesContract).getAbnormieState(abnormieId);
(,,,, bool awakened,) = IAbnormies(abnormiesContract).getSeedState(s.seedNormieId);
uint64 effectiveDeadAtBlock =
s.staticAt == 0 ? IAbnormies(abnormiesContract).seedDeadAtBlock(s.seedNormieId) : s.seedDeadAtBlockAtFreeze;
(bytes memory svg, uint16 cVis, uint16 aVis, uint16 nVis) = _renderSvg(canvas);
bytes memory json = _buildJson(
UriData({
abnormieId: abnormieId,
s: s,
cirrusN: effectiveCirrus,
customized: effectiveCustomized,
burned: effectiveDead,
awakened: awakened,
inverted: inverted,
lightningCount: lightningCount,
thunderCount: thunderCount,
cirrusVisible: cVis,
altocumulusVisible: aVis,
nimbostratusVisible: nVis,
nonSky: cVis + aVis + nVis,
deadAtBlock: effectiveDeadAtBlock,
svg: svg
})
);
return string(abi.encodePacked("data:application/json;base64,", Base64.encode(json)));
}
function computeCanvas(uint256 abnormieId) external view returns (uint8[1600] memory canvas) {
(canvas,,,,,,) = _render(abnormieId);
}
// ---------------------------------------------------------------------
// Internal rendering
// ---------------------------------------------------------------------
struct UriData {
uint256 abnormieId;
AbnormieState s;
uint16 cirrusN;
bool customized;
bool burned;
bool awakened;
bool inverted;
uint16 lightningCount;
uint16 thunderCount;
uint16 cirrusVisible;
uint16 altocumulusVisible;
uint16 nimbostratusVisible;
uint16 nonSky;
uint64 deadAtBlock;
bytes svg;
}
function _render(uint256 abnormieId)
internal
view
returns (
uint8[1600] memory canvas,
uint16 lightningCount,
uint16 thunderCount,
bool inverted,
uint16 effectiveCirrus,
bool effectiveCustomized,
bool effectiveDead
)
{
AbnormieState memory s = IAbnormies(abnormiesContract).getAbnormieState(abnormieId);
if (s.seedNormieId == 0 && s.pairedAtCascadeIndex == 0) {
try IAbnormies(abnormiesContract).ownerOf(abnormieId) returns (
address
) {
// Token exists; proceed.
}
catch {
revert TokenDoesNotExist(abnormieId);
}
}
(, uint16 liveCirrus, bool liveCustomized, bool liveBurned, bool awakened,) =
IAbnormies(abnormiesContract).getSeedState(s.seedNormieId);
Cascade[] memory cascades = IAbnormies(abnormiesContract).getAllCascades();
// Static Abnormies render against the snapshot fields captured at freeze time. Active
// Abnormies render against live seed state.
if (s.staticAt == 0) {
effectiveCirrus = liveCirrus;
effectiveCustomized = liveCustomized;
effectiveDead = liveBurned;
} else {
effectiveCirrus = s.cirrusCountAtFreeze;
effectiveCustomized = s.seedCustomizedAtFreeze;
effectiveDead = s.seedDeadAtFreeze;
}
_paintCirrus(canvas, s.seedNormieId, effectiveCirrus);
if (effectiveCustomized) _paintSourceNimbostratus(canvas, s.seedNormieId);
(lightningCount, thunderCount) = _paintCascades(canvas, abnormieId, s, cascades);
if (awakened && _ownersMatch(s.seedNormieId, abnormieId)) {
_invertCanvas(canvas);
inverted = true;
}
}
function _paintCirrus(uint8[1600] memory canvas, uint16 seedNormieId, uint16 cirrusN) internal pure {
for (uint256 e = 0; e < cirrusN;) {
for (uint256 j = 0; j < 2;) {
uint16 pos = uint16(uint256(keccak256(abi.encode(seedNormieId, "cirrus", e, j))) % CANVAS_SIZE);
_paint(canvas, pos, 1);
unchecked {
++j;
}
}
unchecked {
++e;
}
}
}
function _paintSourceNimbostratus(uint8[1600] memory canvas, uint16 seedNormieId) internal pure {
for (uint256 j = 0; j < 12;) {
uint16 pos = uint16(uint256(keccak256(abi.encode(seedNormieId, "nimbostratus-source", j))) % CANVAS_SIZE);
_paint(canvas, pos, 3);
unchecked {
++j;
}
}
}
function _paintCascades(
uint8[1600] memory canvas,
uint256 abnormieId,
AbnormieState memory s,
Cascade[] memory cascades
) internal pure returns (uint16 lightningCount, uint16 thunderCount) {
uint256 n = cascades.length;
for (uint256 i = 0; i < n;) {
if (cascades[i].action == 2 && _isEligible(abnormieId, s, cascades[i], i)) {
uint16 pos = uint16(
uint256(
keccak256(
abi.encode(
cascades[i].blockNumber,
cascades[i].burnedTokenId,
cascades[i].freezeTargetTokenId,
"lightning",
abnormieId
)
)
) % CANVAS_SIZE
);
_paint(canvas, pos, 3);
unchecked {
++lightningCount;
}
}
unchecked {
++i;
}
}
for (uint256 i = 0; i < n;) {
if (cascades[i].action == 1 && _isEligible(abnormieId, s, cascades[i], i)) {
_paintThunder(canvas, abnormieId, cascades[i]);
unchecked {
++thunderCount;
}
}
unchecked {
++i;
}
}
}
function _paintThunder(uint8[1600] memory canvas, uint256 abnormieId, Cascade memory cascade) internal pure {
bytes32 countSeed = keccak256(
abi.encode(
cascade.blockNumber, cascade.burnedTokenId, cascade.freezeTargetTokenId, "thunder-count", abnormieId
)
);
uint256 N = 5 + (uint256(countSeed) % 6);
for (uint256 j = 0; j < N;) {
uint16 pos = uint16(
uint256(
keccak256(
abi.encode(
cascade.blockNumber,
cascade.burnedTokenId,
cascade.freezeTargetTokenId,
"thunder-pos",
abnormieId,
j
)
)
) % CANVAS_SIZE
);
_paint(canvas, pos, 2);
unchecked {
++j;
}
}
}
function _isEligible(uint256 abnormieId, AbnormieState memory s, Cascade memory cascade, uint256 i)
internal
pure
returns (bool)
{
if (uint256(s.pairedAtCascadeIndex) > i) return false;
if (s.staticAt != 0 && uint256(s.staticAtCascadeIndex) <= i) return false;
if (uint256(cascade.burnedTokenId) == abnormieId) return false;
if (uint256(cascade.freezeTargetTokenId) == abnormieId) return false;
return true;
}
function _paint(uint8[1600] memory canvas, uint256 pos, uint8 color) internal pure {
if (canvas[pos] == 0) {
canvas[pos] = color;
} else {
canvas[pos] = 0;
}
}
function _ownersMatch(uint16 seedNormieId, uint256 abnormieId) internal view returns (bool) {
address seedOwner;
try INormies(normiesContract).ownerOf(uint256(seedNormieId)) returns (address o) {
seedOwner = o;
} catch {
return false;
}
if (seedOwner == address(0)) return false;
address abnOwner;
try IAbnormies(abnormiesContract).ownerOf(abnormieId) returns (address o) {
abnOwner = o;
} catch {
return false;
}
return seedOwner == abnOwner;
}
function _invertCanvas(uint8[1600] memory canvas) internal pure {
for (uint256 k = 0; k < CANVAS_SIZE;) {
uint8 c = canvas[k];
if (c == 0) canvas[k] = 3;
else if (c == 3) canvas[k] = 0;
else if (c == 1) canvas[k] = 2;
else if (c == 2) canvas[k] = 1;
unchecked {
++k;
}
}
}
// ---------------------------------------------------------------------
// SVG with per-row RLE
// ---------------------------------------------------------------------
function _renderSvg(uint8[1600] memory canvas)
internal
pure
returns (bytes memory svg, uint16 cirrusVisible, uint16 altocumulusVisible, uint16 nimbostratusVisible)
{
DynamicBufferLib.DynamicBuffer memory buf;
buf.p(
bytes(
'<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000" viewBox="0 0 40 40" shape-rendering="crispEdges">'
)
);
buf.p(bytes('<rect width="40" height="40" fill="#'));
buf.p(bytes(abi.encodePacked(COLOR_SKY)));
buf.p(bytes('"/>'));
for (uint256 y = 0; y < CANVAS_WIDTH;) {
uint8 runColor = 0;
uint256 runStart = 0;
for (uint256 x = 0; x < CANVAS_WIDTH;) {
uint8 c = canvas[y * CANVAS_WIDTH + x];
if (c != runColor) {
if (runColor != 0) {
_emitRect(buf, runStart, y, x - runStart, runColor);
}
runColor = c;
runStart = x;
}
if (c == 1) {
unchecked {
++cirrusVisible;
}
} else if (c == 2) {
unchecked {
++altocumulusVisible;
}
} else if (c == 3) {
unchecked {
++nimbostratusVisible;
}
}
unchecked {
++x;
}
}
if (runColor != 0) {
_emitRect(buf, runStart, y, CANVAS_WIDTH - runStart, runColor);
}
unchecked {
++y;
}
}
buf.p(bytes("</svg>"));
svg = buf.data;
}
function _emitRect(DynamicBufferLib.DynamicBuffer memory buf, uint256 x, uint256 y, uint256 w, uint8 color)
internal
pure
{
buf.p(bytes('<rect x="'));
buf.p(bytes(LibString.toString(x)));
buf.p(bytes('" y="'));
buf.p(bytes(LibString.toString(y)));
buf.p(bytes('" width="'));
buf.p(bytes(LibString.toString(w)));
buf.p(bytes('" height="1" fill="#'));
buf.p(bytes(abi.encodePacked(_colorFor(color))));
buf.p(bytes('"/>'));
}
function _colorFor(uint8 c) internal pure returns (bytes6) {
if (c == 0) return COLOR_SKY;
if (c == 1) return COLOR_CIRRUS;
if (c == 2) return COLOR_ALTOCUMULUS;
return COLOR_NIMBOSTRATUS;
}
// ---------------------------------------------------------------------
// JSON construction
// ---------------------------------------------------------------------
function _buildJson(UriData memory d) internal view returns (bytes memory) {
DynamicBufferLib.DynamicBuffer memory buf;
buf.p(bytes('{"name":"Abnormie #'));
buf.p(bytes(LibString.toString(d.abnormieId)));
buf.p(
bytes('","description":"Abnormies. The weather around your Normies.","image":"data:image/svg+xml;base64,')
);
buf.p(bytes(Base64.encode(d.svg)));
buf.p(bytes('","attributes":['));
_appendBaseAttrs(buf, d);
if (d.s.staticAt != 0) {
_appendStaticAttrs(buf, d);
}
bool isFirstStatic = false;
if (d.s.staticAt != 0) {
uint16 firstId = IAbnormies(abnormiesContract).firstStaticTokenId();
bool firstSet = IAbnormies(abnormiesContract).firstStaticSet();
if (firstSet && uint256(firstId) == d.abnormieId) {
isFirstStatic = true;
buf.p(bytes(',{"trait_type":"First Static","value":"Yes"}'));
}
}
// suppress unused-warning
isFirstStatic;
if (d.burned) {
buf.p(bytes(',{"display_type":"number","trait_type":"Dead At","value":'));
buf.p(bytes(LibString.toString(uint256(d.deadAtBlock))));
buf.p(bytes("}"));
}
buf.p(bytes(',{"trait_type":"Inverted","value":"'));
buf.p(bytes(d.inverted ? "Yes" : "No"));
buf.p(bytes('"}'));
buf.p(bytes("]}"));
return buf.data;
}
function _appendBaseAttrs(DynamicBufferLib.DynamicBuffer memory buf, UriData memory d) internal pure {
buf.p(bytes('{"trait_type":"Mutability","value":"'));
buf.p(bytes(d.s.staticAt == 0 ? "Active" : "Static"));
buf.p(bytes('"},{"trait_type":"Source Life","value":"'));
buf.p(bytes(d.burned ? "Dead" : "Living"));
buf.p(bytes('"},{"trait_type":"Source Customized","value":"'));
buf.p(bytes(d.customized ? "Yes" : "No"));
buf.p(bytes('"},{"trait_type":"Source Awakened","value":"'));
buf.p(bytes(d.awakened ? "Yes" : "No"));
buf.p(bytes('"},{"trait_type":"Seed Normie","value":"'));
buf.p(bytes(LibString.toString(uint256(d.s.seedNormieId))));
buf.p(bytes('"},{"display_type":"number","trait_type":"Cirrus Events","value":'));
buf.p(bytes(LibString.toString(uint256(d.cirrusN))));
buf.p(bytes('},{"display_type":"number","trait_type":"Lightning Events Received","value":'));
buf.p(bytes(LibString.toString(uint256(d.lightningCount))));
buf.p(bytes('},{"display_type":"number","trait_type":"Thunder Events Received","value":'));
buf.p(bytes(LibString.toString(uint256(d.thunderCount))));
buf.p(bytes('},{"display_type":"number","trait_type":"Visible Cirrus","value":'));
buf.p(bytes(LibString.toString(uint256(d.cirrusVisible))));
buf.p(bytes('},{"display_type":"number","trait_type":"Visible Altocumulus","value":'));
buf.p(bytes(LibString.toString(uint256(d.altocumulusVisible))));
buf.p(bytes('},{"display_type":"number","trait_type":"Visible Nimbostratus","value":'));
buf.p(bytes(LibString.toString(uint256(d.nimbostratusVisible))));
buf.p(bytes('},{"display_type":"number","trait_type":"Total Coverage","max_value":1600,"value":'));
buf.p(bytes(LibString.toString(uint256(d.nonSky))));
buf.p(bytes("}"));
}
function _appendStaticAttrs(DynamicBufferLib.DynamicBuffer memory buf, UriData memory d) internal pure {
buf.p(bytes(',{"display_type":"number","trait_type":"Static At","value":'));
buf.p(bytes(LibString.toString(uint256(d.s.staticAt))));
buf.p(bytes('},{"trait_type":"Frozen By","value":"'));
buf.p(bytes(LibString.toHexString(d.s.frozenBy)));
buf.p(bytes('"},{"trait_type":"Freeze Action","value":"'));
buf.p(bytes(d.s.freezeAction == 1 ? "Thunder" : "Lightning"));
buf.p(bytes('"},{"trait_type":"Frozen After Death","value":"'));
buf.p(bytes(d.s.seedDeadAtFreeze ? "Yes" : "No"));
buf.p(bytes('"}'));
}
}
src/interfaces/IAbnormies.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
struct AbnormieState {
uint16 seedNormieId;
uint64 staticAt;
address frozenBy;
uint8 freezeAction;
bool seedDeadAtFreeze;
uint32 pairedAtCascadeIndex;
uint32 staticAtCascadeIndex;
uint16 cirrusCountAtFreeze;
bool seedCustomizedAtFreeze;
uint64 seedDeadAtBlockAtFreeze;
}
struct Cascade {
uint64 blockNumber;
uint16 burnedTokenId;
uint16 freezeTargetTokenId;
uint8 action;
uint8 thunderSize;
}
interface IAbnormies {
function getAbnormieState(uint256 abnormieId) external view returns (AbnormieState memory);
function getAllCascades() external view returns (Cascade[] memory);
function getSeedState(uint256 normieId)
external
view
returns (address lastOwner, uint16 cirrus, bool customized, bool burned, bool awakened, uint256 boundAgent);
function ownerOf(uint256 tokenId) external view returns (address);
function firstStaticTokenId() external view returns (uint16);
function firstStaticSet() external view returns (bool);
function seedDeadAtBlock(uint256 normieId) external view returns (uint64);
}
src/interfaces/IAdapter8004.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
enum TokenStandard {
ERC721,
ERC1155,
ERC6909
}
interface IAdapter8004 {
struct Binding {
TokenStandard standard;
address tokenContract;
uint256 tokenId;
}
function bindingOf(uint256 agentId) external view returns (Binding memory);
}
src/interfaces/IDelegateRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
/// @dev Minimal surface of the delegate.xyz v2 registry used for delegated Phase 1 claims.
/// Full registry: https://github.com/delegatexyz/delegate-registry (v2).
interface IDelegateRegistry {
/// @notice Returns true if `to` is delegated to act on `from`'s behalf for `contract_`.
/// @param to The hot wallet acting on behalf of the vault.
/// @param from The vault (cold wallet) that granted the delegation.
/// @param contract_ The contract the delegation is scoped to.
/// @param rights Rights identifier; `bytes32(0)` matches both an "all" delegation and a
/// contract-scoped delegation to `contract_`.
function checkDelegateForContract(address to, address from, address contract_, bytes32 rights)
external
view
returns (bool);
}
src/interfaces/INormies.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
interface INormies {
function ownerOf(uint256 tokenId) external view returns (address);
}
src/interfaces/INormiesCanvasStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
interface INormiesCanvasStorage {
function isTransformed(uint256 tokenId) external view returns (bool);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 10000,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"@limitbreak/creator-token-standards/=lib/creator-token-standards/src/",
"@limitbreak/permit-c/=lib/creator-token-standards/lib/PermitC/src/",
"@opensea/tstorish/=lib/creator-token-standards/lib/tstorish/src/",
"@openzeppelin/contracts/=lib/creator-token-standards/lib/openzeppelin-contracts/contracts/",
"erc721a/=lib/creator-token-standards/lib/ERC721A/",
"murky/=lib/creator-token-standards/lib/murky/src/",
"solady/=lib/solady/src/",
"forge-std/=lib/forge-std/src/",
"@rari-capital/solmate/=lib/creator-token-standards/lib/PermitC/lib/solmate/",
"ERC721A/=lib/creator-token-standards/lib/ERC721A/contracts/",
"PermitC/=lib/creator-token-standards/lib/PermitC/",
"creator-token-standards/=lib/creator-token-standards/",
"ds-test/=lib/creator-token-standards/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/creator-token-standards/lib/PermitC/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-metering/=lib/creator-token-standards/lib/PermitC/lib/forge-gas-metering/",
"openzeppelin-contracts/=lib/creator-token-standards/lib/openzeppelin-contracts/",
"openzeppelin/=lib/creator-token-standards/lib/PermitC/lib/openzeppelin-contracts/contracts/",
"solmate/=lib/creator-token-standards/lib/PermitC/lib/solmate/src/",
"tstorish/=lib/creator-token-standards/lib/tstorish/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.