Skip to content
Verified contractPartialMIT

CentrifugeSnapshot

Address0x2d2cbf53282635e076ed546e9538761e724c4bdc
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.38

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.38+commit.1835d247
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,339,250
Creation transaction
0x7bd7b62a24…aae0c27088

contracts/CentrifugeSnapshot.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;

import {ERC7540Snapshot} from "./base/ERC7540Snapshot.sol";

/// @notice Source transcript and exact-amount native quotes for one share token.
/// @dev Epoch quantity replay only derives native getter arguments. Go independently
///      replays all raw epochs and owns binding, reconciliation and NAV policy.
contract CentrifugeSnapshot is ERC7540Snapshot {
    struct Config {
        address batchManager;
        address hubRegistry;
        address vaultRegistry;
        address spoke;
        uint16 domain;
    }

    struct Key {
        uint64 pool;
        bytes16 sc;
        uint128 assetId;
        uint256 shareScale;
        uint256 assetScale;
    }

    struct Cursor {
        uint256 phase;
        uint256 index;
        uint256 pending;
        uint256 issued;
        uint256 remaining;
    }

    function snapshot(
        address owner,
        address token,
        address asset,
        Config calldata config,
        uint256[] calldata extraAmounts
    ) external view returns (SourceResult[] memory) {
        Transcript memory t = _newTranscript();
        Cursor memory cursor;
        if (t.cursor.length != 0) cursor = abi.decode(t.cursor, (Cursor));
        uint256 held = _vaultShares(t, token, owner);
        _vaultShares(t, asset, owner);
        address vault = _address(_readUint(t, token, abi.encodeWithSignature("vault(address)", asset)));
        _read(t, vault, abi.encodeWithSignature("asset()"), 32);
        if (held != 0) _readQuote(t, vault, held);
        for (uint256 i = cursor.phase == 0 ? cursor.index : extraAmounts.length; i < extraAmounts.length; ++i) {
            if (_pause(t, abi.encode(Cursor(0, i, 0, 0, 0)))) return _finish(t);
            if (extraAmounts[i] != 0) _readQuote(t, vault, extraAmounts[i]);
        }
        _readShare(t, vault);
        address manager = _address(_readUint(t, vault, abi.encodeWithSignature("asyncManager()")));
        bytes memory stateData =
            _read(t, manager, abi.encodeWithSignature("investments(address,address)", vault, owner), 320);
        if (stateData.length != 320) return _finish(t);
        uint256[10] memory state = abi.decode(stateData, (uint256[10]));
        for (uint256 i; i < 8; ++i) {
            if (state[i] > type(uint128).max) return _finish(t);
        }
        if (state[8] > 1 || state[9] > 1) return _finish(t);
        // Independently known shares survive an unavailable Hub partition. Go
        // retains their value while the affected pending right fails closed.
        if (state[0] != 0) _readQuote(t, vault, state[0]);
        if (state[7] != 0) _readQuote(t, vault, state[7]);
        uint256 minted = state[0];
        uint256 issued = cursor.issued;
        uint256 remaining = state[5];
        if (state[4] != 0 || state[5] != 0) {
            (Key memory key, bool bound) = _readBinding(t, config, vault, manager, token, asset);
            if (!bound) return _finish(t);
            if (state[4] != 0) {
                if (cursor.phase <= 1) {
                    bool complete;
                    (issued, complete) = _readDeposits(t, config, key, owner, cursor);
                    if (!complete) return _finish(t);
                }
                minted += issued;
            }
            if (state[5] != 0) {
                if (cursor.phase <= 2) {
                    bool complete;
                    (remaining, complete) = _readRedemptions(t, config, key, owner, cursor, issued);
                    if (!complete) return _finish(t);
                } else {
                    remaining = cursor.remaining;
                }
            }
        }
        if (_pause(t, abi.encode(Cursor(3, 0, 0, issued, remaining)))) return _finish(t);
        if (minted != 0 && minted != state[0]) _readQuote(t, vault, minted);
        if (remaining != 0) _readQuote(t, vault, remaining);
        return _finish(t);
    }

    function _readQuote(Transcript memory t, address vault, uint256 shares) private view {
        _read(t, vault, abi.encodeWithSignature("convertToAssets(uint256)", shares), 32);
    }

    function _tryRead(Transcript memory t, address target, bytes memory input, uint256 size)
        private
        view
        returns (bool valid, bytes memory data)
    {
        (bool success, bytes memory result) = _probe(target, input, size);
        _record(t, target, input, success, result);
        return (success && result.length == size, result);
    }

    function _tryReadUint(Transcript memory t, address target, bytes memory input)
        private
        view
        returns (uint256 value, bool valid)
    {
        bytes memory data;
        (valid, data) = _tryRead(t, target, input, 32);
        if (valid) value = abi.decode(data, (uint256));
    }

    function _readBinding(
        Transcript memory t,
        Config memory config,
        address vault,
        address manager,
        address token,
        address asset
    ) private view returns (Key memory key, bool valid) {
        uint256 pool;
        (pool, valid) = _tryReadUint(t, vault, abi.encodeWithSignature("poolId()"));
        if (!valid || pool > type(uint64).max) return (key, false);
        key.pool = uint64(pool);
        uint256 sc;
        (sc, valid) = _tryReadUint(t, vault, abi.encodeWithSignature("scId()"));
        if (!valid || uint128(sc) != 0) return (key, false);
        key.sc = bytes16(bytes32(sc));
        bytes memory detail;
        (valid, detail) =
            _tryRead(t, config.vaultRegistry, abi.encodeWithSignature("vaultDetails(address)", vault), 128);
        if (!valid) return (key, false);
        uint256[4] memory details = abi.decode(detail, (uint256[4]));
        if (details[0] > type(uint128).max) return (key, false);
        key.assetId = uint128(details[0]);
        _read(t, config.spoke, abi.encodeWithSignature("shareToken(uint64,bytes16)", key.pool, key.sc), 32);
        _read(t, config.spoke, abi.encodeWithSignature("requestManager(uint64)", key.pool), 32);
        _read(
            t,
            config.vaultRegistry,
            abi.encodeWithSignature("vault(uint64,bytes16,uint128,address)", key.pool, key.sc, key.assetId, manager),
            32
        );
        _read(
            t,
            config.hubRegistry,
            abi.encodeWithSignature("hubRequestManager(uint64,uint16)", key.pool, config.domain),
            32
        );
        uint256 sd;
        (sd, valid) = _tryReadUint(t, config.hubRegistry, abi.encodeWithSignature("decimals(uint64)", key.pool));
        if (!valid || sd > 18) return (key, false);
        uint256 ad;
        (ad, valid) = _tryReadUint(t, config.hubRegistry, abi.encodeWithSignature("decimals(uint128)", key.assetId));
        if (!valid || ad > 18) return (key, false);
        key.shareScale = 10 ** sd;
        key.assetScale = 10 ** ad;
        _read(t, token, abi.encodeWithSignature("decimals()"), 32);
        _read(t, asset, abi.encodeWithSignature("decimals()"), 32);
    }

    function _readLedger(Transcript memory t, Config memory config, Key memory k, address owner, bool deposit)
        private
        view
        returns (uint256 pending, uint256 queued, uint32 first, uint32 end, bool valid)
    {
        bytes32 investor = bytes32(bytes20(owner));
        bytes memory request;
        (valid, request) = _tryRead(
            t,
            config.batchManager,
            abi.encodeWithSignature(
                deposit
                    ? "depositRequest(uint64,bytes16,uint128,bytes32)"
                    : "redeemRequest(uint64,bytes16,uint128,bytes32)",
                k.pool,
                k.sc,
                k.assetId,
                investor
            ),
            64
        );
        if (!valid) return (0, 0, 0, 0, false);
        (uint256 amount, uint256 firstWord) = abi.decode(request, (uint256, uint256));
        if (amount > type(uint128).max || firstWord > type(uint32).max) return (0, 0, 0, 0, false);
        first = uint32(firstWord);
        pending = amount;
        bytes memory queue;
        (valid, queue) = _tryRead(
            t,
            config.batchManager,
            abi.encodeWithSignature(
                deposit
                    ? "queuedDepositRequest(uint64,bytes16,uint128,bytes32)"
                    : "queuedRedeemRequest(uint64,bytes16,uint128,bytes32)",
                k.pool,
                k.sc,
                k.assetId,
                investor
            ),
            64
        );
        if (!valid) return (0, 0, 0, 0, false);
        (uint256 isQueued, uint256 queuedWord) = abi.decode(queue, (uint256, uint256));
        if (isQueued > 1 || queuedWord > type(uint128).max) return (0, 0, 0, 0, false);
        queued = queuedWord;
        bytes memory epochs;
        (valid, epochs) = _tryRead(
            t,
            config.batchManager,
            abi.encodeWithSignature("epochId(uint64,bytes16,uint128)", k.pool, k.sc, k.assetId),
            128
        );
        if (!valid) return (0, 0, 0, 0, false);
        uint256[4] memory epochWords = abi.decode(epochs, (uint256[4]));
        for (uint256 i; i < 4; ++i) {
            if (epochWords[i] > type(uint32).max) return (0, 0, 0, 0, false);
        }
        end = uint32(deposit ? epochWords[1] : epochWords[3]);
    }

    function _readDeposits(Transcript memory t, Config memory config, Key memory k, address owner, Cursor memory cursor)
        private
        view
        returns (uint256 minted, bool valid)
    {
        (uint256 pending,, uint32 first, uint32 end, bool complete) = _readLedger(t, config, k, owner, true);
        if (!complete) return (0, false);
        uint256 start = first;
        if (cursor.phase == 1) {
            start = cursor.index;
            pending = cursor.pending;
            minted = cursor.issued;
        }
        if (start < first || start > uint256(end) + 1) revert InvalidInput();
        for (uint256 i = start; i <= end && pending != 0; ++i) {
            if (_pause(t, abi.encode(Cursor(1, i, pending, minted, 0)))) return (0, false);
            bytes memory data;
            (valid, data) = _tryRead(
                t,
                config.batchManager,
                abi.encodeWithSignature(
                    "epochInvestAmounts(uint64,bytes16,uint128,uint32)", k.pool, k.sc, k.assetId, uint32(i)
                ),
                192
            );
            if (!valid) return (0, false);
            uint256[6] memory w = abi.decode(data, (uint256[6]));
            if (!_isCanonicalEpoch(w) || w[1] == 0 || w[2] == 0) return (0, false);
            uint256 product = pending * w[1];
            uint256 floor = product / w[2];
            uint256 consumed = floor + (product % w[2] == 0 ? 0 : 1);
            if (consumed > pending) return (0, false);
            pending -= consumed;
            // Valid epochs store floor(approved * price * shareScale /
            // (1e18 * assetScale)) as uint128. Go reconciles that bound, so
            // this numerator is below 2^128 * 1e36 with decimals at most 18.
            if (w[4] != 0) minted += floor * w[3] * k.shareScale / (w[4] * k.assetScale);
        }
        return (minted, true);
    }

    function _readRedemptions(
        Transcript memory t,
        Config memory config,
        Key memory k,
        address owner,
        Cursor memory cursor,
        uint256 issued
    ) private view returns (uint256 remaining, bool valid) {
        (uint256 pending, uint256 queued, uint32 first, uint32 end, bool complete) =
            _readLedger(t, config, k, owner, false);
        if (!complete) return (0, false);
        uint256 start = first;
        if (cursor.phase == 2) {
            start = cursor.index;
            pending = cursor.pending;
        }
        if (start < first || start > uint256(end) + 1) revert InvalidInput();
        for (uint256 i = start; i <= end && pending != 0; ++i) {
            if (_pause(t, abi.encode(Cursor(2, i, pending, issued, 0)))) return (0, false);
            bytes memory data;
            (valid, data) = _tryRead(
                t,
                config.batchManager,
                abi.encodeWithSignature(
                    "epochRedeemAmounts(uint64,bytes16,uint128,uint32)", k.pool, k.sc, k.assetId, uint32(i)
                ),
                192
            );
            if (!valid) return (0, false);
            uint256[6] memory w = abi.decode(data, (uint256[6]));
            if (!_isCanonicalEpoch(w) || w[0] == 0 || w[1] == 0) return (0, false);
            uint256 product = pending * w[0];
            uint256 floor = product / w[1];
            uint256 consumed = floor + (product % w[1] == 0 ? 0 : 1);
            if (consumed > pending) return (0, false);
            pending -= consumed;
        }
        return (pending + queued, true);
    }

    function _isCanonicalEpoch(uint256[6] memory words) private pure returns (bool) {
        for (uint256 i; i < 5; ++i) {
            if (words[i] > type(uint128).max) return false;
        }
        return words[5] <= type(uint64).max;
    }
}

