Verified contractPartialMIT
BitmonsFreeClaim
Address0x63be1ba6efc57dd2233ee25e2b3946a99ea7363d
- Balance
0 ETH
- Transactions
91
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,106,397
- Creation transaction
- 0x5e569e8d2e…6fe7359591
31 files
- src/bitmons/BitmonsFreeClaim.solmain5.83 KB
- lib/chainlink-evm/contracts/src/v0.8/shared/access/ConfirmedOwner.sol390 B
- lib/chainlink-evm/contracts/src/v0.8/shared/access/ConfirmedOwnerWithProposal.sol2.13 KB
- lib/chainlink-evm/contracts/src/v0.8/shared/interfaces/IOwnable.sol234 B
- lib/chainlink-evm/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol8.27 KB
- lib/chainlink-evm/contracts/src/v0.8/vrf/dev/interfaces/IVRFCoordinatorV2Plus.sol2.14 KB
- lib/chainlink-evm/contracts/src/v0.8/vrf/dev/interfaces/IVRFMigratableConsumerV2Plus.sol562 B
- lib/chainlink-evm/contracts/src/v0.8/vrf/dev/interfaces/IVRFSubscriptionV2Plus.sol3.95 KB
- lib/chainlink-evm/contracts/src/v0.8/vrf/dev/libraries/VRFV2PlusClient.sol650 B
- lib/solady/src/auth/Ownable.sol12.55 KB
- lib/solady/src/tokens/ERC2981.sol6.87 KB
- lib/solady/src/tokens/ERC721.sol40 KB
- lib/solady/src/utils/LibBytes.sol38.2 KB
- lib/solady/src/utils/LibString.sol44.26 KB
- lib/solady/src/utils/Multicallable.sol5.73 KB
- lib/solady/src/utils/ReentrancyGuard.sol2.33 KB
- lib/solady/src/utils/SSTORE2.sol12.63 KB
- src/FWAV2/fwair/interfaces/IFWAIRLaunchManagerV2.sol1.4 KB
- src/FWAV2/fwair/interfaces/IFWAIRLaunchPoolV2.sol2.16 KB
- src/FWAV2/fwair/interfaces/IFWAIRLaunchV2.sol3.4 KB
- src/bitmons/Bitmons.sol36.53 KB
- src/bitmons/BitmonsArt.sol19.82 KB
- src/bitmons/BitmonsRevealVRF.sol6.63 KB
- src/bitmons/SoladyERC721C.sol3.33 KB
- src/bitmons/interfaces/IBitmonsLaunchRandomness.sol303 B
- src/bitmons/interfaces/IBitmonsRenderer.sol441 B
- src/bitmons/interfaces/ICreatorToken.sol825 B
- src/bitmons/interfaces/ITransferValidator.sol591 B
- src/bitmons/libraries/BitmonsFreeClaimAllocations.sol15.67 KB
- src/bitmons/libraries/BitmonsOneOfOneDraw.sol1.84 KB
- src/interfaces/IFWAPurchaseCallback.sol1.38 KB
src/bitmons/BitmonsFreeClaim.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {ReentrancyGuard} from "solady/src/utils/ReentrancyGuard.sol";
import {Bitmons} from "./Bitmons.sol";
import {BitmonsFreeClaimAllocations} from "./libraries/BitmonsFreeClaimAllocations.sol";
/// @notice Fixed CSV entitlements for sequential claims from the artist's 300-token holdback.
/// @dev The artist must approve this contract on the collection. Eligibility and the source wallet
/// cannot be changed; only msg.sender can spend its entitlement and receive its NFTs.
contract BitmonsFreeClaim is ReentrancyGuard {
uint256 public constant FIRST_TOKEN_ID = 4145;
uint256 public constant LAST_TOKEN_ID = 4444;
uint256 public constant MAX_CLAIMS = LAST_TOKEN_ID - FIRST_TOKEN_ID + 1;
uint256 public constant CLAIM_DURATION = 30 days;
uint256 public constant SNAPSHOT_TOTAL = BitmonsFreeClaimAllocations.TOTAL_ALLOCATION;
uint256 public constant SNAPSHOT_WALLETS = BitmonsFreeClaimAllocations.RECIPIENT_COUNT;
bytes32 public constant SNAPSHOT_SHA256 = BitmonsFreeClaimAllocations.CSV_SHA256;
Bitmons public immutable collection;
address public immutable sourceWallet;
uint256 public nextTokenId = FIRST_TOKEN_ID;
uint256 public claimStartsAt;
uint256 public claimEndsAt;
mapping(address wallet => uint256 amount) public allocation;
mapping(address wallet => uint256 amount) public claimed;
event Claimed(address indexed claimant, uint256 indexed firstTokenId, uint256 amount, bool withReveal);
event ClaimStarted(uint256 startsAt, uint256 endsAt);
error InvalidCollection();
error InvalidSourceWallet();
error InvalidAmount();
error AllocationExceeded();
error SoldOut();
error Unauthorized();
error ClaimAlreadyStarted();
error ClaimNotOpen();
constructor(address collection_) {
if (collection_.code.length == 0) revert InvalidCollection();
Bitmons nft = Bitmons(collection_);
// Mainnet's holdback is already minted, unlike the separate Sepolia reserve-mint faucet.
if (nft.maxSupply() != LAST_TOKEN_ID || nft.poolSupply() != LAST_TOKEN_ID) revert InvalidCollection();
address artist = nft.launchArtist();
if (artist == address(0) || artist == address(this) || artist == collection_) revert InvalidSourceWallet();
collection = nft;
sourceWallet = artist;
(address[] memory wallets, uint256[] memory amounts) = BitmonsFreeClaimAllocations.allocations();
for (uint256 i; i < wallets.length; ++i) {
allocation[wallets[i]] = amounts[i];
}
}
/// @notice The original artist opens claims once for exactly 30 days, starting immediately.
/// @dev Claims start closed. The deadline cannot be extended or restarted after it is set.
function startClaim() external {
if (msg.sender != sourceWallet) revert Unauthorized();
if (claimEndsAt != 0) revert ClaimAlreadyStarted();
claimStartsAt = block.timestamp;
claimEndsAt = block.timestamp + CLAIM_DURATION;
emit ClaimStarted(claimStartsAt, claimEndsAt);
}
function claimsOpen() public view returns (bool) {
return claimEndsAt != 0 && block.timestamp >= claimStartsAt && block.timestamp < claimEndsAt;
}
/// @notice Claim some or all of your remaining snapshot allocation as Spawns.
/// @return firstTokenId First ID of the contiguous batch sent to msg.sender.
function claim(uint256 amount) external nonReentrant returns (uint256 firstTokenId) {
return _claim(amount, false);
}
/// @notice Claim and request the collection's asynchronous reveal for each unrevealed NFT.
/// @dev Only owners can request a reveal, so this contract briefly holds each NFT before delivery.
/// Already revealed NFTs (including legendary 1/1s) need no request. Any failed transfer or
/// reveal request reverts the entire batch. A pending reveal can be delivered using claim().
function claimAndReveal(uint256 amount) external nonReentrant returns (uint256 firstTokenId) {
return _claim(amount, true);
}
/// @notice Unspent snapshot entitlement, independent of whether the claim window is open.
function claimable(address wallet) public view returns (uint256) {
return allocation[wallet] - claimed[wallet];
}
function totalClaimed() external view returns (uint256) {
return nextTokenId - FIRST_TOKEN_ID;
}
/// @notice Tokens remaining in the holdback; this does not grant additional snapshot entitlement.
function remainingSupply() external view returns (uint256) {
return LAST_TOKEN_ID + 1 - nextTokenId;
}
function _claim(uint256 amount, bool withReveal) private returns (uint256 firstTokenId) {
if (!claimsOpen()) revert ClaimNotOpen();
if (amount == 0) revert InvalidAmount();
if (amount > claimable(msg.sender)) revert AllocationExceeded();
firstTokenId = nextTokenId;
if (amount > LAST_TOKEN_ID + 1 - firstTokenId) revert SoldOut();
// Reserve the complete batch before any validator, receiver or reveal callback can run.
claimed[msg.sender] += amount;
nextTokenId = firstTokenId + amount;
emit Claimed(msg.sender, firstTokenId, amount, withReveal);
for (uint256 i; i < amount; ++i) {
uint256 tokenId = firstTokenId + i;
if (withReveal) {
collection.transferFrom(sourceWallet, address(this), tokenId);
if (!collection.revealed(tokenId)) collection.requestReveal(tokenId);
collection.safeTransferFrom(address(this), msg.sender, tokenId);
} else {
collection.safeTransferFrom(sourceWallet, msg.sender, tokenId);
}
}
}
}
lib/chainlink-evm/contracts/src/v0.8/shared/access/ConfirmedOwner.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ConfirmedOwnerWithProposal} from "./ConfirmedOwnerWithProposal.sol";
/// @title The ConfirmedOwner contract
/// @notice A contract with helpers for basic contract ownership.
contract ConfirmedOwner is ConfirmedOwnerWithProposal {
constructor(
address newOwner
) ConfirmedOwnerWithProposal(newOwner, address(0)) {}
}
lib/chainlink-evm/contracts/src/v0.8/shared/access/ConfirmedOwnerWithProposal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IOwnable} from "../interfaces/IOwnable.sol";
/// @title The ConfirmedOwner contract
/// @notice A contract with helpers for basic contract ownership.
contract ConfirmedOwnerWithProposal is IOwnable {
address private s_owner;
address private s_pendingOwner;
event OwnershipTransferRequested(address indexed from, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
constructor(address newOwner, address pendingOwner) {
// solhint-disable-next-line gas-custom-errors
require(newOwner != address(0), "Cannot set owner to zero");
s_owner = newOwner;
if (pendingOwner != address(0)) {
_transferOwnership(pendingOwner);
}
}
/// @notice Allows an owner to begin transferring ownership to a new address.
function transferOwnership(
address to
) public override onlyOwner {
_transferOwnership(to);
}
/// @notice Allows an ownership transfer to be completed by the recipient.
function acceptOwnership() external override {
// solhint-disable-next-line gas-custom-errors
require(msg.sender == s_pendingOwner, "Must be proposed owner");
address oldOwner = s_owner;
s_owner = msg.sender;
s_pendingOwner = address(0);
emit OwnershipTransferred(oldOwner, msg.sender);
}
/// @notice Get the current owner
function owner() public view override returns (address) {
return s_owner;
}
/// @notice validate, transfer ownership, and emit relevant events
function _transferOwnership(
address to
) private {
// solhint-disable-next-line gas-custom-errors
require(to != msg.sender, "Cannot transfer to self");
s_pendingOwner = to;
emit OwnershipTransferRequested(s_owner, to);
}
/// @notice validate access
function _validateOwnership() internal view {
// solhint-disable-next-line gas-custom-errors
require(msg.sender == s_owner, "Only callable by owner");
}
/// @notice Reverts if called by anyone other than the contract owner.
modifier onlyOwner() {
_validateOwnership();
_;
}
}
lib/chainlink-evm/contracts/src/v0.8/shared/interfaces/IOwnable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IOwnable {
function owner() external returns (address);
function transferOwnership(
address recipient
) external;
function acceptOwnership() external;
}
lib/chainlink-evm/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {ConfirmedOwner} from "../../shared/access/ConfirmedOwner.sol";
import {IVRFCoordinatorV2Plus} from "./interfaces/IVRFCoordinatorV2Plus.sol";
import {IVRFMigratableConsumerV2Plus} from "./interfaces/IVRFMigratableConsumerV2Plus.sol";
/**
*
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness. It ensures 2 things:
* @dev 1. The fulfillment came from the VRFCoordinatorV2Plus.
* @dev 2. The consumer contract implements fulfillRandomWords.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBaseV2Plus, and can
* @dev initialize VRFConsumerBaseV2Plus's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumerV2Plus is VRFConsumerBaseV2Plus {
* @dev constructor(<other arguments>, address _vrfCoordinator, address _subOwner)
* @dev VRFConsumerBaseV2Plus(_vrfCoordinator, _subOwner) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash). Create a subscription, fund it
* @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface
* @dev subscription management functions).
* @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations,
* @dev callbackGasLimit, numWords, extraArgs),
* @dev see (IVRFCoordinatorV2Plus for a description of the arguments).
*
* @dev Once the VRFCoordinatorV2Plus has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomWords method.
*
* @dev The randomness argument to fulfillRandomWords is a set of random words
* @dev generated from your requestId and the blockHash of the request.
*
* @dev If your contract could have concurrent requests open, you can use the
* @dev requestId returned from requestRandomWords to track which response is associated
* @dev with which randomness request.
* @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ.
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBaseV2Plus.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request. It is for this reason that
* @dev that you can signal to an oracle you'd like them to wait longer before
* @dev responding to the request (however this is not enforced in the contract
* @dev and so remains effective only in the case of unmodified oracle software).
*/
abstract contract VRFConsumerBaseV2Plus is IVRFMigratableConsumerV2Plus, ConfirmedOwner {
error OnlyCoordinatorCanFulfill(address have, address want);
error OnlyOwnerOrCoordinator(address have, address owner, address coordinator);
error ZeroAddress();
// s_vrfCoordinator should be used by consumers to make requests to vrfCoordinator
// so that coordinator reference is updated after migration
IVRFCoordinatorV2Plus public s_vrfCoordinator;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
*/
constructor(
address _vrfCoordinator
) ConfirmedOwner(msg.sender) {
if (_vrfCoordinator == address(0)) {
revert ZeroAddress();
}
s_vrfCoordinator = IVRFCoordinatorV2Plus(_vrfCoordinator);
}
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBaseV2Plus expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomWords the VRF output expanded to the requested number of words
*/
// solhint-disable-next-line chainlink-solidity/prefix-internal-functions-with-underscore
function fulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) internal virtual;
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) external {
if (msg.sender != address(s_vrfCoordinator)) {
revert OnlyCoordinatorCanFulfill(msg.sender, address(s_vrfCoordinator));
}
fulfillRandomWords(requestId, randomWords);
}
/**
* @inheritdoc IVRFMigratableConsumerV2Plus
*/
function setCoordinator(
address _vrfCoordinator
) external override onlyOwnerOrCoordinator {
if (_vrfCoordinator == address(0)) {
revert ZeroAddress();
}
s_vrfCoordinator = IVRFCoordinatorV2Plus(_vrfCoordinator);
emit CoordinatorSet(_vrfCoordinator);
}
modifier onlyOwnerOrCoordinator() {
if (msg.sender != owner() && msg.sender != address(s_vrfCoordinator)) {
revert OnlyOwnerOrCoordinator(msg.sender, owner(), address(s_vrfCoordinator));
}
_;
}
}
lib/chainlink-evm/contracts/src/v0.8/vrf/dev/interfaces/IVRFCoordinatorV2Plus.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {VRFV2PlusClient} from "../libraries/VRFV2PlusClient.sol";
import {IVRFSubscriptionV2Plus} from "./IVRFSubscriptionV2Plus.sol";
// Interface that enables consumers of VRFCoordinatorV2Plus to be future-proof for upgrades
// This interface is supported by subsequent versions of VRFCoordinatorV2Plus
interface IVRFCoordinatorV2Plus is IVRFSubscriptionV2Plus {
/**
* @notice Request a set of random words.
* @param req - a struct containing following fields for randomness request:
* keyHash - Corresponds to a particular oracle job which uses
* that key for generating the VRF proof. Different keyHash's have different gas price
* ceilings, so you can select a specific one to bound your maximum per request cost.
* subId - The ID of the VRF subscription. Must be funded
* with the minimum subscription balance required for the selected keyHash.
* requestConfirmations - How many blocks you'd like the
* oracle to wait before responding to the request. See SECURITY CONSIDERATIONS
* for why you may want to request more. The acceptable range is
* [minimumRequestBlockConfirmations, 200].
* callbackGasLimit - How much gas you'd like to receive in your
* fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords
* may be slightly less than this amount because of gas used calling the function
* (argument decoding etc.), so you may need to request slightly more than you expect
* to have inside fulfillRandomWords. The acceptable range is
* [0, maxGasLimit]
* numWords - The number of uint256 random values you'd like to receive
* in your fulfillRandomWords callback. Note these numbers are expanded in a
* secure way by the VRFCoordinator from a single random value supplied by the oracle.
* extraArgs - abi-encoded extra args
* @return requestId - A unique identifier of the request. Can be used to match
* a request to a response in fulfillRandomWords.
*/
function requestRandomWords(
VRFV2PlusClient.RandomWordsRequest calldata req
) external returns (uint256 requestId);
}
lib/chainlink-evm/contracts/src/v0.8/vrf/dev/interfaces/IVRFMigratableConsumerV2Plus.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice The IVRFMigratableConsumerV2Plus interface defines the
/// @notice method required to be implemented by all V2Plus consumers.
/// @dev This interface is designed to be used in VRFConsumerBaseV2Plus.
interface IVRFMigratableConsumerV2Plus {
event CoordinatorSet(address vrfCoordinator);
/// @notice Sets the VRF Coordinator address
/// @notice This method should only be callable by the coordinator or contract owner
function setCoordinator(
address vrfCoordinator
) external;
}
lib/chainlink-evm/contracts/src/v0.8/vrf/dev/interfaces/IVRFSubscriptionV2Plus.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice The IVRFSubscriptionV2Plus interface defines the subscription
/// @notice related methods implemented by the V2Plus coordinator.
interface IVRFSubscriptionV2Plus {
/**
* @notice Add a consumer to a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - New consumer which can use the subscription
*/
function addConsumer(uint256 subId, address consumer) external;
/**
* @notice Remove a consumer from a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - Consumer to remove from the subscription
*/
function removeConsumer(uint256 subId, address consumer) external;
/**
* @notice Cancel a subscription
* @param subId - ID of the subscription
* @param to - Where to send the remaining LINK to
*/
function cancelSubscription(uint256 subId, address to) external;
/**
* @notice Accept subscription owner transfer.
* @param subId - ID of the subscription
* @dev will revert if original owner of subId has
* not requested that msg.sender become the new owner.
*/
function acceptSubscriptionOwnerTransfer(
uint256 subId
) external;
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @param newOwner - proposed new owner of the subscription
*/
function requestSubscriptionOwnerTransfer(uint256 subId, address newOwner) external;
/**
* @notice Create a VRF subscription.
* @return subId - A unique subscription id.
* @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.
* @dev Note to fund the subscription with LINK, use transferAndCall. For example
* @dev LINKTOKEN.transferAndCall(
* @dev address(COORDINATOR),
* @dev amount,
* @dev abi.encode(subId));
* @dev Note to fund the subscription with Native, use fundSubscriptionWithNative. Be sure
* @dev to send Native with the call, for example:
* @dev COORDINATOR.fundSubscriptionWithNative{value: amount}(subId);
*/
function createSubscription() external returns (uint256 subId);
/**
* @notice Get a VRF subscription.
* @param subId - ID of the subscription
* @return balance - LINK balance of the subscription in juels.
* @return nativeBalance - native balance of the subscription in wei.
* @return reqCount - Requests count of subscription.
* @return owner - owner of the subscription.
* @return consumers - list of consumer address which are able to use this subscription.
*/
function getSubscription(
uint256 subId
)
external
view
returns (uint96 balance, uint96 nativeBalance, uint64 reqCount, address owner, address[] memory consumers);
/*
* @notice Check to see if there exists a request commitment consumers
* for all consumers and keyhashes for a given sub.
* @param subId - ID of the subscription
* @return true if there exists at least one unfulfilled request for the subscription, false
* otherwise.
*/
function pendingRequestExists(
uint256 subId
) external view returns (bool);
/**
* @notice Paginate through all active VRF subscriptions.
* @param startIndex index of the subscription to start from
* @param maxCount maximum number of subscriptions to return, 0 to return all
* @dev the order of IDs in the list is **not guaranteed**, therefore, if making successive calls, one
* @dev should consider keeping the blockheight constant to ensure a holistic picture of the contract state
*/
function getActiveSubscriptionIds(uint256 startIndex, uint256 maxCount) external view returns (uint256[] memory);
/**
* @notice Fund a subscription with native.
* @param subId - ID of the subscription
* @notice This method expects msg.value to be greater than or equal to 0.
*/
function fundSubscriptionWithNative(
uint256 subId
) external payable;
}
lib/chainlink-evm/contracts/src/v0.8/vrf/dev/libraries/VRFV2PlusClient.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
// End consumer library.
library VRFV2PlusClient {
// extraArgs will evolve to support new features
bytes4 public constant EXTRA_ARGS_V1_TAG = bytes4(keccak256("VRF ExtraArgsV1"));
struct ExtraArgsV1 {
bool nativePayment;
}
struct RandomWordsRequest {
bytes32 keyHash;
uint256 subId;
uint16 requestConfirmations;
uint32 callbackGasLimit;
uint32 numWords;
bytes extraArgs;
}
function _argsToBytes(
ExtraArgsV1 memory extraArgs
) internal pure returns (bytes memory bts) {
return abi.encodeWithSelector(EXTRA_ARGS_V1_TAG, extraArgs);
}
}
lib/solady/src/auth/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The caller is not authorized to call the function.
error Unauthorized();
/// @dev The `newOwner` cannot be the zero address.
error NewOwnerIsZeroAddress();
/// @dev The `pendingOwner` does not have a valid handover request.
error NoHandoverRequest();
/// @dev Cannot double-initialize.
error AlreadyInitialized();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ownership is transferred from `oldOwner` to `newOwner`.
/// This event is intentionally kept the same as OpenZeppelin's Ownable to be
/// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
/// despite it not being as lightweight as a single argument event.
event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
/// @dev An ownership handover to `pendingOwner` has been requested.
event OwnershipHandoverRequested(address indexed pendingOwner);
/// @dev The ownership handover to `pendingOwner` has been canceled.
event OwnershipHandoverCanceled(address indexed pendingOwner);
/// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;
/// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;
/// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The owner slot is given by:
/// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
/// It is intentionally chosen to be a high value
/// to avoid collision with lower slots.
/// The choice of manual storage layout is to enable compatibility
/// with both regular and upgradeable contracts.
bytes32 internal constant _OWNER_SLOT =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;
/// The ownership handover slot of `newOwner` is given by:
/// ```
/// mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
/// let handoverSlot := keccak256(0x00, 0x20)
/// ```
/// It stores the expiry timestamp of the two-step ownership handover.
uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
function _guardInitializeOwner() internal pure virtual returns (bool guard) {}
/// @dev Initializes the owner directly without authorization guard.
/// This function must be called upon initialization,
/// regardless of whether the contract is upgradeable or not.
/// This is to enable generalization to both regular and upgradeable contracts,
/// and to save gas in case the initial owner is not the caller.
/// For performance reasons, this function will not check if there
/// is an existing owner.
function _initializeOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
if sload(ownerSlot) {
mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
revert(0x1c, 0x04)
}
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
} else {
/// @solidity memory-safe-assembly
assembly {
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(_OWNER_SLOT, newOwner)
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
}
}
/// @dev Sets the owner directly without authorization guard.
function _setOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
}
} else {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, newOwner)
}
}
}
/// @dev Throws if the sender is not the owner.
function _checkOwner() internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// If the caller is not the stored owner, revert.
if iszero(eq(caller(), sload(_OWNER_SLOT))) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Returns how long a two-step ownership handover is valid for in seconds.
/// Override to return a different value if needed.
/// Made internal to conserve bytecode. Wrap it in a public function if needed.
function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
return 48 * 3600;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC UPDATE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Allows the owner to transfer the ownership to `newOwner`.
function transferOwnership(address newOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
if iszero(shl(96, newOwner)) {
mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
revert(0x1c, 0x04)
}
}
_setOwner(newOwner);
}
/// @dev Allows the owner to renounce their ownership.
function renounceOwnership() public payable virtual onlyOwner {
_setOwner(address(0));
}
/// @dev Request a two-step ownership handover to the caller.
/// The request will automatically expire in 48 hours (172800 seconds) by default.
function requestOwnershipHandover() public payable virtual {
unchecked {
uint256 expires = block.timestamp + _ownershipHandoverValidFor();
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to `expires`.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), expires)
// Emit the {OwnershipHandoverRequested} event.
log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
}
}
}
/// @dev Cancels the two-step ownership handover to the caller, if any.
function cancelOwnershipHandover() public payable virtual {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), 0)
// Emit the {OwnershipHandoverCanceled} event.
log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
}
}
/// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
/// Reverts if there is no existing ownership handover requested by `pendingOwner`.
function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
let handoverSlot := keccak256(0x0c, 0x20)
// If the handover does not exist, or has expired.
if gt(timestamp(), sload(handoverSlot)) {
mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
revert(0x1c, 0x04)
}
// Set the handover slot to 0.
sstore(handoverSlot, 0)
}
_setOwner(pendingOwner);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC READ FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the owner of the contract.
function owner() public view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_OWNER_SLOT)
}
}
/// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
function ownershipHandoverExpiresAt(address pendingOwner)
public
view
virtual
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
// Compute the handover slot.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
// Load the handover slot.
result := sload(keccak256(0x0c, 0x20))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* MODIFIERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Marks a function as only callable by the owner.
modifier onlyOwner() virtual {
_checkOwner();
_;
}
}
lib/solady/src/tokens/ERC2981.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple ERC2981 NFT Royalty Standard implementation.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC2981.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/common/ERC2981.sol)
abstract contract ERC2981 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The royalty fee numerator exceeds the fee denominator.
error RoyaltyOverflow();
/// @dev The royalty receiver cannot be the zero address.
error RoyaltyReceiverIsZeroAddress();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The default royalty info is given by:
/// ```
/// let packed := sload(_ERC2981_MASTER_SLOT_SEED)
/// let receiver := shr(96, packed)
/// let royaltyFraction := xor(packed, shl(96, receiver))
/// ```
///
/// The per token royalty info is given by.
/// ```
/// mstore(0x00, tokenId)
/// mstore(0x20, _ERC2981_MASTER_SLOT_SEED)
/// let packed := sload(keccak256(0x00, 0x40))
/// let receiver := shr(96, packed)
/// let royaltyFraction := xor(packed, shl(96, receiver))
/// ```
uint256 private constant _ERC2981_MASTER_SLOT_SEED = 0xaa4ec00224afccfdb7;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC2981 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Checks that `_feeDenominator` is non-zero.
constructor() {
require(_feeDenominator() != 0, "Fee denominator cannot be zero.");
}
/// @dev Returns the denominator for the royalty amount.
/// Defaults to 10000, which represents fees in basis points.
/// Override this function to return a custom amount if needed.
function _feeDenominator() internal pure virtual returns (uint96) {
return 10000;
}
/// @dev Returns true if this contract implements the interface defined by `interfaceId`.
/// See: https://eips.ethereum.org/EIPS/eip-165
/// This function call must use less than 30000 gas.
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
let s := shr(224, interfaceId)
// ERC165: 0x01ffc9a7, ERC2981: 0x2a55205a.
result := or(eq(s, 0x01ffc9a7), eq(s, 0x2a55205a))
}
}
/// @dev Returns the `receiver` and `royaltyAmount` for `tokenId` sold at `salePrice`.
function royaltyInfo(uint256 tokenId, uint256 salePrice)
public
view
virtual
returns (address receiver, uint256 royaltyAmount)
{
uint256 feeDenominator = _feeDenominator();
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, tokenId)
mstore(0x20, _ERC2981_MASTER_SLOT_SEED)
let packed := sload(keccak256(0x00, 0x40))
receiver := shr(96, packed)
if iszero(receiver) {
packed := sload(mload(0x20))
receiver := shr(96, packed)
}
let x := salePrice
let y := xor(packed, shl(96, receiver)) // `feeNumerator`.
// Overflow check, equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
// Out-of-gas revert. Should not be triggered in practice, but included for safety.
returndatacopy(returndatasize(), returndatasize(), mul(y, gt(x, div(not(0), y))))
royaltyAmount := div(mul(x, y), feeDenominator)
}
}
/// @dev Sets the default royalty `receiver` and `feeNumerator`.
///
/// Requirements:
/// - `receiver` must not be the zero address.
/// - `feeNumerator` must not be greater than the fee denominator.
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
uint256 feeDenominator = _feeDenominator();
/// @solidity memory-safe-assembly
assembly {
feeNumerator := shr(160, shl(160, feeNumerator))
if gt(feeNumerator, feeDenominator) {
mstore(0x00, 0x350a88b3) // `RoyaltyOverflow()`.
revert(0x1c, 0x04)
}
let packed := shl(96, receiver)
if iszero(packed) {
mstore(0x00, 0xb4457eaa) // `RoyaltyReceiverIsZeroAddress()`.
revert(0x1c, 0x04)
}
sstore(_ERC2981_MASTER_SLOT_SEED, or(packed, feeNumerator))
}
}
/// @dev Sets the default royalty `receiver` and `feeNumerator` to zero.
function _deleteDefaultRoyalty() internal virtual {
/// @solidity memory-safe-assembly
assembly {
sstore(_ERC2981_MASTER_SLOT_SEED, 0)
}
}
/// @dev Sets the royalty `receiver` and `feeNumerator` for `tokenId`.
///
/// Requirements:
/// - `receiver` must not be the zero address.
/// - `feeNumerator` must not be greater than the fee denominator.
function _setTokenRoyalty(uint256 tokenId, address receiver, uint96 feeNumerator)
internal
virtual
{
uint256 feeDenominator = _feeDenominator();
/// @solidity memory-safe-assembly
assembly {
feeNumerator := shr(160, shl(160, feeNumerator))
if gt(feeNumerator, feeDenominator) {
mstore(0x00, 0x350a88b3) // `RoyaltyOverflow()`.
revert(0x1c, 0x04)
}
let packed := shl(96, receiver)
if iszero(packed) {
mstore(0x00, 0xb4457eaa) // `RoyaltyReceiverIsZeroAddress()`.
revert(0x1c, 0x04)
}
mstore(0x00, tokenId)
mstore(0x20, _ERC2981_MASTER_SLOT_SEED)
sstore(keccak256(0x00, 0x40), or(packed, feeNumerator))
}
}
/// @dev Sets the royalty `receiver` and `feeNumerator` for `tokenId` to zero.
function _resetTokenRoyalty(uint256 tokenId) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, tokenId)
mstore(0x20, _ERC2981_MASTER_SLOT_SEED)
sstore(keccak256(0x00, 0x40), 0)
}
}
}
lib/solady/src/tokens/ERC721.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple ERC721 implementation with storage hitchhiking.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC721.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC721/ERC721.sol)
///
/// @dev Note:
/// - The ERC721 standard allows for self-approvals.
/// For performance, this implementation WILL NOT revert for such actions.
/// Please add any checks with overrides if desired.
/// - For performance, methods are made payable where permitted by the ERC721 standard.
/// - The `safeTransfer` functions use the identity precompile (0x4)
/// to copy memory internally.
///
/// If you are overriding:
/// - NEVER violate the ERC721 invariant:
/// the balance of an owner MUST always be equal to their number of ownership slots.
/// The transfer functions do not have an underflow guard for user token balances.
/// - Make sure all variables written to storage are properly cleaned
/// (e.g. the bool value for `isApprovedForAll` MUST be either 1 or 0 under the hood).
/// - Check that the overridden function is actually used in the function you want to
/// change the behavior of. Much of the code has been manually inlined for performance.
abstract contract ERC721 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev An account can hold up to 4294967295 tokens.
uint256 internal constant _MAX_ACCOUNT_BALANCE = 0xffffffff;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Only the token owner or an approved account can manage the token.
error NotOwnerNorApproved();
/// @dev The token does not exist.
error TokenDoesNotExist();
/// @dev The token already exists.
error TokenAlreadyExists();
/// @dev Cannot query the balance for the zero address.
error BalanceQueryForZeroAddress();
/// @dev Cannot mint or transfer to the zero address.
error TransferToZeroAddress();
/// @dev The token must be owned by `from`.
error TransferFromIncorrectOwner();
/// @dev The recipient's balance has overflowed.
error AccountBalanceOverflow();
/// @dev Cannot safely transfer to a contract that does not implement
/// the ERC721Receiver interface.
error TransferToNonERC721ReceiverImplementer();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Emitted when token `id` is transferred from `from` to `to`.
event Transfer(address indexed from, address indexed to, uint256 indexed id);
/// @dev Emitted when `owner` enables `account` to manage the `id` token.
event Approval(address indexed owner, address indexed account, uint256 indexed id);
/// @dev Emitted when `owner` enables or disables `operator` to manage all of their tokens.
event ApprovalForAll(address indexed owner, address indexed operator, bool isApproved);
/// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`.
uint256 private constant _TRANSFER_EVENT_SIGNATURE =
0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
/// @dev `keccak256(bytes("Approval(address,address,uint256)"))`.
uint256 private constant _APPROVAL_EVENT_SIGNATURE =
0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;
/// @dev `keccak256(bytes("ApprovalForAll(address,address,bool)"))`.
uint256 private constant _APPROVAL_FOR_ALL_EVENT_SIGNATURE =
0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ownership data slot of `id` is given by:
/// ```
/// mstore(0x00, id)
/// mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
/// let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
/// ```
/// Bits Layout:
/// - [0..159] `addr`
/// - [160..255] `extraData`
///
/// The approved address slot is given by: `add(1, ownershipSlot)`.
///
/// See: https://notes.ethereum.org/%40vbuterin/verkle_tree_eip
///
/// The balance slot of `owner` is given by:
/// ```
/// mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
/// mstore(0x00, owner)
/// let balanceSlot := keccak256(0x0c, 0x1c)
/// ```
/// Bits Layout:
/// - [0..31] `balance`
/// - [32..255] `aux`
///
/// The `operator` approval slot of `owner` is given by:
/// ```
/// mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, operator))
/// mstore(0x00, owner)
/// let operatorApprovalSlot := keccak256(0x0c, 0x30)
/// ```
uint256 private constant _ERC721_MASTER_SLOT_SEED = 0x7d8825530a5a2e7a << 192;
/// @dev Pre-shifted and pre-masked constant.
uint256 private constant _ERC721_MASTER_SLOT_SEED_MASKED = 0x0a5a2e7a00000000;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC721 METADATA */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the token collection name.
function name() public view virtual returns (string memory);
/// @dev Returns the token collection symbol.
function symbol() public view virtual returns (string memory);
/// @dev Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) public view virtual returns (string memory);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC721 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the owner of token `id`.
///
/// Requirements:
/// - Token `id` must exist.
function ownerOf(uint256 id) public view virtual returns (address result) {
result = _ownerOf(id);
/// @solidity memory-safe-assembly
assembly {
if iszero(result) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Returns the number of tokens owned by `owner`.
///
/// Requirements:
/// - `owner` must not be the zero address.
function balanceOf(address owner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
// Revert if the `owner` is the zero address.
if iszero(owner) {
mstore(0x00, 0x8f4eb604) // `BalanceQueryForZeroAddress()`.
revert(0x1c, 0x04)
}
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
mstore(0x00, owner)
result := and(sload(keccak256(0x0c, 0x1c)), _MAX_ACCOUNT_BALANCE)
}
}
/// @dev Returns the account approved to manage token `id`.
///
/// Requirements:
/// - Token `id` must exist.
function getApproved(uint256 id) public view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
if iszero(shl(96, sload(ownershipSlot))) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
result := sload(add(1, ownershipSlot))
}
}
/// @dev Sets `account` as the approved account to manage token `id`.
///
/// Requirements:
/// - Token `id` must exist.
/// - The caller must be the owner of the token,
/// or an approved operator for the token owner.
///
/// Emits an {Approval} event.
function approve(address account, uint256 id) public payable virtual {
_approve(msg.sender, account, id);
}
/// @dev Returns whether `operator` is approved to manage the tokens of `owner`.
function isApprovedForAll(address owner, address operator)
public
view
virtual
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x1c, operator)
mstore(0x08, _ERC721_MASTER_SLOT_SEED_MASKED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x30))
}
}
/// @dev Sets whether `operator` is approved to manage the tokens of the caller.
///
/// Emits an {ApprovalForAll} event.
function setApprovalForAll(address operator, bool isApproved) public virtual {
/// @solidity memory-safe-assembly
assembly {
// Convert to 0 or 1.
isApproved := iszero(iszero(isApproved))
// Update the `isApproved` for (`msg.sender`, `operator`).
mstore(0x1c, operator)
mstore(0x08, _ERC721_MASTER_SLOT_SEED_MASKED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x30), isApproved)
// Emit the {ApprovalForAll} event.
mstore(0x00, isApproved)
// forgefmt: disable-next-item
log3(0x00, 0x20, _APPROVAL_FOR_ALL_EVENT_SIGNATURE, caller(), shr(96, shl(96, operator)))
}
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - The caller must be the owner of the token, or be approved to manage the token.
///
/// Emits a {Transfer} event.
function transferFrom(address from, address to, uint256 id) public payable virtual {
_beforeTokenTransfer(from, to, id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
let bitmaskAddress := shr(96, not(0))
from := and(bitmaskAddress, from)
to := and(bitmaskAddress, to)
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, caller()))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let ownershipPacked := sload(ownershipSlot)
let owner := and(bitmaskAddress, ownershipPacked)
// Revert if the token does not exist, or if `from` is not the owner.
if iszero(mul(owner, eq(owner, from))) {
// `TokenDoesNotExist()`, `TransferFromIncorrectOwner()`.
mstore(shl(2, iszero(owner)), 0xceea21b6a1148100)
revert(0x1c, 0x04)
}
// Load, check, and update the token approval.
{
mstore(0x00, from)
let approvedAddress := sload(add(1, ownershipSlot))
// Revert if the caller is not the owner, nor approved.
if iszero(or(eq(caller(), from), eq(caller(), approvedAddress))) {
if iszero(sload(keccak256(0x0c, 0x30))) {
mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
revert(0x1c, 0x04)
}
}
// Delete the approved address if any.
if approvedAddress { sstore(add(1, ownershipSlot), 0) }
}
// Update with the new owner.
sstore(ownershipSlot, xor(ownershipPacked, xor(from, to)))
// Decrement the balance of `from`.
{
let fromBalanceSlot := keccak256(0x0c, 0x1c)
sstore(fromBalanceSlot, sub(sload(fromBalanceSlot), 1))
}
// Increment the balance of `to`.
{
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x1c)
let toBalanceSlotPacked := add(sload(toBalanceSlot), 1)
// Revert if `to` is the zero address, or if the account balance overflows.
if iszero(mul(to, and(toBalanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
// `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
mstore(shl(2, iszero(to)), 0xea553b3401336cea)
revert(0x1c, 0x04)
}
sstore(toBalanceSlot, toBalanceSlotPacked)
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, from, to, id)
}
_afterTokenTransfer(from, to, id);
}
/// @dev Equivalent to `safeTransferFrom(from, to, id, "")`.
function safeTransferFrom(address from, address to, uint256 id) public payable virtual {
transferFrom(from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, "");
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - The caller must be the owner of the token, or be approved to manage the token.
/// - If `to` refers to a smart contract, it must implement
/// {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
///
/// Emits a {Transfer} event.
function safeTransferFrom(address from, address to, uint256 id, bytes calldata data)
public
payable
virtual
{
transferFrom(from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);
}
/// @dev Returns true if this contract implements the interface defined by `interfaceId`.
/// See: https://eips.ethereum.org/EIPS/eip-165
/// This function call must use less than 30000 gas.
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
let s := shr(224, interfaceId)
// ERC165: 0x01ffc9a7, ERC721: 0x80ac58cd, ERC721Metadata: 0x5b5e139f.
result := or(or(eq(s, 0x01ffc9a7), eq(s, 0x80ac58cd)), eq(s, 0x5b5e139f))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL QUERY FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns if token `id` exists.
function _exists(uint256 id) internal view virtual returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
result := iszero(iszero(shl(96, sload(add(id, add(id, keccak256(0x00, 0x20)))))))
}
}
/// @dev Returns the owner of token `id`.
/// Returns the zero address instead of reverting if the token does not exist.
function _ownerOf(uint256 id) internal view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
result := shr(96, shl(96, sload(add(id, add(id, keccak256(0x00, 0x20))))))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL DATA HITCHHIKING FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// For performance, no events are emitted for the hitchhiking setters.
// Please emit your own events if required.
/// @dev Returns the auxiliary data for `owner`.
/// Minting, transferring, burning the tokens of `owner` will not change the auxiliary data.
/// Auxiliary data can be set for any address, even if it does not have any tokens.
function _getAux(address owner) internal view virtual returns (uint224 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
mstore(0x00, owner)
result := shr(32, sload(keccak256(0x0c, 0x1c)))
}
}
/// @dev Set the auxiliary data for `owner` to `value`.
/// Minting, transferring, burning the tokens of `owner` will not change the auxiliary data.
/// Auxiliary data can be set for any address, even if it does not have any tokens.
function _setAux(address owner, uint224 value) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
mstore(0x00, owner)
let balanceSlot := keccak256(0x0c, 0x1c)
let packed := sload(balanceSlot)
sstore(balanceSlot, xor(packed, shl(32, xor(value, shr(32, packed)))))
}
}
/// @dev Returns the extra data for token `id`.
/// Minting, transferring, burning a token will not change the extra data.
/// The extra data can be set on a non-existent token.
function _getExtraData(uint256 id) internal view virtual returns (uint96 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
result := shr(160, sload(add(id, add(id, keccak256(0x00, 0x20)))))
}
}
/// @dev Sets the extra data for token `id` to `value`.
/// Minting, transferring, burning a token will not change the extra data.
/// The extra data can be set on a non-existent token.
function _setExtraData(uint256 id, uint96 value) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let packed := sload(ownershipSlot)
sstore(ownershipSlot, xor(packed, shl(160, xor(value, shr(160, packed)))))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL MINT FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Mints token `id` to `to`.
///
/// Requirements:
///
/// - Token `id` must not exist.
/// - `to` cannot be the zero address.
///
/// Emits a {Transfer} event.
function _mint(address to, uint256 id) internal virtual {
_beforeTokenTransfer(address(0), to, id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
to := shr(96, shl(96, to))
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let ownershipPacked := sload(ownershipSlot)
// Revert if the token already exists.
if shl(96, ownershipPacked) {
mstore(0x00, 0xc991cbb1) // `TokenAlreadyExists()`.
revert(0x1c, 0x04)
}
// Update with the owner.
sstore(ownershipSlot, or(ownershipPacked, to))
// Increment the balance of the owner.
{
mstore(0x00, to)
let balanceSlot := keccak256(0x0c, 0x1c)
let balanceSlotPacked := add(sload(balanceSlot), 1)
// Revert if `to` is the zero address, or if the account balance overflows.
if iszero(mul(to, and(balanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
// `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
mstore(shl(2, iszero(to)), 0xea553b3401336cea)
revert(0x1c, 0x04)
}
sstore(balanceSlot, balanceSlotPacked)
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, 0, to, id)
}
_afterTokenTransfer(address(0), to, id);
}
/// @dev Mints token `id` to `to`, and updates the extra data for token `id` to `value`.
/// Does NOT check if token `id` already exists (assumes `id` is auto-incrementing).
///
/// Requirements:
///
/// - `to` cannot be the zero address.
///
/// Emits a {Transfer} event.
function _mintAndSetExtraDataUnchecked(address to, uint256 id, uint96 value) internal virtual {
_beforeTokenTransfer(address(0), to, id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
to := shr(96, shl(96, to))
// Update with the owner and extra data.
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
sstore(add(id, add(id, keccak256(0x00, 0x20))), or(shl(160, value), to))
// Increment the balance of the owner.
{
mstore(0x00, to)
let balanceSlot := keccak256(0x0c, 0x1c)
let balanceSlotPacked := add(sload(balanceSlot), 1)
// Revert if `to` is the zero address, or if the account balance overflows.
if iszero(mul(to, and(balanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
// `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
mstore(shl(2, iszero(to)), 0xea553b3401336cea)
revert(0x1c, 0x04)
}
sstore(balanceSlot, balanceSlotPacked)
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, 0, to, id)
}
_afterTokenTransfer(address(0), to, id);
}
/// @dev Equivalent to `_safeMint(to, id, "")`.
function _safeMint(address to, uint256 id) internal virtual {
_safeMint(to, id, "");
}
/// @dev Mints token `id` to `to`.
///
/// Requirements:
///
/// - Token `id` must not exist.
/// - `to` cannot be the zero address.
/// - If `to` refers to a smart contract, it must implement
/// {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
///
/// Emits a {Transfer} event.
function _safeMint(address to, uint256 id, bytes memory data) internal virtual {
_mint(to, id);
if (_hasCode(to)) _checkOnERC721Received(address(0), to, id, data);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL BURN FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `_burn(address(0), id)`.
function _burn(uint256 id) internal virtual {
_burn(address(0), id);
}
/// @dev Destroys token `id`, using `by`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - If `by` is not the zero address,
/// it must be the owner of the token, or be approved to manage the token.
///
/// Emits a {Transfer} event.
function _burn(address by, uint256 id) internal virtual {
address owner = ownerOf(id);
_beforeTokenTransfer(owner, address(0), id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
by := shr(96, shl(96, by))
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let ownershipPacked := sload(ownershipSlot)
// Reload the owner in case it is changed in `_beforeTokenTransfer`.
owner := shr(96, shl(96, ownershipPacked))
// Revert if the token does not exist.
if iszero(owner) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
// Load and check the token approval.
{
mstore(0x00, owner)
let approvedAddress := sload(add(1, ownershipSlot))
// If `by` is not the zero address, do the authorization check.
// Revert if the `by` is not the owner, nor approved.
if iszero(or(iszero(by), or(eq(by, owner), eq(by, approvedAddress)))) {
if iszero(sload(keccak256(0x0c, 0x30))) {
mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
revert(0x1c, 0x04)
}
}
// Delete the approved address if any.
if approvedAddress { sstore(add(1, ownershipSlot), 0) }
}
// Clear the owner.
sstore(ownershipSlot, xor(ownershipPacked, owner))
// Decrement the balance of `owner`.
{
let balanceSlot := keccak256(0x0c, 0x1c)
sstore(balanceSlot, sub(sload(balanceSlot), 1))
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, owner, 0, id)
}
_afterTokenTransfer(owner, address(0), id);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL APPROVAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns whether `account` is the owner of token `id`, or is approved to manage it.
///
/// Requirements:
/// - Token `id` must exist.
function _isApprovedOrOwner(address account, uint256 id)
internal
view
virtual
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
result := 1
// Clear the upper 96 bits.
account := shr(96, shl(96, account))
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, account))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let owner := shr(96, shl(96, sload(ownershipSlot)))
// Revert if the token does not exist.
if iszero(owner) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
// Check if `account` is the `owner`.
if iszero(eq(account, owner)) {
mstore(0x00, owner)
// Check if `account` is approved to manage the token.
if iszero(sload(keccak256(0x0c, 0x30))) {
result := eq(account, sload(add(1, ownershipSlot)))
}
}
}
}
/// @dev Returns the account approved to manage token `id`.
/// Returns the zero address instead of reverting if the token does not exist.
function _getApproved(uint256 id) internal view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
result := sload(add(1, add(id, add(id, keccak256(0x00, 0x20)))))
}
}
/// @dev Equivalent to `_approve(address(0), account, id)`.
function _approve(address account, uint256 id) internal virtual {
_approve(address(0), account, id);
}
/// @dev Sets `account` as the approved account to manage token `id`, using `by`.
///
/// Requirements:
/// - Token `id` must exist.
/// - If `by` is not the zero address, `by` must be the owner
/// or an approved operator for the token owner.
///
/// Emits a {Approval} event.
function _approve(address by, address account, uint256 id) internal virtual {
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
let bitmaskAddress := shr(96, not(0))
account := and(bitmaskAddress, account)
by := and(bitmaskAddress, by)
// Load the owner of the token.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let owner := and(bitmaskAddress, sload(ownershipSlot))
// Revert if the token does not exist.
if iszero(owner) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
// If `by` is not the zero address, do the authorization check.
// Revert if `by` is not the owner, nor approved.
if iszero(or(iszero(by), eq(by, owner))) {
mstore(0x00, owner)
if iszero(sload(keccak256(0x0c, 0x30))) {
mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
revert(0x1c, 0x04)
}
}
// Sets `account` as the approved account to manage `id`.
sstore(add(1, ownershipSlot), account)
// Emit the {Approval} event.
log4(codesize(), 0x00, _APPROVAL_EVENT_SIGNATURE, owner, account, id)
}
}
/// @dev Approve or remove the `operator` as an operator for `by`,
/// without authorization checks.
///
/// Emits an {ApprovalForAll} event.
function _setApprovalForAll(address by, address operator, bool isApproved) internal virtual {
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
by := shr(96, shl(96, by))
operator := shr(96, shl(96, operator))
// Convert to 0 or 1.
isApproved := iszero(iszero(isApproved))
// Update the `isApproved` for (`by`, `operator`).
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, operator))
mstore(0x00, by)
sstore(keccak256(0x0c, 0x30), isApproved)
// Emit the {ApprovalForAll} event.
mstore(0x00, isApproved)
log3(0x00, 0x20, _APPROVAL_FOR_ALL_EVENT_SIGNATURE, by, operator)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL TRANSFER FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `_transfer(address(0), from, to, id)`.
function _transfer(address from, address to, uint256 id) internal virtual {
_transfer(address(0), from, to, id);
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - If `by` is not the zero address,
/// it must be the owner of the token, or be approved to manage the token.
///
/// Emits a {Transfer} event.
function _transfer(address by, address from, address to, uint256 id) internal virtual {
_beforeTokenTransfer(from, to, id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
let bitmaskAddress := shr(96, not(0))
from := and(bitmaskAddress, from)
to := and(bitmaskAddress, to)
by := and(bitmaskAddress, by)
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let ownershipPacked := sload(ownershipSlot)
let owner := and(bitmaskAddress, ownershipPacked)
// Revert if the token does not exist, or if `from` is not the owner.
if iszero(mul(owner, eq(owner, from))) {
// `TokenDoesNotExist()`, `TransferFromIncorrectOwner()`.
mstore(shl(2, iszero(owner)), 0xceea21b6a1148100)
revert(0x1c, 0x04)
}
// Load, check, and update the token approval.
{
mstore(0x00, from)
let approvedAddress := sload(add(1, ownershipSlot))
// If `by` is not the zero address, do the authorization check.
// Revert if the `by` is not the owner, nor approved.
if iszero(or(iszero(by), or(eq(by, from), eq(by, approvedAddress)))) {
if iszero(sload(keccak256(0x0c, 0x30))) {
mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
revert(0x1c, 0x04)
}
}
// Delete the approved address if any.
if approvedAddress { sstore(add(1, ownershipSlot), 0) }
}
// Update with the new owner.
sstore(ownershipSlot, xor(ownershipPacked, xor(from, to)))
// Decrement the balance of `from`.
{
let fromBalanceSlot := keccak256(0x0c, 0x1c)
sstore(fromBalanceSlot, sub(sload(fromBalanceSlot), 1))
}
// Increment the balance of `to`.
{
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x1c)
let toBalanceSlotPacked := add(sload(toBalanceSlot), 1)
// Revert if `to` is the zero address, or if the account balance overflows.
if iszero(mul(to, and(toBalanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
// `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
mstore(shl(2, iszero(to)), 0xea553b3401336cea)
revert(0x1c, 0x04)
}
sstore(toBalanceSlot, toBalanceSlotPacked)
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, from, to, id)
}
_afterTokenTransfer(from, to, id);
}
/// @dev Equivalent to `_safeTransfer(from, to, id, "")`.
function _safeTransfer(address from, address to, uint256 id) internal virtual {
_safeTransfer(from, to, id, "");
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - The caller must be the owner of the token, or be approved to manage the token.
/// - If `to` refers to a smart contract, it must implement
/// {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
///
/// Emits a {Transfer} event.
function _safeTransfer(address from, address to, uint256 id, bytes memory data)
internal
virtual
{
_transfer(address(0), from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);
}
/// @dev Equivalent to `_safeTransfer(by, from, to, id, "")`.
function _safeTransfer(address by, address from, address to, uint256 id) internal virtual {
_safeTransfer(by, from, to, id, "");
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - If `by` is not the zero address,
/// it must be the owner of the token, or be approved to manage the token.
/// - If `to` refers to a smart contract, it must implement
/// {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
///
/// Emits a {Transfer} event.
function _safeTransfer(address by, address from, address to, uint256 id, bytes memory data)
internal
virtual
{
_transfer(by, from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HOOKS FOR OVERRIDING */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Hook that is called before any token transfers, including minting and burning.
function _beforeTokenTransfer(address from, address to, uint256 id) internal virtual {}
/// @dev Hook that is called after any token transfers, including minting and burning.
function _afterTokenTransfer(address from, address to, uint256 id) internal virtual {}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns if `a` has bytecode of non-zero length.
function _hasCode(address a) private view returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := extcodesize(a) // Can handle dirty upper bits.
}
}
/// @dev Perform a call to invoke {IERC721Receiver-onERC721Received} on `to`.
/// Reverts if the target does not support the function correctly.
function _checkOnERC721Received(address from, address to, uint256 id, bytes memory data)
private
{
/// @solidity memory-safe-assembly
assembly {
// Prepare the calldata.
let m := mload(0x40)
let onERC721ReceivedSelector := 0x150b7a02
mstore(m, onERC721ReceivedSelector)
mstore(add(m, 0x20), caller()) // The `operator`, which is always `msg.sender`.
mstore(add(m, 0x40), shr(96, shl(96, from)))
mstore(add(m, 0x60), id)
mstore(add(m, 0x80), 0x80)
let n := mload(data)
mstore(add(m, 0xa0), n)
if n { pop(staticcall(gas(), 4, add(data, 0x20), n, add(m, 0xc0), n)) }
// Revert if the call reverts.
if iszero(call(gas(), to, 0, add(m, 0x1c), add(n, 0xa4), m, 0x20)) {
if returndatasize() {
// Bubble up the revert if the call reverts.
returndatacopy(m, 0x00, returndatasize())
revert(m, returndatasize())
}
}
// Load the returndata and compare it.
if iszero(eq(mload(m), shl(224, onERC721ReceivedSelector))) {
mstore(0x00, 0xd1a57ed6) // `TransferToNonERC721ReceiverImplementer()`.
revert(0x1c, 0x04)
}
}
}
}
lib/solady/src/utils/LibBytes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for byte related operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibBytes.sol)
library LibBytes {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Goated bytes storage struct that totally MOGs, no cap, fr.
/// Uses less gas and bytecode than Solidity's native bytes storage. It's meta af.
/// Packs length with the first 31 bytes if <255 bytes, so it’s mad tight.
struct BytesStorage {
bytes32 _spacer;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the bytes.
uint256 internal constant NOT_FOUND = type(uint256).max;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTE STORAGE OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sets the value of the bytes storage `$` to `s`.
function set(BytesStorage storage $, bytes memory s) internal {
/// @solidity memory-safe-assembly
assembly {
let n := mload(s)
let packed := or(0xff, shl(8, n))
for { let i := 0 } 1 {} {
if iszero(gt(n, 0xfe)) {
i := 0x1f
packed := or(n, shl(8, mload(add(s, i))))
if iszero(gt(n, i)) { break }
}
let o := add(s, 0x20)
mstore(0x00, $.slot)
for { let p := keccak256(0x00, 0x20) } 1 {} {
sstore(add(p, shr(5, i)), mload(add(o, i)))
i := add(i, 0x20)
if iszero(lt(i, n)) { break }
}
break
}
sstore($.slot, packed)
}
}
/// @dev Sets the value of the bytes storage `$` to `s`.
function setCalldata(BytesStorage storage $, bytes calldata s) internal {
/// @solidity memory-safe-assembly
assembly {
let packed := or(0xff, shl(8, s.length))
for { let i := 0 } 1 {} {
if iszero(gt(s.length, 0xfe)) {
i := 0x1f
packed := or(s.length, shl(8, shr(8, calldataload(s.offset))))
if iszero(gt(s.length, i)) { break }
}
mstore(0x00, $.slot)
for { let p := keccak256(0x00, 0x20) } 1 {} {
sstore(add(p, shr(5, i)), calldataload(add(s.offset, i)))
i := add(i, 0x20)
if iszero(lt(i, s.length)) { break }
}
break
}
sstore($.slot, packed)
}
}
/// @dev Sets the value of the bytes storage `$` to the empty bytes.
function clear(BytesStorage storage $) internal {
delete $._spacer;
}
/// @dev Returns whether the value stored is `$` is the empty bytes "".
function isEmpty(BytesStorage storage $) internal view returns (bool) {
return uint256($._spacer) & 0xff == uint256(0);
}
/// @dev Returns the length of the value stored in `$`.
function length(BytesStorage storage $) internal view returns (uint256 result) {
result = uint256($._spacer);
/// @solidity memory-safe-assembly
assembly {
let n := and(0xff, result)
result := or(mul(shr(8, result), eq(0xff, n)), mul(n, iszero(eq(0xff, n))))
}
}
/// @dev Returns the value stored in `$`.
function get(BytesStorage storage $) internal view returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let o := add(result, 0x20)
let packed := sload($.slot)
let n := shr(8, packed)
for { let i := 0 } 1 {} {
if iszero(eq(or(packed, 0xff), packed)) {
mstore(o, packed)
n := and(0xff, packed)
i := 0x1f
if iszero(gt(n, i)) { break }
}
mstore(0x00, $.slot)
for { let p := keccak256(0x00, 0x20) } 1 {} {
mstore(add(o, i), sload(add(p, shr(5, i))))
i := add(i, 0x20)
if iszero(lt(i, n)) { break }
}
break
}
mstore(result, n) // Store the length of the memory.
mstore(add(o, n), 0) // Zeroize the slot after the bytes.
mstore(0x40, add(add(o, n), 0x20)) // Allocate memory.
}
}
/// @dev Returns the uint8 at index `i`. If out-of-bounds, returns 0.
function uint8At(BytesStorage storage $, uint256 i) internal view returns (uint8 result) {
/// @solidity memory-safe-assembly
assembly {
for { let packed := sload($.slot) } 1 {} {
if iszero(eq(or(packed, 0xff), packed)) {
if iszero(gt(i, 0x1e)) {
result := byte(i, packed)
break
}
if iszero(gt(i, and(0xff, packed))) {
mstore(0x00, $.slot)
let j := sub(i, 0x1f)
result := byte(and(j, 0x1f), sload(add(keccak256(0x00, 0x20), shr(5, j))))
}
break
}
if iszero(gt(i, shr(8, packed))) {
mstore(0x00, $.slot)
result := byte(and(i, 0x1f), sload(add(keccak256(0x00, 0x20), shr(5, i))))
}
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTES OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `subject` all occurrences of `needle` replaced with `replacement`.
function replace(bytes memory subject, bytes memory needle, bytes memory replacement)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let needleLen := mload(needle)
let replacementLen := mload(replacement)
let d := sub(result, subject) // Memory difference.
let i := add(subject, 0x20) // Subject bytes pointer.
mstore(0x00, add(i, mload(subject))) // End of subject.
if iszero(gt(needleLen, mload(subject))) {
let subjectSearchEnd := add(sub(mload(0x00), needleLen), 1)
let h := 0 // The hash of `needle`.
if iszero(lt(needleLen, 0x20)) {
h := keccak256(add(needle, 0x20), needleLen)
}
let s := mload(add(needle, 0x20))
for { let m := shl(3, sub(0x20, and(needleLen, 0x1f))) } 1 {} {
let t := mload(i)
// Whether the first `needleLen % 32` bytes of `subject` and `needle` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(i, needleLen), h)) {
mstore(add(i, d), t)
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
// Copy the `replacement` one word at a time.
for { let j := 0 } 1 {} {
mstore(add(add(i, d), j), mload(add(add(replacement, 0x20), j)))
j := add(j, 0x20)
if iszero(lt(j, replacementLen)) { break }
}
d := sub(add(d, replacementLen), needleLen)
if needleLen {
i := add(i, needleLen)
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
mstore(add(i, d), t)
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
}
}
let end := mload(0x00)
let n := add(sub(d, add(result, 0x20)), end)
// Copy the rest of the bytes one word at a time.
for {} lt(i, end) { i := add(i, 0x20) } { mstore(add(i, d), mload(i)) }
let o := add(i, d)
mstore(o, 0) // Zeroize the slot after the bytes.
mstore(0x40, add(o, 0x20)) // Allocate memory.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(bytes memory subject, bytes memory needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
result := not(0) // Initialize to `NOT_FOUND`.
for { let subjectLen := mload(subject) } 1 {} {
if iszero(mload(needle)) {
result := from
if iszero(gt(from, subjectLen)) { break }
result := subjectLen
break
}
let needleLen := mload(needle)
let subjectStart := add(subject, 0x20)
subject := add(subjectStart, from)
let end := add(sub(add(subjectStart, subjectLen), needleLen), 1)
let m := shl(3, sub(0x20, and(needleLen, 0x1f)))
let s := mload(add(needle, 0x20))
if iszero(and(lt(subject, end), lt(from, subjectLen))) { break }
if iszero(lt(needleLen, 0x20)) {
for { let h := keccak256(add(needle, 0x20), needleLen) } 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
if eq(keccak256(subject, needleLen), h) {
result := sub(subject, subjectStart)
break
}
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
for {} 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
result := sub(subject, subjectStart)
break
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right, starting from `from`. Optimized for byte needles.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOfByte(bytes memory subject, bytes1 needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
result := not(0) // Initialize to `NOT_FOUND`.
if gt(mload(subject), from) {
let start := add(subject, 0x20)
let end := add(start, mload(subject))
let m := div(not(0), 255) // `0x0101 ... `.
let h := mul(byte(0, needle), m) // Replicating needle mask.
m := not(shl(7, m)) // `0x7f7f ... `.
for { let i := add(start, from) } 1 {} {
let c := xor(mload(i), h) // Load 32-byte chunk and xor with mask.
c := not(or(or(add(and(c, m), m), c), m)) // Each needle byte will be `0x80`.
if c {
c := and(not(shr(shl(3, sub(end, i)), not(0))), c) // Truncate bytes past the end.
if c {
let r := shl(7, lt(0x8421084210842108cc6318c6db6d54be, c)) // Save bytecode.
r := or(shl(6, lt(0xffffffffffffffff, shr(r, c))), r)
// forgefmt: disable-next-item
result := add(sub(i, start), shr(3, xor(byte(and(0x1f, shr(byte(24,
mul(0x02040810204081, shr(r, c))), 0x8421084210842108cc6318c6db6d54be)),
0xc0c8c8d0c8e8d0d8c8e8e0e8d0d8e0f0c8d0e8d0e0e0d8f0d0d0e0d8f8f8f8f8), r)))
break
}
}
i := add(i, 0x20)
if iszero(lt(i, end)) { break }
}
}
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right. Optimized for byte needles.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOfByte(bytes memory subject, bytes1 needle)
internal
pure
returns (uint256 result)
{
return indexOfByte(subject, needle, 0);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(bytes memory subject, bytes memory needle) internal pure returns (uint256) {
return indexOf(subject, needle, 0);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(bytes memory subject, bytes memory needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
for {} 1 {} {
result := not(0) // Initialize to `NOT_FOUND`.
let needleLen := mload(needle)
if gt(needleLen, mload(subject)) { break }
let w := result
let fromMax := sub(mload(subject), needleLen)
if iszero(gt(fromMax, from)) { from := fromMax }
let end := add(add(subject, 0x20), w)
subject := add(add(subject, 0x20), from)
if iszero(gt(subject, end)) { break }
// As this function is not too often used,
// we shall simply use keccak256 for smaller bytecode size.
for { let h := keccak256(add(needle, 0x20), needleLen) } 1 {} {
if eq(keccak256(subject, needleLen), h) {
result := sub(subject, add(end, 1))
break
}
subject := add(subject, w) // `sub(subject, 1)`.
if iszero(gt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(bytes memory subject, bytes memory needle)
internal
pure
returns (uint256)
{
return lastIndexOf(subject, needle, type(uint256).max);
}
/// @dev Returns true if `needle` is found in `subject`, false otherwise.
function contains(bytes memory subject, bytes memory needle) internal pure returns (bool) {
return indexOf(subject, needle) != NOT_FOUND;
}
/// @dev Returns whether `subject` starts with `needle`.
function startsWith(bytes memory subject, bytes memory needle)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(needle)
// Just using keccak256 directly is actually cheaper.
let t := eq(keccak256(add(subject, 0x20), n), keccak256(add(needle, 0x20), n))
result := lt(gt(n, mload(subject)), t)
}
}
/// @dev Returns whether `subject` ends with `needle`.
function endsWith(bytes memory subject, bytes memory needle)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(needle)
let notInRange := gt(n, mload(subject))
// `subject + 0x20 + max(subject.length - needle.length, 0)`.
let t := add(add(subject, 0x20), mul(iszero(notInRange), sub(mload(subject), n)))
// Just using keccak256 directly is actually cheaper.
result := gt(eq(keccak256(t, n), keccak256(add(needle, 0x20), n)), notInRange)
}
}
/// @dev Returns `subject` repeated `times`.
function repeat(bytes memory subject, uint256 times)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
let l := mload(subject) // Subject length.
if iszero(or(iszero(times), iszero(l))) {
result := mload(0x40)
subject := add(subject, 0x20)
let o := add(result, 0x20)
for {} 1 {} {
// Copy the `subject` one word at a time.
for { let j := 0 } 1 {} {
mstore(add(o, j), mload(add(subject, j)))
j := add(j, 0x20)
if iszero(lt(j, l)) { break }
}
o := add(o, l)
times := sub(times, 1)
if iszero(times) { break }
}
mstore(o, 0) // Zeroize the slot after the bytes.
mstore(0x40, add(o, 0x20)) // Allocate memory.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets.
function slice(bytes memory subject, uint256 start, uint256 end)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
let l := mload(subject) // Subject length.
if iszero(gt(l, end)) { end := l }
if iszero(gt(l, start)) { start := l }
if lt(start, end) {
result := mload(0x40)
let n := sub(end, start)
let i := add(subject, start)
let w := not(0x1f)
// Copy the `subject` one word at a time, backwards.
for { let j := and(add(n, 0x1f), w) } 1 {} {
mstore(add(result, j), mload(add(i, j)))
j := add(j, w) // `sub(j, 0x20)`.
if iszero(j) { break }
}
let o := add(add(result, 0x20), n)
mstore(o, 0) // Zeroize the slot after the bytes.
mstore(0x40, add(o, 0x20)) // Allocate memory.
mstore(result, n) // Store the length.
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the bytes.
/// `start` is a byte offset.
function slice(bytes memory subject, uint256 start)
internal
pure
returns (bytes memory result)
{
result = slice(subject, start, type(uint256).max);
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets. Faster than Solidity's native slicing.
function sliceCalldata(bytes calldata subject, uint256 start, uint256 end)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
end := xor(end, mul(xor(end, subject.length), lt(subject.length, end)))
start := xor(start, mul(xor(start, subject.length), lt(subject.length, start)))
result.offset := add(subject.offset, start)
result.length := mul(lt(start, end), sub(end, start))
}
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the bytes.
/// `start` is a byte offset. Faster than Solidity's native slicing.
function sliceCalldata(bytes calldata subject, uint256 start)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
start := xor(start, mul(xor(start, subject.length), lt(subject.length, start)))
result.offset := add(subject.offset, start)
result.length := mul(lt(start, subject.length), sub(subject.length, start))
}
}
/// @dev Reduces the size of `subject` to `n`.
/// If `n` is greater than the size of `subject`, this will be a no-op.
function truncate(bytes memory subject, uint256 n) internal pure returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := subject
mstore(mul(lt(n, mload(result)), result), n)
}
}
/// @dev Returns a copy of `subject`, with the length reduced to `n`.
/// If `n` is greater than the size of `subject`, this will be a no-op.
function truncatedCalldata(bytes calldata subject, uint256 n)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
result.offset := subject.offset
result.length := xor(n, mul(xor(n, subject.length), lt(subject.length, n)))
}
}
/// @dev Returns all the indices of `needle` in `subject`.
/// The indices are byte offsets.
function indicesOf(bytes memory subject, bytes memory needle)
internal
pure
returns (uint256[] memory result)
{
/// @solidity memory-safe-assembly
assembly {
let searchLen := mload(needle)
if iszero(gt(searchLen, mload(subject))) {
result := mload(0x40)
let i := add(subject, 0x20)
let o := add(result, 0x20)
let subjectSearchEnd := add(sub(add(i, mload(subject)), searchLen), 1)
let h := 0 // The hash of `needle`.
if iszero(lt(searchLen, 0x20)) {
h := keccak256(add(needle, 0x20), searchLen)
}
let s := mload(add(needle, 0x20))
for { let m := shl(3, sub(0x20, and(searchLen, 0x1f))) } 1 {} {
let t := mload(i)
// Whether the first `searchLen % 32` bytes of `subject` and `needle` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(i, searchLen), h)) {
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
mstore(o, sub(i, add(subject, 0x20))) // Append to `result`.
o := add(o, 0x20)
i := add(i, searchLen) // Advance `i` by `searchLen`.
if searchLen {
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
}
mstore(result, shr(5, sub(o, add(result, 0x20)))) // Store the length of `result`.
// Allocate memory for result.
// We allocate one more word, so this array can be recycled for {split}.
mstore(0x40, add(o, 0x20))
}
}
}
/// @dev Returns an arrays of bytess based on the `delimiter` inside of the `subject` bytes.
function split(bytes memory subject, bytes memory delimiter)
internal
pure
returns (bytes[] memory result)
{
uint256[] memory indices = indicesOf(subject, delimiter);
/// @solidity memory-safe-assembly
assembly {
let w := not(0x1f)
let indexPtr := add(indices, 0x20)
let indicesEnd := add(indexPtr, shl(5, add(mload(indices), 1)))
mstore(add(indicesEnd, w), mload(subject))
mstore(indices, add(mload(indices), 1))
for { let prevIndex := 0 } 1 {} {
let index := mload(indexPtr)
mstore(indexPtr, 0x60)
if iszero(eq(index, prevIndex)) {
let element := mload(0x40)
let l := sub(index, prevIndex)
mstore(element, l) // Store the length of the element.
// Copy the `subject` one word at a time, backwards.
for { let o := and(add(l, 0x1f), w) } 1 {} {
mstore(add(element, o), mload(add(add(subject, prevIndex), o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
mstore(add(add(element, 0x20), l), 0) // Zeroize the slot after the bytes.
// Allocate memory for the length and the bytes, rounded up to a multiple of 32.
mstore(0x40, add(element, and(add(l, 0x3f), w)))
mstore(indexPtr, element) // Store the `element` into the array.
}
prevIndex := add(index, mload(delimiter))
indexPtr := add(indexPtr, 0x20)
if iszero(lt(indexPtr, indicesEnd)) { break }
}
result := indices
if iszero(mload(delimiter)) {
result := add(indices, 0x20)
mstore(result, sub(mload(indices), 2))
}
}
}
/// @dev Returns a concatenated bytes of `a` and `b`.
/// Cheaper than `bytes.concat()` and does not de-align the free memory pointer.
function concat(bytes memory a, bytes memory b) internal pure returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let w := not(0x1f)
let aLen := mload(a)
// Copy `a` one word at a time, backwards.
for { let o := and(add(aLen, 0x20), w) } 1 {} {
mstore(add(result, o), mload(add(a, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let bLen := mload(b)
let output := add(result, aLen)
// Copy `b` one word at a time, backwards.
for { let o := and(add(bLen, 0x20), w) } 1 {} {
mstore(add(output, o), mload(add(b, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let totalLen := add(aLen, bLen)
let last := add(add(result, 0x20), totalLen)
mstore(last, 0) // Zeroize the slot after the bytes.
mstore(result, totalLen) // Store the length.
mstore(0x40, add(last, 0x20)) // Allocate memory.
}
}
/// @dev Returns whether `a` equals `b`.
function eq(bytes memory a, bytes memory b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
}
}
/// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small bytes.
function eqs(bytes memory a, bytes32 b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
// These should be evaluated on compile time, as far as possible.
let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
let x := not(or(m, or(b, add(m, and(b, m)))))
let r := shl(7, iszero(iszero(shr(128, x))))
r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
}
}
/// @dev Returns 0 if `a == b`, -1 if `a < b`, +1 if `a > b`.
/// If `a` == b[:a.length]`, and `a.length < b.length`, returns -1.
function cmp(bytes memory a, bytes memory b) internal pure returns (int256 result) {
/// @solidity memory-safe-assembly
assembly {
let aLen := mload(a)
let bLen := mload(b)
let n := and(xor(aLen, mul(xor(aLen, bLen), lt(bLen, aLen))), not(0x1f))
if n {
for { let i := 0x20 } 1 {} {
let x := mload(add(a, i))
let y := mload(add(b, i))
if iszero(or(xor(x, y), eq(i, n))) {
i := add(i, 0x20)
continue
}
result := sub(gt(x, y), lt(x, y))
break
}
}
// forgefmt: disable-next-item
if iszero(result) {
let l := 0x201f1e1d1c1b1a191817161514131211100f0e0d0c0b0a090807060504030201
let x := and(mload(add(add(a, 0x20), n)), shl(shl(3, byte(sub(aLen, n), l)), not(0)))
let y := and(mload(add(add(b, 0x20), n)), shl(shl(3, byte(sub(bLen, n), l)), not(0)))
result := sub(gt(x, y), lt(x, y))
if iszero(result) { result := sub(gt(aLen, bLen), lt(aLen, bLen)) }
}
}
}
/// @dev Directly returns `a` without copying.
function directReturn(bytes memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
// Assumes that the bytes does not start from the scratch space.
let retStart := sub(a, 0x20)
let retUnpaddedSize := add(mload(a), 0x40)
// Right pad with zeroes. Just in case the bytes is produced
// by a method that doesn't zero right pad.
mstore(add(retStart, retUnpaddedSize), 0)
mstore(retStart, 0x20) // Store the return offset.
// End the transaction, returning the bytes.
return(retStart, and(not(0x1f), add(0x1f, retUnpaddedSize)))
}
}
/// @dev Directly returns `a` with minimal copying.
function directReturn(bytes[] memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
let n := mload(a) // `a.length`.
let o := add(a, 0x20) // Start of elements in `a`.
let u := a // Highest memory slot.
let w := not(0x1f)
for { let i := 0 } iszero(eq(i, n)) { i := add(i, 1) } {
let c := add(o, shl(5, i)) // Location of pointer to `a[i]`.
let s := mload(c) // `a[i]`.
let l := mload(s) // `a[i].length`.
let r := and(l, 0x1f) // `a[i].length % 32`.
let z := add(0x20, and(l, w)) // Offset of last word in `a[i]` from `s`.
// If `s` comes before `o`, or `s` is not zero right padded.
if iszero(lt(lt(s, o), or(iszero(r), iszero(shl(shl(3, r), mload(add(s, z))))))) {
let m := mload(0x40)
mstore(m, l) // Copy `a[i].length`.
for {} 1 {} {
mstore(add(m, z), mload(add(s, z))) // Copy `a[i]`, backwards.
z := add(z, w) // `sub(z, 0x20)`.
if iszero(z) { break }
}
let e := add(add(m, 0x20), l)
mstore(e, 0) // Zeroize the slot after the copied bytes.
mstore(0x40, add(e, 0x20)) // Allocate memory.
s := m
}
mstore(c, sub(s, o)) // Convert to calldata offset.
let t := add(l, add(s, 0x20))
if iszero(lt(t, u)) { u := t }
}
let retStart := add(a, w) // Assumes `a` doesn't start from scratch space.
mstore(retStart, 0x20) // Store the return offset.
return(retStart, add(0x40, sub(u, retStart))) // End the transaction.
}
}
/// @dev Returns the word at `offset`, without any bounds checks.
function load(bytes memory a, uint256 offset) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(a, 0x20), offset))
}
}
/// @dev Returns the word at `offset`, without any bounds checks.
function loadCalldata(bytes calldata a, uint256 offset) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := calldataload(add(a.offset, offset))
}
}
/// @dev Returns a slice representing a static struct in the calldata. Performs bounds checks.
function staticStructInCalldata(bytes calldata a, uint256 offset)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
let l := sub(a.length, 0x20)
result.offset := add(a.offset, offset)
result.length := sub(a.length, offset)
if or(shr(64, or(l, a.offset)), gt(offset, l)) { revert(l, 0x00) }
}
}
/// @dev Returns a slice representing a dynamic struct in the calldata. Performs bounds checks.
function dynamicStructInCalldata(bytes calldata a, uint256 offset)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
let l := sub(a.length, 0x20)
let s := calldataload(add(a.offset, offset)) // Relative offset of `result` from `a.offset`.
result.offset := add(a.offset, s)
result.length := sub(a.length, s)
if or(shr(64, or(s, or(l, a.offset))), gt(offset, l)) { revert(l, 0x00) }
}
}
/// @dev Returns bytes in calldata. Performs bounds checks.
function bytesInCalldata(bytes calldata a, uint256 offset)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
let l := sub(a.length, 0x20)
let s := calldataload(add(a.offset, offset)) // Relative offset of `result` from `a.offset`.
result.offset := add(add(a.offset, s), 0x20)
result.length := calldataload(add(a.offset, s))
// forgefmt: disable-next-item
if or(shr(64, or(result.length, or(s, or(l, a.offset)))),
or(gt(add(s, result.length), l), gt(offset, l))) { revert(l, 0x00) }
}
}
/// @dev Checks if `x` is in `a`. Assumes `a` has been checked.
function checkInCalldata(bytes calldata x, bytes calldata a) internal pure {
/// @solidity memory-safe-assembly
assembly {
if or(
or(lt(x.offset, a.offset), gt(add(x.offset, x.length), add(a.length, a.offset))),
shr(64, or(x.length, x.offset))
) { revert(0x00, 0x00) }
}
}
/// @dev Checks if `x` is in `a`. Assumes `a` has been checked.
function checkInCalldata(bytes[] calldata x, bytes calldata a) internal pure {
/// @solidity memory-safe-assembly
assembly {
let e := sub(add(a.length, a.offset), 0x20)
if or(lt(x.offset, a.offset), shr(64, x.offset)) { revert(0x00, 0x00) }
for { let i := 0 } iszero(eq(x.length, i)) { i := add(i, 1) } {
let o := calldataload(add(x.offset, shl(5, i)))
let t := add(o, x.offset)
let l := calldataload(t)
if or(shr(64, or(l, o)), gt(add(t, l), e)) { revert(0x00, 0x00) }
}
}
}
/// @dev Returns empty calldata bytes. For silencing the compiler.
function emptyCalldata() internal pure returns (bytes calldata result) {
/// @solidity memory-safe-assembly
assembly {
result.length := 0
}
}
/// @dev Returns the most significant 20 bytes as an address.
function msbToAddress(bytes32 x) internal pure returns (address) {
return address(bytes20(x));
}
/// @dev Returns the least significant 20 bytes as an address.
function lsbToAddress(bytes32 x) internal pure returns (address) {
return address(uint160(uint256(x)));
}
}
lib/solady/src/utils/LibString.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {LibBytes} from "./LibBytes.sol";
/// @notice Library for converting numbers into strings and other string operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibString.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol)
///
/// @dev Note:
/// For performance and bytecode compactness, most of the string operations are restricted to
/// byte strings (7-bit ASCII), except where otherwise specified.
/// Usage of byte string operations on charsets with runes spanning two or more bytes
/// can lead to undefined behavior.
library LibString {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Goated string storage struct that totally MOGs, no cap, fr.
/// Uses less gas and bytecode than Solidity's native string storage. It's meta af.
/// Packs length with the first 31 bytes if <255 bytes, so it’s mad tight.
struct StringStorage {
bytes32 _spacer;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The length of the output is too small to contain all the hex digits.
error HexLengthInsufficient();
/// @dev The length of the string is more than 32 bytes.
error TooBigForSmallString();
/// @dev The input string must be a 7-bit ASCII.
error StringNot7BitASCII();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the string.
uint256 internal constant NOT_FOUND = type(uint256).max;
/// @dev Lookup for '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant ALPHANUMERIC_7_BIT_ASCII = 0x7fffffe07fffffe03ff000000000000;
/// @dev Lookup for 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant LETTERS_7_BIT_ASCII = 0x7fffffe07fffffe0000000000000000;
/// @dev Lookup for 'abcdefghijklmnopqrstuvwxyz'.
uint128 internal constant LOWERCASE_7_BIT_ASCII = 0x7fffffe000000000000000000000000;
/// @dev Lookup for 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant UPPERCASE_7_BIT_ASCII = 0x7fffffe0000000000000000;
/// @dev Lookup for '0123456789'.
uint128 internal constant DIGITS_7_BIT_ASCII = 0x3ff000000000000;
/// @dev Lookup for '0123456789abcdefABCDEF'.
uint128 internal constant HEXDIGITS_7_BIT_ASCII = 0x7e0000007e03ff000000000000;
/// @dev Lookup for '01234567'.
uint128 internal constant OCTDIGITS_7_BIT_ASCII = 0xff000000000000;
/// @dev Lookup for '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'.
uint128 internal constant PRINTABLE_7_BIT_ASCII = 0x7fffffffffffffffffffffff00003e00;
/// @dev Lookup for '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'.
uint128 internal constant PUNCTUATION_7_BIT_ASCII = 0x78000001f8000001fc00fffe00000000;
/// @dev Lookup for ' \t\n\r\x0b\x0c'.
uint128 internal constant WHITESPACE_7_BIT_ASCII = 0x100003e00;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRING STORAGE OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sets the value of the string storage `$` to `s`.
function set(StringStorage storage $, string memory s) internal {
LibBytes.set(bytesStorage($), bytes(s));
}
/// @dev Sets the value of the string storage `$` to `s`.
function setCalldata(StringStorage storage $, string calldata s) internal {
LibBytes.setCalldata(bytesStorage($), bytes(s));
}
/// @dev Sets the value of the string storage `$` to the empty string.
function clear(StringStorage storage $) internal {
delete $._spacer;
}
/// @dev Returns whether the value stored is `$` is the empty string "".
function isEmpty(StringStorage storage $) internal view returns (bool) {
return uint256($._spacer) & 0xff == uint256(0);
}
/// @dev Returns the length of the value stored in `$`.
function length(StringStorage storage $) internal view returns (uint256) {
return LibBytes.length(bytesStorage($));
}
/// @dev Returns the value stored in `$`.
function get(StringStorage storage $) internal view returns (string memory) {
return string(LibBytes.get(bytesStorage($)));
}
/// @dev Returns the uint8 at index `i`. If out-of-bounds, returns 0.
function uint8At(StringStorage storage $, uint256 i) internal view returns (uint8) {
return LibBytes.uint8At(bytesStorage($), i);
}
/// @dev Helper to cast `$` to a `BytesStorage`.
function bytesStorage(StringStorage storage $)
internal
pure
returns (LibBytes.BytesStorage storage casted)
{
/// @solidity memory-safe-assembly
assembly {
casted.slot := $.slot
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the base 10 decimal representation of `value`.
function toString(uint256 value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits.
result := add(mload(0x40), 0x80)
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end of the memory to calculate the length later.
let w := not(0) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
result := add(result, w) // `sub(result, 1)`.
// Store the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(result, add(48, mod(temp, 10)))
temp := div(temp, 10) // Keep dividing `temp` until zero.
if iszero(temp) { break }
}
let n := sub(end, result)
result := sub(result, 0x20) // Move the pointer 32 bytes back to make room for the length.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the base 10 decimal representation of `value`.
function toString(int256 value) internal pure returns (string memory result) {
if (value >= 0) return toString(uint256(value));
unchecked {
result = toString(~uint256(value) + 1);
}
/// @solidity memory-safe-assembly
assembly {
// We still have some spare memory space on the left,
// as we have allocated 3 words (96 bytes) for up to 78 digits.
let n := mload(result) // Load the string length.
mstore(result, 0x2d) // Store the '-' character.
result := sub(result, 1) // Move back the string pointer by a byte.
mstore(result, add(n, 1)) // Update the string length.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HEXADECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `byteCount` bytes.
/// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
/// giving a total length of `byteCount * 2 + 2` bytes.
/// Reverts if `byteCount` is too small for the output to contain all the digits.
function toHexString(uint256 value, uint256 byteCount)
internal
pure
returns (string memory result)
{
result = toHexStringNoPrefix(value, byteCount);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `byteCount` bytes.
/// The output is not prefixed with "0x" and is encoded using 2 hexadecimal digits per byte,
/// giving a total length of `byteCount * 2` bytes.
/// Reverts if `byteCount` is too small for the output to contain all the digits.
function toHexStringNoPrefix(uint256 value, uint256 byteCount)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, `byteCount * 2` bytes
// for the digits, 0x02 bytes for the prefix, and 0x20 bytes for the length.
// We add 0x20 to the total and round down to a multiple of 0x20.
// (0x20 + 0x20 + 0x02 + 0x20) = 0x62.
result := add(mload(0x40), and(add(shl(1, byteCount), 0x42), not(0x1f)))
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end to calculate the length later.
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let start := sub(result, add(byteCount, byteCount))
let w := not(1) // Tsk.
let temp := value
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for {} 1 {} {
result := add(result, w) // `sub(result, 2)`.
mstore8(add(result, 1), mload(and(temp, 15)))
mstore8(result, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(xor(result, start)) { break }
}
if temp {
mstore(0x00, 0x2194895a) // `HexLengthInsufficient()`.
revert(0x1c, 0x04)
}
let n := sub(end, result)
result := sub(result, 0x20)
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2 + 2` bytes.
function toHexString(uint256 value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x".
/// The output excludes leading "0" from the `toHexString` output.
/// `0x00: "0x0", 0x01: "0x1", 0x12: "0x12", 0x123: "0x123"`.
function toMinimalHexString(uint256 value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(result, 0x20))), 0x30) // Whether leading zero is present.
let n := add(mload(result), 2) // Compute the length.
mstore(add(result, o), 0x3078) // Store the "0x" prefix, accounting for leading zero.
result := sub(add(result, o), 2) // Move the pointer, accounting for leading zero.
mstore(result, sub(n, o)) // Store the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output excludes leading "0" from the `toHexStringNoPrefix` output.
/// `0x00: "0", 0x01: "1", 0x12: "12", 0x123: "123"`.
function toMinimalHexStringNoPrefix(uint256 value)
internal
pure
returns (string memory result)
{
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(result, 0x20))), 0x30) // Whether leading zero is present.
let n := mload(result) // Get the length.
result := add(result, o) // Move the pointer, accounting for leading zero.
mstore(result, sub(n, o)) // Store the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2` bytes.
function toHexStringNoPrefix(uint256 value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x40 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x40) is 0xa0.
result := add(mload(0x40), 0x80)
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end to calculate the length later.
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
let w := not(1) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
result := add(result, w) // `sub(result, 2)`.
mstore8(add(result, 1), mload(and(temp, 15)))
mstore8(result, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(temp) { break }
}
let n := sub(end, result)
result := sub(result, 0x20)
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x", encoded using 2 hexadecimal digits per byte,
/// and the alphabets are capitalized conditionally according to
/// https://eips.ethereum.org/EIPS/eip-55
function toHexStringChecksummed(address value) internal pure returns (string memory result) {
result = toHexString(value);
/// @solidity memory-safe-assembly
assembly {
let mask := shl(6, div(not(0), 255)) // `0b010000000100000000 ...`
let o := add(result, 0x22)
let hashed := and(keccak256(o, 40), mul(34, mask)) // `0b10001000 ... `
let t := shl(240, 136) // `0b10001000 << 240`
for { let i := 0 } 1 {} {
mstore(add(i, i), mul(t, byte(i, hashed)))
i := add(i, 1)
if eq(i, 20) { break }
}
mstore(o, xor(mload(o), shr(1, and(mload(0x00), and(mload(o), mask)))))
o := add(o, 0x20)
mstore(o, xor(mload(o), shr(1, and(mload(0x20), and(mload(o), mask)))))
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
function toHexString(address value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(address value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
// Allocate memory.
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x28 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x28) is 0x80.
mstore(0x40, add(result, 0x80))
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
result := add(result, 2)
mstore(result, 40) // Store the length.
let o := add(result, 0x20)
mstore(add(o, 40), 0) // Zeroize the slot after the string.
value := shl(96, value)
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let i := 0 } 1 {} {
let p := add(o, add(i, i))
let temp := byte(i, value)
mstore8(add(p, 1), mload(and(temp, 15)))
mstore8(p, mload(shr(4, temp)))
i := add(i, 1)
if eq(i, 20) { break }
}
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexString(bytes memory raw) internal pure returns (string memory result) {
result = toHexStringNoPrefix(raw);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(bytes memory raw) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(raw)
result := add(mload(0x40), 2) // Skip 2 bytes for the optional prefix.
mstore(result, add(n, n)) // Store the length of the output.
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
let o := add(result, 0x20)
let end := add(raw, n)
for {} iszero(eq(raw, end)) {} {
raw := add(raw, 1)
mstore8(add(o, 1), mload(and(mload(raw), 15)))
mstore8(o, mload(and(shr(4, mload(raw)), 15)))
o := add(o, 2)
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RUNE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the number of UTF characters in the string.
function runeCount(string memory s) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
if mload(s) {
mstore(0x00, div(not(0), 255))
mstore(0x20, 0x0202020202020202020202020202020202020202020202020303030304040506)
let o := add(s, 0x20)
let end := add(o, mload(s))
for { result := 1 } 1 { result := add(result, 1) } {
o := add(o, byte(0, mload(shr(250, mload(o)))))
if iszero(lt(o, end)) { break }
}
}
}
}
/// @dev Returns if this string is a 7-bit ASCII string.
/// (i.e. all characters codes are in [0..127])
function is7BitASCII(string memory s) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
let mask := shl(7, div(not(0), 255))
let n := mload(s)
if n {
let o := add(s, 0x20)
let end := add(o, n)
let last := mload(end)
mstore(end, 0)
for {} 1 {} {
if and(mask, mload(o)) {
result := 0
break
}
o := add(o, 0x20)
if iszero(lt(o, end)) { break }
}
mstore(end, last)
}
}
}
/// @dev Returns if this string is a 7-bit ASCII string,
/// AND all characters are in the `allowed` lookup.
/// Note: If `s` is empty, returns true regardless of `allowed`.
function is7BitASCII(string memory s, uint128 allowed) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
if mload(s) {
let allowed_ := shr(128, shl(128, allowed))
let o := add(s, 0x20)
for { let end := add(o, mload(s)) } 1 {} {
result := and(result, shr(byte(0, mload(o)), allowed_))
o := add(o, 1)
if iszero(and(result, lt(o, end))) { break }
}
}
}
}
/// @dev Converts the bytes in the 7-bit ASCII string `s` to
/// an allowed lookup for use in `is7BitASCII(s, allowed)`.
/// To save runtime gas, you can cache the result in an immutable variable.
function to7BitASCIIAllowedLookup(string memory s) internal pure returns (uint128 result) {
/// @solidity memory-safe-assembly
assembly {
if mload(s) {
let o := add(s, 0x20)
for { let end := add(o, mload(s)) } 1 {} {
result := or(result, shl(byte(0, mload(o)), 1))
o := add(o, 1)
if iszero(lt(o, end)) { break }
}
if shr(128, result) {
mstore(0x00, 0xc9807e0d) // `StringNot7BitASCII()`.
revert(0x1c, 0x04)
}
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// For performance and bytecode compactness, byte string operations are restricted
// to 7-bit ASCII strings. All offsets are byte offsets, not UTF character offsets.
// Usage of byte string operations on charsets with runes spanning two or more bytes
// can lead to undefined behavior.
/// @dev Returns `subject` all occurrences of `needle` replaced with `replacement`.
function replace(string memory subject, string memory needle, string memory replacement)
internal
pure
returns (string memory)
{
return string(LibBytes.replace(bytes(subject), bytes(needle), bytes(replacement)));
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(string memory subject, string memory needle, uint256 from)
internal
pure
returns (uint256)
{
return LibBytes.indexOf(bytes(subject), bytes(needle), from);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(string memory subject, string memory needle) internal pure returns (uint256) {
return LibBytes.indexOf(bytes(subject), bytes(needle), 0);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(string memory subject, string memory needle, uint256 from)
internal
pure
returns (uint256)
{
return LibBytes.lastIndexOf(bytes(subject), bytes(needle), from);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(string memory subject, string memory needle)
internal
pure
returns (uint256)
{
return LibBytes.lastIndexOf(bytes(subject), bytes(needle), type(uint256).max);
}
/// @dev Returns true if `needle` is found in `subject`, false otherwise.
function contains(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.contains(bytes(subject), bytes(needle));
}
/// @dev Returns whether `subject` starts with `needle`.
function startsWith(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.startsWith(bytes(subject), bytes(needle));
}
/// @dev Returns whether `subject` ends with `needle`.
function endsWith(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.endsWith(bytes(subject), bytes(needle));
}
/// @dev Returns `subject` repeated `times`.
function repeat(string memory subject, uint256 times) internal pure returns (string memory) {
return string(LibBytes.repeat(bytes(subject), times));
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets.
function slice(string memory subject, uint256 start, uint256 end)
internal
pure
returns (string memory)
{
return string(LibBytes.slice(bytes(subject), start, end));
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the string.
/// `start` is a byte offset.
function slice(string memory subject, uint256 start) internal pure returns (string memory) {
return string(LibBytes.slice(bytes(subject), start, type(uint256).max));
}
/// @dev Returns all the indices of `needle` in `subject`.
/// The indices are byte offsets.
function indicesOf(string memory subject, string memory needle)
internal
pure
returns (uint256[] memory)
{
return LibBytes.indicesOf(bytes(subject), bytes(needle));
}
/// @dev Returns an arrays of strings based on the `delimiter` inside of the `subject` string.
function split(string memory subject, string memory delimiter)
internal
pure
returns (string[] memory result)
{
bytes[] memory a = LibBytes.split(bytes(subject), bytes(delimiter));
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Returns a concatenated string of `a` and `b`.
/// Cheaper than `string.concat()` and does not de-align the free memory pointer.
function concat(string memory a, string memory b) internal pure returns (string memory) {
return string(LibBytes.concat(bytes(a), bytes(b)));
}
/// @dev Returns a copy of the string in either lowercase or UPPERCASE.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function toCase(string memory subject, bool toUpper)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(subject)
if n {
result := mload(0x40)
let o := add(result, 0x20)
let d := sub(subject, result)
let flags := shl(add(70, shl(5, toUpper)), 0x3ffffff)
for { let end := add(o, n) } 1 {} {
let b := byte(0, mload(add(d, o)))
mstore8(o, xor(and(shr(b, flags), 0x20), b))
o := add(o, 1)
if eq(o, end) { break }
}
mstore(result, n) // Store the length.
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
}
/// @dev Returns a string from a small bytes32 string.
/// `s` must be null-terminated, or behavior will be undefined.
function fromSmallString(bytes32 s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let n := 0
for {} // Scan for '\0'.
byte(n, s) { n := add(n, 1) } {}
mstore(result, n) // Store the length.
let o := add(result, 0x20)
mstore(o, s) // Store the bytes of the string.
mstore(add(o, n), 0) // Zeroize the slot after the string.
mstore(0x40, add(result, 0x40)) // Allocate memory.
}
}
/// @dev Returns the small string, with all bytes after the first null byte zeroized.
function normalizeSmallString(bytes32 s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
for {} // Scan for '\0'.
byte(result, s) { result := add(result, 1) } {}
mstore(0x00, s)
mstore(result, 0x00)
result := mload(0x00)
}
}
/// @dev Returns the string as a normalized null-terminated small string.
function toSmallString(string memory s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(s)
if iszero(lt(result, 33)) {
mstore(0x00, 0xec92f9a3) // `TooBigForSmallString()`.
revert(0x1c, 0x04)
}
result := shl(shl(3, sub(32, result)), mload(add(s, result)))
}
}
/// @dev Returns a lowercased copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function lower(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, false);
}
/// @dev Returns an UPPERCASED copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function upper(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, true);
}
/// @dev Escapes the string to be used within HTML tags.
function escapeHTML(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let end := add(s, mload(s))
let o := add(result, 0x20)
// Store the bytes of the packed offsets and strides into the scratch space.
// `packed = (stride << 5) | offset`. Max offset is 20. Max stride is 6.
mstore(0x1f, 0x900094)
mstore(0x08, 0xc0000000a6ab)
// Store ""&'<>" into the scratch space.
mstore(0x00, shl(64, 0x2671756f743b26616d703b262333393b266c743b2667743b))
for {} iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
// Not in `["\"","'","&","<",">"]`.
if iszero(and(shl(c, 1), 0x500000c400000000)) {
mstore8(o, c)
o := add(o, 1)
continue
}
let t := shr(248, mload(c))
mstore(o, mload(and(t, 0x1f)))
o := add(o, shr(5, t))
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
/// If `addDoubleQuotes` is true, the result will be enclosed in double-quotes.
function escapeJSON(string memory s, bool addDoubleQuotes)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let o := add(result, 0x20)
if addDoubleQuotes {
mstore8(o, 34)
o := add(1, o)
}
// Store "\\u0000" in scratch space.
// Store "0123456789abcdef" in scratch space.
// Also, store `{0x08:"b", 0x09:"t", 0x0a:"n", 0x0c:"f", 0x0d:"r"}`.
// into the scratch space.
mstore(0x15, 0x5c75303030303031323334353637383961626364656662746e006672)
// Bitmask for detecting `["\"","\\"]`.
let e := or(shl(0x22, 1), shl(0x5c, 1))
for { let end := add(s, mload(s)) } iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
if iszero(lt(c, 0x20)) {
if iszero(and(shl(c, 1), e)) {
// Not in `["\"","\\"]`.
mstore8(o, c)
o := add(o, 1)
continue
}
mstore8(o, 0x5c) // "\\".
mstore8(add(o, 1), c)
o := add(o, 2)
continue
}
if iszero(and(shl(c, 1), 0x3700)) {
// Not in `["\b","\t","\n","\f","\d"]`.
mstore8(0x1d, mload(shr(4, c))) // Hex value.
mstore8(0x1e, mload(and(c, 15))) // Hex value.
mstore(o, mload(0x19)) // "\\u00XX".
o := add(o, 6)
continue
}
mstore8(o, 0x5c) // "\\".
mstore8(add(o, 1), mload(add(c, 8)))
o := add(o, 2)
}
if addDoubleQuotes {
mstore8(o, 34)
o := add(1, o)
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
function escapeJSON(string memory s) internal pure returns (string memory result) {
result = escapeJSON(s, false);
}
/// @dev Encodes `s` so that it can be safely used in a URI,
/// just like `encodeURIComponent` in JavaScript.
/// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
/// See: https://datatracker.ietf.org/doc/html/rfc2396
/// See: https://datatracker.ietf.org/doc/html/rfc3986
function encodeURIComponent(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
// Store "0123456789ABCDEF" in scratch space.
// Uppercased to be consistent with JavaScript's implementation.
mstore(0x0f, 0x30313233343536373839414243444546)
let o := add(result, 0x20)
for { let end := add(s, mload(s)) } iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
// If not in `[0-9A-Z-a-z-_.!~*'()]`.
if iszero(and(1, shr(c, 0x47fffffe87fffffe03ff678200000000))) {
mstore8(o, 0x25) // '%'.
mstore8(add(o, 1), mload(and(shr(4, c), 15)))
mstore8(add(o, 2), mload(and(c, 15)))
o := add(o, 3)
continue
}
mstore8(o, c)
o := add(o, 1)
}
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Returns whether `a` equals `b`.
function eq(string memory a, string memory b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
}
}
/// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small string.
function eqs(string memory a, bytes32 b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
// These should be evaluated on compile time, as far as possible.
let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
let x := not(or(m, or(b, add(m, and(b, m)))))
let r := shl(7, iszero(iszero(shr(128, x))))
r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
}
}
/// @dev Returns 0 if `a == b`, -1 if `a < b`, +1 if `a > b`.
/// If `a` == b[:a.length]`, and `a.length < b.length`, returns -1.
function cmp(string memory a, string memory b) internal pure returns (int256) {
return LibBytes.cmp(bytes(a), bytes(b));
}
/// @dev Packs a single string with its length into a single word.
/// Returns `bytes32(0)` if the length is zero or greater than 31.
function packOne(string memory a) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
// We don't need to zero right pad the string,
// since this is our own custom non-standard packing scheme.
result := mul(
// Load the length and the bytes.
mload(add(a, 0x1f)),
// `length != 0 && length < 32`. Abuses underflow.
// Assumes that the length is valid and within the block gas limit.
lt(sub(mload(a), 1), 0x1f)
)
}
}
/// @dev Unpacks a string packed using {packOne}.
/// Returns the empty string if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packOne}, the output behavior is undefined.
function unpackOne(bytes32 packed) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40) // Grab the free memory pointer.
mstore(0x40, add(result, 0x40)) // Allocate 2 words (1 for the length, 1 for the bytes).
mstore(result, 0) // Zeroize the length slot.
mstore(add(result, 0x1f), packed) // Store the length and bytes.
mstore(add(add(result, 0x20), mload(result)), 0) // Right pad with zeroes.
}
}
/// @dev Packs two strings with their lengths into a single word.
/// Returns `bytes32(0)` if combined length is zero or greater than 30.
function packTwo(string memory a, string memory b) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let aLen := mload(a)
// We don't need to zero right pad the strings,
// since this is our own custom non-standard packing scheme.
result := mul(
or( // Load the length and the bytes of `a` and `b`.
shl(shl(3, sub(0x1f, aLen)), mload(add(a, aLen))),
shr(shl(3, add(aLen, 1)), mload(add(b, 0x1f)))
),
// `totalLen != 0 && totalLen < 31`. Abuses underflow.
// Assumes that the lengths are valid and within the block gas limit.
lt(sub(add(aLen, mload(b)), 1), 0x1e)
)
}
}
/// @dev Unpacks strings packed using {packTwo}.
/// Returns the empty strings if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packTwo}, the output behavior is undefined.
function unpackTwo(bytes32 packed)
internal
pure
returns (string memory resultA, string memory resultB)
{
/// @solidity memory-safe-assembly
assembly {
resultA := mload(0x40) // Grab the free memory pointer.
resultB := add(resultA, 0x40)
// Allocate 2 words for each string (1 for the length, 1 for the byte). Total 4 words.
mstore(0x40, add(resultB, 0x40))
// Zeroize the length slots.
mstore(resultA, 0)
mstore(resultB, 0)
// Store the lengths and bytes.
mstore(add(resultA, 0x1f), packed)
mstore(add(resultB, 0x1f), mload(add(add(resultA, 0x20), mload(resultA))))
// Right pad with zeroes.
mstore(add(add(resultA, 0x20), mload(resultA)), 0)
mstore(add(add(resultB, 0x20), mload(resultB)), 0)
}
}
/// @dev Directly returns `a` without copying.
function directReturn(string memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
// Assumes that the string does not start from the scratch space.
let retStart := sub(a, 0x20)
let retUnpaddedSize := add(mload(a), 0x40)
// Right pad with zeroes. Just in case the string is produced
// by a method that doesn't zero right pad.
mstore(add(retStart, retUnpaddedSize), 0)
mstore(retStart, 0x20) // Store the return offset.
// End the transaction, returning the string.
return(retStart, and(not(0x1f), add(0x1f, retUnpaddedSize)))
}
}
}
lib/solady/src/utils/Multicallable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Contract that enables a single call to call multiple methods on itself.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Multicallable.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Multicallable.sol)
///
/// WARNING:
/// This implementation is NOT to be used with ERC2771 out-of-the-box.
/// https://blog.openzeppelin.com/arbitrary-address-spoofing-vulnerability-erc2771context-multicall-public-disclosure
/// This also applies to potentially other ERCs / patterns appending to the back of calldata.
///
/// We do NOT have a check for ERC2771, as we do not inherit from OpenZeppelin's context.
/// Moreover, it is infeasible and inefficient for us to add checks and mitigations
/// for all possible ERC / patterns appending to the back of calldata.
///
/// We would highly recommend using an alternative pattern such as
/// https://github.com/Vectorized/multicaller
/// which is more flexible, futureproof, and safer by default.
abstract contract Multicallable {
/// @dev Apply `delegatecall` with the current contract to each calldata in `data`,
/// and store the `abi.encode` formatted results of each `delegatecall` into `results`.
/// If any of the `delegatecall`s reverts, the entire context is reverted,
/// and the error is bubbled up.
///
/// By default, this function directly returns the results and terminates the call context.
/// If you need to add before and after actions to the multicall, please override this function.
function multicall(bytes[] calldata data) public payable virtual returns (bytes[] memory) {
// Revert if `msg.value` is non-zero by default to guard against double-spending.
// (See: https://www.paradigm.xyz/2021/08/two-rights-might-make-a-wrong)
//
// If you really need to pass in a `msg.value`, then you will have to
// override this function and add in any relevant before and after checks.
if (msg.value != 0) revert();
// `_multicallDirectReturn` returns the results directly and terminates the call context.
_multicallDirectReturn(_multicall(data));
}
/// @dev The inner logic of `multicall`.
/// This function is included so that you can override `multicall`
/// to add before and after actions, and use the `_multicallDirectReturn` function.
function _multicall(bytes[] calldata data) internal virtual returns (bytes32 results) {
/// @solidity memory-safe-assembly
assembly {
results := mload(0x40)
mstore(results, 0x20)
mstore(add(0x20, results), data.length)
let c := add(0x40, results)
let s := c
let end := shl(5, data.length)
calldatacopy(c, data.offset, end)
end := add(c, end)
let m := end
if data.length {
for {} 1 {} {
let o := add(data.offset, mload(c))
calldatacopy(m, add(o, 0x20), calldataload(o))
// forgefmt: disable-next-item
if iszero(delegatecall(gas(), address(), m, calldataload(o), codesize(), 0x00)) {
// Bubble up the revert if the delegatecall reverts.
returndatacopy(results, 0x00, returndatasize())
revert(results, returndatasize())
}
mstore(c, sub(m, s))
c := add(0x20, c)
// Append the `returndatasize()`, and the return data.
mstore(m, returndatasize())
let b := add(m, 0x20)
returndatacopy(b, 0x00, returndatasize())
// Advance `m` by `returndatasize() + 0x20`,
// rounded up to the next multiple of 32.
m := and(add(add(b, returndatasize()), 0x1f), 0xffffffffffffffe0)
mstore(add(b, returndatasize()), 0) // Zeroize the slot after the returndata.
if iszero(lt(c, end)) { break }
}
}
mstore(0x40, m) // Allocate memory.
results := or(shl(64, sub(m, results)), results) // Pack the bytes length into `results`.
}
}
/// @dev Decodes the `results` into an array of bytes.
/// This can be useful if you need to access the results or re-encode it.
function _multicallResultsToBytesArray(bytes32 results)
internal
pure
virtual
returns (bytes[] memory decoded)
{
/// @solidity memory-safe-assembly
assembly {
decoded := mload(0x40)
let c := and(0xffffffffffffffff, results) // Extract the offset.
mstore(decoded, mload(add(c, 0x20))) // Store the length.
let o := add(decoded, 0x20) // Start of elements in `decoded`.
let end := add(o, shl(5, mload(decoded)))
mstore(0x40, end) // Allocate memory.
let s := add(c, 0x40) // Start of elements in `results`.
let d := sub(s, o) // Difference between input and output pointers.
for {} iszero(eq(o, end)) { o := add(o, 0x20) } { mstore(o, add(mload(add(d, o)), s)) }
}
}
/// @dev Directly returns the `results` and terminates the current call context.
/// `results` must be from `_multicall`, else behavior is undefined.
function _multicallDirectReturn(bytes32 results) internal pure virtual {
/// @solidity memory-safe-assembly
assembly {
return(and(0xffffffffffffffff, results), shr(64, results))
}
}
}
lib/solady/src/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Reentrancy guard mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unauthorized reentrant call.
error Reentrancy();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
/// 9 bytes is large enough to avoid collisions with lower slots,
/// but not too large to result in excessive bytecode bloat.
uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* REENTRANCY GUARD */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Guards a function from reentrancy.
modifier nonReentrant() virtual {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
sstore(_REENTRANCY_GUARD_SLOT, address())
}
_;
/// @solidity memory-safe-assembly
assembly {
sstore(_REENTRANCY_GUARD_SLOT, codesize())
}
}
/// @dev Guards a view function from read-only reentrancy.
modifier nonReadReentrant() virtual {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
}
_;
}
}
lib/solady/src/utils/SSTORE2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Read and write to persistent storage at a fraction of the cost.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SSTORE2.sol)
/// @author Saw-mon-and-Natalie (https://github.com/Saw-mon-and-Natalie)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SSTORE2.sol)
/// @author Modified from 0xSequence (https://github.com/0xSequence/sstore2/blob/master/contracts/SSTORE2.sol)
/// @author Modified from SSTORE3 (https://github.com/Philogy/sstore3)
library SSTORE2 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The proxy initialization code.
uint256 private constant _CREATE3_PROXY_INITCODE = 0x67363d3d37363d34f03d5260086018f3;
/// @dev Hash of the `_CREATE3_PROXY_INITCODE`.
/// Equivalent to `keccak256(abi.encodePacked(hex"67363d3d37363d34f03d5260086018f3"))`.
bytes32 internal constant CREATE3_PROXY_INITCODE_HASH =
0x21c35dbe1b344a2488cf3321d6ce542f8e9f305544ff09e4993a62319a497c1f;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unable to deploy the storage contract.
error DeploymentFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* WRITE LOGIC */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Writes `data` into the bytecode of a storage contract and returns its address.
function write(bytes memory data) internal returns (address pointer) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(data) // Let `l` be `n + 1`. +1 as we prefix a STOP opcode.
/**
* ---------------------------------------------------+
* Opcode | Mnemonic | Stack | Memory |
* ---------------------------------------------------|
* 61 l | PUSH2 l | l | |
* 80 | DUP1 | l l | |
* 60 0xa | PUSH1 0xa | 0xa l l | |
* 3D | RETURNDATASIZE | 0 0xa l l | |
* 39 | CODECOPY | l | [0..l): code |
* 3D | RETURNDATASIZE | 0 l | [0..l): code |
* F3 | RETURN | | [0..l): code |
* 00 | STOP | | |
* ---------------------------------------------------+
* @dev Prefix the bytecode with a STOP opcode to ensure it cannot be called.
* Also PUSH2 is used since max contract size cap is 24,576 bytes which is less than 2 ** 16.
*/
// Do a out-of-gas revert if `n + 1` is more than 2 bytes.
mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
// Deploy a new contract with the generated creation code.
pointer := create(0, add(data, 0x15), add(n, 0xb))
if iszero(pointer) {
mstore(0x00, 0x30116425) // `DeploymentFailed()`.
revert(0x1c, 0x04)
}
mstore(data, n) // Restore the length of `data`.
}
}
/// @dev Writes `data` into the bytecode of a storage contract with `salt`
/// and returns its normal CREATE2 deterministic address.
function writeCounterfactual(bytes memory data, bytes32 salt)
internal
returns (address pointer)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(data)
// Do a out-of-gas revert if `n + 1` is more than 2 bytes.
mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
// Deploy a new contract with the generated creation code.
pointer := create2(0, add(data, 0x15), add(n, 0xb), salt)
if iszero(pointer) {
mstore(0x00, 0x30116425) // `DeploymentFailed()`.
revert(0x1c, 0x04)
}
mstore(data, n) // Restore the length of `data`.
}
}
/// @dev Writes `data` into the bytecode of a storage contract and returns its address.
/// This uses the so-called "CREATE3" workflow,
/// which means that `pointer` is agnostic to `data, and only depends on `salt`.
function writeDeterministic(bytes memory data, bytes32 salt)
internal
returns (address pointer)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(data)
mstore(0x00, _CREATE3_PROXY_INITCODE) // Store the `_PROXY_INITCODE`.
let proxy := create2(0, 0x10, 0x10, salt)
if iszero(proxy) {
mstore(0x00, 0x30116425) // `DeploymentFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, proxy) // Store the proxy's address.
// 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01).
// 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex).
mstore(0x00, 0xd694)
mstore8(0x34, 0x01) // Nonce of the proxy contract (1).
pointer := keccak256(0x1e, 0x17)
// Do a out-of-gas revert if `n + 1` is more than 2 bytes.
mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
if iszero(
mul( // The arguments of `mul` are evaluated last to first.
extcodesize(pointer),
call(gas(), proxy, 0, add(data, 0x15), add(n, 0xb), codesize(), 0x00)
)
) {
mstore(0x00, 0x30116425) // `DeploymentFailed()`.
revert(0x1c, 0x04)
}
mstore(data, n) // Restore the length of `data`.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ADDRESS CALCULATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the initialization code hash of the storage contract for `data`.
/// Used for mining vanity addresses with create2crunch.
function initCodeHash(bytes memory data) internal pure returns (bytes32 hash) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(data)
// Do a out-of-gas revert if `n + 1` is more than 2 bytes.
returndatacopy(returndatasize(), returndatasize(), gt(n, 0xfffe))
mstore(data, add(0x61000180600a3d393df300, shl(0x40, n)))
hash := keccak256(add(data, 0x15), add(n, 0xb))
mstore(data, n) // Restore the length of `data`.
}
}
/// @dev Equivalent to `predictCounterfactualAddress(data, salt, address(this))`
function predictCounterfactualAddress(bytes memory data, bytes32 salt)
internal
view
returns (address pointer)
{
pointer = predictCounterfactualAddress(data, salt, address(this));
}
/// @dev Returns the CREATE2 address of the storage contract for `data`
/// deployed with `salt` by `deployer`.
/// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
function predictCounterfactualAddress(bytes memory data, bytes32 salt, address deployer)
internal
pure
returns (address predicted)
{
bytes32 hash = initCodeHash(data);
/// @solidity memory-safe-assembly
assembly {
// Compute and store the bytecode hash.
mstore8(0x00, 0xff) // Write the prefix.
mstore(0x35, hash)
mstore(0x01, shl(96, deployer))
mstore(0x15, salt)
predicted := keccak256(0x00, 0x55)
// Restore the part of the free memory pointer that has been overwritten.
mstore(0x35, 0)
}
}
/// @dev Equivalent to `predictDeterministicAddress(salt, address(this))`.
function predictDeterministicAddress(bytes32 salt) internal view returns (address pointer) {
pointer = predictDeterministicAddress(salt, address(this));
}
/// @dev Returns the "CREATE3" deterministic address for `salt` with `deployer`.
function predictDeterministicAddress(bytes32 salt, address deployer)
internal
pure
returns (address pointer)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x00, deployer) // Store `deployer`.
mstore8(0x0b, 0xff) // Store the prefix.
mstore(0x20, salt) // Store the salt.
mstore(0x40, CREATE3_PROXY_INITCODE_HASH) // Store the bytecode hash.
mstore(0x14, keccak256(0x0b, 0x55)) // Store the proxy's address.
mstore(0x40, m) // Restore the free memory pointer.
// 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01).
// 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex).
mstore(0x00, 0xd694)
mstore8(0x34, 0x01) // Nonce of the proxy contract (1).
pointer := keccak256(0x1e, 0x17)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* READ LOGIC */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `read(pointer, 0, 2 ** 256 - 1)`.
function read(address pointer) internal view returns (bytes memory data) {
/// @solidity memory-safe-assembly
assembly {
data := mload(0x40)
let n := and(0xffffffffff, sub(extcodesize(pointer), 0x01))
extcodecopy(pointer, add(data, 0x1f), 0x00, add(n, 0x21))
mstore(data, n) // Store the length.
mstore(0x40, add(n, add(data, 0x40))) // Allocate memory.
}
}
/// @dev Equivalent to `read(pointer, start, 2 ** 256 - 1)`.
function read(address pointer, uint256 start) internal view returns (bytes memory data) {
/// @solidity memory-safe-assembly
assembly {
data := mload(0x40)
let n := and(0xffffffffff, sub(extcodesize(pointer), 0x01))
let l := sub(n, and(0xffffff, mul(lt(start, n), start)))
extcodecopy(pointer, add(data, 0x1f), start, add(l, 0x21))
mstore(data, mul(sub(n, start), lt(start, n))) // Store the length.
mstore(0x40, add(data, add(0x40, mload(data)))) // Allocate memory.
}
}
/// @dev Returns a slice of the data on `pointer` from `start` to `end`.
/// `start` and `end` will be clamped to the range `[0, args.length]`.
/// The `pointer` MUST be deployed via the SSTORE2 write functions.
/// Otherwise, the behavior is undefined.
/// Out-of-gas reverts if `pointer` does not have any code.
function read(address pointer, uint256 start, uint256 end)
internal
view
returns (bytes memory data)
{
/// @solidity memory-safe-assembly
assembly {
data := mload(0x40)
if iszero(lt(end, 0xffff)) { end := 0xffff }
let d := mul(sub(end, start), lt(start, end))
extcodecopy(pointer, add(data, 0x1f), start, add(d, 0x01))
if iszero(and(0xff, mload(add(data, d)))) {
let n := sub(extcodesize(pointer), 0x01)
returndatacopy(returndatasize(), returndatasize(), shr(40, n))
d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n))))
}
mstore(data, d) // Store the length.
mstore(add(add(data, 0x20), d), 0) // Zeroize the slot after the bytes.
mstore(0x40, add(add(data, 0x40), d)) // Allocate memory.
}
}
}
src/FWAV2/fwair/interfaces/IFWAIRLaunchManagerV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title FWAIR Launch manager V2 interface
interface IFWAIRLaunchManagerV2 {
function fwa() external view returns (address);
function whitelistAuthority() external view returns (address);
function vrfV2PlusWrapper() external view returns (address);
function purchaseNotifier() external view returns (address);
function permissionlessLaunches() external view returns (bool);
function intakeEnabled() external view returns (bool);
function activeLaunch() external view returns (address);
function prepareLaunch(uint256 launchId) external;
function completeLaunch() external;
function canResumePool() external view returns (bool);
function activeWithdrawalBaseDelay() external view returns (uint64);
function activeWithdrawalIncrement() external view returns (uint64);
function activeWithdrawalTimingRevision() external view returns (uint64);
function isLaunch(address launch) external view returns (bool);
function launchActiveWithdrawalTiming(address launch) external view returns (uint64 baseDelay, uint64 increment);
function consumeSupportWindowUpdate(uint64 newSupportStart, uint64 newSupportDeadline) external;
function reserveCollection() external;
function activateCollection() external;
function restoreActivatedCollection(address collection) external;
}
src/FWAV2/fwair/interfaces/IFWAIRLaunchPoolV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title FWAV2 pool interface used by FWAIR Launch V2
interface IFWAIRLaunchPoolV2 {
enum ListingStatus {
None,
Active,
Allocated,
Withdrawn,
Settled,
Staged
}
function listNFT(address collection, uint256 tokenId) external payable returns (uint256 listingId);
function unsettledAcquisitionCount() external view returns (uint256);
function withdrawListing(uint256 listingId) external;
function claimTopSpot(uint256 listingId) external;
function depositorReclaimBacking(uint256 listingId) external;
function depositorReclaimNFT(uint256 listingId) external;
function recoverStuckNFT(uint256 listingId) external;
function setCollectionsWhitelisted(address[] calldata collections, bool allowed) external;
function collectionWhitelisted(address collection) external view returns (bool);
function fwairLaunchRegistry() external view returns (address);
function BPS() external view returns (uint256);
function fwairListing(uint256 listingId) external view returns (bool);
function settlementFeeBpsForListing(uint256 listingId) external view returns (uint256);
function pendingFees(uint256 listingId) external view returns (uint256);
function feeCredit(address depositor) external view returns (uint256);
function claimListingFees(uint256[] calldata listingIds) external returns (uint256 total);
function withdrawEarnings() external returns (uint256 amount);
function rewards() external view returns (address);
function token() external view returns (address);
function stuckNFTRecipient(uint256 listingId) external view returns (address);
function listings(uint256 listingId)
external
view
returns (
address collection,
address depositor,
address purchaser,
uint256 tokenId,
uint256 weight,
uint256 value,
uint256 feeShare,
uint256 feeDebt,
uint256 slot,
uint64 allocatedAt,
ListingStatus status
);
}
src/FWAV2/fwair/interfaces/IFWAIRLaunchV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title FWAIR Launch V2 interface
interface IFWAIRLaunchV2 {
enum Phase {
Uninitialized,
Supporting,
Randomizing,
ProcessingAwards,
Complete,
Failed
}
enum PositionState {
None,
Launched,
SettledETH,
SettledNFT,
Withdrawn,
BackerAwarded
}
enum PaymentContext {
None,
ListingFees,
AggregateFees,
TimedWithdrawal,
AwardWithdrawal
}
function manager() external view returns (address);
function fwa() external view returns (address);
function purchaseNotifier() external view returns (address);
function artist() external view returns (address);
function collection() external view returns (address);
function startTokenId() external view returns (uint256);
function tokenCount() external view returns (uint32);
function supportedCount() external view returns (uint32);
function backingClosedAt() external view returns (uint64);
function awardsProcessedCount() external view returns (uint32);
function awardCount() external view returns (uint32);
function MAX_AWARD_BATCH() external view returns (uint8);
function backingPrice() external view returns (uint96);
function maxBackingMultiplier() external view returns (uint8);
function supportStart() external view returns (uint64);
function supportDeadline() external view returns (uint64);
function launchId() external view returns (uint256);
function registered() external view returns (bool);
function phase() external view returns (Phase);
function percentToBackers() external view returns (uint8);
function vrfConsumer() external view returns (address);
function tokenIdForListing(uint256 listingId) external view returns (uint256);
function activeListingWithdrawalEligibleAt(uint256 tokenId) external view returns (uint256);
function withdrawalContext() external view returns (PaymentContext reason, uint256 tokenId, uint256 listingId);
function positions(uint256 tokenId)
external
view
returns (
address supporter,
uint256 listingId,
PositionState state,
uint8 beneficiary,
uint8 status,
uint96 backing,
uint64 activeWithdrawalEligibleAt
);
function register(uint256 launchId, uint32 maxSupportPerWallet) external;
function support(uint16 count, uint8 backingMultiplier) external payable returns (uint256 firstTokenId);
function setMaxBackingMultiplier(uint8 newMultiplier) external;
function setPercentToBackers(uint8 newPercent) external;
function requestRandomness() external payable returns (uint256 requestId, uint256 requestPrice);
function closeBacking() external;
function processAwards(uint8 count) external;
function deliverAward(uint256 tokenId) external returns (bool delivered);
function setSupportWindow(uint64 newSupportStart, uint64 newSupportDeadline) external;
function emergencyFail() external;
function withdrawActiveListing(uint256 tokenId, bool takeNFT) external returns (uint256 returnedBacking);
function syncPosition(uint256 tokenId)
external
returns (PositionState state, uint8 status, uint256 principalAmount);
}
src/bitmons/Bitmons.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {ERC2981} from "solady/src/tokens/ERC2981.sol";
import {LibString} from "solady/src/utils/LibString.sol";
import {SoladyERC721C} from "./SoladyERC721C.sol";
import {BitmonsRevealVRF} from "./BitmonsRevealVRF.sol";
import {BitmonsArt} from "./BitmonsArt.sol";
import {BitmonsOneOfOneDraw} from "./libraries/BitmonsOneOfOneDraw.sol";
import {IBitmonsLaunchRandomness} from "./interfaces/IBitmonsLaunchRandomness.sol";
import {IBitmonsRenderer} from "./interfaces/IBitmonsRenderer.sol";
import {IFWAPurchaseCallback} from "../interfaces/IFWAPurchaseCallback.sol";
import {IFWAIRLaunchPoolV2} from "../FWAV2/fwair/interfaces/IFWAIRLaunchPoolV2.sol";
import {IFWAIRLaunchV2} from "../FWAV2/fwair/interfaces/IFWAIRLaunchV2.sol";
import {IFWAIRLaunchManagerV2} from "../FWAV2/fwair/interfaces/IFWAIRLaunchManagerV2.sol";
interface IBitmonsPoolHistory is IFWAIRLaunchPoolV2 {
function nextListingId() external view returns (uint256);
}
interface IBitmonsCatalogRenderer {
function collection() external view returns (address);
function art() external view returns (address);
}
/// @title BitMON
/// @notice Spawns earn a tier during their first FWA visit; canonical pool history determines reveals.
/// @dev FWA is not modified. Allocation timestamps and durable launch receipts determine effective
/// state even if notification fails. Purchaser traits use the accepted public listing hash.
/// Owner-initiated Spawn reveals use one separate, permanently committed VRF draw. The collection
/// owner can explicitly reroll finalized artwork without changing that draw or lifecycle history.
contract Bitmons is SoladyERC721C, ERC2981, IFWAPurchaseCallback {
using LibString for uint256;
enum EggStage {
Blue,
Gold,
Holofoil,
Secret
}
enum RevealState {
Egg,
Preview,
Revealed,
Pending
}
enum RevealSource {
None,
FWA,
Owner
}
uint256 public constant GOLD_AGE = 3 days;
uint256 public constant HOLOFOIL_AGE = 132 hours;
/// @notice Production maximum; maxLaunchBacking() also reflects a reduced Sepolia test base.
uint256 public constant MAX_LAUNCH_BACKING = 0.5 ether;
uint256 public constant MAX_MINT_BATCH = 250;
uint256 public constant MAX_METADATA_SYNC_BATCH = 1000;
uint8 private constant ENTERED = 1;
uint8 private constant EXITED = 2;
uint8 private constant LAUNCH_FIRST = 4;
uint8 private constant MANUAL_NOTIFIED = 8;
/// @dev Two slots: a full-width listing ID and packed timestamps/commitment flags. The listing
/// reference can advance for a Spawn, but never after a permanent purchaser reveal.
struct PoolHistory {
uint256 listingId;
uint64 enteredAt;
uint64 firstExitAt;
uint8 manualStagePlusOne;
uint8 flags;
}
struct FWAListing {
address collection;
address depositor;
address purchaser;
uint256 tokenId;
uint256 backing;
uint256 receipt;
uint256 settlementAmount;
uint64 allocatedAt;
IFWAIRLaunchPoolV2.ListingStatus status;
}
struct LaunchPosition {
uint256 listingId;
uint96 backing;
IFWAIRLaunchV2.PositionState state;
}
struct RenderData {
EggStage stage;
RevealState state;
RevealSource source;
uint256 seed;
uint256 backing;
uint256 listingId;
uint64 enteredAt;
uint64 cutoffAt;
}
uint256 public immutable maxSupply;
uint256 public immutable poolSupply;
uint256 public immutable freeClaimSupply;
/// @notice Fixed recipient of the launch allocation and artist of the original launch.
address public immutable launchArtist;
uint256 public launchMinted;
uint256 public totalSupply;
address public immutable fwa;
address public immutable purchaseNotifier;
BitmonsRevealVRF public immutable revealVRF;
address public fwairLaunch;
address public freeClaimRevealer;
/// @notice Artist-appointed setup delegate; this is not the FWAIR factory/registry.
address public setupManager;
string public unrevealedURI;
string public baseURI;
IBitmonsRenderer public renderer;
/// @notice Permanently disables future administrative rerolls for every token.
bool public adminRerollsDisabled;
mapping(uint256 tokenId => PoolHistory) public poolHistory;
/// @notice Zero preserves the original reveal; each admin reroll derives a new trait seed.
mapping(uint256 tokenId => uint256) public adminRerollCount;
/// @notice Optional sealed five-design catalog, fixed before binding the original launch.
address public oneOfOneArt;
event FWAIRLaunchBound(address indexed launch);
event FirstPoolEntry(uint256 indexed tokenId, uint64 timestamp);
event FirstPoolExit(uint256 indexed tokenId, uint64 timestamp);
event FreeClaimMinted(uint256 indexed tokenId, address indexed claimant);
event BitmonRevealed(uint256 indexed tokenId, uint256 indexed listingId);
event RevealRequested(uint256 indexed tokenId, uint256 indexed requestId);
event FreeClaimRevealerUpdated(address indexed previousRevealer, address indexed newRevealer);
event MetadataUpdate(uint256 tokenId);
event BatchMetadataUpdate(uint256 fromTokenId, uint256 toTokenId);
event MetadataURIsUpdated(string unrevealedURI, string baseURI);
event RendererUpdated(address indexed previousRenderer, address indexed newRenderer);
event RoyaltyUpdated(address indexed receiver, uint96 royaltyBps);
event AdminRerolled(uint256 indexed tokenId, uint256 previousSeed, uint256 newSeed, uint256 rerollCount);
event AdminRerollsDisabled();
event SetupManagerUpdated(address indexed previousManager, address indexed newManager);
event LaunchBatchMinted(address indexed artist, uint256 firstTokenId, uint256 count);
event OneOfOnesConfigured(address indexed art);
error InvalidConfiguration();
error InvalidSupply();
error InvalidFreeClaimSupply();
error UnauthorizedCallback();
error InvalidSettlement();
error InvalidRenderer();
error InvalidPoolVisit();
error InvalidRevealState();
error DeliveryPending();
error RevealNotComplete();
error NotFreeClaimToken();
error UnauthorizedFreeClaim();
error InvalidFreeClaimRevealer();
error InvalidClaimant();
error TimestampOverflow();
error InvalidLaunch();
error LaunchAlreadyBound();
error NotTokenOwner();
error PendingReveal();
error RerollsDisabled();
error SetupClosed();
error InvalidMintCount();
error LaunchMintingIncomplete();
error InvalidMetadataBatchSize();
error OneOfOnesAlreadyConfigured();
error OneOfOneImmutable();
modifier onlyOwnerOrSetupManager() {
if (!canConfigure(msg.sender)) {
if (msg.sender != address(0) && msg.sender == setupManager && owner() == launchArtist) {
revert SetupClosed();
}
revert Unauthorized();
}
_;
}
/// @param vrfConfig_ Subscription used for owner-initiated reveals, including free claims.
constructor(
address owner_,
address setupManager_,
uint256 totalSupply_,
address fwa_,
address purchaseNotifier_,
string memory unrevealedURI_,
string memory baseURI_,
address royaltyReceiver_,
uint96 royaltyBps_,
uint256 freeClaimSupply_,
BitmonsRevealVRF.Config memory vrfConfig_
) {
if (
owner_ == address(0) || owner_ == address(this) || fwa_.code.length == 0
|| purchaseNotifier_.code.length == 0 || setupManager_ == address(this)
) revert InvalidConfiguration();
if (totalSupply_ == 0) revert InvalidSupply();
if (freeClaimSupply_ > totalSupply_) revert InvalidFreeClaimSupply();
_initializeOwner(owner_);
maxSupply = totalSupply_;
poolSupply = totalSupply_ - freeClaimSupply_;
freeClaimSupply = freeClaimSupply_;
launchArtist = owner_;
setupManager = setupManager_;
fwa = fwa_;
purchaseNotifier = purchaseNotifier_;
revealVRF = new BitmonsRevealVRF(address(this), vrfConfig_);
unrevealedURI = unrevealedURI_;
baseURI = baseURI_;
_setDefaultRoyalty(royaltyReceiver_, royaltyBps_);
emit SetupManagerUpdated(address(0), setupManager_);
emit MetadataURIsUpdated(unrevealedURI_, baseURI_);
emit RoyaltyUpdated(royaltyReceiver_, royaltyBps_);
}
function name() public pure override returns (string memory) {
return "BitMON";
}
function symbol() public pure override returns (string memory) {
return "BITMON";
}
function supportsInterface(bytes4 interfaceId) public view override(SoladyERC721C, ERC2981) returns (bool) {
return interfaceId == type(IFWAPurchaseCallback).interfaceId || interfaceId == 0x49064906
|| SoladyERC721C.supportsInterface(interfaceId) || ERC2981.supportsInterface(interfaceId);
}
/// @notice The owner can always configure; its delegate is limited to the original artist's setup.
/// @dev Ownership changes invalidate delegation. Once the bound launch starts or closes, only
/// the owner retains configuration authority. Neither path grants ERC721 transfer approvals.
function canConfigure(address account) public view returns (bool) {
if (account == address(0)) return false;
address currentOwner = owner();
if (account == currentOwner) return true;
if (account != setupManager || currentOwner != launchArtist) return false;
address launch = fwairLaunch;
if (launch == address(0)) return true;
IFWAIRLaunchV2 candidate = IFWAIRLaunchV2(launch);
return candidate.phase() == IFWAIRLaunchV2.Phase.Supporting && candidate.supportedCount() == 0
&& block.timestamp < candidate.supportStart();
}
/// @notice Replace or revoke the setup delegate. Only collection ownership can grant this role.
function setSetupManager(address newManager) external onlyOwner {
if (newManager == address(this)) revert InvalidConfiguration();
address previousManager = setupManager;
setupManager = newManager;
emit SetupManagerUpdated(previousManager, newManager);
}
/// @dev Ownership transfer or renunciation also revokes the previous owner's setup delegation.
function _setOwner(address newOwner) internal override {
if (newOwner != owner() && setupManager != address(0)) {
address previousManager = setupManager;
setupManager = address(0);
emit SetupManagerUpdated(previousManager, address(0));
}
super._setOwner(newOwner);
}
/// @notice Mint the next bounded part of the fixed launch allocation to its original artist.
/// @dev Exact counts, sequential IDs, and a separate counter keep reserve claims independent.
/// Uses the same ERC721 mint behavior as the former constructor mint; no receiver callback.
function mintLaunchBatch(uint256 count) external onlyOwnerOrSetupManager returns (uint256 firstTokenId) {
if (fwairLaunch != address(0)) revert LaunchAlreadyBound();
uint256 minted = launchMinted;
if (count == 0 || count > MAX_MINT_BATCH || count > poolSupply - minted) revert InvalidMintCount();
firstTokenId = minted + 1;
launchMinted = minted + count;
totalSupply += count;
for (uint256 i; i < count; ++i) {
_mint(launchArtist, firstTokenId + i);
}
emit LaunchBatchMinted(launchArtist, firstTokenId, count);
}
/// @notice Bind the canonical launch once, before its first backing.
function setFWAIRLaunch(address launch) external onlyOwnerOrSetupManager {
if (fwairLaunch != address(0)) revert LaunchAlreadyBound();
if (launchMinted != poolSupply) revert LaunchMintingIncomplete();
if (launch.code.length == 0) revert InvalidLaunch();
IFWAIRLaunchV2 candidate = IFWAIRLaunchV2(launch);
address manager = candidate.manager();
uint256 start = candidate.startTokenId();
uint256 count = candidate.tokenCount();
if (
manager.code.length == 0 || manager != IFWAIRLaunchPoolV2(fwa).fwairLaunchRegistry()
|| !IFWAIRLaunchManagerV2(manager).isLaunch(launch) || candidate.collection() != address(this)
|| candidate.artist() != launchArtist || candidate.fwa() != fwa
|| candidate.purchaseNotifier() != purchaseNotifier || candidate.supportedCount() != 0
|| !candidate.registered() || candidate.phase() != IFWAIRLaunchV2.Phase.Supporting || start == 0
|| count == 0 || start > poolSupply || count > poolSupply - start + 1
) revert InvalidLaunch();
if (msg.sender != owner() && block.timestamp >= candidate.supportStart()) revert SetupClosed();
_validateLaunchPolicy(candidate);
(IFWAIRLaunchV2.PaymentContext context, uint256 contextToken, uint256 contextListing) =
candidate.withdrawalContext();
if (context != IFWAIRLaunchV2.PaymentContext.None || contextToken != 0 || contextListing != 0) {
revert InvalidLaunch();
}
fwairLaunch = launch;
emit FWAIRLaunchBound(launch);
emit BatchMetadataUpdate(start, start + count - 1);
}
function _validateLaunchPolicy(IFWAIRLaunchV2 launch) private view {
uint256 price = launch.backingPrice();
if (
(price != 0.05 ether && (block.chainid != 11155111 || price != 0.005 ether))
|| launch.maxBackingMultiplier() != 10 || launch.percentToBackers() != 10
) revert InvalidLaunch();
}
/// @notice Maximum backing for the bound launch's ten-step policy.
/// @dev Before launch binding, returns the production reference of 0.5 ETH.
function maxLaunchBacking() public view returns (uint256) {
address launch = fwairLaunch;
return launch == address(0) ? MAX_LAUNCH_BACKING : uint256(IFWAIRLaunchV2(launch).backingPrice()) * 10;
}
/// @notice Enable five reserved designs before the launch (and therefore its seed) is bound.
/// @dev The catalog and assignment rule cannot be replaced. Existing catalogs remain opt-in.
function configureOneOfOnes(address catalog) external onlyOwnerOrSetupManager {
if (oneOfOneArt != address(0)) revert OneOfOnesAlreadyConfigured();
if (fwairLaunch != address(0)) revert InvalidLaunch();
if (
catalog.code.length == 0 || maxSupply < 5 || !BitmonsArt(catalog).isSealed()
|| BitmonsArt(catalog).oneOfOneCount() != 5
) revert InvalidConfiguration();
if (address(renderer) != address(0)) _validateOneOfOneRenderer(address(renderer), catalog);
oneOfOneArt = catalog;
emit OneOfOnesConfigured(catalog);
emit BatchMetadataUpdate(1, maxSupply);
}
/// @notice Design IDs 1-5, or zero before the launch draw/for an ordinary token.
/// @dev Includes valid unminted IDs: the draw covers all maxSupply IDs, not the backed cohort.
function oneOfOneId(uint256 tokenId) public view returns (uint8 id) {
(id,) = _oneOfOneData(tokenId);
}
/// @notice One token ID per design, in design order; all zeros until randomness is fulfilled.
function oneOfOneTokenIds() public view returns (uint256[5] memory ids) {
(bool ready, uint256 seed) = _oneOfOneRandomness();
if (ready) ids = BitmonsOneOfOneDraw.tokenIds(seed, address(this), fwairLaunch, maxSupply);
}
function _oneOfOneRandomness() private view returns (bool ready, uint256 seed) {
if (oneOfOneArt == address(0) || fwairLaunch == address(0)) return (false, 0);
IBitmonsLaunchRandomness randomizer = IBitmonsLaunchRandomness(IFWAIRLaunchV2(fwairLaunch).vrfConsumer());
ready = randomizer.fulfilled();
// A fulfilled zero word is valid. Never substitute a holder or keeper controlled seed.
if (ready) seed = randomizer.randomWord();
}
function _oneOfOneData(uint256 tokenId) private view returns (uint8 id, uint256 seed) {
if (tokenId == 0 || tokenId > maxSupply) return (0, 0);
bool ready;
(ready, seed) = _oneOfOneRandomness();
if (!ready) return (0, 0);
uint256[5] memory ids = BitmonsOneOfOneDraw.tokenIds(seed, address(this), fwairLaunch, maxSupply);
for (uint8 i; i < 5; ++i) {
if (ids[i] == tokenId) return (i + 1, seed);
}
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
ownerOf(tokenId);
IBitmonsRenderer current = renderer;
if (address(current) != address(0)) return current.tokenURI(tokenId);
if (!revealed(tokenId)) return unrevealedURI;
return bytes(baseURI).length == 0 ? "" : string.concat(baseURI, tokenId.toString());
}
/// @notice Includes allocation before settlement; no notification is needed to make the view correct.
function renderData(uint256 tokenId)
external
view
returns (
uint8 stage,
uint8 state,
uint8 source,
uint256 seed,
uint256 backing,
uint256 listingId,
uint64 enteredAt,
uint64 cutoffAt
)
{
ownerOf(tokenId);
RenderData memory data = _renderData(tokenId);
return (
uint8(data.stage),
uint8(data.state),
uint8(data.source),
data.seed,
data.backing,
data.listingId,
data.enteredAt,
data.cutoffAt
);
}
function eggStage(uint256 tokenId) public view returns (EggStage) {
ownerOf(tokenId);
return _renderData(tokenId).stage;
}
/// @notice Preview counts as visibly revealed, but only original launch cash-out can restore its Spawn.
function revealed(uint256 tokenId) public view returns (bool) {
ownerOf(tokenId);
RevealState state = _renderData(tokenId).state;
return state == RevealState.Preview || state == RevealState.Revealed;
}
function revealSeed(uint256 tokenId) public view returns (uint256) {
ownerOf(tokenId);
RenderData memory data = _renderData(tokenId);
if (data.state != RevealState.Preview && data.state != RevealState.Revealed) revert RevealNotComplete();
return data.seed;
}
function poolDurationSeconds(uint256 tokenId) external view returns (uint256) {
ownerOf(tokenId);
PoolHistory memory history = poolHistory[tokenId];
if (history.flags & ENTERED == 0) return 0;
RenderData memory data = _renderData(tokenId);
uint256 end = data.cutoffAt == 0 ? block.timestamp : data.cutoffAt;
return end > data.enteredAt ? end - data.enteredAt : 0;
}
function firstPoolExitAt(uint256 tokenId) external view returns (uint64) {
ownerOf(tokenId);
return poolHistory[tokenId].firstExitAt;
}
/// @dev Notification refreshes metadata; it is not required to advance the effective lifecycle.
function onFWAPurchase(
address callbackFwa,
uint256 listingId,
address purchaser,
address,
uint256 backing,
uint256 settlementAmount,
Outcome outcome
) external {
if (msg.sender != purchaseNotifier || callbackFwa != fwa) revert UnauthorizedCallback();
FWAListing memory listing = _listing(listingId);
if (
listing.collection != address(this) || listing.status != IFWAIRLaunchPoolV2.ListingStatus.Settled
|| listing.purchaser == address(0) || listing.purchaser != purchaser || listing.backing != backing
|| settlementAmount > backing
) revert InvalidSettlement();
if (IFWAIRLaunchPoolV2(fwa).fwairListing(listingId)) {
if (listing.receipt != (4 | uint256(outcome)) || listing.settlementAmount != settlementAmount) {
revert InvalidSettlement();
}
if (
(outcome == Outcome.PurchaserKeptNFT || outcome == Outcome.PurchaserRelistedNFT)
&& settlementAmount != backing
) revert InvalidSettlement();
}
ownerOf(listing.tokenId);
emit MetadataUpdate(listing.tokenId);
}
/// @notice Anyone may refresh metadata for a bounded list of existing tokens without changing state.
/// @dev Emits one event per input in order, including duplicates. Any nonexistent token reverts
/// the entire batch. A singleton array refreshes one token; no reveal inputs are changed.
function syncMetadata(uint256[] calldata tokenIds) external {
uint256 count = tokenIds.length;
if (count == 0 || count > MAX_METADATA_SYNC_BATCH) revert InvalidMetadataBatchSize();
for (uint256 i; i < count; ++i) {
uint256 tokenId = tokenIds[i];
ownerOf(tokenId);
emit MetadataUpdate(tokenId);
}
}
function commitFreeClaim(uint256 tokenId, address claimant) external {
if (msg.sender != freeClaimRevealer || msg.sender == address(0)) revert UnauthorizedFreeClaim();
if (!isFreeClaimToken(tokenId)) revert NotFreeClaimToken();
if (claimant == address(0) || claimant == fwa || claimant == address(this) || claimant == fwairLaunch) {
revert InvalidClaimant();
}
++totalSupply;
_safeMint(claimant, tokenId);
emit FreeClaimMinted(tokenId, claimant);
}
/// @notice Only the current owner can initiate the eligible Spawn's one independent reveal.
function requestReveal(uint256 tokenId) external returns (uint256 requestId) {
address holder = ownerOf(tokenId);
if (msg.sender != holder) revert NotTokenOwner();
if (holder == fwa || holder == fwairLaunch || holder == address(this)) revert DeliveryPending();
RenderData memory data = _renderData(tokenId);
if (data.state != RevealState.Egg) revert InvalidRevealState();
PoolHistory storage history = poolHistory[tokenId];
if (history.manualStagePlusOne != 0) revert InvalidRevealState();
// Pins Blue even when an owner reveals before the token has any pool or launch history.
history.manualStagePlusOne = uint8(data.stage) + 1;
requestId = revealVRF.requestReveal(tokenId);
emit RevealRequested(tokenId, requestId);
emit MetadataUpdate(tokenId);
}
/// @notice Complete notification with the stored word; never request replacement randomness.
function finalizeReveal(uint256 tokenId) external returns (bool) {
ownerOf(tokenId);
PoolHistory storage history = poolHistory[tokenId];
if (history.manualStagePlusOne == 0) revert InvalidRevealState();
(bool fulfilled,) = revealVRF.getReveal(tokenId);
if (!fulfilled) return false;
if (history.flags & MANUAL_NOTIFIED == 0) {
history.flags |= MANUAL_NOTIFIED;
emit BitmonRevealed(tokenId, 0);
emit MetadataUpdate(tokenId);
}
return true;
}
/// @notice Reroll finalized traits to repair a missed incompatible combination.
/// @dev Only the collection owner may reroll, including after an NFT has been sold. This is a
/// deterministic admin override, not a new VRF draw. Spawns and purchaser previews cannot
/// be changed. Stage, reveal source, ownership and all pool/backing history stay intact.
function adminReroll(uint256 tokenId) external onlyOwner returns (uint256 newSeed) {
if (adminRerollsDisabled) revert RerollsDisabled();
ownerOf(tokenId);
if (oneOfOneId(tokenId) != 0) revert OneOfOneImmutable();
RenderData memory data = _canonicalRenderData(tokenId);
if (data.state != RevealState.Revealed) revert InvalidRevealState();
uint256 count = adminRerollCount[tokenId];
uint256 previousSeed = _rerolledSeed(tokenId, data.seed, count);
adminRerollCount[tokenId] = ++count;
newSeed = _rerolledSeed(tokenId, data.seed, count);
emit AdminRerolled(tokenId, previousSeed, newSeed, count);
emit MetadataUpdate(tokenId);
}
/// @notice Irreversibly disable admin rerolls for the entire collection, including future reveals.
/// @dev Existing repaired seeds remain effective. This does not lock renderer/metadata settings
/// or prevent ordinary first reveals. There is no function to enable rerolls again.
function disableAdminRerolls() external onlyOwner {
if (adminRerollsDisabled) revert RerollsDisabled();
adminRerollsDisabled = true;
emit AdminRerollsDisabled();
}
function _renderData(uint256 tokenId) private view returns (RenderData memory data) {
data = _canonicalRenderData(tokenId);
(uint8 special, uint256 launchSeed) = _oneOfOneData(tokenId);
if (special != 0) {
data.state = RevealState.Revealed;
// This artwork comes from the collection-wide draw, not a purchaser or owner reveal.
data.source = RevealSource.None;
data.seed = launchSeed;
return data;
}
if (data.state == RevealState.Revealed) {
data.seed = _rerolledSeed(tokenId, data.seed, adminRerollCount[tokenId]);
}
}
function _rerolledSeed(uint256 tokenId, uint256 originalSeed, uint256 count) private view returns (uint256) {
if (count == 0) return originalSeed;
return uint256(
keccak256(abi.encode(keccak256("Bitmons.adminReroll.v1"), address(this), tokenId, originalSeed, count))
);
}
function _canonicalRenderData(uint256 tokenId) private view returns (RenderData memory data) {
PoolHistory memory history = poolHistory[tokenId];
data.enteredAt = history.enteredAt;
if (history.flags & EXITED != 0) data.cutoffAt = history.firstExitAt;
LaunchPosition memory position = _position(tokenId);
data.backing = position.backing;
FWAListing memory original;
if (position.listingId != 0) {
original = _checkedListing(position.listingId, tokenId);
data.cutoffAt = _earlier(data.cutoffAt, original.allocatedAt);
}
FWAListing memory current;
if (history.listingId != 0) {
current = history.listingId == position.listingId ? original : _checkedListing(history.listingId, tokenId);
data.cutoffAt = _earlier(data.cutoffAt, current.allocatedAt);
if (position.backing == 0) data.backing = current.backing;
}
data.listingId = history.listingId;
// Preserve historical cutoff metadata as well as the committed tier. A manual result
// takes priority over original cash-out receipts and any subsequent pool activity.
if (history.manualStagePlusOne != 0) {
data.stage = EggStage(history.manualStagePlusOne - 1);
data.source = RevealSource.Owner;
(bool fulfilled, uint256 word) = revealVRF.getReveal(tokenId);
data.state = fulfilled ? RevealState.Revealed : RevealState.Pending;
data.seed = word;
return data;
}
// The award exception belongs to the first visit. An ordinary pre-launch withdrawal or
// permanent reveal cannot gain a new tier by entering a launch later.
bool launchFirst = history.flags & LAUNCH_FIRST != 0;
bool award = launchFirst && position.state == IFWAIRLaunchV2.PositionState.BackerAwarded;
if (
!award && launchFirst && position.listingId != 0 && position.state == IFWAIRLaunchV2.PositionState.Launched
&& original.status == IFWAIRLaunchPoolV2.ListingStatus.Withdrawn
) {
(IFWAIRLaunchV2.PaymentContext reason, uint256 contextToken, uint256 contextListing) =
IFWAIRLaunchV2(fwairLaunch).withdrawalContext();
award = reason == IFWAIRLaunchV2.PaymentContext.AwardWithdrawal && contextToken == tokenId
&& contextListing == position.listingId;
}
if (award) {
uint256 maximum = maxLaunchBacking();
data.stage = position.backing == maximum
? EggStage.Holofoil
: position.backing >= maximum * 4 / 10 ? EggStage.Gold : EggStage.Blue;
} else if (history.flags & ENTERED != 0) {
uint256 end = data.cutoffAt == 0 ? block.timestamp : data.cutoffAt;
uint256 age = end > data.enteredAt ? end - data.enteredAt : 0;
if (age >= HOLOFOIL_AGE) {
bool secret = launchFirst && position.backing == maxLaunchBacking()
&& (history.flags & EXITED != 0 || original.allocatedAt != 0 || current.allocatedAt != 0);
data.stage = secret ? EggStage.Secret : EggStage.Holofoil;
} else if (age >= GOLD_AGE) {
data.stage = EggStage.Gold;
}
}
if (current.allocatedAt == 0) return data;
data.source = RevealSource.FWA;
data.seed = uint256(keccak256(abi.encode(history.listingId, current.purchaser, current.backing, tokenId)));
if (history.listingId != position.listingId) {
data.state = RevealState.Revealed;
return data;
}
if (current.status == IFWAIRLaunchPoolV2.ListingStatus.Settled && _hasReceipt(current)) {
uint256 outcome = current.receipt & 3;
if (outcome == uint256(Outcome.PurchaserTookETH) || outcome == uint256(Outcome.PurchaserTookFWA)) {
data.source = RevealSource.None;
data.seed = 0;
return data;
}
data.state = RevealState.Revealed;
} else {
// Includes delivery before FWA records the final receipt. No owner reveal is allowed.
data.state = RevealState.Preview;
}
}
function _position(uint256 tokenId) private view returns (LaunchPosition memory position) {
if (fwairLaunch == address(0) || isFreeClaimToken(tokenId)) return position;
(, position.listingId, position.state,,, position.backing,) = IFWAIRLaunchV2(fwairLaunch).positions(tokenId);
}
function _listing(uint256 listingId) private view returns (FWAListing memory listing) {
(
listing.collection,
listing.depositor,
listing.purchaser,
listing.tokenId,
,
listing.backing,
listing.receipt,
listing.settlementAmount,
,
listing.allocatedAt,
listing.status
) = IFWAIRLaunchPoolV2(fwa).listings(listingId);
}
function _checkedListing(uint256 listingId, uint256 tokenId) private view returns (FWAListing memory listing) {
listing = _listing(listingId);
if (
listing.collection != address(this) || listing.tokenId != tokenId
|| listing.status == IFWAIRLaunchPoolV2.ListingStatus.None
) revert InvalidPoolVisit();
}
function _hasReceipt(FWAListing memory listing) private pure returns (bool) {
return listing.receipt >= 4 && listing.receipt <= 7;
}
function _earlier(uint64 first, uint64 second) private pure returns (uint64) {
if (first == 0) return second;
return second != 0 && second < first ? second : first;
}
/// @dev Only canonical FWA operations can start/freeze history. Its nonReentrant listNFT pulls
/// before incrementing nextListingId; subsequent reads validate this candidate association.
function _afterTokenTransfer(address from, address to, uint256 tokenId) internal override {
super._afterTokenTransfer(from, to, tokenId);
if (from == address(0)) return;
PoolHistory storage history = poolHistory[tokenId];
if (to == fwa && history.manualStagePlusOne != 0 && oneOfOneId(tokenId) == 0) {
(bool fulfilled,) = revealVRF.getReveal(tokenId);
if (!fulfilled) revert PendingReveal();
}
if (msg.sender != fwa) return;
if (to == fwa && from != fwa) {
if (from == fwairLaunch) {
_validateLaunchPolicy(IFWAIRLaunchV2(fwairLaunch));
} else if (from.code.length != 0) {
address registry = IFWAIRLaunchPoolV2(fwa).fwairLaunchRegistry();
if (registry != address(0) && IFWAIRLaunchManagerV2(registry).isLaunch(from)) revert InvalidLaunch();
}
if (history.manualStagePlusOne != 0) return;
if (history.flags & ENTERED != 0) {
RenderData memory beforeEntry = _renderData(tokenId);
if (beforeEntry.state == RevealState.Revealed) return;
if (beforeEntry.state != RevealState.Egg) revert InvalidRevealState();
} else {
history.enteredAt = _timestamp();
history.flags |= ENTERED;
if (from == fwairLaunch) history.flags |= LAUNCH_FIRST;
emit FirstPoolEntry(tokenId, history.enteredAt);
}
history.listingId = IBitmonsPoolHistory(fwa).nextListingId();
if (history.listingId == 0) revert InvalidPoolVisit();
} else if (from == fwa && to != fwa && history.flags & ENTERED != 0 && history.flags & EXITED == 0) {
history.firstExitAt = _timestamp();
history.flags |= EXITED;
emit FirstPoolExit(tokenId, history.firstExitAt);
}
}
function _timestamp() private view returns (uint64) {
if (block.timestamp == 0 || block.timestamp > type(uint64).max) revert TimestampOverflow();
return uint64(block.timestamp);
}
function isFreeClaimToken(uint256 tokenId) public view returns (bool) {
return tokenId > poolSupply && tokenId <= maxSupply;
}
function setFreeClaimRevealer(address revealer) external onlyOwnerOrSetupManager {
if (revealer == address(this) || revealer.code.length == 0) revert InvalidFreeClaimRevealer();
address previous = freeClaimRevealer;
freeClaimRevealer = revealer;
emit FreeClaimRevealerUpdated(previous, revealer);
}
function setMetadataURIs(string calldata unrevealedURI_, string calldata baseURI_)
external
onlyOwnerOrSetupManager
{
unrevealedURI = unrevealedURI_;
baseURI = baseURI_;
emit MetadataURIsUpdated(unrevealedURI_, baseURI_);
emit BatchMetadataUpdate(1, maxSupply);
}
/// @notice The renderer handles both Spawns and revealed artwork.
function setRenderer(address renderer_) external onlyOwnerOrSetupManager {
if (renderer_ != address(0) && (renderer_ == address(this) || renderer_.code.length == 0)) {
revert InvalidRenderer();
}
if (oneOfOneArt != address(0)) _validateOneOfOneRenderer(renderer_, oneOfOneArt);
address previous = address(renderer);
renderer = IBitmonsRenderer(renderer_);
emit RendererUpdated(previous, renderer_);
emit BatchMetadataUpdate(1, maxSupply);
}
function _validateOneOfOneRenderer(address candidate, address catalog) private view {
if (candidate.code.length == 0) revert InvalidRenderer();
try IBitmonsCatalogRenderer(candidate).collection() returns (address source) {
if (source != address(this)) revert InvalidRenderer();
} catch {
revert InvalidRenderer();
}
try IBitmonsCatalogRenderer(candidate).art() returns (address candidateArt) {
if (candidateArt != catalog) revert InvalidRenderer();
} catch {
revert InvalidRenderer();
}
}
function setTransferValidator(address validator) public override onlyOwnerOrSetupManager {
_setTransferValidator(validator);
}
function setRoyalty(address receiver, uint96 royaltyBps) external onlyOwner {
_setDefaultRoyalty(receiver, royaltyBps);
emit RoyaltyUpdated(receiver, royaltyBps);
}
}
src/bitmons/BitmonsArt.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {Ownable} from "solady/src/auth/Ownable.sol";
import {Multicallable} from "solady/src/utils/Multicallable.sol";
import {SSTORE2} from "solady/src/utils/SSTORE2.sol";
/// @notice Indexed pixel art and curated layer combinations, permanently immutable after sealing.
/// @dev Layer order: Background, Monster, Eyes, Horns, Headgear, Accessory. Pixel 0 is transparent;
/// pixel 1 means BG_MATCH; indices 2 through 255 refer to RGB triplets in the shared palette.
/// Optional per-frame bitplanes retain white/black masks and animated-material identity.
contract BitmonsArt is Ownable, Multicallable {
struct TraitInput {
string name;
uint8 category;
uint8 frameCount;
bytes pixels;
}
struct StoredTrait {
string name;
address pixelsPointer;
uint8 category;
uint8 frameCount;
}
uint256 public constant MAX_TRAITS = 256;
uint256 public constant MAX_COMBINATIONS = 1024;
uint256 public constant PIXELS_PER_FRAME = 256;
uint256 public constant CATEGORY_COUNT = 6;
uint16 public immutable paletteColorCount;
uint8 public immutable whiteIndex;
uint8 public immutable maskBlackIndex;
address private immutable _palettePointer;
uint16 public traitCount;
bool public isSealed;
mapping(uint256 id => StoredTrait) private _traits;
uint16[6][] private _combinations;
address private _rarityPointer;
uint16[6][4] private _eggs;
uint32 public accessoryNoneWeight;
bytes32 public rarityHash;
uint8 public oneOfOneCount;
address[5] private _oneOfOnes;
address private _oneOfOnePalettePointer;
uint16 public oneOfOneReservationCount;
mapping(bytes32 combinationHash => bool) public oneOfOneReserved;
uint16[6][] private _oneOfOneReservations;
uint16[6] private _normalFallback;
event TraitAdded(uint16 indexed id, uint8 indexed category, string name, uint8 frameCount);
event CombinationAdded(uint256 indexed index, uint16[6] ids);
event ArtSealed(uint16 traitCount, uint256 combinationCount);
event OneOfOnesConfigured(bytes32 indexed paletteHash, bytes32 indexed designsHash);
event OneOfOneReservationsConfigured(bytes32 indexed reservationsHash, uint16[6] fallbackIds);
error InvalidOwner();
error InvalidPalette();
error AlreadySealed();
error InvalidTraitName();
error InvalidCategory();
error InvalidFrameCount();
error InvalidPixelsLength();
error InvalidPixelIndex(uint256 offset, uint8 index);
error InvalidPixelFlags(uint256 offset);
error TraitLimitReached();
error InvalidTraitId(uint256 id);
error MissingRequiredTrait(uint8 category);
error TraitCategoryMismatch(uint8 category, uint16 id);
error CombinationLimitReached();
error InvalidCombinationIndex(uint256 index);
error EmptyCombinations();
error InvalidRarity();
error InvalidStage();
error OneOfOnesAlreadyConfigured();
error InvalidOneOfOneId();
error DuplicateOneOfOne();
error OneOfOneReservationsAlreadyConfigured();
error InvalidOneOfOneReservations();
error DuplicateOneOfOneReservation();
error InvalidNormalFallback();
error IncompatibleOneOfOneTraits();
/// @param palette_ One through 254 RGB colors, encoded as consecutive three-byte RGB triplets.
constructor(address owner_, bytes memory palette_) {
if (owner_ == address(0)) revert InvalidOwner();
if (palette_.length == 0 || palette_.length > 254 * 3 || palette_.length % 3 != 0) {
revert InvalidPalette();
}
_initializeOwner(owner_);
paletteColorCount = uint16(palette_.length / 3);
uint8 white;
uint8 black;
for (uint256 i; i < palette_.length; i += 3) {
if (palette_[i] == 0xff && palette_[i + 1] == 0xff && palette_[i + 2] == 0xff && white == 0) {
white = uint8(i / 3 + 2);
}
if (palette_[i] == 0x05 && palette_[i + 1] == 0x05 && palette_[i + 2] == 0x05 && black == 0) {
black = uint8(i / 3 + 2);
}
}
whiteIndex = white;
maskBlackIndex = black;
_palettePointer = SSTORE2.write(palette_);
}
/// @notice Execute several catalog operations atomically as the owner.
/// @dev Calls target this contract and preserve the caller. Every operation retains its
/// ownership, validation, and sealing guards. Any failure reverts the entire batch.
/// The inherited implementation rejects nonzero ETH, including for an empty batch.
function multicall(bytes[] calldata data) public payable override onlyOwner returns (bytes[] memory) {
return super.multicall(data);
}
/// @notice Append an indexed trait. IDs start at one; zero is reserved for an absent layer.
/// @dev Starts with frame-major, row-major 16x16 palette indices. An optional suffix has
/// 64 bytes per frame: 32 white/black-mask bytes then 32 material-mask bytes. Pixel p
/// uses bit (p & 7) in byte (p >> 3). White/black pixels have color zero; material pixels
/// retain their compiled RGB index. Background white/black effects are compiled offline.
function addTrait(TraitInput calldata input) external onlyOwner returns (uint16 id) {
if (isSealed) revert AlreadySealed();
if (traitCount == MAX_TRAITS) revert TraitLimitReached();
if (bytes(input.name).length == 0 || bytes(input.name).length > 96) revert InvalidTraitName();
if (input.category >= CATEGORY_COUNT) revert InvalidCategory();
if (input.frameCount != 1 && input.frameCount != 3 && input.frameCount != 9) revert InvalidFrameCount();
uint256 pixelCount = PIXELS_PER_FRAME * input.frameCount;
bool hasMasks = input.pixels.length == pixelCount + uint256(input.frameCount) * 64;
if (input.pixels.length != pixelCount && !hasMasks) revert InvalidPixelsLength();
uint256 indexLimit = uint256(paletteColorCount) + 2;
for (uint256 i; i < pixelCount; ++i) {
uint8 index = uint8(input.pixels[i]);
if (index >= indexLimit) revert InvalidPixelIndex(i, index);
if (hasMasks) {
uint256 maskOffset = pixelCount + (i / PIXELS_PER_FRAME) * 64 + (i % PIXELS_PER_FRAME) / 8;
uint8 bit = uint8(1 << (i & 7));
bool bw = uint8(input.pixels[maskOffset]) & bit != 0;
bool material = uint8(input.pixels[maskOffset + 32]) & bit != 0;
if ((bw && (index != 0 || material || input.category == 0)) || (material && index < 2)) {
revert InvalidPixelFlags(i);
}
if (bw && (whiteIndex == 0 || maskBlackIndex == 0)) revert InvalidPalette();
}
}
id = traitCount + 1;
traitCount = id;
_traits[id] = StoredTrait({
name: input.name,
pixelsPointer: SSTORE2.write(input.pixels),
category: input.category,
frameCount: input.frameCount
});
emit TraitAdded(id, input.category, input.name, input.frameCount);
}
function trait(uint256 id)
external
view
returns (string memory name, uint8 category, uint8 frameCount, bytes memory pixels)
{
if (id == 0 || id > traitCount) revert InvalidTraitId(id);
StoredTrait storage stored = _traits[id];
return (stored.name, stored.category, stored.frameCount, SSTORE2.read(stored.pixelsPointer));
}
function palette() external view returns (bytes memory) {
return SSTORE2.read(_palettePointer);
}
/// @notice Append one curated combination in category/layer order.
/// @dev Background, Monster, and Eyes are required. Trait compatibility and blocked combinations
/// are validated by the importer before upload; no rarity or selection policy is stored here.
function addCombination(uint16[6] calldata ids) external onlyOwner {
if (isSealed) revert AlreadySealed();
if (_combinations.length == MAX_COMBINATIONS) revert CombinationLimitReached();
for (uint8 category; category < CATEGORY_COUNT; ++category) {
uint16 id = ids[category];
if (id == 0) {
if (category < 3) revert MissingRequiredTrait(category);
} else {
if (id > traitCount) revert InvalidTraitId(id);
if (_traits[id].category != category) revert TraitCategoryMismatch(category, id);
}
}
uint256 index = _combinations.length;
_combinations.push(ids);
emit CombinationAdded(index, ids);
}
function combination(uint256 index) external view returns (uint16[6] memory) {
if (index >= _combinations.length) revert InvalidCombinationIndex(index);
return _combinations[index];
}
function combinationCount() external view returns (uint256) {
return _combinations.length;
}
/// @notice Install five standalone designs with their own RGB palette before sealing.
/// @dev Each design contains 1, 3, or 9 complete 16x16 frames. Index zero is transparent;
/// index one is forbidden because standalone artwork has no BG_MATCH layer.
function configureOneOfOnes(bytes calldata palette_, bytes[5] calldata designs) external onlyOwner {
if (isSealed) revert AlreadySealed();
if (oneOfOneCount != 0) revert OneOfOnesAlreadyConfigured();
if (palette_.length == 0 || palette_.length > 254 * 3 || palette_.length % 3 != 0) {
revert InvalidPalette();
}
uint256 colorCount = palette_.length / 3;
uint24[254] memory colors;
for (uint256 i; i < colorCount; ++i) {
uint256 offset = i * 3;
uint24 color = (uint24(uint8(palette_[offset])) << 16) | (uint24(uint8(palette_[offset + 1])) << 8)
| uint24(uint8(palette_[offset + 2]));
for (uint256 j; j < i; ++j) {
if (colors[j] == color) revert InvalidPalette();
}
colors[i] = color;
}
bytes32[5] memory hashes;
for (uint256 i; i < 5; ++i) {
bytes calldata pixels = designs[i];
if (pixels.length != 256 && pixels.length != 768 && pixels.length != 2304) revert InvalidPixelsLength();
for (uint256 pixel; pixel < pixels.length; ++pixel) {
uint8 index = uint8(pixels[pixel]);
if (index == 1 || index >= colorCount + 2) revert InvalidPixelIndex(pixel, index);
}
bytes32 hash = keccak256(pixels);
for (uint256 j; j < i; ++j) {
if (hashes[j] == hash) revert DuplicateOneOfOne();
}
hashes[i] = hash;
_oneOfOnes[i] = SSTORE2.write(pixels);
}
_oneOfOnePalettePointer = SSTORE2.write(palette_);
oneOfOneCount = 5;
emit OneOfOnesConfigured(keccak256(palette_), keccak256(abi.encode(designs)));
}
function oneOfOne(uint8 id) external view returns (uint8 frameCount, bytes memory pixels) {
if (id == 0 || id > oneOfOneCount) revert InvalidOneOfOneId();
pixels = SSTORE2.read(_oneOfOnes[id - 1]);
frameCount = uint8(pixels.length / PIXELS_PER_FRAME);
}
function oneOfOnePalette() external view returns (bytes memory) {
if (oneOfOneCount == 0) revert InvalidOneOfOneId();
return SSTORE2.read(_oneOfOnePalettePointer);
}
/// @notice Exclude ordinary trait tuples that reproduce standalone 1/1 artwork.
/// @dev Curated visual aliases are reserved by their exact six-ID hashes;
/// matching ordinary draws use one compatible, nonreserved fallback without retries.
function configureOneOfOneReservations(uint16[6][] calldata reserved, uint16[6] calldata fallbackIds)
external
onlyOwner
{
if (isSealed) revert AlreadySealed();
if (oneOfOneReservationCount != 0) revert OneOfOneReservationsAlreadyConfigured();
if (oneOfOneCount != 5 || reserved.length == 0 || reserved.length > MAX_COMBINATIONS) {
revert InvalidOneOfOneReservations();
}
for (uint256 i; i < reserved.length; ++i) {
_validateReservationIds(reserved[i]);
bytes32 hash = keccak256(abi.encode(reserved[i]));
if (oneOfOneReserved[hash]) revert DuplicateOneOfOneReservation();
oneOfOneReserved[hash] = true;
_oneOfOneReservations.push(reserved[i]);
}
_validateReservationIds(fallbackIds);
if (oneOfOneReserved[keccak256(abi.encode(fallbackIds))]) revert InvalidNormalFallback();
_normalFallback = fallbackIds;
oneOfOneReservationCount = uint16(reserved.length);
emit OneOfOneReservationsConfigured(keccak256(abi.encode(reserved)), fallbackIds);
}
function normalFallback() external view returns (uint16[6] memory) {
if (oneOfOneReservationCount == 0) revert InvalidNormalFallback();
return _normalFallback;
}
function _validateReservationIds(uint16[6] calldata ids) private view {
for (uint8 category; category < CATEGORY_COUNT; ++category) {
uint16 id = ids[category];
if (id == 0) {
if (category < 3) revert MissingRequiredTrait(category);
} else {
if (id > traitCount) revert InvalidTraitId(id);
if (_traits[id].category != category) revert TraitCategoryMismatch(category, id);
}
}
}
function _validateReservationCompatibility(uint16[6] memory ids, bytes memory rarity, bool fallback_)
private
pure
{
for (uint256 category; category < CATEGORY_COUNT; ++category) {
uint256 id = ids[category];
if (id == 0) {
if (fallback_ && (category == 3 || category == 4)) {
for (uint256 candidateOffset; candidateOffset < rarity.length; candidateOffset += 38) {
if (
uint8(rarity[candidateOffset + 4]) == category
&& uint8(rarity[candidateOffset + 5]) & 2 == 0
) revert InvalidNormalFallback();
}
}
continue;
}
uint256 offset = (id - 1) * 38;
if (fallback_ && uint8(rarity[offset + 5]) & 2 != 0) revert InvalidNormalFallback();
uint256 compatible;
assembly ("memory-safe") {
compatible := mload(add(add(rarity, 38), offset))
}
for (uint256 other = category + 1; other < CATEGORY_COUNT; ++other) {
uint256 otherId = ids[other];
if (otherId != 0 && compatible & (uint256(1) << (otherId - 1)) == 0) {
revert IncompatibleOneOfOneTraits();
}
}
}
}
/// @notice Install the weighted selection policy and four two-layer Spawn compositions.
/// @dev One 38-byte record per trait: uint32 weight, uint8 category, uint8 flags
/// (Special=1, excluded from final draws=2), uint256 compatibility mask. Integers
/// are big-endian; mask bit id-1 identifies a compatible trait. None has its own
/// unboosted Accessory weight. Coverage combinations never determine rarity.
function configureRarity(bytes calldata data, uint32 noneWeight, uint16[6][4] calldata eggs) external onlyOwner {
if (isSealed) revert AlreadySealed();
uint256 count = traitCount;
if (count == 0 || data.length != count * 38 || noneWeight == 0) revert InvalidRarity();
uint256 validBits = count == 256 ? type(uint256).max : (uint256(1) << count) - 1;
uint256[6] memory pools;
for (uint256 i; i < count; ++i) {
uint256 offset = i * 38;
uint256 weight;
uint256 compatible;
assembly ("memory-safe") {
weight := shr(224, calldataload(add(data.offset, offset)))
compatible := calldataload(add(add(data.offset, offset), 6))
}
uint8 category = uint8(data[offset + 4]);
uint8 flags = uint8(data[offset + 5]);
if (weight == 0 || category != _traits[i + 1].category || flags > 3 || compatible & ~validBits != 0) {
revert InvalidRarity();
}
if (flags & 2 == 0) pools[category] |= uint256(1) << i;
for (uint256 j; j < i; ++j) {
uint256 other;
assembly ("memory-safe") {
other := calldataload(add(add(data.offset, mul(j, 38)), 6))
}
if (((compatible >> j) & 1) != ((other >> i) & 1)) revert InvalidRarity();
}
}
if (pools[0] == 0 || pools[1] == 0 || pools[2] == 0) revert InvalidRarity();
// A witness compatible with every earlier eligible trait guarantees that each
// populated mandatory category can complete any prefix. This bounds selection to
// six scans and avoids retries, backtracking, or an incompatible fallback.
uint256 prior;
for (uint256 step; step < 5; ++step) {
uint256 category = step == 3 ? 4 : step == 4 ? 3 : step;
uint256 pool = pools[category];
bool witness = pool == 0;
for (uint256 i; i < count && !witness; ++i) {
if ((pool >> i) & 1 == 0) continue;
uint256 compatible;
assembly ("memory-safe") {
compatible := calldataload(add(add(data.offset, mul(i, 38)), 6))
}
witness = compatible & prior == prior;
}
if (!witness) revert InvalidRarity();
prior |= pool;
}
for (uint256 stage; stage < 4; ++stage) {
for (uint256 category; category < 6; ++category) {
uint16 id = eggs[stage][category];
if (category < 2) {
if (id == 0 || id > count || _traits[id].category != category) revert InvalidRarity();
} else if (id != 0) {
revert InvalidRarity();
}
}
}
_rarityPointer = SSTORE2.write(data);
_eggs = eggs;
accessoryNoneWeight = noneWeight;
rarityHash = keccak256(abi.encode(data, noneWeight, eggs));
}
function rarityData() external view returns (bytes memory) {
if (_rarityPointer == address(0)) revert InvalidRarity();
return SSTORE2.read(_rarityPointer);
}
function egg(uint8 stage) external view returns (uint16[6] memory) {
if (stage > 3) revert InvalidStage();
if (_rarityPointer == address(0)) revert InvalidRarity();
return _eggs[stage];
}
/// @notice Irrevocably freeze the art catalog and its combinations.
function seal() external onlyOwner {
if (isSealed) revert AlreadySealed();
if (_combinations.length == 0) revert EmptyCombinations();
if (_rarityPointer == address(0) || SSTORE2.read(_rarityPointer).length != uint256(traitCount) * 38) {
revert InvalidRarity();
}
if (oneOfOneReservationCount != 0) {
bytes memory rarity = SSTORE2.read(_rarityPointer);
for (uint256 i; i < oneOfOneReservationCount; ++i) {
_validateReservationCompatibility(_oneOfOneReservations[i], rarity, false);
}
_validateReservationCompatibility(_normalFallback, rarity, true);
}
isSealed = true;
emit ArtSealed(traitCount, _combinations.length);
}
}
src/bitmons/BitmonsRevealVRF.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {VRFConsumerBaseV2Plus} from "@chainlink/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol";
import {VRFV2PlusClient} from "@chainlink/contracts/src/v0.8/vrf/dev/libraries/VRFV2PlusClient.sol";
interface IBitmonsRevealNotification {
function finalizeReveal(uint256 tokenId) external returns (bool);
}
/// @notice Chainlink VRF v2.5 reveals with one request and one permanent result per BitMON.
/// @dev Deployed by the collection, which is also the inherited coordinator-management owner.
/// Fulfillment stores the verified word and block before a bounded metadata notification.
/// Collection views reveal the stored word immediately even if the notification fails.
contract BitmonsRevealVRF is VRFConsumerBaseV2Plus {
struct Config {
address coordinator;
uint256 subscriptionId;
bytes32 keyHash;
uint16 requestConfirmations;
bool nativePayment;
}
struct Request {
uint256 tokenId;
bool exists;
bool fulfilled;
uint64 fulfilledBlock;
uint256 randomWord;
}
uint32 public constant CALLBACK_GAS_LIMIT = 100_000;
uint32 public constant NUM_WORDS = 1;
uint32 public constant NOTIFICATION_GAS_LIMIT = 30_000;
address public immutable collection;
uint256 public immutable subscriptionId;
bytes32 public immutable keyHash;
uint16 public immutable requestConfirmations;
bool public immutable nativePayment;
/// @notice The sole successful request submitted for a token.
mapping(uint256 tokenId => uint256 requestId) public requestIdForToken;
mapping(uint256 tokenId => bool requested) private _requested;
mapping(uint256 requestId => Request request) private _requests;
event RevealRandomnessRequested(uint256 indexed tokenId, uint256 indexed requestId);
event RevealRandomnessFulfilled(uint256 indexed tokenId, uint256 indexed requestId, uint256 randomWord);
event RevealNotificationAttempted(uint256 indexed tokenId, bool success);
error InvalidConfiguration();
error UnauthorizedCaller();
error RequestAlreadyMade();
error InvalidRequestId();
constructor(address collection_, Config memory config)
VRFConsumerBaseV2Plus(_validateCoordinator(config.coordinator))
{
if (
collection_ == address(0) || config.subscriptionId == 0 || config.keyHash == bytes32(0)
|| config.requestConfirmations < 3 || config.requestConfirmations > 200
) revert InvalidConfiguration();
// The collection deploys this consumer inside its constructor, before its code exists.
collection = collection_;
subscriptionId = config.subscriptionId;
keyHash = config.keyHash;
requestConfirmations = config.requestConfirmations;
nativePayment = config.nativePayment;
}
/// @notice Request fresh randomness after the collection has committed a token's reveal inputs.
/// @dev A successful request cannot be replaced, even while fulfillment is pending.
/// A coordinator revert rolls back the guard so a failed submission can be tried again.
function requestReveal(uint256 tokenId) external returns (uint256 requestId) {
if (msg.sender != collection) revert UnauthorizedCaller();
if (_requested[tokenId]) revert RequestAlreadyMade();
_requested[tokenId] = true;
return _submit(tokenId);
}
function _submit(uint256 tokenId) private returns (uint256 requestId) {
requestId = s_vrfCoordinator.requestRandomWords(
VRFV2PlusClient.RandomWordsRequest({
keyHash: keyHash,
subId: subscriptionId,
requestConfirmations: requestConfirmations,
callbackGasLimit: CALLBACK_GAS_LIMIT,
numWords: NUM_WORDS,
extraArgs: VRFV2PlusClient._argsToBytes(VRFV2PlusClient.ExtraArgsV1({nativePayment: nativePayment}))
})
);
if (requestId == 0 || _requests[requestId].exists) revert InvalidRequestId();
_requests[requestId] =
Request({tokenId: tokenId, exists: true, fulfilled: false, fulfilledBlock: 0, randomWord: 0});
requestIdForToken[tokenId] = requestId;
emit RevealRandomnessRequested(tokenId, requestId);
}
function getReveal(uint256 tokenId) external view returns (bool fulfilled, uint256 randomWord) {
Request storage request = _requests[requestIdForToken[tokenId]];
return (request.fulfilled, request.randomWord);
}
/// @notice Immutable fulfillment snapshot. Use the boolean because a zero word is valid.
function getRevealStatus(uint256 tokenId)
external
view
returns (bool fulfilled, uint256 randomWord, uint64 fulfilledBlock)
{
Request storage request = _requests[requestIdForToken[tokenId]];
return (request.fulfilled, request.randomWord, request.fulfilledBlock);
}
/// @dev The base authenticates the coordinator. Ignore malformed, unknown and duplicate responses.
/// Blocks use the collection's uint64 chain assumption. Notification failure cannot discard
/// the stored fulfillment; collection views and permissionless finalization can recover it.
function fulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) internal override {
Request storage request = _requests[requestId];
if (!request.exists || request.fulfilled || randomWords.length != NUM_WORDS) return;
uint256 tokenId = request.tokenId;
request.fulfilled = true;
request.fulfilledBlock = uint64(block.number);
request.randomWord = randomWords[0];
emit RevealRandomnessFulfilled(tokenId, requestId, randomWords[0]);
address target = collection;
uint32 selector = uint32(IBitmonsRevealNotification.finalizeReveal.selector);
uint256 gasLimit = NOTIFICATION_GAS_LIMIT;
bool success;
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, shl(224, selector))
mstore(add(ptr, 4), tokenId)
// Copy no return data: a reverting or oversized response cannot exhaust the consumer.
success := call(gasLimit, target, 0, ptr, 0x24, 0, 0)
}
emit RevealNotificationAttempted(tokenId, success);
}
function _validateCoordinator(address coordinator) private view returns (address) {
if (coordinator.code.length == 0) revert InvalidConfiguration();
return coordinator;
}
}
src/bitmons/SoladyERC721C.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {ERC721} from "solady/src/tokens/ERC721.sol";
import {Ownable} from "solady/src/auth/Ownable.sol";
import {ICreatorToken, ICreatorTokenLegacy} from "./interfaces/ICreatorToken.sol";
import {ITransferValidator, ITransferValidatorSetTokenType} from "./interfaces/ITransferValidator.sol";
/// @notice Solady ERC721 with the Creator Token transfer validation interface.
/// @dev The derived contract must initialize Ownable. Validation is disabled until
/// the owner sets a validator; royalty enforcement also requires a suitable validator policy.
abstract contract SoladyERC721C is ERC721, Ownable, ICreatorToken {
error InvalidTransferValidator();
// Limit Break's PermitC defines TOKEN_TYPE_ERC721 as 721.
// https://github.com/limitbreakinc/PermitC/blob/v1.0.0/src/Constants.sol
uint16 private constant _TOKEN_TYPE_ERC721 = 721;
address private _transferValidator;
function getTransferValidator() public view virtual override returns (address validator) {
return _transferValidator;
}
/// @notice Sets the validator, or disables validation by setting the zero address.
/// @dev Installing a validator does not grant it any token transfer approvals.
function setTransferValidator(address validator) public virtual override onlyOwner {
_setTransferValidator(validator);
}
/// @dev Derived contracts may expose a narrower setup delegation without changing transfer rights.
function _setTransferValidator(address validator) internal {
if (validator != address(0) && validator.code.length == 0) revert InvalidTransferValidator();
address oldValidator = _transferValidator;
_transferValidator = validator;
emit TransferValidatorUpdated(oldValidator, validator);
if (validator != address(0)) {
// Limit Break validators can use this registration. OpenSea's Creator Token
// interface does not require it, so validators without the extension still work.
try ITransferValidatorSetTokenType(validator).setTokenTypeOfCollection(address(this), _TOKEN_TYPE_ERC721) {}
catch {}
}
}
function getTransferValidationFunction()
public
pure
virtual
override
returns (bytes4 functionSignature, bool isViewFunction)
{
return (ITransferValidator.validateTransfer.selector, true);
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(ICreatorToken).interfaceId || interfaceId == type(ICreatorTokenLegacy).interfaceId
|| super.supportsInterface(interfaceId);
}
/// @dev Every transfer is checked, including owner, pool, marketplace, and validator calls.
/// Mints and burns are excluded. Derived hooks must retain the call to super.
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
address validator = getTransferValidator();
if (from != address(0) && to != address(0) && validator != address(0)) {
ITransferValidator(validator).validateTransfer(msg.sender, from, to, tokenId);
}
}
}
src/bitmons/interfaces/IBitmonsLaunchRandomness.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @notice Immutable-result reads from the canonical launch's existing randomness consumer.
interface IBitmonsLaunchRandomness {
function fulfilled() external view returns (bool);
function randomWord() external view returns (uint256);
}
src/bitmons/interfaces/IBitmonsRenderer.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @notice Metadata renderer for existing BitMON, including Spawns and purchaser previews.
/// @dev Implementations read the collection's effective renderData. The studio renderer uses
/// a sealed art catalog and the token's earned stage for weighted trait selection.
interface IBitmonsRenderer {
function tokenURI(uint256 tokenId) external view returns (string memory);
}
src/bitmons/interfaces/ICreatorToken.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @notice Creator Token interface recognized by OpenSea and transfer validators.
/// @dev https://docs.opensea.io/docs/creator-fee-enforcement
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);
}
/// @notice Earlier Creator Token interface, retained for ERC165 discovery.
interface ICreatorTokenLegacy {
function getTransferValidator() external view returns (address validator);
function setTransferValidator(address validator) external;
}
src/bitmons/interfaces/ITransferValidator.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @notice ERC721 transfer validation entry point used by Creator Token validators.
interface ITransferValidator {
/// @dev Reverts when the collection's policy does not authorize this transfer.
function validateTransfer(address caller, address from, address to, uint256 tokenId) external view;
}
/// @notice Optional Limit Break validator extension for registering a collection's token type.
interface ITransferValidatorSetTokenType {
function setTokenTypeOfCollection(address collection, uint16 tokenType) external;
}
src/bitmons/libraries/BitmonsFreeClaimAllocations.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
// Generated from src/bitmons/free_claims.csv; do not edit by hand.
// Regenerate: python3 script/bitmons/generate-free-claims.py
/// @notice Fixed wallet allowances, preserving the reviewed CSV row order.
library BitmonsFreeClaimAllocations {
uint256 internal constant RECIPIENT_COUNT = 163;
uint256 internal constant TOTAL_ALLOCATION = 253;
bytes32 internal constant CSV_SHA256 = 0xdd16c57fadeaabff746d9d33d1e432f0c3e8a2e365757bff739128359606bf15;
function allocations() internal pure returns (address[] memory wallets, uint256[] memory amounts) {
wallets = new address[](RECIPIENT_COUNT);
amounts = new uint256[](RECIPIENT_COUNT);
wallets[0] = 0x852548338cd5A8DE1384FdE3bFc678A8669C0F4d;
amounts[0] = 9;
wallets[1] = 0x03E0fE58a86ed7B5966780441d8ECEAc1FfB7575;
amounts[1] = 6;
wallets[2] = 0x23602Ca06e977C86339FFddAd74966e824aB691e;
amounts[2] = 6;
wallets[3] = 0xA2b8F1bDa189A596B2C7bA6958E4c4c67384F582;
amounts[3] = 5;
wallets[4] = 0xC211C420e4CCfc34346147b4Af1Ae7Fa15C41c29;
amounts[4] = 5;
wallets[5] = 0xF78dcC14cb66b3ba98E3fEF21d79ba7525a3eedE;
amounts[5] = 5;
wallets[6] = 0x3b98f03C8C7bAEBBCd3516a0F47458e1B0dd0D60;
amounts[6] = 4;
wallets[7] = 0x570FF649bB5aE8E032A4f9456aa1Ad74cc3f3e8f;
amounts[7] = 4;
wallets[8] = 0x7Fe049272a8F7B043180280a6Cd1E9808c04a579;
amounts[8] = 4;
wallets[9] = 0xAd31AD089f44bF44792deCDdf37c14650eB0d7b5;
amounts[9] = 4;
wallets[10] = 0xf88c8FA48C3587aFB73f7FdbD5c2E73d24846ED3;
amounts[10] = 4;
wallets[11] = 0x0d0Ec585E3B3C82010e2192c4176FafC9D33E528;
amounts[11] = 3;
wallets[12] = 0x1156a767b4De8af9F77Adc8F30313bbe7946B14D;
amounts[12] = 3;
wallets[13] = 0x12aD5707401114453020A92A7384F267c9C559f2;
amounts[13] = 3;
wallets[14] = 0x14273493f5E508FF7c002e532aa7C4829660E18C;
amounts[14] = 3;
wallets[15] = 0x3A88bc828083eaDEA53F87520250e092B72350f2;
amounts[15] = 3;
wallets[16] = 0xa816D5f2333817B0843eB85E01BBA823885a913c;
amounts[16] = 3;
wallets[17] = 0xdBc53B3cC2251c10660774B08166325d3742CE88;
amounts[17] = 3;
wallets[18] = 0xfA413F911677512Dda3a340370f635bc77789e0e;
amounts[18] = 3;
wallets[19] = 0x05833bC715f6eb040224d166c7B7195c223d02CD;
amounts[19] = 2;
wallets[20] = 0x098C02D4323d10592693f073897c7a782D97ab56;
amounts[20] = 2;
wallets[21] = 0x16e9Cfe34541d8601Da1fAb1707FE2B1b867887F;
amounts[21] = 2;
wallets[22] = 0x27F871136BF46eB1c87d8a407cb531B184D80Ce7;
amounts[22] = 2;
wallets[23] = 0x3A661a18CB0258119636DfDDe098648c6ad5bA62;
amounts[23] = 2;
wallets[24] = 0x3d280fDe2Ddb59323C891CF30995E1862510342f;
amounts[24] = 2;
wallets[25] = 0x44c2A80F8b924858DB469A5b35128908E55C531F;
amounts[25] = 2;
wallets[26] = 0x463fC06d16E146eC9E4Cb2aB8C3077732c75F38B;
amounts[26] = 2;
wallets[27] = 0x530c4169A57eB47457e783FD2969773094FfCD23;
amounts[27] = 2;
wallets[28] = 0x7915e43086Cd78Be341Df73726C0947B6334b978;
amounts[28] = 2;
wallets[29] = 0x795D7d64D16c1b30DA853e5Ca5c45568a41a93CC;
amounts[29] = 2;
wallets[30] = 0x896Ad7c1a8f93A48258beA5B6BB43f8FCbcA945B;
amounts[30] = 2;
wallets[31] = 0x8E64fe4f19F2d1768a7820B80e9268eb52752926;
amounts[31] = 2;
wallets[32] = 0x955EfBfaf490682045cD70132D6ADa5DccfDB682;
amounts[32] = 2;
wallets[33] = 0x95f8018494CeF5b069D009d115e05D360B81a34d;
amounts[33] = 2;
wallets[34] = 0x99e73A69536f7365fD4f2F2e5391f5dAa484b99b;
amounts[34] = 2;
wallets[35] = 0xa8674b0F20d44fE47A3F733036038977cC31f8FD;
amounts[35] = 2;
wallets[36] = 0xACdE31cb0eBa050DbbE499051A2F5BD9FEABa60F;
amounts[36] = 2;
wallets[37] = 0xad050BF165033DD1b86D23a75504e079B2053F2C;
amounts[37] = 2;
wallets[38] = 0xaEA57cBf427757d9D51F0FB024cd7DFEB15c0275;
amounts[38] = 2;
wallets[39] = 0xBA5EDc0d2Ae493C9574328d77dc36eEF19F699e2;
amounts[39] = 2;
wallets[40] = 0xBE03aB0c13af2fD997B437425f0061c046F18f1A;
amounts[40] = 2;
wallets[41] = 0xD2e39bFE299634b4269cBA0b273c0bA207128B4f;
amounts[41] = 2;
wallets[42] = 0xDa6B34b0624521F3C051995Bd3aF29e8284179E2;
amounts[42] = 2;
wallets[43] = 0xDc8BF95C4850224E09f79B0a753D1EDF4eF7a0BA;
amounts[43] = 2;
wallets[44] = 0xE2D481cdD32F67eA3A07E416F45927830acc273B;
amounts[44] = 2;
wallets[45] = 0xE5CA890A0eF2F128EB3267e4711c6bf3306Ec024;
amounts[45] = 2;
wallets[46] = 0xF0e1BDa8021506B4Eee4c969F1Dd5b49271660d8;
amounts[46] = 2;
wallets[47] = 0xFe5573C66273313034F7fF6050c54b5402553716;
amounts[47] = 2;
wallets[48] = 0x0496c84FD12aBE8F892Fa705B1f2046113404023;
amounts[48] = 1;
wallets[49] = 0x089786580b66E76131D8EF9f7D165D1525338143;
amounts[49] = 1;
wallets[50] = 0x08a032033EBaC2822221a813B16a714A6eBA9B3b;
amounts[50] = 1;
wallets[51] = 0x0a3b151beeb0ACb8a16CDaD2E186bc6685b821B0;
amounts[51] = 1;
wallets[52] = 0x0B7576A64A0F4b4924D55eD328Ede4979446521B;
amounts[52] = 1;
wallets[53] = 0x0c368d683c616073D48fA26f7796DFe3F8d46526;
amounts[53] = 1;
wallets[54] = 0x0C963DC578B6106Cf526021a320f80C42Fc41884;
amounts[54] = 1;
wallets[55] = 0x0DBb9738319F1B2A8C087cC738Cd7EDdBF8676c5;
amounts[55] = 1;
wallets[56] = 0x0f7A303222FdD8A6Ef67E1F67E8BBF1b9Ce9484a;
amounts[56] = 1;
wallets[57] = 0x149fD340cA0DF54228aACdAD7755B05d0E2b23d9;
amounts[57] = 1;
wallets[58] = 0x1625Ad776034675046aFf7a48f3ac61B62C0e27b;
amounts[58] = 1;
wallets[59] = 0x17A9664077a3B50682d5C12415c3e88C23377708;
amounts[59] = 1;
wallets[60] = 0x17dE8591163A8A9B6752efB9d05Cb7290e887A6C;
amounts[60] = 1;
wallets[61] = 0x184E1642E3Afcd1f4FdCC584CC70f969FAE3e3e1;
amounts[61] = 1;
wallets[62] = 0x18E804E61C44FD194753Ce89B32A87aCD8435A8D;
amounts[62] = 1;
wallets[63] = 0x1939A73FEB7CD1799D116Feeda5f2deAC56C1a5f;
amounts[63] = 1;
wallets[64] = 0x19BB567Ac0116876fC74f2F5512EAeEC07cCF968;
amounts[64] = 1;
wallets[65] = 0x1D047394a82D08aC977ca5e5AAd0eA752C8c7b02;
amounts[65] = 1;
wallets[66] = 0x1D13bAc26f5e81bA836c9C8b110B10Aa20dfb8e8;
amounts[66] = 1;
wallets[67] = 0x1d935f516D5008Ff3153ab789258Bf5d8cF604f5;
amounts[67] = 1;
wallets[68] = 0x203B3AF2F20F9acA9B16EA04d5E9dE5A9570F907;
amounts[68] = 1;
wallets[69] = 0x238FF6b24f34F09e04d26Be3eEAA67c7449Cd0B1;
amounts[69] = 1;
wallets[70] = 0x24aC005adCBb3d9551474B43f855191e12e8A4Ec;
amounts[70] = 1;
wallets[71] = 0x26440CbF9BDbEAE1e96504007b6AA6c1d0e98237;
amounts[71] = 1;
wallets[72] = 0x27dA2bc427D470a1fD264fB4f17D3F28B9438dBd;
amounts[72] = 1;
wallets[73] = 0x2A41282434f89f5bbF272B1091A7A0ceFD22Ccd8;
amounts[73] = 1;
wallets[74] = 0x2CE4997282a150c4e844c9084E9C7eA616F16cc1;
amounts[74] = 1;
wallets[75] = 0x2E0D63fFCB08eA20fF3AcDbB72dfEc97343885d2;
amounts[75] = 1;
wallets[76] = 0x34433Cb54D406d231cD511567f33CE1914FC888E;
amounts[76] = 1;
wallets[77] = 0x38d23C7451E405d6ea982783273b46099F764d15;
amounts[77] = 1;
wallets[78] = 0x3B0e003793011c012d8261B0Aafd993eAB01F2Cf;
amounts[78] = 1;
wallets[79] = 0x3C86431f46f421b6c881217891Bc0D772C19356e;
amounts[79] = 1;
wallets[80] = 0x3Cc3245178Ca4B8b763E1E5689e716c747BB33de;
amounts[80] = 1;
wallets[81] = 0x3d79952D73bb733fc3C68C6CaC405Dd7B7EB64ac;
amounts[81] = 1;
wallets[82] = 0x3D7f2165d3d54eAF9F6af52fd8D91669D4E02ebC;
amounts[82] = 1;
wallets[83] = 0x3dC7F8850CbfE558eeE8442d553fdE8eb49DcF5D;
amounts[83] = 1;
wallets[84] = 0x43350Cd91b1f9b61A885688FA122cC2Af5e39461;
amounts[84] = 1;
wallets[85] = 0x437d4b9A93F4a7fF5e8F855C85F8590D1c01d1fD;
amounts[85] = 1;
wallets[86] = 0x473C923543d9c91209B087f456d4A796B52EF96C;
amounts[86] = 1;
wallets[87] = 0x4A6fb087F838a2AD01311b1Ca981D88932d77AA3;
amounts[87] = 1;
wallets[88] = 0x4B92e36CeD303EEB59Bd6c5daC555b2be13Fe2B6;
amounts[88] = 1;
wallets[89] = 0x504Db4b96Cb3462C9B2e16F20d8c26926CBa6d47;
amounts[89] = 1;
wallets[90] = 0x514c9C0F1BC120f57183BFE4ae092fF0Be13A31f;
amounts[90] = 1;
wallets[91] = 0x51ec5e1b8B3C4C6baE49619e657F94C4AD577b45;
amounts[91] = 1;
wallets[92] = 0x55ecA4D1c9eA7021509a7cd88C68c279dABDd37d;
amounts[92] = 1;
wallets[93] = 0x568B491Fb2b4B9440f6D05E7723Df0060fDAEF1c;
amounts[93] = 1;
wallets[94] = 0x59D14847C0D1584a867fe98acAbB1Dc95AB1496f;
amounts[94] = 1;
wallets[95] = 0x5B24b3E12C965140E0512FB9d1b58Cc7F4E1AEAD;
amounts[95] = 1;
wallets[96] = 0x5bd565DFA27C47C31468eCAC5c13205E7ebca159;
amounts[96] = 1;
wallets[97] = 0x5d972c305f05757D9F8c80c821469fe41B058558;
amounts[97] = 1;
wallets[98] = 0x6121dd45f2cbFB60B50aAb17589269dF19f59b80;
amounts[98] = 1;
wallets[99] = 0x618De692363B578091EA53a8fCAE92d909Eed0e1;
amounts[99] = 1;
wallets[100] = 0x634Dd995909a93b0611924f1FfE500846A0fe112;
amounts[100] = 1;
wallets[101] = 0x6B1C1Efd69bc7F8964A32914CBC95Ab5320f5487;
amounts[101] = 1;
wallets[102] = 0x6efF21c2BFDf83a33aa690fe3DB17Fc672244907;
amounts[102] = 1;
wallets[103] = 0x71CB3467D3d2528cCeACa2c3931b51ad0379C25B;
amounts[103] = 1;
wallets[104] = 0x72BFfD1C8D60d31404eFfADB2494D2372DeF794f;
amounts[104] = 1;
wallets[105] = 0x73954a7081ae0bE4a0b1D3bDEa98666eA8Aa0ba8;
amounts[105] = 1;
wallets[106] = 0x773D715200aB5c07F39dB9772E3c83C48534a585;
amounts[106] = 1;
wallets[107] = 0x7e5b399E254665590266ac6a9e2A1e3336576CC0;
amounts[107] = 1;
wallets[108] = 0x80eC8c4e035A9A200155a3F8d3E5fD29b2d8Ca42;
amounts[108] = 1;
wallets[109] = 0x83b97b9454D90791480cFdA42c01D461D4D4EaA3;
amounts[109] = 1;
wallets[110] = 0x8603Fb5889f35BCB792c75507cb9B4701aA96c86;
amounts[110] = 1;
wallets[111] = 0x8E20e3826Ddb5b0949DDea3af1ccEE1de7e6BCf4;
amounts[111] = 1;
wallets[112] = 0x9204c91Bf387F26D98493CaB3F9b5B1a59E55dBE;
amounts[112] = 1;
wallets[113] = 0x92C5ADf5a4f709B55bb67150f3aF69b3419647AC;
amounts[113] = 1;
wallets[114] = 0x940A8d538bA3DbcB2598394821f1AD8f7da62002;
amounts[114] = 1;
wallets[115] = 0x994212438EAB21e807308cc992AD49A94D80b5eb;
amounts[115] = 1;
wallets[116] = 0x9EAb4b2feEd9483838D2e9B7c1AD407A18624dF4;
amounts[116] = 1;
wallets[117] = 0xa31A547758f695822fE582C76a6C404D5adC988F;
amounts[117] = 1;
wallets[118] = 0xA35A48a2A309F7bC519D40305c9D290cf4DB37F2;
amounts[118] = 1;
wallets[119] = 0xA61430D015a73958b1eA26eA64B6204FdAfbEF1f;
amounts[119] = 1;
wallets[120] = 0xa6667F1A0beA0D7B96B47CC1357631842d05E40F;
amounts[120] = 1;
wallets[121] = 0xa93c67d5E1676C9D87557405DA38E8A89d6717df;
amounts[121] = 1;
wallets[122] = 0xAb8dFD3191a182855c8f5C297DFa8f9f3795EC88;
amounts[122] = 1;
wallets[123] = 0xb08901cf8Ce4639745aA98759d6d71B130b44B5f;
amounts[123] = 1;
wallets[124] = 0xB11A3F8739dFD4f1993FB86FA305710BF60B3994;
amounts[124] = 1;
wallets[125] = 0xb14C35B69CA390C359B75A6CD51B30429D8024E0;
amounts[125] = 1;
wallets[126] = 0xb26647Ad89B557C82aDF494142814FE44Cb3bB62;
amounts[126] = 1;
wallets[127] = 0xb796f2847B022C91bF80cdAB05C3F0C0C948963c;
amounts[127] = 1;
wallets[128] = 0xB7D7597994A0ee274F50d071a38104201D9db0d5;
amounts[128] = 1;
wallets[129] = 0xb855567A17c266C1D82a52bb093EF5b6a66Deb01;
amounts[129] = 1;
wallets[130] = 0xB8DC9d4Bbeb6705FdBa1F89458a4bC2a2066a6c9;
amounts[130] = 1;
wallets[131] = 0xbD947650EB696fed8d260936e33bc43dE41B8462;
amounts[131] = 1;
wallets[132] = 0xc1BC1b00A67838bb6d862c5B333aEc45b1a9BB03;
amounts[132] = 1;
wallets[133] = 0xC228548e89566fBABF7ddC9b51E442cB10f1c338;
amounts[133] = 1;
wallets[134] = 0xC3b8Fdbb0E0D7c4027084b0996f0129AB1a29DC2;
amounts[134] = 1;
wallets[135] = 0xc657ce843243AA3bD9275CD8cFD0112F0EAE2996;
amounts[135] = 1;
wallets[136] = 0xC709c2e280f246123d0bb72394BC79f10fBDAb4c;
amounts[136] = 1;
wallets[137] = 0xcB20F188dC526074F89267EfBFB18ac874Cee4B9;
amounts[137] = 1;
wallets[138] = 0xCE44bEA3722D0352cF83BF2359fda0ed27E7134C;
amounts[138] = 1;
wallets[139] = 0xD2B481b6e48F9Ef4204EB6061BA7cf33dadCC286;
amounts[139] = 1;
wallets[140] = 0xd3433226789c415a06c787dB599eb5fC86cb4212;
amounts[140] = 1;
wallets[141] = 0xd70676Cfa67Abc65A8C39f049d62EEA30E3080CF;
amounts[141] = 1;
wallets[142] = 0xD91DC7c83bd01b91Cb25019DFc4E35BC6FaaB814;
amounts[142] = 1;
wallets[143] = 0xda21d116A3F1A001C3e3a300DD75422263c8DcD6;
amounts[143] = 1;
wallets[144] = 0xDA8bbc8B25AB8b5cB47e7c271400Fe130Fcc2CE7;
amounts[144] = 1;
wallets[145] = 0xdC0c9924DD2509105f6F6Bc322E35224f342BD12;
amounts[145] = 1;
wallets[146] = 0xDe1F3CA8d0666DD3d53a608a9DA1c4D472d135bB;
amounts[146] = 1;
wallets[147] = 0xdFd3B58cFc180168FAEBb6366b98aFF25FE1F8F1;
amounts[147] = 1;
wallets[148] = 0xe0D209b7324d982BACb757F724EbE00a9792aC28;
amounts[148] = 1;
wallets[149] = 0xE236E5f3e7BB981237Bc88767Be0444f9f159487;
amounts[149] = 1;
wallets[150] = 0xe3b84986472f7FeA21e7f7B447456160b304D2Ed;
amounts[150] = 1;
wallets[151] = 0xE840fE7f29E61e2DbC6a7C1947E51fAd47f20B5d;
amounts[151] = 1;
wallets[152] = 0xec15cBF5E27a9C0f0Df21D18dcF2C5FaBc621686;
amounts[152] = 1;
wallets[153] = 0xef664E3Aa27Ff8aE65Fff226D3E231866180d921;
amounts[153] = 1;
wallets[154] = 0xf07D2231948Fb5Bc45e3f2014dfa4f2511A0d637;
amounts[154] = 1;
wallets[155] = 0xf2177E53DB73cDAA0BD15D891D3d3378a4098376;
amounts[155] = 1;
wallets[156] = 0xF50D4d008c249B26c16a7047B5Ef2C8d551570Ea;
amounts[156] = 1;
wallets[157] = 0xf754cE4Cd7A8Ec94716c0cEd4BD1a8DA8a8E1Bbf;
amounts[157] = 1;
wallets[158] = 0xf884Be46c53B7F12D0bDe56E934af05A1CAaF1A2;
amounts[158] = 1;
wallets[159] = 0xFA4E98A3973AC6D51918e69D49f749219518C5A5;
amounts[159] = 1;
wallets[160] = 0xfd3f0628e539c0d346d920832ECCadB296c2EA9C;
amounts[160] = 1;
wallets[161] = 0xfe8828D8040e101d5118B8E5C3628532182256fD;
amounts[161] = 1;
wallets[162] = 0xffa4410D9d8e63f255146475f0e3326667996482;
amounts[162] = 1;
}
}
src/bitmons/libraries/BitmonsOneOfOneDraw.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @notice Five distinct token IDs from the complete collection, using the fixed launch word.
/// @dev A separate domain keeps these assignments independent of the launch's backer awards.
library BitmonsOneOfOneDraw {
bytes32 internal constant DOMAIN = keccak256("Bitmons.one-of-one.v1");
uint256 internal constant COUNT = 5;
error InvalidSupply();
function tokenIds(uint256 seed, address collection, address launch, uint256 supply)
internal
pure
returns (uint256[5] memory ids)
{
if (supply < COUNT) revert InvalidSupply();
// Sparse, in-memory partial Fisher-Yates: only the five changed slots are needed.
uint256[5] memory slots;
uint256[5] memory offsets;
for (uint256 i; i < COUNT; ++i) {
uint256 remaining = supply - i;
uint256 threshold = (type(uint256).max % remaining + 1) % remaining;
uint256 word;
uint256 attempt;
do {
word = uint256(keccak256(abi.encode(DOMAIN, seed, collection, launch, supply, i, attempt++)));
} while (word < threshold);
uint256 slot = word % remaining;
ids[i] = _offset(slot, slots, offsets, i) + 1;
uint256 last = _offset(remaining - 1, slots, offsets, i);
slots[i] = slot;
offsets[i] = last;
}
}
function _offset(uint256 slot, uint256[5] memory slots, uint256[5] memory offsets, uint256 count)
private
pure
returns (uint256)
{
// Latest write wins. Removed tail slots are outside every subsequent draw's range.
while (count != 0) {
--count;
if (slots[count] == slot) return offsets[count];
}
return slot;
}
}
src/interfaces/IFWAPurchaseCallback.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title IFWAPurchaseCallback
/// @notice Settlement notification for a registry-recognized FWAIR launch or an ERC-165-opted-in NFT collection.
/// @dev Implementations must authenticate both `msg.sender` (the notifier trusted by `fwa`) and
/// `fwa`. Notifications are best-effort, so correctness must not depend on receiving one.
interface IFWAPurchaseCallback {
enum Outcome {
PurchaserKeptNFT,
PurchaserTookETH,
PurchaserTookFWA,
PurchaserRelistedNFT
}
/// @param fwa Pool in which the purchase settled.
/// @param listingId Settled FWA listing.
/// @param purchaser Address originally allocated the NFT by FWA.
/// @param resolver Address that submitted the successful settlement transaction.
/// @param backing Gross ETH backing attached to the listing.
/// @param settlementAmount Net ETH returned to the depositor for NFT/relist outcomes, or the ETH paid
/// to the purchaser/consumed by the token buy for backing outcomes.
/// @param outcome Asset/result selected by the successful resolution path.
function onFWAPurchase(
address fwa,
uint256 listingId,
address purchaser,
address resolver,
uint256 backing,
uint256 settlementAmount,
Outcome outcome
) external;
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"solady/=lib/solady/",
"forge-std/=lib/forge-std/src/",
"@chainlink/contracts/=lib/chainlink-evm/contracts/",
"@uniswap/v4-core/=lib/v4-core/",
"@uniswap/v4-periphery/=lib/v4-periphery/",
"@openzeppelin/contracts/=lib/v4-core/lib/openzeppelin-contracts/contracts/",
"@openzeppelin/[email protected]/=test/bitmons/vendor/openzeppelin-4.9.6/",
"project/=/",
"solady-0.1.26/=lib/solady-0.1.26/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"chainlink-evm/=lib/chainlink-evm/",
"ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"permit2/=lib/v4-periphery/lib/permit2/",
"solmate/=lib/v4-core/lib/solmate/",
"v4-core/=lib/v4-core/src/",
"v4-periphery/=lib/v4-periphery/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.