Verified contractPartialMIT
PanoramaWorkflowLedger
Address0xe2f6571a4c42002ba157fda9ed957368579a891b
- Balance
0 ETH
- Transactions
67
- Compiler
solc 0.8.34
- Same code
Only this contract
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- Yes, 10,000 runs
- EVM version
- prague
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,193,246
- Creation transaction
- 0x56c288203e…6a12978226
8 files
- src/PanoramaWorkflowLedger.solmain11.28 KB
- node_modules/solady/src/auth/Ownable.sol12.55 KB
- node_modules/solady/src/utils/DynamicBufferLib.sol43.74 KB
- node_modules/solady/src/utils/LibBytes.sol38.18 KB
- node_modules/solady/src/utils/LibString.sol44.25 KB
- node_modules/solady/src/utils/SSTORE2.sol12.63 KB
- src/interfaces/IPanoramaStorage.sol7.71 KB
- src/interfaces/IPanoramaWorkflowLedger.sol1.82 KB
src/PanoramaWorkflowLedger.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;
import { Ownable } from "solady/auth/Ownable.sol";
import { SSTORE2 } from "solady/utils/SSTORE2.sol";
import { LibString } from "solady/utils/LibString.sol";
import { DynamicBufferLib } from "solady/utils/DynamicBufferLib.sol";
import { IPanoramaStorage } from "./interfaces/IPanoramaStorage.sol";
import { IPanoramaWorkflowLedger } from "./interfaces/IPanoramaWorkflowLedger.sol";
/// @title PanoramaWorkflowLedger
/// @author Yigit Duman (@yigitduman)
/// @notice Companion to PanoramaStorage that records, per tableau, the ORDERED list of
/// generation steps that made it: tile, seam, retouch composite, inpaint repaints,
/// grain. Each step names a workflow registered in PanoramaStorage's `Workflow[]`
/// (or `NO_WORKFLOW` for a deterministic non-ComfyUI step such as a composite or
/// the grain pass) plus that step's parameters as opaque bytes (JSON written by the
/// pipeline), so a tableau can be reproduced step by step.
///
/// PanoramaStorage is immutable and has no spare field, so the steps live here and
/// PanoramaRendererV3 reads them through `renderWorkflows`. Workflow names stay out
/// of NFT metadata: a step there is its workflow id and its parameters.
/// Writers are PanoramaStorage's own owner and authorized operators (the pipeline's
/// minter wallet already is one); only the store owner can clear a token's steps.
/// Steps are append-only otherwise. Parameters are stored with SSTORE2 in chunks of
/// at most `MAX_CHUNK_SIZE` bytes, so their size is bounded only by gas.
contract PanoramaWorkflowLedger is IPanoramaWorkflowLedger {
using LibString for uint256;
using DynamicBufferLib for DynamicBufferLib.DynamicBuffer;
/// @notice Workflow id of a step that ran no registered ComfyUI workflow.
uint16 public constant NO_WORKFLOW = type(uint16).max;
/// @notice Largest SSTORE2 chunk (the EIP-170 code size limit minus the STOP prefix).
uint256 public constant MAX_CHUNK_SIZE = 24_575;
/// @notice Steps a token can hold, so rendering a tokenURI stays bounded.
uint256 public constant MAX_STEPS = 64;
/// @dev Panorama mints token ids 1-365.
uint256 internal constant MAX_TOKEN_ID = 365;
struct Step {
uint16 workflowId;
/// @dev SSTORE2 pointers; the params are their concatenation (none = empty params).
address[] paramChunks;
}
// forge-lint: disable-next-line(screaming-snake-case-immutable)
IPanoramaStorage public immutable store;
mapping(uint256 tokenId => Step[]) internal _steps;
constructor(IPanoramaStorage store_) {
store = store_;
}
/// @dev PanoramaStorage's owner or one of its authorized operators.
modifier onlyWriter() {
if (msg.sender != _storeOwner() && !store.authorizedOperators(msg.sender)) revert Unauthorized();
_;
}
/*//////////////////////////////////////////////////////////////
MUTATIONS
//////////////////////////////////////////////////////////////*/
/// @notice Appends steps to a token, after any it already has.
function appendSteps(uint256 tokenId, uint16[] calldata workflowIds, bytes[] calldata params) external onlyWriter {
_append(tokenId, workflowIds, params, store.getWorkflowCount());
}
/// @notice `appendSteps` for several tokens in one transaction (backfills).
function appendStepsBatch(
uint256[] calldata tokenIds,
uint16[][] calldata workflowIds,
bytes[][] calldata params
) external onlyWriter {
uint256 len = tokenIds.length;
if (len != workflowIds.length || len != params.length) revert LengthMismatch();
if (len == 0) revert NoSteps();
uint256 workflowCount = store.getWorkflowCount();
for (uint256 i; i < len; ++i) {
_append(tokenIds[i], workflowIds[i], params[i], workflowCount);
}
}
/// @notice Removes every step of a token (corrections). Store owner only.
function clearSteps(uint256 tokenId) external {
if (msg.sender != _storeOwner()) revert Unauthorized();
if (tokenId == 0 || tokenId > MAX_TOKEN_ID) revert InvalidTokenId();
delete _steps[tokenId];
emit StepsCleared(tokenId);
}
function _append(
uint256 tokenId,
uint16[] calldata workflowIds,
bytes[] calldata params,
uint256 workflowCount
) internal {
if (tokenId == 0 || tokenId > MAX_TOKEN_ID) revert InvalidTokenId();
uint256 count = workflowIds.length;
if (count != params.length) revert LengthMismatch();
if (count == 0) revert NoSteps();
Step[] storage steps = _steps[tokenId];
uint256 fromIndex = steps.length;
if (fromIndex + count > MAX_STEPS) revert TooManySteps();
for (uint256 i; i < count; ++i) {
uint16 workflowId = workflowIds[i];
if (workflowId != NO_WORKFLOW && workflowId >= workflowCount) revert UnknownWorkflow(workflowId);
Step storage step = steps.push();
step.workflowId = workflowId;
bytes calldata data = params[i];
uint256 size = data.length;
for (uint256 start; start < size; start += MAX_CHUNK_SIZE) {
uint256 end = start + MAX_CHUNK_SIZE;
if (end > size) end = size;
step.paramChunks.push(SSTORE2.write(data[start:end]));
}
}
emit StepsAppended(tokenId, fromIndex, count);
}
/*//////////////////////////////////////////////////////////////
VIEWS
//////////////////////////////////////////////////////////////*/
function stepCount(uint256 tokenId) external view returns (uint256) {
return _steps[tokenId].length;
}
function getStep(uint256 tokenId, uint256 index) external view returns (uint16 workflowId, bytes memory params) {
Step[] storage steps = _steps[tokenId];
if (index >= steps.length) revert StepIndexOutOfBounds();
Step storage step = steps[index];
return (step.workflowId, _readParams(step));
}
function getSteps(uint256 tokenId) external view returns (uint16[] memory workflowIds, bytes[] memory params) {
Step[] storage steps = _steps[tokenId];
uint256 count = steps.length;
workflowIds = new uint16[](count);
params = new bytes[](count);
for (uint256 i; i < count; ++i) {
workflowIds[i] = steps[i].workflowId;
params[i] = _readParams(steps[i]);
}
}
/*//////////////////////////////////////////////////////////////
RENDERING
//////////////////////////////////////////////////////////////*/
/// @notice A token's steps as a JSON array, "" when it has none:
/// `[{"step":1,"id":3,"params":"<params>"},{"step":2,"params":"..."}]`.
/// `NO_WORKFLOW` steps carry no id. Params are always embedded as an
/// escaped JSON string (never raw) and bytes that are not valid UTF-8 become
/// U+FFFD, so no write can break the tokenURI JSON.
function renderWorkflows(uint256 tokenId) external view returns (string memory) {
Step[] storage steps = _steps[tokenId];
uint256 count = steps.length;
if (count == 0) return "";
DynamicBufferLib.DynamicBuffer memory buf;
buf.p("[");
for (uint256 i; i < count; ++i) {
Step storage step = steps[i];
buf.p(i == 0 ? bytes('{"step":') : bytes(',{"step":'));
buf.p(bytes((i + 1).toString()));
uint16 workflowId = step.workflowId;
if (workflowId != NO_WORKFLOW) {
buf.p(',"id":');
buf.p(bytes(uint256(workflowId).toString()));
}
buf.p(',"params":"');
buf.p(bytes(_escape(_readParams(step))));
buf.p('"}');
}
buf.p("]");
return string(buf.data);
}
/*//////////////////////////////////////////////////////////////
INTERNAL
//////////////////////////////////////////////////////////////*/
function _storeOwner() internal view returns (address) {
return Ownable(address(store)).owner();
}
function _readParams(Step storage step) internal view returns (bytes memory) {
address[] storage chunks = step.paramChunks;
uint256 count = chunks.length;
if (count == 0) return "";
if (count == 1) return SSTORE2.read(chunks[0]);
DynamicBufferLib.DynamicBuffer memory buf;
for (uint256 i; i < count; ++i) {
buf.p(SSTORE2.read(chunks[i]));
}
return buf.data;
}
/// @dev JSON-escapes `s` for use inside double quotes, after replacing invalid UTF-8.
function _escape(bytes memory s) internal pure returns (string memory) {
if (!LibString.is7BitASCII(string(s))) s = _toValidUtf8(s);
return LibString.escapeJSON(string(s));
}
/// @dev `s` itself when it is valid UTF-8, else a copy in which every byte that does not
/// start a valid sequence is replaced by U+FFFD.
function _toValidUtf8(bytes memory s) internal pure returns (bytes memory) {
uint256 len = s.length;
uint256 i;
while (i < len) {
uint256 n = _utf8SequenceLength(s, i);
if (n == 0) break;
i += n;
}
if (i == len) return s;
bytes memory out = new bytes(len * 3);
uint256 o;
i = 0;
while (i < len) {
uint256 n = _utf8SequenceLength(s, i);
if (n == 0) {
out[o] = 0xEF;
out[o + 1] = 0xBF;
out[o + 2] = 0xBD;
o += 3;
++i;
} else {
for (uint256 k; k < n; ++k) {
out[o++] = s[i++];
}
}
}
assembly ("memory-safe") {
mstore(out, o) // Shrink to the bytes written.
}
return out;
}
/// @dev Length of the well-formed UTF-8 sequence starting at `s[i]` (RFC 3629: no
/// overlongs, surrogates or code points past U+10FFFF), or 0 if there is none.
function _utf8SequenceLength(bytes memory s, uint256 i) internal pure returns (uint256) {
uint8 c = uint8(s[i]);
if (c < 0x80) return 1;
uint256 n;
uint8 lo = 0x80;
uint8 hi = 0xBF;
if (c >= 0xC2 && c <= 0xDF) {
n = 2;
} else if (c >= 0xE0 && c <= 0xEF) {
n = 3;
if (c == 0xE0) lo = 0xA0;
else if (c == 0xED) hi = 0x9F;
} else if (c >= 0xF0 && c <= 0xF4) {
n = 4;
if (c == 0xF0) lo = 0x90;
else if (c == 0xF4) hi = 0x8F;
} else {
return 0;
}
if (i + n > s.length) return 0;
for (uint256 k = 1; k < n; ++k) {
uint8 b = uint8(s[i + k]);
if (b < lo || b > hi) return 0;
lo = 0x80;
hi = 0xBF;
}
return n;
}
}
node_modules/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();
_;
}
}
node_modules/solady/src/utils/DynamicBufferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for buffers with automatic capacity resizing.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/DynamicBufferLib.sol)
/// @author Modified from cozyco (https://github.com/samkingco/cozyco/blob/main/contracts/utils/DynamicBuffer.sol)
library DynamicBufferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Type to represent a dynamic buffer in memory.
/// You can directly assign to `data`, and the `p` function will
/// take care of the memory allocation.
struct DynamicBuffer {
bytes data;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// Some of these functions return the same buffer for function chaining.
// e.g. `buffer.p("1").p("2")`.
/// @dev Shorthand for `buffer.data.length`.
function length(DynamicBuffer memory buffer) internal pure returns (uint256) {
return buffer.data.length;
}
/// @dev Reserves at least `minimum` amount of contiguous memory.
function reserve(DynamicBuffer memory buffer, uint256 minimum)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = buffer;
uint256 n = buffer.data.length;
if (minimum > n) {
uint256 i = 0x40;
do {} while ((i <<= 1) < minimum);
bytes memory data;
/// @solidity memory-safe-assembly
assembly {
data := 0x01
mstore(data, sub(i, n))
}
result = p(result, data);
}
}
/// @dev Clears the buffer without deallocating the memory.
function clear(DynamicBuffer memory buffer)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
/// @solidity memory-safe-assembly
assembly {
mstore(mload(buffer), 0)
}
result = buffer;
}
/// @dev Returns a string pointing to the underlying bytes data.
/// Note: The string WILL change if the buffer is updated.
function s(DynamicBuffer memory buffer) internal pure returns (string memory) {
return string(buffer.data);
}
/// @dev Appends `data` to `buffer`.
function p(DynamicBuffer memory buffer, bytes memory data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = buffer;
if (data.length == uint256(0)) return result;
/// @solidity memory-safe-assembly
assembly {
let w := not(0x1f)
let bufData := mload(buffer)
let bufDataLen := mload(bufData)
let newBufDataLen := add(mload(data), bufDataLen)
// Some random prime number to multiply `cap`, so that
// we know that the `cap` is for a dynamic buffer.
// Selected to be larger than any memory pointer realistically.
let prime := 1621250193422201
let cap := mload(add(bufData, w)) // `mload(sub(bufData, 0x20))`.
// Extract `cap`, initializing it to zero if it is not a multiple of `prime`.
cap := mul(div(cap, prime), iszero(mod(cap, prime)))
// Expand / Reallocate memory if required.
// Note that we need to allocate an extra word for the length, and
// and another extra word as a safety word (giving a total of 0x40 bytes).
// Without the safety word, the backwards copying can cause a buffer overflow.
for {} iszero(lt(newBufDataLen, cap)) {} {
// Approximately more than double the capacity to ensure more than enough space.
let newCap := and(add(cap, add(or(cap, newBufDataLen), 0x20)), w)
// If the memory is contiguous, we can simply expand it.
if iszero(or(xor(mload(0x40), add(bufData, add(0x40, cap))), iszero(cap))) {
// Store `cap * prime` in the word before the length.
mstore(add(bufData, w), mul(prime, newCap))
mstore(0x40, add(bufData, add(0x40, newCap))) // Expand the memory allocation.
break
}
// Set the `newBufData` to point to the word after `cap`.
let newBufData := add(mload(0x40), 0x20)
mstore(0x40, add(newBufData, add(0x40, newCap))) // Reallocate the memory.
mstore(buffer, newBufData) // Store the `newBufData`.
// Copy `bufData` one word at a time, backwards.
for { let o := and(add(bufDataLen, 0x20), w) } 1 {} {
mstore(add(newBufData, o), mload(add(bufData, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
// Store `cap * prime` in the word before the length.
mstore(add(newBufData, w), mul(prime, newCap))
bufData := newBufData // Assign `newBufData` to `bufData`.
break
}
// If it's a reserve operation, set the variables to skip the appending.
if eq(data, 0x01) {
mstore(data, 0x00)
newBufDataLen := bufDataLen
}
// Copy `data` one word at a time, backwards.
for { let o := and(add(mload(data), 0x20), w) } 1 {} {
mstore(add(add(bufData, bufDataLen), o), mload(add(data, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
mstore(add(add(bufData, 0x20), newBufDataLen), 0) // Zeroize the word after the buffer.
mstore(bufData, newBufDataLen) // Store the length.
}
}
/// @dev Appends `data0`, `data1` to `buffer`.
function p(DynamicBuffer memory buffer, bytes memory data0, bytes memory data1)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(p(buffer, data0), data1);
}
/// @dev Appends `data0` .. `data2` to `buffer`.
function p(
DynamicBuffer memory buffer,
bytes memory data0,
bytes memory data1,
bytes memory data2
) internal pure returns (DynamicBuffer memory result) {
_deallocate(result);
result = p(p(p(buffer, data0), data1), data2);
}
/// @dev Appends `data0` .. `data3` to `buffer`.
function p(
DynamicBuffer memory buffer,
bytes memory data0,
bytes memory data1,
bytes memory data2,
bytes memory data3
) internal pure returns (DynamicBuffer memory result) {
_deallocate(result);
result = p(p(p(p(buffer, data0), data1), data2), data3);
}
/// @dev Appends `data0` .. `data4` to `buffer`.
function p(
DynamicBuffer memory buffer,
bytes memory data0,
bytes memory data1,
bytes memory data2,
bytes memory data3,
bytes memory data4
) internal pure returns (DynamicBuffer memory result) {
_deallocate(result);
result = p(p(p(p(p(buffer, data0), data1), data2), data3), data4);
}
/// @dev Appends `data0` .. `data5` to `buffer`.
function p(
DynamicBuffer memory buffer,
bytes memory data0,
bytes memory data1,
bytes memory data2,
bytes memory data3,
bytes memory data4,
bytes memory data5
) internal pure returns (DynamicBuffer memory result) {
_deallocate(result);
result = p(p(p(p(p(p(buffer, data0), data1), data2), data3), data4), data5);
}
/// @dev Appends `data0` .. `data6` to `buffer`.
function p(
DynamicBuffer memory buffer,
bytes memory data0,
bytes memory data1,
bytes memory data2,
bytes memory data3,
bytes memory data4,
bytes memory data5,
bytes memory data6
) internal pure returns (DynamicBuffer memory result) {
_deallocate(result);
result = p(p(p(p(p(p(p(buffer, data0), data1), data2), data3), data4), data5), data6);
}
/// @dev Appends `abi.encodePacked(bool(data))` to buffer.
function pBool(DynamicBuffer memory buffer, bool data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
uint256 casted;
/// @solidity memory-safe-assembly
assembly {
casted := iszero(iszero(data))
}
result = p(buffer, _single(casted, 1));
}
/// @dev Appends `abi.encodePacked(address(data))` to buffer.
function pAddress(DynamicBuffer memory buffer, address data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(uint256(uint160(data)), 20));
}
/// @dev Appends `abi.encodePacked(uint8(data))` to buffer.
function pUint8(DynamicBuffer memory buffer, uint8 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 1));
}
/// @dev Appends `abi.encodePacked(uint16(data))` to buffer.
function pUint16(DynamicBuffer memory buffer, uint16 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 2));
}
/// @dev Appends `abi.encodePacked(uint24(data))` to buffer.
function pUint24(DynamicBuffer memory buffer, uint24 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 3));
}
/// @dev Appends `abi.encodePacked(uint32(data))` to buffer.
function pUint32(DynamicBuffer memory buffer, uint32 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 4));
}
/// @dev Appends `abi.encodePacked(uint40(data))` to buffer.
function pUint40(DynamicBuffer memory buffer, uint40 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 5));
}
/// @dev Appends `abi.encodePacked(uint48(data))` to buffer.
function pUint48(DynamicBuffer memory buffer, uint48 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 6));
}
/// @dev Appends `abi.encodePacked(uint56(data))` to buffer.
function pUint56(DynamicBuffer memory buffer, uint56 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 7));
}
/// @dev Appends `abi.encodePacked(uint64(data))` to buffer.
function pUint64(DynamicBuffer memory buffer, uint64 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 8));
}
/// @dev Appends `abi.encodePacked(uint72(data))` to buffer.
function pUint72(DynamicBuffer memory buffer, uint72 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 9));
}
/// @dev Appends `abi.encodePacked(uint80(data))` to buffer.
function pUint80(DynamicBuffer memory buffer, uint80 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 10));
}
/// @dev Appends `abi.encodePacked(uint88(data))` to buffer.
function pUint88(DynamicBuffer memory buffer, uint88 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 11));
}
/// @dev Appends `abi.encodePacked(uint96(data))` to buffer.
function pUint96(DynamicBuffer memory buffer, uint96 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 12));
}
/// @dev Appends `abi.encodePacked(uint104(data))` to buffer.
function pUint104(DynamicBuffer memory buffer, uint104 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 13));
}
/// @dev Appends `abi.encodePacked(uint112(data))` to buffer.
function pUint112(DynamicBuffer memory buffer, uint112 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 14));
}
/// @dev Appends `abi.encodePacked(uint120(data))` to buffer.
function pUint120(DynamicBuffer memory buffer, uint120 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 15));
}
/// @dev Appends `abi.encodePacked(uint128(data))` to buffer.
function pUint128(DynamicBuffer memory buffer, uint128 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 16));
}
/// @dev Appends `abi.encodePacked(uint136(data))` to buffer.
function pUint136(DynamicBuffer memory buffer, uint136 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 17));
}
/// @dev Appends `abi.encodePacked(uint144(data))` to buffer.
function pUint144(DynamicBuffer memory buffer, uint144 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 18));
}
/// @dev Appends `abi.encodePacked(uint152(data))` to buffer.
function pUint152(DynamicBuffer memory buffer, uint152 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 19));
}
/// @dev Appends `abi.encodePacked(uint160(data))` to buffer.
function pUint160(DynamicBuffer memory buffer, uint160 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 20));
}
/// @dev Appends `abi.encodePacked(uint168(data))` to buffer.
function pUint168(DynamicBuffer memory buffer, uint168 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 21));
}
/// @dev Appends `abi.encodePacked(uint176(data))` to buffer.
function pUint176(DynamicBuffer memory buffer, uint176 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 22));
}
/// @dev Appends `abi.encodePacked(uint184(data))` to buffer.
function pUint184(DynamicBuffer memory buffer, uint184 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 23));
}
/// @dev Appends `abi.encodePacked(uint192(data))` to buffer.
function pUint192(DynamicBuffer memory buffer, uint192 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 24));
}
/// @dev Appends `abi.encodePacked(uint200(data))` to buffer.
function pUint200(DynamicBuffer memory buffer, uint200 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 25));
}
/// @dev Appends `abi.encodePacked(uint208(data))` to buffer.
function pUint208(DynamicBuffer memory buffer, uint208 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 26));
}
/// @dev Appends `abi.encodePacked(uint216(data))` to buffer.
function pUint216(DynamicBuffer memory buffer, uint216 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 27));
}
/// @dev Appends `abi.encodePacked(uint224(data))` to buffer.
function pUint224(DynamicBuffer memory buffer, uint224 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 28));
}
/// @dev Appends `abi.encodePacked(uint232(data))` to buffer.
function pUint232(DynamicBuffer memory buffer, uint232 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 29));
}
/// @dev Appends `abi.encodePacked(uint240(data))` to buffer.
function pUint240(DynamicBuffer memory buffer, uint240 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 30));
}
/// @dev Appends `abi.encodePacked(uint248(data))` to buffer.
function pUint248(DynamicBuffer memory buffer, uint248 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 31));
}
/// @dev Appends `abi.encodePacked(uint256(data))` to buffer.
function pUint256(DynamicBuffer memory buffer, uint256 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(data, 32));
}
/// @dev Appends `abi.encodePacked(bytes1(data))` to buffer.
function pBytes1(DynamicBuffer memory buffer, bytes1 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 1));
}
/// @dev Appends `abi.encodePacked(bytes2(data))` to buffer.
function pBytes2(DynamicBuffer memory buffer, bytes2 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 2));
}
/// @dev Appends `abi.encodePacked(bytes3(data))` to buffer.
function pBytes3(DynamicBuffer memory buffer, bytes3 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 3));
}
/// @dev Appends `abi.encodePacked(bytes4(data))` to buffer.
function pBytes4(DynamicBuffer memory buffer, bytes4 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 4));
}
/// @dev Appends `abi.encodePacked(bytes5(data))` to buffer.
function pBytes5(DynamicBuffer memory buffer, bytes5 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 5));
}
/// @dev Appends `abi.encodePacked(bytes6(data))` to buffer.
function pBytes6(DynamicBuffer memory buffer, bytes6 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 6));
}
/// @dev Appends `abi.encodePacked(bytes7(data))` to buffer.
function pBytes7(DynamicBuffer memory buffer, bytes7 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 7));
}
/// @dev Appends `abi.encodePacked(bytes8(data))` to buffer.
function pBytes8(DynamicBuffer memory buffer, bytes8 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 8));
}
/// @dev Appends `abi.encodePacked(bytes9(data))` to buffer.
function pBytes9(DynamicBuffer memory buffer, bytes9 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 9));
}
/// @dev Appends `abi.encodePacked(bytes10(data))` to buffer.
function pBytes10(DynamicBuffer memory buffer, bytes10 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 10));
}
/// @dev Appends `abi.encodePacked(bytes11(data))` to buffer.
function pBytes11(DynamicBuffer memory buffer, bytes11 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 11));
}
/// @dev Appends `abi.encodePacked(bytes12(data))` to buffer.
function pBytes12(DynamicBuffer memory buffer, bytes12 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 12));
}
/// @dev Appends `abi.encodePacked(bytes13(data))` to buffer.
function pBytes13(DynamicBuffer memory buffer, bytes13 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 13));
}
/// @dev Appends `abi.encodePacked(bytes14(data))` to buffer.
function pBytes14(DynamicBuffer memory buffer, bytes14 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 14));
}
/// @dev Appends `abi.encodePacked(bytes15(data))` to buffer.
function pBytes15(DynamicBuffer memory buffer, bytes15 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 15));
}
/// @dev Appends `abi.encodePacked(bytes16(data))` to buffer.
function pBytes16(DynamicBuffer memory buffer, bytes16 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 16));
}
/// @dev Appends `abi.encodePacked(bytes17(data))` to buffer.
function pBytes17(DynamicBuffer memory buffer, bytes17 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 17));
}
/// @dev Appends `abi.encodePacked(bytes18(data))` to buffer.
function pBytes18(DynamicBuffer memory buffer, bytes18 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 18));
}
/// @dev Appends `abi.encodePacked(bytes19(data))` to buffer.
function pBytes19(DynamicBuffer memory buffer, bytes19 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 19));
}
/// @dev Appends `abi.encodePacked(bytes20(data))` to buffer.
function pBytes20(DynamicBuffer memory buffer, bytes20 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 20));
}
/// @dev Appends `abi.encodePacked(bytes21(data))` to buffer.
function pBytes21(DynamicBuffer memory buffer, bytes21 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 21));
}
/// @dev Appends `abi.encodePacked(bytes22(data))` to buffer.
function pBytes22(DynamicBuffer memory buffer, bytes22 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 22));
}
/// @dev Appends `abi.encodePacked(bytes23(data))` to buffer.
function pBytes23(DynamicBuffer memory buffer, bytes23 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 23));
}
/// @dev Appends `abi.encodePacked(bytes24(data))` to buffer.
function pBytes24(DynamicBuffer memory buffer, bytes24 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 24));
}
/// @dev Appends `abi.encodePacked(bytes25(data))` to buffer.
function pBytes25(DynamicBuffer memory buffer, bytes25 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 25));
}
/// @dev Appends `abi.encodePacked(bytes26(data))` to buffer.
function pBytes26(DynamicBuffer memory buffer, bytes26 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 26));
}
/// @dev Appends `abi.encodePacked(bytes27(data))` to buffer.
function pBytes27(DynamicBuffer memory buffer, bytes27 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 27));
}
/// @dev Appends `abi.encodePacked(bytes28(data))` to buffer.
function pBytes28(DynamicBuffer memory buffer, bytes28 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 28));
}
/// @dev Appends `abi.encodePacked(bytes29(data))` to buffer.
function pBytes29(DynamicBuffer memory buffer, bytes29 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 29));
}
/// @dev Appends `abi.encodePacked(bytes30(data))` to buffer.
function pBytes30(DynamicBuffer memory buffer, bytes30 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 30));
}
/// @dev Appends `abi.encodePacked(bytes31(data))` to buffer.
function pBytes31(DynamicBuffer memory buffer, bytes31 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 31));
}
/// @dev Appends `abi.encodePacked(bytes32(data))` to buffer.
function pBytes32(DynamicBuffer memory buffer, bytes32 data)
internal
pure
returns (DynamicBuffer memory result)
{
_deallocate(result);
result = p(buffer, _single(bytes32(data), 32));
}
/// @dev Shorthand for returning a new buffer.
function p() internal pure returns (DynamicBuffer memory result) {}
/// @dev Shorthand for `p(p(), data)`.
function p(bytes memory data) internal pure returns (DynamicBuffer memory result) {
p(result, data);
}
/// @dev Shorthand for `p(p(), data0, data1)`.
function p(bytes memory data0, bytes memory data1)
internal
pure
returns (DynamicBuffer memory result)
{
p(p(result, data0), data1);
}
/// @dev Shorthand for `p(p(), data0, .., data2)`.
function p(bytes memory data0, bytes memory data1, bytes memory data2)
internal
pure
returns (DynamicBuffer memory result)
{
p(p(p(result, data0), data1), data2);
}
/// @dev Shorthand for `p(p(), data0, .., data3)`.
function p(bytes memory data0, bytes memory data1, bytes memory data2, bytes memory data3)
internal
pure
returns (DynamicBuffer memory result)
{
p(p(p(p(result, data0), data1), data2), data3);
}
/// @dev Shorthand for `p(p(), data0, .., data4)`.
function p(
bytes memory data0,
bytes memory data1,
bytes memory data2,
bytes memory data3,
bytes memory data4
) internal pure returns (DynamicBuffer memory result) {
p(p(p(p(p(result, data0), data1), data2), data3), data4);
}
/// @dev Shorthand for `p(p(), data0, .., data5)`.
function p(
bytes memory data0,
bytes memory data1,
bytes memory data2,
bytes memory data3,
bytes memory data4,
bytes memory data5
) internal pure returns (DynamicBuffer memory result) {
p(p(p(p(p(p(result, data0), data1), data2), data3), data4), data5);
}
/// @dev Shorthand for `p(p(), data0, .., data6)`.
function p(
bytes memory data0,
bytes memory data1,
bytes memory data2,
bytes memory data3,
bytes memory data4,
bytes memory data5,
bytes memory data6
) internal pure returns (DynamicBuffer memory result) {
p(p(p(p(p(p(p(result, data0), data1), data2), data3), data4), data5), data6);
}
/// @dev Shorthand for `pBool(p(), data)`.
function pBool(bool data) internal pure returns (DynamicBuffer memory result) {
pBool(result, data);
}
/// @dev Shorthand for `pAddress(p(), data)`.
function pAddress(address data) internal pure returns (DynamicBuffer memory result) {
pAddress(result, data);
}
/// @dev Shorthand for `pUint8(p(), data)`.
function pUint8(uint8 data) internal pure returns (DynamicBuffer memory result) {
pUint8(result, data);
}
/// @dev Shorthand for `pUint16(p(), data)`.
function pUint16(uint16 data) internal pure returns (DynamicBuffer memory result) {
pUint16(result, data);
}
/// @dev Shorthand for `pUint24(p(), data)`.
function pUint24(uint24 data) internal pure returns (DynamicBuffer memory result) {
pUint24(result, data);
}
/// @dev Shorthand for `pUint32(p(), data)`.
function pUint32(uint32 data) internal pure returns (DynamicBuffer memory result) {
pUint32(result, data);
}
/// @dev Shorthand for `pUint40(p(), data)`.
function pUint40(uint40 data) internal pure returns (DynamicBuffer memory result) {
pUint40(result, data);
}
/// @dev Shorthand for `pUint48(p(), data)`.
function pUint48(uint48 data) internal pure returns (DynamicBuffer memory result) {
pUint48(result, data);
}
/// @dev Shorthand for `pUint56(p(), data)`.
function pUint56(uint56 data) internal pure returns (DynamicBuffer memory result) {
pUint56(result, data);
}
/// @dev Shorthand for `pUint64(p(), data)`.
function pUint64(uint64 data) internal pure returns (DynamicBuffer memory result) {
pUint64(result, data);
}
/// @dev Shorthand for `pUint72(p(), data)`.
function pUint72(uint72 data) internal pure returns (DynamicBuffer memory result) {
pUint72(result, data);
}
/// @dev Shorthand for `pUint80(p(), data)`.
function pUint80(uint80 data) internal pure returns (DynamicBuffer memory result) {
pUint80(result, data);
}
/// @dev Shorthand for `pUint88(p(), data)`.
function pUint88(uint88 data) internal pure returns (DynamicBuffer memory result) {
pUint88(result, data);
}
/// @dev Shorthand for `pUint96(p(), data)`.
function pUint96(uint96 data) internal pure returns (DynamicBuffer memory result) {
pUint96(result, data);
}
/// @dev Shorthand for `pUint104(p(), data)`.
function pUint104(uint104 data) internal pure returns (DynamicBuffer memory result) {
pUint104(result, data);
}
/// @dev Shorthand for `pUint112(p(), data)`.
function pUint112(uint112 data) internal pure returns (DynamicBuffer memory result) {
pUint112(result, data);
}
/// @dev Shorthand for `pUint120(p(), data)`.
function pUint120(uint120 data) internal pure returns (DynamicBuffer memory result) {
pUint120(result, data);
}
/// @dev Shorthand for `pUint128(p(), data)`.
function pUint128(uint128 data) internal pure returns (DynamicBuffer memory result) {
pUint128(result, data);
}
/// @dev Shorthand for `pUint136(p(), data)`.
function pUint136(uint136 data) internal pure returns (DynamicBuffer memory result) {
pUint136(result, data);
}
/// @dev Shorthand for `pUint144(p(), data)`.
function pUint144(uint144 data) internal pure returns (DynamicBuffer memory result) {
pUint144(result, data);
}
/// @dev Shorthand for `pUint152(p(), data)`.
function pUint152(uint152 data) internal pure returns (DynamicBuffer memory result) {
pUint152(result, data);
}
/// @dev Shorthand for `pUint160(p(), data)`.
function pUint160(uint160 data) internal pure returns (DynamicBuffer memory result) {
pUint160(result, data);
}
/// @dev Shorthand for `pUint168(p(), data)`.
function pUint168(uint168 data) internal pure returns (DynamicBuffer memory result) {
pUint168(result, data);
}
/// @dev Shorthand for `pUint176(p(), data)`.
function pUint176(uint176 data) internal pure returns (DynamicBuffer memory result) {
pUint176(result, data);
}
/// @dev Shorthand for `pUint184(p(), data)`.
function pUint184(uint184 data) internal pure returns (DynamicBuffer memory result) {
pUint184(result, data);
}
/// @dev Shorthand for `pUint192(p(), data)`.
function pUint192(uint192 data) internal pure returns (DynamicBuffer memory result) {
pUint192(result, data);
}
/// @dev Shorthand for `pUint200(p(), data)`.
function pUint200(uint200 data) internal pure returns (DynamicBuffer memory result) {
pUint200(result, data);
}
/// @dev Shorthand for `pUint208(p(), data)`.
function pUint208(uint208 data) internal pure returns (DynamicBuffer memory result) {
pUint208(result, data);
}
/// @dev Shorthand for `pUint216(p(), data)`.
function pUint216(uint216 data) internal pure returns (DynamicBuffer memory result) {
pUint216(result, data);
}
/// @dev Shorthand for `pUint224(p(), data)`.
function pUint224(uint224 data) internal pure returns (DynamicBuffer memory result) {
pUint224(result, data);
}
/// @dev Shorthand for `pUint232(p(), data)`.
function pUint232(uint232 data) internal pure returns (DynamicBuffer memory result) {
pUint232(result, data);
}
/// @dev Shorthand for `pUint240(p(), data)`.
function pUint240(uint240 data) internal pure returns (DynamicBuffer memory result) {
pUint240(result, data);
}
/// @dev Shorthand for `pUint248(p(), data)`.
function pUint248(uint248 data) internal pure returns (DynamicBuffer memory result) {
pUint248(result, data);
}
/// @dev Shorthand for `pUint256(p(), data)`.
function pUint256(uint256 data) internal pure returns (DynamicBuffer memory result) {
pUint256(result, data);
}
/// @dev Shorthand for `pBytes1(p(), data)`.
function pBytes1(bytes1 data) internal pure returns (DynamicBuffer memory result) {
pBytes1(result, data);
}
/// @dev Shorthand for `pBytes2(p(), data)`.
function pBytes2(bytes2 data) internal pure returns (DynamicBuffer memory result) {
pBytes2(result, data);
}
/// @dev Shorthand for `pBytes3(p(), data)`.
function pBytes3(bytes3 data) internal pure returns (DynamicBuffer memory result) {
pBytes3(result, data);
}
/// @dev Shorthand for `pBytes4(p(), data)`.
function pBytes4(bytes4 data) internal pure returns (DynamicBuffer memory result) {
pBytes4(result, data);
}
/// @dev Shorthand for `pBytes5(p(), data)`.
function pBytes5(bytes5 data) internal pure returns (DynamicBuffer memory result) {
pBytes5(result, data);
}
/// @dev Shorthand for `pBytes6(p(), data)`.
function pBytes6(bytes6 data) internal pure returns (DynamicBuffer memory result) {
pBytes6(result, data);
}
/// @dev Shorthand for `pBytes7(p(), data)`.
function pBytes7(bytes7 data) internal pure returns (DynamicBuffer memory result) {
pBytes7(result, data);
}
/// @dev Shorthand for `pBytes8(p(), data)`.
function pBytes8(bytes8 data) internal pure returns (DynamicBuffer memory result) {
pBytes8(result, data);
}
/// @dev Shorthand for `pBytes9(p(), data)`.
function pBytes9(bytes9 data) internal pure returns (DynamicBuffer memory result) {
pBytes9(result, data);
}
/// @dev Shorthand for `pBytes10(p(), data)`.
function pBytes10(bytes10 data) internal pure returns (DynamicBuffer memory result) {
pBytes10(result, data);
}
/// @dev Shorthand for `pBytes11(p(), data)`.
function pBytes11(bytes11 data) internal pure returns (DynamicBuffer memory result) {
pBytes11(result, data);
}
/// @dev Shorthand for `pBytes12(p(), data)`.
function pBytes12(bytes12 data) internal pure returns (DynamicBuffer memory result) {
pBytes12(result, data);
}
/// @dev Shorthand for `pBytes13(p(), data)`.
function pBytes13(bytes13 data) internal pure returns (DynamicBuffer memory result) {
pBytes13(result, data);
}
/// @dev Shorthand for `pBytes14(p(), data)`.
function pBytes14(bytes14 data) internal pure returns (DynamicBuffer memory result) {
pBytes14(result, data);
}
/// @dev Shorthand for `pBytes15(p(), data)`.
function pBytes15(bytes15 data) internal pure returns (DynamicBuffer memory result) {
pBytes15(result, data);
}
/// @dev Shorthand for `pBytes16(p(), data)`.
function pBytes16(bytes16 data) internal pure returns (DynamicBuffer memory result) {
pBytes16(result, data);
}
/// @dev Shorthand for `pBytes17(p(), data)`.
function pBytes17(bytes17 data) internal pure returns (DynamicBuffer memory result) {
pBytes17(result, data);
}
/// @dev Shorthand for `pBytes18(p(), data)`.
function pBytes18(bytes18 data) internal pure returns (DynamicBuffer memory result) {
pBytes18(result, data);
}
/// @dev Shorthand for `pBytes19(p(), data)`.
function pBytes19(bytes19 data) internal pure returns (DynamicBuffer memory result) {
pBytes19(result, data);
}
/// @dev Shorthand for `pBytes20(p(), data)`.
function pBytes20(bytes20 data) internal pure returns (DynamicBuffer memory result) {
pBytes20(result, data);
}
/// @dev Shorthand for `pBytes21(p(), data)`.
function pBytes21(bytes21 data) internal pure returns (DynamicBuffer memory result) {
pBytes21(result, data);
}
/// @dev Shorthand for `pBytes22(p(), data)`.
function pBytes22(bytes22 data) internal pure returns (DynamicBuffer memory result) {
pBytes22(result, data);
}
/// @dev Shorthand for `pBytes23(p(), data)`.
function pBytes23(bytes23 data) internal pure returns (DynamicBuffer memory result) {
pBytes23(result, data);
}
/// @dev Shorthand for `pBytes24(p(), data)`.
function pBytes24(bytes24 data) internal pure returns (DynamicBuffer memory result) {
pBytes24(result, data);
}
/// @dev Shorthand for `pBytes25(p(), data)`.
function pBytes25(bytes25 data) internal pure returns (DynamicBuffer memory result) {
pBytes25(result, data);
}
/// @dev Shorthand for `pBytes26(p(), data)`.
function pBytes26(bytes26 data) internal pure returns (DynamicBuffer memory result) {
pBytes26(result, data);
}
/// @dev Shorthand for `pBytes27(p(), data)`.
function pBytes27(bytes27 data) internal pure returns (DynamicBuffer memory result) {
pBytes27(result, data);
}
/// @dev Shorthand for `pBytes28(p(), data)`.
function pBytes28(bytes28 data) internal pure returns (DynamicBuffer memory result) {
pBytes28(result, data);
}
/// @dev Shorthand for `pBytes29(p(), data)`.
function pBytes29(bytes29 data) internal pure returns (DynamicBuffer memory result) {
pBytes29(result, data);
}
/// @dev Shorthand for `pBytes30(p(), data)`.
function pBytes30(bytes30 data) internal pure returns (DynamicBuffer memory result) {
pBytes30(result, data);
}
/// @dev Shorthand for `pBytes31(p(), data)`.
function pBytes31(bytes31 data) internal pure returns (DynamicBuffer memory result) {
pBytes31(result, data);
}
/// @dev Shorthand for `pBytes32(p(), data)`.
function pBytes32(bytes32 data) internal pure returns (DynamicBuffer memory result) {
pBytes32(result, data);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Helper for deallocating an automatically allocated `buffer` pointer.
function _deallocate(DynamicBuffer memory result) private pure {
/// @solidity memory-safe-assembly
assembly {
mstore(0x40, result) // Deallocate, as we have already allocated.
}
}
/// @dev Returns a temporary bytes string of length `n` for `data`.
function _single(uint256 data, uint256 n) private pure returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := 0x00
mstore(n, data)
mstore(result, n)
}
}
/// @dev Returns a temporary bytes string of length `n` for `data`.
function _single(bytes32 data, uint256 n) private pure returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := 0x00
mstore(0x20, data)
mstore(result, n)
}
}
}
node_modules/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)));
}
}
node_modules/solady/src/utils/LibString.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {LibBytes} from "./LibBytes.sol";
/// @notice Library for converting numbers into strings and other string operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibString.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol)
///
/// @dev Note:
/// For performance and bytecode compactness, most of the string operations are restricted to
/// byte strings (7-bit ASCII), except where otherwise specified.
/// Usage of byte string operations on charsets with runes spanning two or more bytes
/// can lead to undefined behavior.
library LibString {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Goated string storage struct that totally MOGs, no cap, fr.
/// Uses less gas and bytecode than Solidity's native string storage. It's meta af.
/// Packs length with the first 31 bytes if <255 bytes, so it’s mad tight.
struct StringStorage {
bytes32 _spacer;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The length of the output is too small to contain all the hex digits.
error HexLengthInsufficient();
/// @dev The length of the string is more than 32 bytes.
error TooBigForSmallString();
/// @dev The input string must be a 7-bit ASCII.
error StringNot7BitASCII();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the string.
uint256 internal constant NOT_FOUND = type(uint256).max;
/// @dev Lookup for '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant ALPHANUMERIC_7_BIT_ASCII = 0x7fffffe07fffffe03ff000000000000;
/// @dev Lookup for 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant LETTERS_7_BIT_ASCII = 0x7fffffe07fffffe0000000000000000;
/// @dev Lookup for 'abcdefghijklmnopqrstuvwxyz'.
uint128 internal constant LOWERCASE_7_BIT_ASCII = 0x7fffffe000000000000000000000000;
/// @dev Lookup for 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant UPPERCASE_7_BIT_ASCII = 0x7fffffe0000000000000000;
/// @dev Lookup for '0123456789'.
uint128 internal constant DIGITS_7_BIT_ASCII = 0x3ff000000000000;
/// @dev Lookup for '0123456789abcdefABCDEF'.
uint128 internal constant HEXDIGITS_7_BIT_ASCII = 0x7e0000007e03ff000000000000;
/// @dev Lookup for '01234567'.
uint128 internal constant OCTDIGITS_7_BIT_ASCII = 0xff000000000000;
/// @dev Lookup for '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'.
uint128 internal constant PRINTABLE_7_BIT_ASCII = 0x7fffffffffffffffffffffff00003e00;
/// @dev Lookup for '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'.
uint128 internal constant PUNCTUATION_7_BIT_ASCII = 0x78000001f8000001fc00fffe00000000;
/// @dev Lookup for ' \t\n\r\x0b\x0c'.
uint128 internal constant WHITESPACE_7_BIT_ASCII = 0x100003e00;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRING STORAGE OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sets the value of the string storage `$` to `s`.
function set(StringStorage storage $, string memory s) internal {
LibBytes.set(bytesStorage($), bytes(s));
}
/// @dev Sets the value of the string storage `$` to `s`.
function setCalldata(StringStorage storage $, string calldata s) internal {
LibBytes.setCalldata(bytesStorage($), bytes(s));
}
/// @dev Sets the value of the string storage `$` to the empty string.
function clear(StringStorage storage $) internal {
delete $._spacer;
}
/// @dev Returns whether the value stored is `$` is the empty string "".
function isEmpty(StringStorage storage $) internal view returns (bool) {
return uint256($._spacer) & 0xff == uint256(0);
}
/// @dev Returns the length of the value stored in `$`.
function length(StringStorage storage $) internal view returns (uint256) {
return LibBytes.length(bytesStorage($));
}
/// @dev Returns the value stored in `$`.
function get(StringStorage storage $) internal view returns (string memory) {
return string(LibBytes.get(bytesStorage($)));
}
/// @dev Returns the uint8 at index `i`. If out-of-bounds, returns 0.
function uint8At(StringStorage storage $, uint256 i) internal view returns (uint8) {
return LibBytes.uint8At(bytesStorage($), i);
}
/// @dev Helper to cast `$` to a `BytesStorage`.
function bytesStorage(StringStorage storage $)
internal
pure
returns (LibBytes.BytesStorage storage casted)
{
/// @solidity memory-safe-assembly
assembly {
casted.slot := $.slot
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the base 10 decimal representation of `value`.
function toString(uint256 value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits.
result := add(mload(0x40), 0x80)
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end of the memory to calculate the length later.
let w := not(0) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
result := add(result, w) // `sub(result, 1)`.
// Store the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(result, add(48, mod(temp, 10)))
temp := div(temp, 10) // Keep dividing `temp` until zero.
if iszero(temp) { break }
}
let n := sub(end, result)
result := sub(result, 0x20) // Move the pointer 32 bytes back to make room for the length.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the base 10 decimal representation of `value`.
function toString(int256 value) internal pure returns (string memory result) {
if (value >= 0) return toString(uint256(value));
unchecked {
result = toString(~uint256(value) + 1);
}
/// @solidity memory-safe-assembly
assembly {
// We still have some spare memory space on the left,
// as we have allocated 3 words (96 bytes) for up to 78 digits.
let n := mload(result) // Load the string length.
mstore(result, 0x2d) // Store the '-' character.
result := sub(result, 1) // Move back the string pointer by a byte.
mstore(result, add(n, 1)) // Update the string length.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HEXADECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `byteCount` bytes.
/// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
/// giving a total length of `byteCount * 2 + 2` bytes.
/// Reverts if `byteCount` is too small for the output to contain all the digits.
function toHexString(uint256 value, uint256 byteCount)
internal
pure
returns (string memory result)
{
result = toHexStringNoPrefix(value, byteCount);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `byteCount` bytes.
/// The output is not prefixed with "0x" and is encoded using 2 hexadecimal digits per byte,
/// giving a total length of `byteCount * 2` bytes.
/// Reverts if `byteCount` is too small for the output to contain all the digits.
function toHexStringNoPrefix(uint256 value, uint256 byteCount)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, `byteCount * 2` bytes
// for the digits, 0x02 bytes for the prefix, and 0x20 bytes for the length.
// We add 0x20 to the total and round down to a multiple of 0x20.
// (0x20 + 0x20 + 0x02 + 0x20) = 0x62.
result := add(mload(0x40), and(add(shl(1, byteCount), 0x42), not(0x1f)))
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end to calculate the length later.
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let start := sub(result, add(byteCount, byteCount))
let w := not(1) // Tsk.
let temp := value
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for {} 1 {} {
result := add(result, w) // `sub(result, 2)`.
mstore8(add(result, 1), mload(and(temp, 15)))
mstore8(result, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(xor(result, start)) { break }
}
if temp {
mstore(0x00, 0x2194895a) // `HexLengthInsufficient()`.
revert(0x1c, 0x04)
}
let n := sub(end, result)
result := sub(result, 0x20)
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2 + 2` bytes.
function toHexString(uint256 value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x".
/// The output excludes leading "0" from the `toHexString` output.
/// `0x00: "0x0", 0x01: "0x1", 0x12: "0x12", 0x123: "0x123"`.
function toMinimalHexString(uint256 value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(result, 0x20))), 0x30) // Whether leading zero is present.
let n := add(mload(result), 2) // Compute the length.
mstore(add(result, o), 0x3078) // Store the "0x" prefix, accounting for leading zero.
result := sub(add(result, o), 2) // Move the pointer, accounting for leading zero.
mstore(result, sub(n, o)) // Store the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output excludes leading "0" from the `toHexStringNoPrefix` output.
/// `0x00: "0", 0x01: "1", 0x12: "12", 0x123: "123"`.
function toMinimalHexStringNoPrefix(uint256 value)
internal
pure
returns (string memory result)
{
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(result, 0x20))), 0x30) // Whether leading zero is present.
let n := mload(result) // Get the length.
result := add(result, o) // Move the pointer, accounting for leading zero.
mstore(result, sub(n, o)) // Store the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2` bytes.
function toHexStringNoPrefix(uint256 value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x40 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x40) is 0xa0.
result := add(mload(0x40), 0x80)
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end to calculate the length later.
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
let w := not(1) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
result := add(result, w) // `sub(result, 2)`.
mstore8(add(result, 1), mload(and(temp, 15)))
mstore8(result, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(temp) { break }
}
let n := sub(end, result)
result := sub(result, 0x20)
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x", encoded using 2 hexadecimal digits per byte,
/// and the alphabets are capitalized conditionally according to
/// https://eips.ethereum.org/EIPS/eip-55
function toHexStringChecksummed(address value) internal pure returns (string memory result) {
result = toHexString(value);
/// @solidity memory-safe-assembly
assembly {
let mask := shl(6, div(not(0), 255)) // `0b010000000100000000 ...`
let o := add(result, 0x22)
let hashed := and(keccak256(o, 40), mul(34, mask)) // `0b10001000 ... `
let t := shl(240, 136) // `0b10001000 << 240`
for { let i := 0 } 1 {} {
mstore(add(i, i), mul(t, byte(i, hashed)))
i := add(i, 1)
if eq(i, 20) { break }
}
mstore(o, xor(mload(o), shr(1, and(mload(0x00), and(mload(o), mask)))))
o := add(o, 0x20)
mstore(o, xor(mload(o), shr(1, and(mload(0x20), and(mload(o), mask)))))
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
function toHexString(address value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(address value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
// Allocate memory.
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x28 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x28) is 0x80.
mstore(0x40, add(result, 0x80))
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
result := add(result, 2)
mstore(result, 40) // Store the length.
let o := add(result, 0x20)
mstore(add(o, 40), 0) // Zeroize the slot after the string.
value := shl(96, value)
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let i := 0 } 1 {} {
let p := add(o, add(i, i))
let temp := byte(i, value)
mstore8(add(p, 1), mload(and(temp, 15)))
mstore8(p, mload(shr(4, temp)))
i := add(i, 1)
if eq(i, 20) { break }
}
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexString(bytes memory raw) internal pure returns (string memory result) {
result = toHexStringNoPrefix(raw);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(bytes memory raw) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(raw)
result := add(mload(0x40), 2) // Skip 2 bytes for the optional prefix.
mstore(result, add(n, n)) // Store the length of the output.
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
let o := add(result, 0x20)
let end := add(raw, n)
for {} iszero(eq(raw, end)) {} {
raw := add(raw, 1)
mstore8(add(o, 1), mload(and(mload(raw), 15)))
mstore8(o, mload(and(shr(4, mload(raw)), 15)))
o := add(o, 2)
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RUNE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the number of UTF characters in the string.
function runeCount(string memory s) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
if mload(s) {
mstore(0x00, div(not(0), 255))
mstore(0x20, 0x0202020202020202020202020202020202020202020202020303030304040506)
let o := add(s, 0x20)
let end := add(o, mload(s))
for { result := 1 } 1 { result := add(result, 1) } {
o := add(o, byte(0, mload(shr(250, mload(o)))))
if iszero(lt(o, end)) { break }
}
}
}
}
/// @dev Returns if this string is a 7-bit ASCII string.
/// (i.e. all characters codes are in [0..127])
function is7BitASCII(string memory s) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
let mask := shl(7, div(not(0), 255))
let n := mload(s)
if n {
let o := add(s, 0x20)
let end := add(o, n)
let last := mload(end)
mstore(end, 0)
for {} 1 {} {
if and(mask, mload(o)) {
result := 0
break
}
o := add(o, 0x20)
if iszero(lt(o, end)) { break }
}
mstore(end, last)
}
}
}
/// @dev Returns if this string is a 7-bit ASCII string,
/// AND all characters are in the `allowed` lookup.
/// Note: If `s` is empty, returns true regardless of `allowed`.
function is7BitASCII(string memory s, uint128 allowed) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
if mload(s) {
let allowed_ := shr(128, shl(128, allowed))
let o := add(s, 0x20)
for { let end := add(o, mload(s)) } 1 {} {
result := and(result, shr(byte(0, mload(o)), allowed_))
o := add(o, 1)
if iszero(and(result, lt(o, end))) { break }
}
}
}
}
/// @dev Converts the bytes in the 7-bit ASCII string `s` to
/// an allowed lookup for use in `is7BitASCII(s, allowed)`.
/// To save runtime gas, you can cache the result in an immutable variable.
function to7BitASCIIAllowedLookup(string memory s) internal pure returns (uint128 result) {
/// @solidity memory-safe-assembly
assembly {
if mload(s) {
let o := add(s, 0x20)
for { let end := add(o, mload(s)) } 1 {} {
result := or(result, shl(byte(0, mload(o)), 1))
o := add(o, 1)
if iszero(lt(o, end)) { break }
}
if shr(128, result) {
mstore(0x00, 0xc9807e0d) // `StringNot7BitASCII()`.
revert(0x1c, 0x04)
}
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// For performance and bytecode compactness, byte string operations are restricted
// to 7-bit ASCII strings. All offsets are byte offsets, not UTF character offsets.
// Usage of byte string operations on charsets with runes spanning two or more bytes
// can lead to undefined behavior.
/// @dev Returns `subject` all occurrences of `needle` replaced with `replacement`.
function replace(string memory subject, string memory needle, string memory replacement)
internal
pure
returns (string memory)
{
return string(LibBytes.replace(bytes(subject), bytes(needle), bytes(replacement)));
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(string memory subject, string memory needle, uint256 from)
internal
pure
returns (uint256)
{
return LibBytes.indexOf(bytes(subject), bytes(needle), from);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(string memory subject, string memory needle) internal pure returns (uint256) {
return LibBytes.indexOf(bytes(subject), bytes(needle), 0);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(string memory subject, string memory needle, uint256 from)
internal
pure
returns (uint256)
{
return LibBytes.lastIndexOf(bytes(subject), bytes(needle), from);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(string memory subject, string memory needle)
internal
pure
returns (uint256)
{
return LibBytes.lastIndexOf(bytes(subject), bytes(needle), type(uint256).max);
}
/// @dev Returns true if `needle` is found in `subject`, false otherwise.
function contains(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.contains(bytes(subject), bytes(needle));
}
/// @dev Returns whether `subject` starts with `needle`.
function startsWith(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.startsWith(bytes(subject), bytes(needle));
}
/// @dev Returns whether `subject` ends with `needle`.
function endsWith(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.endsWith(bytes(subject), bytes(needle));
}
/// @dev Returns `subject` repeated `times`.
function repeat(string memory subject, uint256 times) internal pure returns (string memory) {
return string(LibBytes.repeat(bytes(subject), times));
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets.
function slice(string memory subject, uint256 start, uint256 end)
internal
pure
returns (string memory)
{
return string(LibBytes.slice(bytes(subject), start, end));
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the string.
/// `start` is a byte offset.
function slice(string memory subject, uint256 start) internal pure returns (string memory) {
return string(LibBytes.slice(bytes(subject), start, type(uint256).max));
}
/// @dev Returns all the indices of `needle` in `subject`.
/// The indices are byte offsets.
function indicesOf(string memory subject, string memory needle)
internal
pure
returns (uint256[] memory)
{
return LibBytes.indicesOf(bytes(subject), bytes(needle));
}
/// @dev Returns an arrays of strings based on the `delimiter` inside of the `subject` string.
function split(string memory subject, string memory delimiter)
internal
pure
returns (string[] memory result)
{
bytes[] memory a = LibBytes.split(bytes(subject), bytes(delimiter));
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Returns a concatenated string of `a` and `b`.
/// Cheaper than `string.concat()` and does not de-align the free memory pointer.
function concat(string memory a, string memory b) internal pure returns (string memory) {
return string(LibBytes.concat(bytes(a), bytes(b)));
}
/// @dev Returns a copy of the string in either lowercase or UPPERCASE.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function toCase(string memory subject, bool toUpper)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(subject)
if n {
result := mload(0x40)
let o := add(result, 0x20)
let d := sub(subject, result)
let flags := shl(add(70, shl(5, toUpper)), 0x3ffffff)
for { let end := add(o, n) } 1 {} {
let b := byte(0, mload(add(d, o)))
mstore8(o, xor(and(shr(b, flags), 0x20), b))
o := add(o, 1)
if eq(o, end) { break }
}
mstore(result, n) // Store the length.
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
}
/// @dev Returns a string from a small bytes32 string.
/// `s` must be null-terminated, or behavior will be undefined.
function fromSmallString(bytes32 s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let n := 0
for {} byte(n, s) { n := add(n, 1) } {} // Scan for '\0'.
mstore(result, n) // Store the length.
let o := add(result, 0x20)
mstore(o, s) // Store the bytes of the string.
mstore(add(o, n), 0) // Zeroize the slot after the string.
mstore(0x40, add(result, 0x40)) // Allocate memory.
}
}
/// @dev Returns the small string, with all bytes after the first null byte zeroized.
function normalizeSmallString(bytes32 s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
for {} byte(result, s) { result := add(result, 1) } {} // Scan for '\0'.
mstore(0x00, s)
mstore(result, 0x00)
result := mload(0x00)
}
}
/// @dev Returns the string as a normalized null-terminated small string.
function toSmallString(string memory s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(s)
if iszero(lt(result, 33)) {
mstore(0x00, 0xec92f9a3) // `TooBigForSmallString()`.
revert(0x1c, 0x04)
}
result := shl(shl(3, sub(32, result)), mload(add(s, result)))
}
}
/// @dev Returns a lowercased copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function lower(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, false);
}
/// @dev Returns an UPPERCASED copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function upper(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, true);
}
/// @dev Escapes the string to be used within HTML tags.
function escapeHTML(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let end := add(s, mload(s))
let o := add(result, 0x20)
// Store the bytes of the packed offsets and strides into the scratch space.
// `packed = (stride << 5) | offset`. Max offset is 20. Max stride is 6.
mstore(0x1f, 0x900094)
mstore(0x08, 0xc0000000a6ab)
// Store ""&'<>" into the scratch space.
mstore(0x00, shl(64, 0x2671756f743b26616d703b262333393b266c743b2667743b))
for {} iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
// Not in `["\"","'","&","<",">"]`.
if iszero(and(shl(c, 1), 0x500000c400000000)) {
mstore8(o, c)
o := add(o, 1)
continue
}
let t := shr(248, mload(c))
mstore(o, mload(and(t, 0x1f)))
o := add(o, shr(5, t))
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
/// If `addDoubleQuotes` is true, the result will be enclosed in double-quotes.
function escapeJSON(string memory s, bool addDoubleQuotes)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let o := add(result, 0x20)
if addDoubleQuotes {
mstore8(o, 34)
o := add(1, o)
}
// Store "\\u0000" in scratch space.
// Store "0123456789abcdef" in scratch space.
// Also, store `{0x08:"b", 0x09:"t", 0x0a:"n", 0x0c:"f", 0x0d:"r"}`.
// into the scratch space.
mstore(0x15, 0x5c75303030303031323334353637383961626364656662746e006672)
// Bitmask for detecting `["\"","\\"]`.
let e := or(shl(0x22, 1), shl(0x5c, 1))
for { let end := add(s, mload(s)) } iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
if iszero(lt(c, 0x20)) {
if iszero(and(shl(c, 1), e)) {
// Not in `["\"","\\"]`.
mstore8(o, c)
o := add(o, 1)
continue
}
mstore8(o, 0x5c) // "\\".
mstore8(add(o, 1), c)
o := add(o, 2)
continue
}
if iszero(and(shl(c, 1), 0x3700)) {
// Not in `["\b","\t","\n","\f","\d"]`.
mstore8(0x1d, mload(shr(4, c))) // Hex value.
mstore8(0x1e, mload(and(c, 15))) // Hex value.
mstore(o, mload(0x19)) // "\\u00XX".
o := add(o, 6)
continue
}
mstore8(o, 0x5c) // "\\".
mstore8(add(o, 1), mload(add(c, 8)))
o := add(o, 2)
}
if addDoubleQuotes {
mstore8(o, 34)
o := add(1, o)
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
function escapeJSON(string memory s) internal pure returns (string memory result) {
result = escapeJSON(s, false);
}
/// @dev Encodes `s` so that it can be safely used in a URI,
/// just like `encodeURIComponent` in JavaScript.
/// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
/// See: https://datatracker.ietf.org/doc/html/rfc2396
/// See: https://datatracker.ietf.org/doc/html/rfc3986
function encodeURIComponent(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
// Store "0123456789ABCDEF" in scratch space.
// Uppercased to be consistent with JavaScript's implementation.
mstore(0x0f, 0x30313233343536373839414243444546)
let o := add(result, 0x20)
for { let end := add(s, mload(s)) } iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
// If not in `[0-9A-Z-a-z-_.!~*'()]`.
if iszero(and(1, shr(c, 0x47fffffe87fffffe03ff678200000000))) {
mstore8(o, 0x25) // '%'.
mstore8(add(o, 1), mload(and(shr(4, c), 15)))
mstore8(add(o, 2), mload(and(c, 15)))
o := add(o, 3)
continue
}
mstore8(o, c)
o := add(o, 1)
}
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Returns whether `a` equals `b`.
function eq(string memory a, string memory b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
}
}
/// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small string.
function eqs(string memory a, bytes32 b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
// These should be evaluated on compile time, as far as possible.
let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
let x := not(or(m, or(b, add(m, and(b, m)))))
let r := shl(7, iszero(iszero(shr(128, x))))
r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
}
}
/// @dev Returns 0 if `a == b`, -1 if `a < b`, +1 if `a > b`.
/// If `a` == b[:a.length]`, and `a.length < b.length`, returns -1.
function cmp(string memory a, string memory b) internal pure returns (int256) {
return LibBytes.cmp(bytes(a), bytes(b));
}
/// @dev Packs a single string with its length into a single word.
/// Returns `bytes32(0)` if the length is zero or greater than 31.
function packOne(string memory a) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
// We don't need to zero right pad the string,
// since this is our own custom non-standard packing scheme.
result :=
mul(
// Load the length and the bytes.
mload(add(a, 0x1f)),
// `length != 0 && length < 32`. Abuses underflow.
// Assumes that the length is valid and within the block gas limit.
lt(sub(mload(a), 1), 0x1f)
)
}
}
/// @dev Unpacks a string packed using {packOne}.
/// Returns the empty string if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packOne}, the output behavior is undefined.
function unpackOne(bytes32 packed) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40) // Grab the free memory pointer.
mstore(0x40, add(result, 0x40)) // Allocate 2 words (1 for the length, 1 for the bytes).
mstore(result, 0) // Zeroize the length slot.
mstore(add(result, 0x1f), packed) // Store the length and bytes.
mstore(add(add(result, 0x20), mload(result)), 0) // Right pad with zeroes.
}
}
/// @dev Packs two strings with their lengths into a single word.
/// Returns `bytes32(0)` if combined length is zero or greater than 30.
function packTwo(string memory a, string memory b) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let aLen := mload(a)
// We don't need to zero right pad the strings,
// since this is our own custom non-standard packing scheme.
result :=
mul(
or( // Load the length and the bytes of `a` and `b`.
shl(shl(3, sub(0x1f, aLen)), mload(add(a, aLen))), mload(sub(add(b, 0x1e), aLen))),
// `totalLen != 0 && totalLen < 31`. Abuses underflow.
// Assumes that the lengths are valid and within the block gas limit.
lt(sub(add(aLen, mload(b)), 1), 0x1e)
)
}
}
/// @dev Unpacks strings packed using {packTwo}.
/// Returns the empty strings if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packTwo}, the output behavior is undefined.
function unpackTwo(bytes32 packed)
internal
pure
returns (string memory resultA, string memory resultB)
{
/// @solidity memory-safe-assembly
assembly {
resultA := mload(0x40) // Grab the free memory pointer.
resultB := add(resultA, 0x40)
// Allocate 2 words for each string (1 for the length, 1 for the byte). Total 4 words.
mstore(0x40, add(resultB, 0x40))
// Zeroize the length slots.
mstore(resultA, 0)
mstore(resultB, 0)
// Store the lengths and bytes.
mstore(add(resultA, 0x1f), packed)
mstore(add(resultB, 0x1f), mload(add(add(resultA, 0x20), mload(resultA))))
// Right pad with zeroes.
mstore(add(add(resultA, 0x20), mload(resultA)), 0)
mstore(add(add(resultB, 0x20), mload(resultB)), 0)
}
}
/// @dev Directly returns `a` without copying.
function directReturn(string memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
// Assumes that the string does not start from the scratch space.
let retStart := sub(a, 0x20)
let retUnpaddedSize := add(mload(a), 0x40)
// Right pad with zeroes. Just in case the string is produced
// by a method that doesn't zero right pad.
mstore(add(retStart, retUnpaddedSize), 0)
mstore(retStart, 0x20) // Store the return offset.
// End the transaction, returning the string.
return(retStart, and(not(0x1f), add(0x1f, retUnpaddedSize)))
}
}
}
node_modules/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/interfaces/IPanoramaStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;
interface IPanoramaStorage {
error InvalidIndex();
error LengthMismatch();
error HtmlTemplateNotSet();
error InvalidWorkflowId();
error NotOwnerOrOperator();
error FragmentIndexOutOfBounds();
error FragmentAlreadyUploaded();
error FragmentHashMismatch();
error NotFullyUploaded();
error NoFragmentsConfigured();
event EntryAdded(uint256 indexed tokenId, uint256 indexed price, int256 indexed changeBps);
event WorkflowAdded(uint256 indexed id, string name);
event WorkflowUpdated(uint256 indexed id);
event ImageFragmentHashesSet(uint256 indexed tokenId, uint256 indexed fragmentCount);
event ImageFragmentUploaded(uint256 indexed tokenId, uint256 indexed fragmentIndex, address indexed pointer);
event TableauFinalized(uint256 indexed tokenId, uint256 indexed fragmentCount);
event AuthorizedOperatorUpdated(address indexed operator, bool indexed authorized);
/// @dev Each tableau is a single 1920x1080 AI-generated painting in the panorama.
/// Its image can be stored fully on-chain by splitting the raw image bytes (WebP)
/// into ordered fragments. The owner commits keccak256 hashes for each fragment,
/// then anyone can upload the corresponding data (hash-verified, permissionless).
/// Once all fragments are uploaded, `uploadImageFragment` automatically
/// finalizes the tableau. The image is served directly via `getOnchainImageDataUri`,
/// fully retrievable from contract storage without any external dependency.
struct TableauData {
uint256 price;
int256 changeBps;
uint40 timestamp;
uint8 moodIndex;
uint8 workflowId;
uint8 season;
uint256 seed;
string prompt;
string name;
string description;
/// @dev Ordered keccak256 hashes of each image fragment. Set by the owner/operator
/// before upload begins. The image bytes are split into N sequential chunks off-chain,
/// each chunk hashed, and the hash array committed here. This serves as a commitment
/// scheme: uploaders must provide data matching each hash exactly.
bytes32[] imageFragmentHashes;
/// @dev SSTORE2 pointers to uploaded fragment data, parallel to imageFragmentHashes.
/// Each slot starts as address(0) and is filled when the corresponding fragment is
/// uploaded via `uploadImageFragment`. Reading the stored bytes: `SSTORE2.read(pointer)`.
address[] imageFragmentPointers;
/// @dev Number of fragments uploaded so far. When this equals imageFragmentHashes.length,
/// the image is fully on-chain and `finalizeOnchainTableau` can be called.
uint256 uploadedFragmentCount;
}
struct Workflow {
string name;
address jsonPointer;
string gpuUsed;
string cudaVersion;
bytes32[] modelSha256;
string[] customNodeNames;
string[] customNodeVersions;
bytes32[] customNodeSha256;
string[] modelDownloadLinks;
}
// State
function panorama() external view returns (address);
function authorizedOperators(address operator) external view returns (bool);
function erc20TokenDescription() external view returns (string memory);
function externalUrl() external view returns (string memory);
function startTimestamp() external view returns (uint40);
function cdnBase() external view returns (string memory);
function panoramaHtmlPrefixPointer() external view returns (address);
function panoramaHtmlSuffixPointer() external view returns (address);
function entryCount() external view returns (uint256);
// View — Tableau
function getTableauData(uint256 tokenId) external view returns (TableauData memory);
function getPanoramaHtmlPrefixData() external view returns (bytes memory);
function getPanoramaHtmlSuffixData() external view returns (bytes memory);
// View — Image Fragments
function getImageFragmentHashes(uint256 tokenId) external view returns (bytes32[] memory);
function getTotalFragments(uint256 tokenId) external view returns (uint256);
function getFragmentPointer(uint256 tokenId, uint256 index) external view returns (address);
function getFragmentPointers(uint256 tokenId) external view returns (address[] memory);
function getUploadedFragmentCount(uint256 tokenId) external view returns (uint256);
function isFullyUploaded(uint256 tokenId) external view returns (bool);
function getOnchainImageDataUri(uint256 tokenId) external view returns (string memory);
// View — Workflows
function getWorkflow(uint256 id) external view returns (Workflow memory);
function getWorkflowCount() external view returns (uint256);
function getWorkflowJson(uint256 id) external view returns (bytes memory);
// Mutations — Config
function setPanorama(address _panorama) external;
function setAuthorizedOperator(address operator, bool authorized) external;
function setCdnBase(string calldata _cdnBase) external;
function setExternalUrl(string calldata _url) external;
function setStartTimestamp(uint40 _startTimestamp) external;
function updateErc20Description(string calldata _description) external;
function setPanoramaHtmlPrefix(bytes calldata _data) external;
function setPanoramaHtmlSuffix(bytes calldata _data) external;
// Mutations — Tableau
function addTableauEntry(TableauData calldata data) external;
function batchAddTableauEntries(TableauData[] calldata entries) external;
function setTableauPrice(uint256 tokenId, uint256 price) external;
function setTableauChangeBps(uint256 tokenId, int256 changeBps) external;
function setTableauTimestamp(uint256 tokenId, uint40 timestamp) external;
function setTableauMoodIndex(uint256 tokenId, uint8 moodIndex) external;
function setTableauWorkflowId(uint256 tokenId, uint8 workflowId) external;
function setTableauSeason(uint256 tokenId, uint8 season) external;
function setTableauSeed(uint256 tokenId, uint256 seed) external;
function setTableauPrompt(uint256 tokenId, string calldata prompt) external;
function setCustomTableauName(uint256 tokenId, string calldata _name) external;
function setCustomTableauDescription(uint256 tokenId, string calldata description) external;
// Mutations — Image Fragments
function setTableauImageFragmentHashes(uint256 tokenId, bytes32[] calldata hashes) external;
function batchSetTableauImageFragmentHashes(uint256[] calldata tokenIds, bytes32[][] calldata hashes) external;
function uploadImageFragment(uint256 tokenId, uint256 fragmentIndex, bytes calldata data) external;
function setFragmentPointer(uint256 tokenId, uint256 fragmentIndex, address pointer) external;
function removeFragmentPointer(uint256 tokenId, uint256 fragmentIndex) external;
function clearFragmentData(uint256 tokenId) external;
// Mutations — Workflows
function addWorkflow(Workflow calldata wf, bytes calldata json) external returns (uint256 id);
function updateWorkflowName(uint256 id, string calldata _name) external;
function updateWorkflowJson(uint256 id, bytes calldata json) external;
function updateWorkflowGpu(uint256 id, string calldata gpu, string calldata cuda) external;
function updateWorkflowModels(uint256 id, bytes32[] calldata modelHashes, string[] calldata downloadLinks) external;
function updateWorkflowCustomNodes(
uint256 id,
string[] calldata names,
string[] calldata versions,
bytes32[] calldata nodeHashes
) external;
}
src/interfaces/IPanoramaWorkflowLedger.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;
import { IPanoramaStorage } from "./IPanoramaStorage.sol";
/// @notice Ordered generation steps per Panorama tableau: which registered ComfyUI workflow
/// ran at each step and with which parameters, so a tableau can be reproduced step
/// by step (tile → seam → retouch composite → inpaint repaints → grain).
interface IPanoramaWorkflowLedger {
error Unauthorized();
error InvalidTokenId();
error UnknownWorkflow(uint16 workflowId);
error LengthMismatch();
error NoSteps();
error TooManySteps();
error StepIndexOutOfBounds();
event StepsAppended(uint256 indexed tokenId, uint256 fromIndex, uint256 count);
event StepsCleared(uint256 indexed tokenId);
// State
function store() external view returns (IPanoramaStorage);
function NO_WORKFLOW() external view returns (uint16);
function MAX_CHUNK_SIZE() external view returns (uint256);
function MAX_STEPS() external view returns (uint256);
// Mutations
function appendSteps(uint256 tokenId, uint16[] calldata workflowIds, bytes[] calldata params) external;
function appendStepsBatch(
uint256[] calldata tokenIds,
uint16[][] calldata workflowIds,
bytes[][] calldata params
) external;
function clearSteps(uint256 tokenId) external;
// Views
function stepCount(uint256 tokenId) external view returns (uint256);
function getStep(uint256 tokenId, uint256 index) external view returns (uint16 workflowId, bytes memory params);
function getSteps(uint256 tokenId) external view returns (uint16[] memory workflowIds, bytes[] memory params);
// Rendering (read by PanoramaRendererV3)
function renderWorkflows(uint256 tokenId) external view returns (string memory);
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 10000,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
"@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
"forge-std/=node_modules/forge-std/",
"solady/=node_modules/solady/src/",
"@uniswap/v4-core/=node_modules/@uniswap/v4-core/",
"@uniswap/v4-periphery/=node_modules/@uniswap/v4-periphery/",
"@ensdomains/=node_modules/@ensdomains/",
"@manifoldxyz/=node_modules/@manifoldxyz/",
"ds-test/=node_modules/@uniswap/v4-core/lib/solmate/lib/ds-test/",
"erc4626-tests/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=node_modules/@uniswap/v4-periphery/lib/permit2/lib/forge-gas-snapshot/",
"openzeppelin-contracts/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/",
"permit2/=node_modules/@uniswap/v4-periphery/lib/permit2/",
"solmate/=node_modules/@uniswap/v4-core/lib/solmate/",
"v4-core/=node_modules/@uniswap/v4-periphery/lib/v4-core/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.