contracts/base/BoundedStaticReader.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;

/// @dev Static source calls and canonical scalar decoding.
abstract contract BoundedStaticReader {
    error InvalidInput();
    error SourceReadFailed(address target, bytes4 selector);

    function _readUint(address target, bytes memory input) internal view returns (uint256 value) {
        (bool success, bytes memory data) = _probe(target, input, 32);
        if (!success || data.length != 32) revert SourceReadFailed(target, bytes4(input));
        return abi.decode(data, (uint256));
    }

    function _probe(address target, bytes memory input, uint256 maxBytes)
        internal
        view
        returns (bool success, bytes memory data)
    {
        if (target == address(0) || input.length < 4) revert InvalidInput();
        (success, data) = target.staticcall(input);
        if (success && data.length > maxBytes) revert SourceReadFailed(target, bytes4(input));
    }

    function _address(uint256 value) internal pure returns (address) {
        if (value > type(uint160).max) revert InvalidInput();
        return address(uint160(value));
    }

    function _bool(uint256 value) internal pure returns (bool) {
        if (value > 1) revert InvalidInput();
        return value == 1;
    }

    function _uint(uint256 value, uint256 bits) internal pure returns (uint256) {
        if (bits < 256 && value >> bits != 0) revert InvalidInput();
        return value;
    }
}

contracts/base/ERC4626Snapshot.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;

import {SnapshotReader} from "./SnapshotReader.sol";

/// @dev Standard vault facts; concrete collectors decide inventory and valuation.
abstract contract ERC4626Snapshot is SnapshotReader {
    function _vaultAsset(Transcript memory t, address vault) internal view returns (address) {
        return _address(_readUint(t, vault, abi.encodeWithSignature("asset()")));
    }

    function _vaultShares(Transcript memory t, address share, address owner) internal view returns (uint256) {
        return _readUint(t, share, abi.encodeWithSignature("balanceOf(address)", owner));
    }

    function _convertToAssets(Transcript memory t, address vault, uint256 shares) internal view returns (uint256) {
        return _readUint(t, vault, abi.encodeWithSignature("convertToAssets(uint256)", shares));
    }

    function _previewRedeem(Transcript memory t, address vault, uint256 shares) internal view returns (uint256) {
        return _readUint(t, vault, abi.encodeWithSignature("previewRedeem(uint256)", shares));
    }
}

contracts/base/ERC7540Snapshot.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;

import {ERC4626Snapshot} from "./ERC4626Snapshot.sol";

/// @dev Standard request facts; protocol collectors own conversion and entitlement policy.
abstract contract ERC7540Snapshot is ERC4626Snapshot {
    uint8 internal constant ASYNC_DEPOSIT = 1;
    uint8 internal constant ASYNC_REDEEM = 2;

    struct Requests {
        uint256 heldShares;
        uint256 pendingRedeemShares;
        uint256 claimableDepositAssets;
        uint256 claimableRedeemShares;
    }

    function _readShare(Transcript memory t, address vault) internal view returns (bytes memory) {
        return _read(t, vault, abi.encodeWithSignature("share()"), 32);
    }

    function _vault(Transcript memory t, address vault, address owner, uint256 requestId, uint8 sides)
        internal
        view
        returns (Requests memory requests)
    {
        if (vault == address(0) || owner == address(0) || sides == 0 || sides > 3) revert InvalidInput();
        address asset = _vaultAsset(t, vault);
        address share = _address(_readUint(t, vault, abi.encodeWithSignature("share()")));
        _uint(_readUint(t, share, abi.encodeWithSignature("decimals()")), 8);
        _uint(_readUint(t, asset, abi.encodeWithSignature("decimals()")), 8);
        if ((sides & ASYNC_DEPOSIT) != 0) {
            _bool(_readUint(t, vault, abi.encodeWithSignature("supportsInterface(bytes4)", bytes4(0xce3bbe50))));
        }
        if ((sides & ASYNC_REDEEM) != 0) {
            _bool(_readUint(t, vault, abi.encodeWithSignature("supportsInterface(bytes4)", bytes4(0x620ee8e4))));
        }
        requests.heldShares = _vaultShares(t, share, owner);
        if ((sides & ASYNC_DEPOSIT) != 0) {
            _readUint(t, vault, abi.encodeWithSignature("pendingDepositRequest(uint256,address)", requestId, owner));
            requests.claimableDepositAssets = _readUint(
                t, vault, abi.encodeWithSignature("claimableDepositRequest(uint256,address)", requestId, owner)
            );
        }
        if ((sides & ASYNC_REDEEM) != 0) {
            requests.pendingRedeemShares =
                _readUint(t, vault, abi.encodeWithSignature("pendingRedeemRequest(uint256,address)", requestId, owner));
            requests.claimableRedeemShares = _readUint(
                t, vault, abi.encodeWithSignature("claimableRedeemRequest(uint256,address)", requestId, owner)
            );
        }
    }
}

contracts/base/SnapshotReader.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;

import {BoundedStaticReader} from "./BoundedStaticReader.sol";
import {DynamicArrayLib} from "solady/utils/DynamicArrayLib.sol";

/// @dev Collects source replies. Consumers validate and value these facts in Go.
abstract contract SnapshotReader is BoundedStaticReader {
    struct SourceResult {
        address target;
        bytes input;
        bool success;
        bytes data;
    }

    struct Transcript {
        SourceResult[] rows;
        uint256 used;
        bytes cursor;
        bool paused;
        uint256 progress;
        uint256 encodedBytes;
        uint256 checkpointGas;
        uint256 unitGas;
    }

    function page(bytes calldata snapshotCall, bytes calldata continuation)
        external
        view
        returns (SourceResult[] memory)
    {
        if (msg.sender == address(this) || snapshotCall.length < 4) revert InvalidInput();
        (bool success, bytes memory result) =
            address(this).staticcall(abi.encodePacked(snapshotCall, continuation, uint256(continuation.length)));
        if (!success) {
            assembly ("memory-safe") { revert(add(result, 32), mload(result)) }
        }
        assembly ("memory-safe") { return(add(result, 32), mload(result)) }
    }

    function _newTranscript() internal view returns (Transcript memory t) {
        uint256[] memory slots = DynamicArrayLib.malloc(64);
        SourceResult[] memory rows;
        // Only populated pointer slots are read.
        assembly ("memory-safe") { rows := slots }
        t.rows = rows;
        t.encodedBytes = 64;
        if (msg.sender == address(this)) {
            uint256 length;
            assembly ("memory-safe") { length := calldataload(sub(calldatasize(), 32)) }
            bytes calldata continuation = msg.data[msg.data.length - 32 - length:msg.data.length - 32];
            if (length != 0) {
                (t.progress, t.cursor) = abi.decode(continuation, (uint256, bytes));
            }
        }
    }

    // Checkpoints precede complete resumable units; the first unit always gets an attempt.
    function _pause(Transcript memory t, bytes memory nextState) internal view returns (bool) {
        uint256 remaining = gasleft();
        if (t.checkpointGas != 0) {
            uint256 spent = t.checkpointGas > remaining ? t.checkpointGas - remaining : 0;
            if (spent > t.unitGas) t.unitGas = spent;
            uint256 free;
            assembly ("memory-safe") { free := mload(0x40) }
            // Reserve ABI construction plus the outer self-call return copy.
            uint256 encodedBytes = t.encodedBytes + 352 + ((nextState.length + 31) & ~uint256(31));
            uint256 words = (free + 2 * encodedBytes + 31) / 32;
            uint256 currentWords = (free + 31) / 32;
            uint256 memoryGas = 3 * (words - currentWords) + (words * words - currentWords * currentWords) / 512;
            uint256 reserve = 30_000 + memoryGas + t.used * 500 + (encodedBytes / 32) * 24;
            uint256 nextGas = t.unitGas > 10_000 ? t.unitGas : 10_000;
            if (remaining <= reserve + nextGas) {
                _record(
                    t,
                    address(this),
                    abi.encodeWithSignature("snapshotContinuation()"),
                    true,
                    abi.encode(t.progress, nextState)
                );
                t.paused = true;
                return true;
            }
        }
        t.checkpointGas = gasleft();
        ++t.progress;
        return false;
    }

    function _record(Transcript memory t, address target, bytes memory input, bool success, bytes memory data)
        internal
        pure
    {
        if (t.used == t.rows.length) {
            uint256[] memory slots = DynamicArrayLib.malloc(t.rows.length * 2);
            SourceResult[] memory rows;
            assembly ("memory-safe") { rows := slots }
            for (uint256 i; i < t.used; ++i) {
                rows[i] = t.rows[i];
            }
            t.rows = rows;
        }
        t.rows[t.used++] = SourceResult(target, input, success, data);
        t.encodedBytes += 224 + ((input.length + 31) & ~uint256(31)) + ((data.length + 31) & ~uint256(31));
    }

    function _read(Transcript memory t, address target, bytes memory input, uint256 maxBytes)
        internal
        view
        returns (bytes memory data)
    {
        bool success;
        (success, data) = _probe(target, input, maxBytes);
        _record(t, target, input, success, data);
    }

    function _readUint(Transcript memory t, address target, bytes memory input) internal view returns (uint256 value) {
        (bool success, bytes memory data) = _probe(target, input, 32);
        if (!success || data.length != 32) revert SourceReadFailed(target, bytes4(input));
        value = abi.decode(data, (uint256));
        _record(t, target, input, true, data);
    }

    function _finish(Transcript memory t) internal pure returns (SourceResult[] memory rows) {
        rows = t.rows;
        uint256 used = t.used;
        assembly ("memory-safe") { mstore(rows, used) }
    }

    // Go owns admission and valuation. Collect exact full-amount source probes
    // for its normalization, including negative probes. Cycles stop acquisition;
    // Go rejects them when normalization requires the repeated asset.
    function _readWrapper(Transcript memory t, address asset, uint256 amount) internal view {
        if (amount == 0) return;
        address[] memory seen = new address[](8);
        for (uint256 depth; asset != address(0); ++depth) {
            for (uint256 i; i < depth; ++i) {
                if (seen[i] == asset) return;
            }
            if (depth == seen.length) {
                address[] memory grown = new address[](seen.length * 2);
                for (uint256 i; i < depth; ++i) {
                    grown[i] = seen[i];
                }
                seen = grown;
            }
            seen[depth] = asset;
            bool ok;
            address next;
            (bool addressOK, uint256 addressWord) = _readOptionalUint(t, asset, abi.encodeWithSignature("asset()"));
            (ok, amount) = _readOptionalUint(t, asset, abi.encodeWithSignature("previewRedeem(uint256)", amount));
            if (!addressOK || addressWord == 0 || addressWord > type(uint160).max) return;
            next = address(uint160(addressWord));
            if (!ok) return;
            asset = next;
        }
    }

    function _readNormalization(Transcript memory t, address target, bytes memory input)
        internal
        view
        returns (bool success, bytes memory data)
    {
        bytes32 key = keccak256(input);
        for (uint256 i; i < t.used; ++i) {
            SourceResult memory previous = t.rows[i];
            if (previous.target == target && keccak256(previous.input) == key) {
                return (previous.success, previous.data);
            }
        }
        (success, data) = target.staticcall(input);
        _record(t, target, input, success, data);
    }

    // Invalid optional facts stay in the transcript; Go decides whether they are needed.
    function _readOptionalUint(Transcript memory t, address target, bytes memory input)
        internal
        view
        returns (bool usable, uint256 value)
    {
        (bool success, bytes memory data) = _readNormalization(t, target, input);
        if (!success || data.length != 32) return (false, 0);
        return (true, abi.decode(data, (uint256)));
    }
}

lib/solady/src/utils/DynamicArrayLib.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Library for memory arrays with automatic capacity resizing.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/DynamicArrayLib.sol)
library DynamicArrayLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STRUCTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Type to represent a dynamic array in memory.
    /// You can directly assign to `data`, and the `p` function will
    /// take care of the memory allocation.
    ///
    /// Note: The capacity is a prime-checksummed word before the array. If you assign
    /// an array you did not allocate (e.g. from calldata), that word can
    /// masquerade as a capacity, making `p` skip reallocation and write out of bounds.
    /// Arrays brought in via `wrap` carry the same risk, as `wrap` assigns to `data` too.
    /// If you are not assigning to `data` or using `wrap`, you don't have to worry about it.
    struct DynamicArray {
        uint256[] data;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The constant returned when the element is not found in the array.
    uint256 internal constant NOT_FOUND = type(uint256).max;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  UINT256 ARRAY OPERATIONS                  */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // Low level minimalist uint256 array operations.
    // If you don't need syntax sugar, it's recommended to use these.
    // Some of these functions return the same array for function chaining.
    // e.g. `array.set(0, 1).set(1, 2)`.

    /// @dev Returns a uint256 array with `n` elements. The elements are not zeroized.
    function malloc(uint256 n) internal pure returns (uint256[] memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := or(sub(0, shr(32, n)), mload(0x40))
            mstore(result, n)
            mstore(0x40, add(add(result, 0x20), shl(5, n)))
        }
    }

    /// @dev Zeroizes all the elements of `a`.
    function zeroize(uint256[] memory a) internal pure returns (uint256[] memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := a
            calldatacopy(add(result, 0x20), calldatasize(), shl(5, mload(result)))
        }
    }

    /// @dev Returns the element at `a[i]`, without bounds checking.
    function get(uint256[] memory a, uint256 i) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(add(add(a, 0x20), shl(5, i)))
        }
    }

    /// @dev Returns the element at `a[i]`, without bounds checking.
    function getUint256(uint256[] memory a, uint256 i) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(add(add(a, 0x20), shl(5, i)))
        }
    }

    /// @dev Returns the element at `a[i]`, without bounds checking.
    function getAddress(uint256[] memory a, uint256 i) internal pure returns (address result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(add(add(a, 0x20), shl(5, i)))
        }
    }

    /// @dev Returns the element at `a[i]`, without bounds checking.
    function getBool(uint256[] memory a, uint256 i) internal pure returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(add(add(a, 0x20), shl(5, i)))
        }
    }

    /// @dev Returns the element at `a[i]`, without bounds checking.
    function getBytes32(uint256[] memory a, uint256 i) internal pure returns (bytes32 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(add(add(a, 0x20), shl(5, i)))
        }
    }

    /// @dev Sets `a.data[i]` to `data`, without bounds checking.
    function set(uint256[] memory a, uint256 i, uint256 data)
        internal
        pure
        returns (uint256[] memory result)
    {
        result = a;
        /// @solidity memory-safe-assembly
        assembly {
            mstore(add(add(result, 0x20), shl(5, i)), data)
        }
    }

    /// @dev Sets `a.data[i]` to `data`, without bounds checking.
    function set(uint256[] memory a, uint256 i, address data)
        internal
        pure
        returns (uint256[] memory result)
    {
        result = a;
        /// @solidity memory-safe-assembly
        assembly {
            mstore(add(add(result, 0x20), shl(5, i)), shr(96, shl(96, data)))
        }
    }

    /// @dev Sets `a.data[i]` to `data`, without bounds checking.
    function set(uint256[] memory a, uint256 i, bool data)
        internal
        pure
        returns (uint256[] memory result)
    {
        result = a;
        /// @solidity memory-safe-assembly
        assembly {
            mstore(add(add(result, 0x20), shl(5, i)), iszero(iszero(data)))
        }
    }

    /// @dev Sets `a.data[i]` to `data`, without bounds checking.
    function set(uint256[] memory a, uint256 i, bytes32 data)
        internal
        pure
        returns (uint256[] memory result)
    {
        result = a;
        /// @solidity memory-safe-assembly
        assembly {
            mstore(add(add(result, 0x20), shl(5, i)), data)
        }
    }

    /// @dev Casts `a` to `address[]`.
    function asAddressArray(uint256[] memory a) internal pure returns (address[] memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := a
        }
    }

    /// @dev Casts `a` to `bool[]`.
    function asBoolArray(uint256[] memory a) internal pure returns (bool[] memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := a
        }
    }

    /// @dev Casts `a` to `bytes32[]`.
    function asBytes32Array(uint256[] memory a) internal pure returns (bytes32[] memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := a
        }
    }

    /// @dev Casts `a` to `uint256[]`.
    function toUint256Array(address[] memory a) internal pure returns (uint256[] memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := a
        }
    }

    /// @dev Casts `a` to `uint256[]`.
    function toUint256Array(bool[] memory a) internal pure returns (uint256[] memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := a
        }
    }

    /// @dev Casts `a` to `uint256[]`.
    function toUint256Array(bytes32[] memory a) internal pure returns (uint256[] memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := a
        }
    }

    /// @dev Reduces the size of `a` to `n`.
    /// If `n` is greater than the size of `a`, this will be a no-op.
    function truncate(uint256[] memory a, uint256 n)
        internal
        pure
        returns (uint256[] memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := a
            mstore(mul(lt(n, mload(result)), result), n)
        }
    }

    /// @dev Clears the array and attempts to free the memory if possible.
    function free(uint256[] memory a) internal pure returns (uint256[] memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := a
            let n := mload(result)
            mstore(shl(6, lt(iszero(n), eq(add(shl(5, add(1, n)), result), mload(0x40)))), result)
            mstore(result, 0)
        }
    }

    /// @dev Equivalent to `keccak256(abi.encodePacked(a))`.
    function hash(uint256[] memory a) internal pure returns (bytes32 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := keccak256(add(a, 0x20), shl(5, mload(a)))
        }
    }

    /// @dev Returns a copy of `a` sliced from `start` to `end` (exclusive).
    function slice(uint256[] memory a, uint256 start, uint256 end)
        internal
        pure
        returns (uint256[] memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let arrayLen := mload(a)
            if iszero(gt(arrayLen, end)) { end := arrayLen }
            if iszero(gt(arrayLen, start)) { start := arrayLen }
            if lt(start, end) {
                result := mload(0x40)
                let resultLen := sub(end, start)
                mstore(result, resultLen)
                a := add(a, shl(5, start))
                // Copy the `a` one word at a time, backwards.
                let o := shl(5, resultLen)
                mstore(0x40, add(add(result, o), 0x20)) // Allocate memory.
                for {} 1 {} {
                    mstore(add(result, o), mload(add(a, o)))
                    o := sub(o, 0x20)
                    if iszero(o) { break }
                }
            }
        }
    }

    /// @dev Returns a copy of `a` sliced from `start` to the end of the array.
    function slice(uint256[] memory a, uint256 start)
        internal
        pure
        returns (uint256[] memory result)
    {
        result = slice(a, start, type(uint256).max);
    }

    /// @dev Returns a copy of the array.
    function copy(uint256[] memory a) internal pure returns (uint256[] memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            let end := add(add(result, 0x20), shl(5, mload(a)))
            let o := result
            for { let d := sub(a, result) } 1 {} {
                mstore(o, mload(add(o, d)))
                o := add(0x20, o)
                if eq(o, end) { break }
            }
            mstore(0x40, o)
        }
    }

    /// @dev Returns if `needle` is in `a`.
    function contains(uint256[] memory a, uint256 needle) internal pure returns (bool) {
        return ~indexOf(a, needle, 0) != 0;
    }

    /// @dev Returns the first index of `needle`, scanning forward from `from`.
    /// If `needle` is not in `a`, returns `NOT_FOUND`.
    function indexOf(uint256[] memory a, uint256 needle, uint256 from)
        internal
        pure
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := not(0)
            if lt(from, mload(a)) {
                let o := add(a, shl(5, from))
                let end := add(shl(5, add(1, mload(a))), a)
                let c := mload(end) // Cache the word after the array.
                for { mstore(end, needle) } 1 {} {
                    o := add(o, 0x20)
                    if eq(mload(o), needle) { break }
                }
                mstore(end, c) // Restore the word after the array.
                if iszero(eq(o, end)) { result := shr(5, sub(o, add(0x20, a))) }
            }
        }
    }

    /// @dev Returns the first index of `needle`.
    /// If `needle` is not in `a`, returns `NOT_FOUND`.
    function indexOf(uint256[] memory a, uint256 needle) internal pure returns (uint256 result) {
        result = indexOf(a, needle, 0);
    }

    /// @dev Returns the last index of `needle`, scanning backwards from `from`.
    /// If `needle` is not in `a`, returns `NOT_FOUND`.
    function lastIndexOf(uint256[] memory a, uint256 needle, uint256 from)
        internal
        pure
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := not(0)
            let n := mload(a)
            if n {
                if iszero(lt(from, n)) { from := sub(n, 1) }
                let o := add(shl(5, add(2, from)), a)
                for { mstore(a, needle) } 1 {} {
                    o := sub(o, 0x20)
                    if eq(mload(o), needle) { break }
                }
                mstore(a, n) // Restore the length.
                if iszero(eq(o, a)) { result := shr(5, sub(o, add(0x20, a))) }
            }
        }
    }

    /// @dev Returns the first index of `needle`.
    /// If `needle` is not in `a`, returns `NOT_FOUND`.
    function lastIndexOf(uint256[] memory a, uint256 needle)
        internal
        pure
        returns (uint256 result)
    {
        result = lastIndexOf(a, needle, NOT_FOUND);
    }

    /// @dev Directly returns `a` without copying.
    function directReturn(uint256[] memory a) internal pure {
        /// @solidity memory-safe-assembly
        assembly {
            let retStart := sub(a, 0x20)
            mstore(retStart, 0x20)
            return(retStart, add(0x40, shl(5, mload(a))))
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  DYNAMIC ARRAY OPERATIONS                  */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // Some of these functions return the same array for function chaining.
    // e.g. `a.p("1").p("2")`.

    /// @dev Shorthand for `a.data.length`.
    function length(DynamicArray memory a) internal pure returns (uint256) {
        return a.data.length;
    }

    /// @dev Wraps `a` in a dynamic array struct.
    function wrap(uint256[] memory a) internal pure returns (DynamicArray memory result) {
        result.data = a;
    }

    /// @dev Wraps `a` in a dynamic array struct.
    function wrap(address[] memory a) internal pure returns (DynamicArray memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(result, a)
        }
    }

    /// @dev Wraps `a` in a dynamic array struct.
    function wrap(bool[] memory a) internal pure returns (DynamicArray memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(result, a)
        }
    }

    /// @dev Wraps `a` in a dynamic array struct.
    function wrap(bytes32[] memory a) internal pure returns (DynamicArray memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(result, a)
        }
    }

    /// @dev Clears the array without deallocating the memory.
    function clear(DynamicArray memory a) internal pure returns (DynamicArray memory result) {
        _deallocate(result);
        result = a;
        /// @solidity memory-safe-assembly
        assembly {
            mstore(mload(result), 0)
        }
    }

    /// @dev Clears the array and attempts to free the memory if possible.
    function free(DynamicArray memory a) internal pure returns (DynamicArray memory result) {
        _deallocate(result);
        result = a;
        /// @solidity memory-safe-assembly
        assembly {
            let arrData := mload(result)
            if iszero(eq(arrData, 0x60)) {
                let prime := 8188386068317523
                let cap := mload(sub(arrData, 0x20))
                // Extract `cap`, initializing it to zero if it is not a multiple of `prime`.
                cap := mul(div(cap, prime), iszero(mod(cap, prime)))
                // If `cap` is non-zero and the memory is contiguous, we can free it.
                if lt(iszero(cap), eq(mload(0x40), add(arrData, add(0x20, cap)))) {
                    mstore(0x40, sub(arrData, 0x20))
                }
                mstore(result, 0x60)
            }
        }
    }

    /// @dev Resizes the array to contain `n` elements. New elements will be zeroized.
    function resize(DynamicArray memory a, uint256 n)
        internal
        pure
        returns (DynamicArray memory result)
    {
        _deallocate(result);
        result = a;
        reserve(result, n);
        /// @solidity memory-safe-assembly
        assembly {
            let arrData := mload(result)
            let arrLen := mload(arrData)
            if iszero(lt(n, arrLen)) {
                calldatacopy(
                    add(arrData, shl(5, add(1, arrLen))),
                    calldatasize(),
                    shl(5, sub(n, arrLen))
                )
            }
            mstore(arrData, n)
        }
    }

    /// @dev Increases the size of `a` to `n`.
    /// If `n` is less than the size of `a`, this will be a no-op.
    /// This method does not zeroize any newly created elements.
    function expand(DynamicArray memory a, uint256 n)
        internal
        pure
        returns (DynamicArray memory result)
    {
        _deallocate(result);
        result = a;
        if (n >= a.data.length) {
            reserve(result, n);
            /// @solidity memory-safe-assembly
            assembly {
                mstore(mload(result), n)
            }
        }
    }

    /// @dev Reduces the size of `a` to `n`.
    /// If `n` is greater than the size of `a`, this will be a no-op.
    function truncate(DynamicArray memory a, uint256 n)
        internal
        pure
        returns (DynamicArray memory result)
    {
        _deallocate(result);
        result = a;
        /// @solidity memory-safe-assembly
        assembly {
            mstore(mul(lt(n, mload(mload(result))), mload(result)), n)
        }
    }

    /// @dev Reserves at least `minimum` amount of contiguous memory.
    function reserve(DynamicArray memory a, uint256 minimum)
        internal
        pure
        returns (DynamicArray memory result)
    {
        _deallocate(result);
        result = a;
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(lt(minimum, 0xffffffff)) { invalid() } // For extra safety.
            for { let arrData := mload(a) } 1 {} {
                // Some random prime number to multiply `cap`, so that
                // we know that the `cap` is for a dynamic array.
                // Selected to be larger than any memory pointer realistically.
                let prime := 8188386068317523
                // Special case for `arrData` pointing to zero pointer.
                if eq(arrData, 0x60) {
                    let newCap := shl(5, add(1, minimum))
                    let capSlot := mload(0x40)
                    mstore(capSlot, mul(prime, newCap)) // Store the capacity.
                    let newArrData := add(0x20, capSlot)
                    mstore(newArrData, 0) // Store the length.
                    mstore(0x40, add(newArrData, add(0x20, newCap))) // Allocate memory.
                    mstore(a, newArrData)
                    break
                }
                let w := not(0x1f)
                let cap := mload(add(arrData, w)) // `mload(sub(arrData, w))`.
                // Extract `cap`, initializing it to zero if it is not a multiple of `prime`.
                cap := mul(div(cap, prime), iszero(mod(cap, prime)))
                let newCap := shl(5, minimum)
                // If we don't need to grow the memory.
                if iszero(and(gt(minimum, mload(arrData)), gt(newCap, cap))) { break }
                // If the memory is contiguous, we can simply expand it.
                if eq(mload(0x40), add(arrData, add(0x20, cap))) {
                    mstore(add(arrData, w), mul(prime, newCap)) // Store the capacity.
                    mstore(0x40, add(arrData, add(0x20, newCap))) // Expand the memory allocation.
                    break
                }
                let capSlot := mload(0x40)
                let newArrData := add(capSlot, 0x20)
                mstore(0x40, add(newArrData, add(0x20, newCap))) // Reallocate the memory.
                mstore(a, newArrData) // Store the `newArrData`.
                // Copy `arrData` one word at a time, backwards.
                for { let o := add(0x20, shl(5, mload(arrData))) } 1 {} {
                    mstore(add(newArrData, o), mload(add(arrData, o)))
                    o := add(o, w) // `sub(o, 0x20)`.
                    if iszero(o) { break }
                }
                mstore(capSlot, mul(prime, newCap)) // Store the capacity.
                mstore(newArrData, mload(arrData)) // Store the length.
                break
            }
        }
    }

    /// @dev Appends `data` to `a`.
    function p(DynamicArray memory a, uint256 data)
        internal
        pure
        returns (DynamicArray memory result)
    {
        _deallocate(result);
        result = a;
        /// @solidity memory-safe-assembly
        assembly {
            let arrData := mload(a)
            let newArrLen := add(mload(arrData), 1)
            let newArrBytesLen := shl(5, newArrLen)
            // Some random prime number to multiply `cap`, so that
            // we know that the `cap` is for a dynamic array.
            // Selected to be larger than any memory pointer realistically.
            let prime := 8188386068317523
            let cap := mload(sub(arrData, 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.
            for {} iszero(lt(newArrBytesLen, cap)) {} {
                // Approximately more than double the capacity to ensure more than enough space.
                let newCap := add(cap, or(cap, newArrBytesLen))
                // If the memory is contiguous, we can simply expand it.
                if iszero(or(xor(mload(0x40), add(arrData, add(0x20, cap))), iszero(cap))) {
                    mstore(sub(arrData, 0x20), mul(prime, newCap)) // Store the capacity.
                    mstore(0x40, add(arrData, add(0x20, newCap))) // Expand the memory allocation.
                    break
                }
                // Set the `newArrData` to point to the word after `cap`.
                let newArrData := add(mload(0x40), 0x20)
                mstore(0x40, add(newArrData, add(0x20, newCap))) // Reallocate the memory.
                mstore(a, newArrData) // Store the `newArrData`.
                let w := not(0x1f)
                // Copy `arrData` one word at a time, backwards.
                for { let o := newArrBytesLen } 1 {} {
                    mstore(add(newArrData, o), mload(add(arrData, o)))
                    o := add(o, w) // `sub(o, 0x20)`.
                    if iszero(o) { break }
                }
                mstore(add(newArrData, w), mul(prime, newCap)) // Store the memory.
                arrData := newArrData // Assign `newArrData` to `arrData`.
                break
            }
            mstore(add(arrData, newArrBytesLen), data) // Append `data`.
            mstore(arrData, newArrLen) // Store the length.
        }
    }

    /// @dev Appends `data` to `a`.
    function p(DynamicArray memory a, address data)
        internal
        pure
        returns (DynamicArray memory result)
    {
        _deallocate(result);
        result = p(a, uint256(uint160(data)));
    }

    /// @dev Appends `data` to `a`.
    function p(DynamicArray memory a, bool data)
        internal
        pure
        returns (DynamicArray memory result)
    {
        _deallocate(result);
        result = p(a, _toUint(data));
    }

    /// @dev Appends `data` to `a`.
    function p(DynamicArray memory a, bytes32 data)
        internal
        pure
        returns (DynamicArray memory result)
    {
        _deallocate(result);
        result = p(a, uint256(data));
    }

    /// @dev Shorthand for returning an empty array.
    function p() internal pure returns (DynamicArray memory result) {}

    /// @dev Shorthand for `p(p(), data)`.
    function p(uint256 data) internal pure returns (DynamicArray memory result) {
        p(result, uint256(data));
    }

    /// @dev Shorthand for `p(p(), data)`.
    function p(address data) internal pure returns (DynamicArray memory result) {
        p(result, uint256(uint160(data)));
    }

    /// @dev Shorthand for `p(p(), data)`.
    function p(bool data) internal pure returns (DynamicArray memory result) {
        p(result, _toUint(data));
    }

    /// @dev Shorthand for `p(p(), data)`.
    function p(bytes32 data) internal pure returns (DynamicArray memory result) {
        p(result, uint256(data));
    }

    /// @dev Removes and returns the last element of `a`.
    /// Returns 0 and does not pop anything if the array is empty.
    function pop(DynamicArray memory a) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            let o := mload(a)
            let n := mload(o)
            result := mload(add(o, shl(5, n)))
            mstore(o, sub(n, iszero(iszero(n))))
        }
    }

    /// @dev Removes and returns the last element of `a`.
    /// Returns 0 and does not pop anything if the array is empty.
    function popUint256(DynamicArray memory a) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            let o := mload(a)
            let n := mload(o)
            result := mload(add(o, shl(5, n)))
            mstore(o, sub(n, iszero(iszero(n))))
        }
    }

    /// @dev Removes and returns the last element of `a`.
    /// Returns 0 and does not pop anything if the array is empty.
    function popAddress(DynamicArray memory a) internal pure returns (address result) {
        /// @solidity memory-safe-assembly
        assembly {
            let o := mload(a)
            let n := mload(o)
            result := mload(add(o, shl(5, n)))
            mstore(o, sub(n, iszero(iszero(n))))
        }
    }

    /// @dev Removes and returns the last element of `a`.
    /// Returns 0 and does not pop anything if the array is empty.
    function popBool(DynamicArray memory a) internal pure returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            let o := mload(a)
            let n := mload(o)
            result := mload(add(o, shl(5, n)))
            mstore(o, sub(n, iszero(iszero(n))))
        }
    }

    /// @dev Removes and returns the last element of `a`.
    /// Returns 0 and does not pop anything if the array is empty.
    function popBytes32(DynamicArray memory a) internal pure returns (bytes32 result) {
        /// @solidity memory-safe-assembly
        assembly {
            let o := mload(a)
            let n := mload(o)
            result := mload(add(o, shl(5, n)))
            mstore(o, sub(n, iszero(iszero(n))))
        }
    }

    /// @dev Returns the element at `a.data[i]`, without bounds checking.
    function get(DynamicArray memory a, uint256 i) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(add(add(mload(a), 0x20), shl(5, i)))
        }
    }

    /// @dev Returns the element at `a.data[i]`, without bounds checking.
    function getUint256(DynamicArray memory a, uint256 i) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(add(add(mload(a), 0x20), shl(5, i)))
        }
    }

    /// @dev Returns the element at `a.data[i]`, without bounds checking.
    function getAddress(DynamicArray memory a, uint256 i) internal pure returns (address result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(add(add(mload(a), 0x20), shl(5, i)))
        }
    }

    /// @dev Returns the element at `a.data[i]`, without bounds checking.
    function getBool(DynamicArray memory a, uint256 i) internal pure returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(add(add(mload(a), 0x20), shl(5, i)))
        }
    }

    /// @dev Returns the element at `a.data[i]`, without bounds checking.
    function getBytes32(DynamicArray memory a, uint256 i) internal pure returns (bytes32 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(add(add(mload(a), 0x20), shl(5, i)))
        }
    }

    /// @dev Sets `a.data[i]` to `data`, without bounds checking.
    function set(DynamicArray memory a, uint256 i, uint256 data)
        internal
        pure
        returns (DynamicArray memory result)
    {
        _deallocate(result);
        result = a;
        /// @solidity memory-safe-assembly
        assembly {
            mstore(add(add(mload(result), 0x20), shl(5, i)), data)
        }
    }

    /// @dev Sets `a.data[i]` to `data`, without bounds checking.
    function set(DynamicArray memory a, uint256 i, address data)
        internal
        pure
        returns (DynamicArray memory result)
    {
        _deallocate(result);
        result = a;
        /// @solidity memory-safe-assembly
        assembly {
            mstore(add(add(mload(result), 0x20), shl(5, i)), shr(96, shl(96, data)))
        }
    }

    /// @dev Sets `a.data[i]` to `data`, without bounds checking.
    function set(DynamicArray memory a, uint256 i, bool data)
        internal
        pure
        returns (DynamicArray memory result)
    {
        _deallocate(result);
        result = a;
        /// @solidity memory-safe-assembly
        assembly {
            mstore(add(add(mload(result), 0x20), shl(5, i)), iszero(iszero(data)))
        }
    }

    /// @dev Sets `a.data[i]` to `data`, without bounds checking.
    function set(DynamicArray memory a, uint256 i, bytes32 data)
        internal
        pure
        returns (DynamicArray memory result)
    {
        _deallocate(result);
        result = a;
        /// @solidity memory-safe-assembly
        assembly {
            mstore(add(add(mload(result), 0x20), shl(5, i)), data)
        }
    }

    /// @dev Returns the underlying array as a `uint256[]`.
    function asUint256Array(DynamicArray memory a) internal pure returns (uint256[] memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(a)
        }
    }

    /// @dev Returns the underlying array as a `address[]`.
    function asAddressArray(DynamicArray memory a) internal pure returns (address[] memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(a)
        }
    }

    /// @dev Returns the underlying array as a `bool[]`.
    function asBoolArray(DynamicArray memory a) internal pure returns (bool[] memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(a)
        }
    }

    /// @dev Returns the underlying array as a `bytes32[]`.
    function asBytes32Array(DynamicArray memory a) internal pure returns (bytes32[] memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(a)
        }
    }

    /// @dev Returns a copy of `a` sliced from `start` to `end` (exclusive).
    function slice(DynamicArray memory a, uint256 start, uint256 end)
        internal
        pure
        returns (DynamicArray memory result)
    {
        result.data = slice(a.data, start, end);
    }

    /// @dev Returns a copy of `a` sliced from `start` to the end of the array.
    function slice(DynamicArray memory a, uint256 start)
        internal
        pure
        returns (DynamicArray memory result)
    {
        result.data = slice(a.data, start, type(uint256).max);
    }

    /// @dev Returns a copy of `a`.
    function copy(DynamicArray memory a) internal pure returns (DynamicArray memory result) {
        result.data = copy(a.data);
    }

    /// @dev Returns if `needle` is in `a`.
    function contains(DynamicArray memory a, uint256 needle) internal pure returns (bool) {
        return ~indexOf(a.data, needle, 0) != 0;
    }

    /// @dev Returns if `needle` is in `a`.
    function contains(DynamicArray memory a, address needle) internal pure returns (bool) {
        return ~indexOf(a.data, uint160(needle), 0) != 0;
    }

    /// @dev Returns if `needle` is in `a`.
    function contains(DynamicArray memory a, bytes32 needle) internal pure returns (bool) {
        return ~indexOf(a.data, uint256(needle), 0) != 0;
    }

    /// @dev Returns the first index of `needle`, scanning forward from `from`.
    /// If `needle` is not in `a`, returns `NOT_FOUND`.
    function indexOf(DynamicArray memory a, uint256 needle, uint256 from)
        internal
        pure
        returns (uint256)
    {
        return indexOf(a.data, needle, from);
    }

    /// @dev Returns the first index of `needle`, scanning forward from `from`.
    /// If `needle` is not in `a`, returns `NOT_FOUND`.
    function indexOf(DynamicArray memory a, address needle, uint256 from)
        internal
        pure
        returns (uint256)
    {
        return indexOf(a.data, uint160(needle), from);
    }

    /// @dev Returns the first index of `needle`, scanning forward from `from`.
    /// If `needle` is not in `a`, returns `NOT_FOUND`.
    function indexOf(DynamicArray memory a, bytes32 needle, uint256 from)
        internal
        pure
        returns (uint256)
    {
        return indexOf(a.data, uint256(needle), from);
    }

    /// @dev Returns the first index of `needle`.
    /// If `needle` is not in `a`, returns `NOT_FOUND`.
    function indexOf(DynamicArray memory a, uint256 needle) internal pure returns (uint256) {
        return indexOf(a.data, needle, 0);
    }

    /// @dev Returns the first index of `needle`.
    /// If `needle` is not in `a`, returns `NOT_FOUND`.
    function indexOf(DynamicArray memory a, address needle) internal pure returns (uint256) {
        return indexOf(a.data, uint160(needle), 0);
    }

    /// @dev Returns the first index of `needle`.
    /// If `needle` is not in `a`, returns `NOT_FOUND`.
    function indexOf(DynamicArray memory a, bytes32 needle) internal pure returns (uint256) {
        return indexOf(a.data, uint256(needle), 0);
    }

    /// @dev Returns the last index of `needle`, scanning backwards from `from`.
    /// If `needle` is not in `a`, returns `NOT_FOUND`.
    function lastIndexOf(DynamicArray memory a, uint256 needle, uint256 from)
        internal
        pure
        returns (uint256)
    {
        return lastIndexOf(a.data, needle, from);
    }

    /// @dev Returns the last index of `needle`, scanning backwards from `from`.
    /// If `needle` is not in `a`, returns `NOT_FOUND`.
    function lastIndexOf(DynamicArray memory a, address needle, uint256 from)
        internal
        pure
        returns (uint256)
    {
        return lastIndexOf(a.data, uint160(needle), from);
    }

    /// @dev Returns the last index of `needle`, scanning backwards from `from`.
    /// If `needle` is not in `a`, returns `NOT_FOUND`.
    function lastIndexOf(DynamicArray memory a, bytes32 needle, uint256 from)
        internal
        pure
        returns (uint256)
    {
        return lastIndexOf(a.data, uint256(needle), from);
    }

    /// @dev Returns the last index of `needle`.
    /// If `needle` is not in `a`, returns `NOT_FOUND`.
    function lastIndexOf(DynamicArray memory a, uint256 needle) internal pure returns (uint256) {
        return lastIndexOf(a.data, needle, NOT_FOUND);
    }

    /// @dev Returns the last index of `needle`.
    /// If `needle` is not in `a`, returns `NOT_FOUND`.
    function lastIndexOf(DynamicArray memory a, address needle) internal pure returns (uint256) {
        return lastIndexOf(a.data, uint160(needle), NOT_FOUND);
    }

    /// @dev Returns the last index of `needle`.
    /// If `needle` is not in `a`, returns `NOT_FOUND`.
    function lastIndexOf(DynamicArray memory a, bytes32 needle) internal pure returns (uint256) {
        return lastIndexOf(a.data, uint256(needle), NOT_FOUND);
    }

    /// @dev Equivalent to `keccak256(abi.encodePacked(a.data))`.
    function hash(DynamicArray memory a) internal pure returns (bytes32 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := keccak256(add(mload(a), 0x20), shl(5, mload(mload(a))))
        }
    }

    /// @dev Directly returns `a` without copying.
    function directReturn(DynamicArray memory a) internal pure {
        /// @solidity memory-safe-assembly
        assembly {
            let arrData := mload(a)
            let retStart := sub(arrData, 0x20)
            mstore(retStart, 0x20)
            return(retStart, add(0x40, shl(5, mload(arrData))))
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      PRIVATE HELPERS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Helper for deallocating an automatically allocated array pointer.
    function _deallocate(DynamicArray memory result) private pure {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x40, result) // Deallocate, as we have already allocated.
        }
    }

    /// @dev Casts the bool into a uint256.
    function _toUint(bool b) private pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := iszero(iszero(b))
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "viaSSACFG": false,
  "evmVersion": "cancun",
  "remappings": [
    "solady/=lib/solady/src/"
  ],
  "experimental": false
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.