Skip to content
Verified contractExactBUSL-1.1

LazyAirdropToken

Address0x5054565b8ee0da1f573edd137920fbe30e45f5e6
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,594,299
Creation transaction
0x8f9e46f7af…873fab6185

src/LazyAirdropToken.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import {AirdropSnapshot} from "./libraries/AirdropSnapshot.sol";

interface IAirdrop4FunFactory {
    function launcherOf(address) external view returns (address);
}

/// @title LazyAirdropToken
/// @notice Minimal immutable ERC-20 deployed as a LibClone minimal proxy of a
///         single implementation. The initial airdrop is stored as an
///         address-keyed snapshot in SSTORE2 contract bytecode (see
///         AirdropSnapshot): the token amount each holder receives is derived
///         as `count × perItem` at read time, where `perItem` is set by the
///         factory at initialization and never changes.
/// @dev    Top bit of `_balances[addr]` is a "materialized" flag. Every balance
///         write must OR in the flag (even when value is zero) so drained holders
///         don't fall back to the snapshot lookup and double-credit. No admin,
///         no mint, no pause. The implementation contract self-initializes in
///         its constructor so only clones can ever be initialized. A cosmetic
///         `owner()` view returns the current launcher (Etherscan token-info
///         submission rights only) and grants no on-chain power.
contract LazyAirdropToken {
    using AirdropSnapshot for AirdropSnapshot.Snapshot;

    // --- ERC-20 metadata ---
    string public name;
    string public symbol;
    uint8 public constant decimals = 18;
    uint256 public totalSupply;

    // --- launch parameters (set once at initialize) ---
    address public factory;
    uint256 public perItem; // wei per NFT, fixed at initialization

    // --- storage ---
    mapping(address => uint256) private _balances;
    mapping(address => mapping(address => uint256)) public allowance;

    AirdropSnapshot.Snapshot private _snapshot;
    bytes32 public snapshotRoot;
    bool public initialized;

    // --- Mode B (chunked) state; all zero/false in Mode A, whose paths are
    //     byte-for-byte unchanged. These four pack into one slot (29 bytes). ---
    /// @dev ONE SSTORE2 blob: aggregate header + fixed-width 180 B chunk records
    ///      (see AirdropSnapshot chunk-table format). address(0) in Mode A.
    address private _chunkTable;
    /// @notice Next CHUNK index `emitMints` will announce; equals the chunk
    ///         count once emission is complete.
    uint32 public emitCursor;
    /// @dev Chunk count, cached from the table header for the emit guard.
    uint32 private _nChunks;
    /// @notice True for a Mode-B (paged-emission) token; selects the chunked
    ///          balance/emit read path.
    bool public chunked;

    // --- constants ---
    uint256 private constant MATERIALIZED_BIT = 1 << 255;
    uint256 private constant BALANCE_MASK = MATERIALIZED_BIT - 1;

    // --- events ---
    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
    event SnapshotCommitted(bytes32 indexed root, uint256 entries, uint256 pointers);
    /// @notice A chunk's holders were announced via `emitMints`.
    event MintsEmitted(uint32 indexed chunkIndex, uint32 nEntries);
    /// @notice The final chunk's holders were announced; all mint events are live.
    event EmissionCompleted(bytes32 indexed root);

    // --- errors ---
    error AlreadyInitialized();
    error InsufficientBalance();
    error InsufficientAllowance();
    error SupplyOverflow();
    error FactoryPortionExceedsSupply();
    error SupplyMismatch();
    error HolderIsFactory();
    /// @dev `emitMints` page didn't match the next chunk's content-address.
    error WrongSlice();
    /// @dev Every chunk has already been announced.
    error EmissionComplete();
    /// @dev `emitMints` called on a Mode-A (inline-emit) token.
    error NotChunked();

    /// @dev Locks the implementation: only clones (whose storage starts empty)
    ///      can be initialized.
    constructor() {
        initialized = true;
    }

    /// @notice One-shot initialization, called by the factory in the same
    ///         transaction that creates the clone. Mints the full supply to the
    ///         factory (Transfer(0, factory, totalSupply)), then emits one
    ///         Transfer(factory, holder, count × perItem) per snapshot holder so
    ///         wallets/Etherscan index the airdrop against a named source rather
    ///         than the null address. Event-derived balances net to
    ///         factory = totalSupply − Σamt = factoryPortion (the materialized
    ///         storage value) and holder = amt; the existing SupplyMismatch
    ///         check enforces that identity.
    /// @param entries  Full 24-byte (address, uint32 count) calldata entries,
    ///                 needed here for the per-holder events; only the
    ///                 compressed snapshot in `snap` is persisted.
    /// @param snap     Snapshot descriptor built (or reused) by the factory.
    ///                 The SSTORE2 chunks it points at are immutable and may
    ///                 be shared with other tokens launched off the same root.
    function initialize(
        string calldata name_,
        string calldata symbol_,
        uint256 totalSupply_,
        uint256 factoryPortion,
        uint256 perItem_,
        bytes calldata entries,
        uint32 nHolders,
        AirdropSnapshot.Snapshot calldata snap
    ) external {
        if (initialized) revert AlreadyInitialized();
        initialized = true;

        if (totalSupply_ > BALANCE_MASK) revert SupplyOverflow();
        if (factoryPortion > totalSupply_) revert FactoryPortionExceedsSupply();

        factory = msg.sender;
        name = name_;
        symbol = symbol_;
        totalSupply = totalSupply_;
        perItem = perItem_;
        _snapshot = snap;
        bytes32 root = keccak256(entries);
        snapshotRoot = root;

        _balances[msg.sender] = MATERIALIZED_BIT | factoryPortion;
        // Mint the FULL supply to the factory in the event log; each holder
        // tranche below is then emitted as Transfer(factory, holder, …), so the
        // named factory (not the null address) is the source of every airdrop
        // credit wallets/Etherscan show. The storage balance above stays at
        // factoryPortion; the log nets back to it after the tranches.
        emit Transfer(address(0), msg.sender, totalSupply_);

        // Per-holder Transfer events + conservation. Each tranche is emitted as
        // Transfer(factory, holder, count × perItem), debiting the full-supply
        // mint above; event-derived balances net to
        // factory = totalSupply − Σamt = factoryPortion (the materialized
        // storage value) and holder = amt. factoryPortion + Σ(count × perItem)
        // must equal totalSupply, otherwise the supply label is a lie.
        uint256 sum;
        for (uint256 i; i < nHolders; ++i) {
            (address to, uint256 cnt) = AirdropSnapshot.readEntry(entries, i);
            // The factory (msg.sender) is pre-materialized to factoryPortion
            // above; a snapshot listing it as a holder would still add its
            // tranche to `sum` and emit a Transfer, but balanceOf ignores the
            // snapshot for the materialized factory, so those tokens exist in
            // no balance (Σ balances < totalSupply). Reject outright.
            if (to == msg.sender) revert HolderIsFactory();
            uint256 amt = cnt * perItem_;
            sum += amt;
            emit Transfer(msg.sender, to, amt);
        }
        if (factoryPortion + sum != totalSupply_) revert SupplyMismatch();

        emit SnapshotCommitted(
            root,
            nHolders,
            snap.singlesPointers.length + snap.multisPointers.length
        );
    }

    /// @notice Mode-B one-shot initialization for collections above the single-tx
    ///         caps. Unlike `initialize`, the holder mint events are NOT emitted
    ///         here; the token trades immediately and holders are announced
    ///         progressively by permissionless `emitMints` pages (one per chunk).
    ///         The chunk sections are serialized into ONE SSTORE2 table blob
    ///         (no per-holder storage loop), so this stays O(chunks) in holders.
    /// @dev    Conservation is INDEPENDENT of the factory's launch arithmetic:
    ///         the token re-sums the per-chunk `totalCounts` it was handed (each
    ///         traceable to `AirdropSnapshot.build` at staging) and requires
    ///         `factoryPortion + perItem_ * Σ == totalSupply_`. `totalCounts`
    ///         is the factory's own sum, cross-checked against Σ.
    /// @param chunks     Per-chunk views (pointers + address bounds + counts),
    ///                   address-ascending and non-overlapping (enforced by the
    ///                   factory's stitch before this call).
    /// @param chunkRoots The ordered content-addresses; `emitMints` verifies each
    ///                   page against these, and the assembled root is
    ///                   keccak256(abi.encodePacked(chunkRoots)).
    function initializeChunked(
        string calldata name_,
        string calldata symbol_,
        uint256 totalSupply_,
        uint256 factoryPortion,
        uint256 perItem_,
        uint256 totalCounts,
        AirdropSnapshot.ChunkView[] calldata chunks,
        bytes32[] calldata chunkRoots
    ) external {
        if (initialized) revert AlreadyInitialized();
        initialized = true;
        chunked = true;

        if (totalSupply_ > BALANCE_MASK) revert SupplyOverflow();
        if (factoryPortion > totalSupply_) revert FactoryPortionExceedsSupply();
        // The table records `chunks` but the committed root spans `chunkRoots`;
        // a length mismatch would commit to roots the table can never announce.
        if (chunks.length != chunkRoots.length) revert SupplyMismatch();

        // Independent conservation: sum counts + holders + pointers straight
        // from the staged chunk views, not from a single factory-supplied total.
        uint256 sum;
        uint256 holders;
        uint256 pointers;
        for (uint256 i; i < chunks.length; ++i) {
            sum += chunks[i].totalCounts;
            holders += chunks[i].snap.nHolders;
            pointers += chunks[i].snap.singlesPointers.length + chunks[i].snap.multisPointers.length;
        }
        // Σ must match the factory's own total AND conserve the labeled supply.
        if (sum != totalCounts) revert SupplyMismatch();
        if (factoryPortion + perItem_ * sum != totalSupply_) revert SupplyMismatch();

        factory = msg.sender;
        name = name_;
        symbol = symbol_;
        totalSupply = totalSupply_;
        perItem = perItem_;

        _chunkTable = AirdropSnapshot.serializeChunkTable(chunks, chunkRoots);
        _nChunks = uint32(chunks.length);

        bytes32 root = keccak256(abi.encodePacked(chunkRoots));
        snapshotRoot = root;

        // Full supply materialized to the factory; holder tranches are debited
        // from it as `emitMints` pages fire (Transfer(factory, holder, amt)).
        _balances[msg.sender] = MATERIALIZED_BIT | factoryPortion;
        emit Transfer(address(0), msg.sender, totalSupply_);

        emit SnapshotCommitted(root, holders, pointers);
    }

    /// @notice Announce one chunk's holders: emits Transfer(factory, holder,
    ///         count × perItem) for every entry in `entries`, which MUST be the
    ///         exact bytes of the next un-emitted chunk (verified against its
    ///         content-address `chunkRoot`). Permissionless and resumable by
    ///         anyone; pages must run in order (cursor advances one chunk/call).
    /// @dev    Verification is against the content-address `keccak256(entries)`,
    ///         which commits the FULL 20-byte addresses, so a page can never
    ///         announce a forged holder. No conservation check needed per page —
    ///         the root commits the counts, and `initializeChunked` already
    ///         conserved the totals.
    function emitMints(bytes calldata entries) external {
        if (!chunked) revert NotChunked();
        uint32 cursor = emitCursor;
        uint32 n = _nChunks;
        if (cursor >= n) revert EmissionComplete();
        if (keccak256(entries) != AirdropSnapshot.chunkRootAt(_chunkTable, cursor)) revert WrongSlice();

        uint256 nEntries = entries.length / AirdropSnapshot.ENTRY_BYTES;
        uint256 pi = perItem;
        address f = factory;
        for (uint256 i; i < nEntries; ++i) {
            (address to, uint256 cnt) = AirdropSnapshot.readEntry(entries, i);
            emit Transfer(f, to, cnt * pi);
        }

        unchecked {
            emitCursor = cursor + 1;
        }
        emit MintsEmitted(cursor, uint32(nEntries));
        if (cursor + 1 == n) emit EmissionCompleted(snapshotRoot);
    }

    // --- ERC-20 core ---

    function balanceOf(address a) public view returns (uint256) {
        uint256 b = _balances[a];
        if (b & MATERIALIZED_BIT != 0) return b & BALANCE_MASK;
        if (chunked) return AirdropSnapshot.readCountChunked(_chunkTable, a) * perItem;
        return _snapshot.readCount(a) * perItem;
    }

    /// @notice Cosmetic, off-chain only. Current launcher (LP-fee beneficiary in
    ///         LpLocker, reassignable via transferLauncher). Etherscan's token-info
    ///         form accepts submissions only from the deployer or owner(); every
    ///         token here is a factory clone, so this is the only path to a logo/
    ///         site/description. Zero on-chain power: no onlyOwner, no transferOwnership.
    function owner() external view returns (address) {
        return IAirdrop4FunFactory(factory).launcherOf(address(this));
    }

    function transfer(address to, uint256 amount) external returns (bool) {
        _transfer(msg.sender, to, amount);
        return true;
    }

    function transferFrom(address from, address to, uint256 amount) external returns (bool) {
        uint256 allowed = allowance[from][msg.sender];
        if (allowed != type(uint256).max) {
            if (allowed < amount) revert InsufficientAllowance();
            unchecked { allowance[from][msg.sender] = allowed - amount; }
        }
        _transfer(from, to, amount);
        return true;
    }

    function approve(address spender, uint256 amount) external returns (bool) {
        allowance[msg.sender][spender] = amount;
        emit Approval(msg.sender, spender, amount);
        return true;
    }

    // --- internals ---

    function _materialize(address a) private {
        uint256 b = _balances[a];
        if (b & MATERIALIZED_BIT != 0) return;
        uint256 cnt = chunked ? AirdropSnapshot.readCountChunked(_chunkTable, a) : _snapshot.readCount(a);
        _balances[a] = MATERIALIZED_BIT | (cnt * perItem);
    }

    function _transfer(address from, address to, uint256 amount) private {
        _materialize(from);
        _materialize(to);

        uint256 fromBal = _balances[from] & BALANCE_MASK;
        if (fromBal < amount) revert InsufficientBalance();

        unchecked {
            _balances[from] = MATERIALIZED_BIT | (fromBal - amount);
            // Re-read `to` AFTER the debit so a self-transfer (from == to) sees
            // the decremented balance and nets zero instead of minting `amount`.
            uint256 toBal = _balances[to] & BALANCE_MASK;
            _balances[to] = MATERIALIZED_BIT | (toBal + amount);
        }

        emit Transfer(from, to, amount);
    }

    // --- diagnostics ---

    /// @dev Count width (bits) of the fixed 24-byte calldata codec; always 32.
    function countBits() external pure returns (uint8) {
        return 32;
    }

    function snapshotPointerCount() external view returns (uint256) {
        if (chunked) {
            (,,,, uint32 nPointers) = AirdropSnapshot.chunkTableHeader(_chunkTable);
            return nPointers;
        }
        return _snapshot.singlesPointers.length + _snapshot.multisPointers.length;
    }

    /// @notice Chunk count of a Mode-B token (0 in Mode A). With `emitCursor`,
    ///         lets anyone check announcement progress and finish `emitMints`
    ///         permissionlessly without off-chain help.
    function snapshotNChunks() external view returns (uint32) {
        return _nChunks;
    }

    /// @dev Singles chunks first, then multis chunks (per chunk, in Mode B).
    function snapshotPointerAt(uint256 i) external view returns (address) {
        if (chunked) return AirdropSnapshot.chunkTablePointerAt(_chunkTable, i);
        uint256 nS = _snapshot.singlesPointers.length;
        return i < nS ? _snapshot.singlesPointers[i] : _snapshot.multisPointers[i - nS];
    }

    function snapshotNHolders() external view returns (uint32) {
        if (chunked) {
            (, uint32 nHolders,,,) = AirdropSnapshot.chunkTableHeader(_chunkTable);
            return nHolders;
        }
        return _snapshot.nHolders;
    }

    function snapshotSections() external view returns (uint32 nSingles, uint32 nMultis) {
        if (chunked) {
            (,, nSingles, nMultis,) = AirdropSnapshot.chunkTableHeader(_chunkTable);
            return (nSingles, nMultis);
        }
        return (_snapshot.nSingles, _snapshot.nMultis);
    }

    function isMaterialized(address a) external view returns (bool) {
        return _balances[a] & MATERIALIZED_BIT != 0;
    }
}

lib/solady/src/utils/SSTORE2.sol

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

/// @notice Read and write to persistent storage at a fraction of the cost.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SSTORE2.sol)
/// @author Saw-mon-and-Natalie (https://github.com/Saw-mon-and-Natalie)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SSTORE2.sol)
/// @author Modified from 0xSequence (https://github.com/0xSequence/sstore2/blob/master/contracts/SSTORE2.sol)
/// @author Modified from SSTORE3 (https://github.com/Philogy/sstore3)
library SSTORE2 {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The proxy initialization code.
    uint256 private constant _CREATE3_PROXY_INITCODE = 0x67363d3d37363d34f03d5260086018f3;

    /// @dev Hash of the `_CREATE3_PROXY_INITCODE`.
    /// Equivalent to `keccak256(abi.encodePacked(hex"67363d3d37363d34f03d5260086018f3"))`.
    bytes32 internal constant CREATE3_PROXY_INITCODE_HASH =
        0x21c35dbe1b344a2488cf3321d6ce542f8e9f305544ff09e4993a62319a497c1f;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                        CUSTOM ERRORS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Unable to deploy the storage contract.
    error DeploymentFailed();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         WRITE LOGIC                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Writes `data` into the bytecode of a storage contract and returns its address.
    function write(bytes memory data) internal returns (address pointer) {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(data) // Let `l` be `n + 1`. +1 as we prefix a STOP opcode.
            /**
             * ---------------------------------------------------+
             * Opcode | Mnemonic       | Stack     | Memory       |
             * ---------------------------------------------------|
             * 61 l   | PUSH2 l        | l         |              |
             * 80     | DUP1           | l l       |              |
             * 60 0xa | PUSH1 0xa      | 0xa l l   |              |
             * 3D     | RETURNDATASIZE | 0 0xa l l |              |
             * 39     | CODECOPY       | l         | [0..l): code |
             * 3D     | RETURNDATASIZE | 0 l       | [0..l): code |
             * F3     | RETURN         |           | [0..l): code |
             * 00     | STOP           |           |              |
             * ---------------------------------------------------+
             * @dev Prefix the bytecode with a STOP opcode to ensure it cannot be called.
             * Also PUSH2 is used since max contract size cap is 24,576 bytes which is less than 2 ** 16.
             */
            // Do a out-of-gas revert if `n + 1` is more than 2 bytes.
            mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
            // Deploy a new contract with the generated creation code.
            pointer := create(0, add(data, 0x15), add(n, 0xb))
            if iszero(pointer) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(data, n) // Restore the length of `data`.
        }
    }

    /// @dev Writes `data` into the bytecode of a storage contract with `salt`
    /// and returns its normal CREATE2 deterministic address.
    function writeCounterfactual(bytes memory data, bytes32 salt)
        internal
        returns (address pointer)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(data)
            // Do a out-of-gas revert if `n + 1` is more than 2 bytes.
            mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
            // Deploy a new contract with the generated creation code.
            pointer := create2(0, add(data, 0x15), add(n, 0xb), salt)
            if iszero(pointer) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(data, n) // Restore the length of `data`.
        }
    }

    /// @dev Writes `data` into the bytecode of a storage contract and returns its address.
    /// This uses the so-called "CREATE3" workflow,
    /// which means that `pointer` is agnostic to `data, and only depends on `salt`.
    function writeDeterministic(bytes memory data, bytes32 salt)
        internal
        returns (address pointer)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(data)
            mstore(0x00, _CREATE3_PROXY_INITCODE) // Store the `_PROXY_INITCODE`.
            let proxy := create2(0, 0x10, 0x10, salt)
            if iszero(proxy) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x14, proxy) // Store the proxy's address.
            // 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01).
            // 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex).
            mstore(0x00, 0xd694)
            mstore8(0x34, 0x01) // Nonce of the proxy contract (1).
            pointer := keccak256(0x1e, 0x17)

            // Do a out-of-gas revert if `n + 1` is more than 2 bytes.
            mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
            if iszero(
                mul( // The arguments of `mul` are evaluated last to first.
                    extcodesize(pointer),
                    call(gas(), proxy, 0, add(data, 0x15), add(n, 0xb), codesize(), 0x00)
                )
            ) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(data, n) // Restore the length of `data`.
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                    ADDRESS CALCULATIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the initialization code hash of the storage contract for `data`.
    /// Used for mining vanity addresses with create2crunch.
    function initCodeHash(bytes memory data) internal pure returns (bytes32 hash) {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(data)
            // Do a out-of-gas revert if `n + 1` is more than 2 bytes.
            returndatacopy(returndatasize(), returndatasize(), gt(n, 0xfffe))
            mstore(data, add(0x61000180600a3d393df300, shl(0x40, n)))
            hash := keccak256(add(data, 0x15), add(n, 0xb))
            mstore(data, n) // Restore the length of `data`.
        }
    }

    /// @dev Equivalent to `predictCounterfactualAddress(data, salt, address(this))`
    function predictCounterfactualAddress(bytes memory data, bytes32 salt)
        internal
        view
        returns (address pointer)
    {
        pointer = predictCounterfactualAddress(data, salt, address(this));
    }

    /// @dev Returns the CREATE2 address of the storage contract for `data`
    /// deployed with `salt` by `deployer`.
    /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
    function predictCounterfactualAddress(bytes memory data, bytes32 salt, address deployer)
        internal
        pure
        returns (address predicted)
    {
        bytes32 hash = initCodeHash(data);
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and store the bytecode hash.
            mstore8(0x00, 0xff) // Write the prefix.
            mstore(0x35, hash)
            mstore(0x01, shl(96, deployer))
            mstore(0x15, salt)
            predicted := keccak256(0x00, 0x55)
            // Restore the part of the free memory pointer that has been overwritten.
            mstore(0x35, 0)
        }
    }

    /// @dev Equivalent to `predictDeterministicAddress(salt, address(this))`.
    function predictDeterministicAddress(bytes32 salt) internal view returns (address pointer) {
        pointer = predictDeterministicAddress(salt, address(this));
    }

    /// @dev Returns the "CREATE3" deterministic address for `salt` with `deployer`.
    function predictDeterministicAddress(bytes32 salt, address deployer)
        internal
        pure
        returns (address pointer)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x00, deployer) // Store `deployer`.
            mstore8(0x0b, 0xff) // Store the prefix.
            mstore(0x20, salt) // Store the salt.
            mstore(0x40, CREATE3_PROXY_INITCODE_HASH) // Store the bytecode hash.

            mstore(0x14, keccak256(0x0b, 0x55)) // Store the proxy's address.
            mstore(0x40, m) // Restore the free memory pointer.
            // 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01).
            // 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex).
            mstore(0x00, 0xd694)
            mstore8(0x34, 0x01) // Nonce of the proxy contract (1).
            pointer := keccak256(0x1e, 0x17)
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         READ LOGIC                         */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Equivalent to `read(pointer, 0, 2 ** 256 - 1)`.
    function read(address pointer) internal view returns (bytes memory data) {
        /// @solidity memory-safe-assembly
        assembly {
            data := mload(0x40)
            let n := and(0xffffffffff, sub(extcodesize(pointer), 0x01))
            extcodecopy(pointer, add(data, 0x1f), 0x00, add(n, 0x21))
            mstore(data, n) // Store the length.
            mstore(0x40, add(n, add(data, 0x40))) // Allocate memory.
        }
    }

    /// @dev Equivalent to `read(pointer, start, 2 ** 256 - 1)`.
    function read(address pointer, uint256 start) internal view returns (bytes memory data) {
        /// @solidity memory-safe-assembly
        assembly {
            data := mload(0x40)
            let n := and(0xffffffffff, sub(extcodesize(pointer), 0x01))
            let l := sub(n, and(0xffffff, mul(lt(start, n), start)))
            extcodecopy(pointer, add(data, 0x1f), start, add(l, 0x21))
            mstore(data, mul(sub(n, start), lt(start, n))) // Store the length.
            mstore(0x40, add(data, add(0x40, mload(data)))) // Allocate memory.
        }
    }

    /// @dev Returns a slice of the data on `pointer` from `start` to `end`.
    /// `start` and `end` will be clamped to the range `[0, args.length]`.
    /// The `pointer` MUST be deployed via the SSTORE2 write functions.
    /// Otherwise, the behavior is undefined.
    /// Out-of-gas reverts if `pointer` does not have any code.
    function read(address pointer, uint256 start, uint256 end)
        internal
        view
        returns (bytes memory data)
    {
        /// @solidity memory-safe-assembly
        assembly {
            data := mload(0x40)
            if iszero(lt(end, 0xffff)) { end := 0xffff }
            let d := mul(sub(end, start), lt(start, end))
            extcodecopy(pointer, add(data, 0x1f), start, add(d, 0x01))
            if iszero(and(0xff, mload(add(data, d)))) {
                let n := sub(extcodesize(pointer), 0x01)
                returndatacopy(returndatasize(), returndatasize(), shr(40, n))
                d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n))))
            }
            mstore(data, d) // Store the length.
            mstore(add(add(data, 0x20), d), 0) // Zeroize the slot after the bytes.
            mstore(0x40, add(add(data, 0x40), d)) // Allocate memory.
        }
    }
}

src/libraries/AirdropSnapshot.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import {SSTORE2} from "solady/utils/SSTORE2.sol";

/// @title AirdropSnapshot
/// @notice Address-keyed holder snapshot stored as SSTORE2 contract bytecode,
///         split into two sorted sections:
///           - singles: holders with count == 1, stored as the full 20-byte
///             address. Count is implicit.
///           - multis:  holders with count > 1, stored as the full 20-byte
///             address + 4-byte uint32 count (24 bytes per entry).
///         Token amount is NOT stored; it is derived as `count × perItem`
///         at read time, with `perItem` fixed on the consuming token.
///
///         The CALLDATA format is fixed 24-byte (20-byte address, 4-byte
///         uint32 count) entries sorted ascending by address;
///         root = keccak256(entries). The stored form keeps the WHOLE address.
/// @dev    Security: `readCount` matches on the FULL 20-byte address, so a
///         balance is reachable only by the exact holder address, never by any
///         other address. (A predecessor stored a 12-byte digest, which let two
///         addresses sharing their upper 12 bytes collide, a ~2^48 birthday
///         search when both are attacker-chosen; storing the full address
///         removes that entirely.) `build` still rejects a non-ascending list,
///         so an exact duplicate address cannot appear twice.
library AirdropSnapshot {
    /// @dev Per-chunk data cap = EIP-170 24576 - STOP byte (1) - read-padding (31).
    uint256 internal constant MAX_CHUNK_DATA_BYTES = 24544;
    uint256 internal constant READ_PADDING = 31;
    uint256 internal constant ENTRY_BYTES = 24;  // calldata format
    uint256 internal constant SINGLE_BYTES = 20; // stored singles (full address)
    uint256 internal constant MULTI_BYTES = 24;  // stored multis (address + count)

    error InvalidLength();
    error NHoldersZero();
    error NotSortedAscending();
    error ZeroCount();

    struct Snapshot {
        address[] singlesPointers;
        address[] multisPointers;
        uint32 nSingles;
        uint32 nMultis;
        uint32 nHolders;
    }

    /// @dev The full 20-byte address as the stored lookup key. Balances are
    ///      keyed on the ENTIRE address so two distinct addresses can never
    ///      resolve to the same entry.
    function addrKey(address a) internal pure returns (uint256) {
        return uint256(uint160(a));
    }

    /// @dev Read calldata entry `i`: 20-byte address + 4-byte count. Calldata
    ///      reads auto-zero-pad past the end, so the trailing entry is safe.
    function readEntry(bytes calldata entries, uint256 i)
        internal
        pure
        returns (address a, uint256 c)
    {
        uint256 word;
        assembly {
            word := calldataload(add(entries.offset, mul(i, 24)))
        }
        a = address(uint160(word >> 96));
        c = (word >> 64) & 0xffffffff;
    }

    /// @dev Sum of all counts, plus whether `who` appears as a holder: one
    ///      tight calldataload pass (~10 gas/entry), NO validation (`build`
    ///      still validates everything). Lets the factory reject doomed
    ///      launches (zero counts, zero per-item tranche, factory listed as a
    ///      holder) BEFORE build's multi-million-gas SSTORE2 writes without
    ///      taxing the success path. Calldata reads auto-zero-pad past the
    ///      end, so the trailing entry's over-read is safe (same as
    ///      `readEntry`).
    function sumCounts(bytes calldata entries, uint256 nHolders, address who)
        internal
        pure
        returns (uint256 totalCounts, bool containsWho)
    {
        assembly ("memory-safe") {
            let off := entries.offset
            let end := add(off, mul(nHolders, 24))
            for { } lt(off, end) { off := add(off, 24) } {
                let word := calldataload(off)
                // Branchless: or() of 0/1 eq results stays 0/1.
                containsWho := or(containsWho, eq(shr(96, word), who))
                // uint32 count: bytes 20..23 of the entry.
                totalCounts := add(totalCounts, and(shr(64, word), 0xffffffff))
            }
        }
    }

    /// @dev Validates `entries` (length, strict ascending address sort, nonzero
    ///      counts), splits into singles/multis sections, and persists them as
    ///      SSTORE2 chunks. The strict sort also rejects a duplicate address.
    ///      Returns the in-memory snapshot descriptor and the count sum.
    function build(bytes calldata entries, uint32 nHolders)
        internal
        returns (Snapshot memory snap, uint256 totalCounts)
    {
        if (nHolders == 0) revert NHoldersZero();
        if (entries.length != uint256(nHolders) * ENTRY_BYTES) revert InvalidLength();

        // Pass 1: validate + measure.
        uint256 nSingles;
        uint256 nMultis;
        {
            address prev;
            for (uint256 i; i < nHolders; ++i) {
                (address a, uint256 c) = readEntry(entries, i);
                if (a <= prev) revert NotSortedAscending();
                if (c == 0) revert ZeroCount();
                unchecked {
                    totalCounts += c;
                    if (c == 1) ++nSingles;
                    else ++nMultis;
                }
                prev = a;
            }
        }

        snap.nHolders = nHolders;
        snap.nSingles = uint32(nSingles);
        snap.nMultis = uint32(nMultis);

        // Pass 2: fill padded section buffers. Each mstore writes a full word
        // (zeroing bytes ahead); sequential ascending offsets make that safe,
        // and the trailing READ_PADDING absorbs the final word's overrun.
        bytes memory sBuf = new bytes(nSingles * SINGLE_BYTES + READ_PADDING);
        bytes memory mBuf = new bytes(nMultis * MULTI_BYTES + READ_PADDING);
        {
            uint256 sOff;
            uint256 mOff;
            for (uint256 i; i < nHolders; ++i) {
                (address a, uint256 c) = readEntry(entries, i);
                uint256 k = uint256(uint160(a));
                if (c == 1) {
                    // Full 20-byte address in the top 20 bytes of the word.
                    assembly {
                        mstore(add(add(sBuf, 0x20), sOff), shl(96, k))
                    }
                    unchecked { sOff += SINGLE_BYTES; }
                } else {
                    // 20-byte address + 4-byte count = 24 bytes, top-aligned.
                    uint256 e = (k << 32) | c;
                    assembly {
                        mstore(add(add(mBuf, 0x20), mOff), shl(64, e))
                    }
                    unchecked { mOff += MULTI_BYTES; }
                }
            }
        }

        snap.singlesPointers = _writeChunks(sBuf, nSingles, SINGLE_BYTES);
        snap.multisPointers = _writeChunks(mBuf, nMultis, MULTI_BYTES);
    }

    /// @dev Count for `who`: 1 if its address is in singles, the stored count
    ///      if in multis, else 0.
    function readCount(Snapshot storage s, address who) internal view returns (uint256) {
        uint256 k = addrKey(who);
        (bool foundS, ) = _search(s.singlesPointers, s.nSingles, SINGLE_BYTES, k);
        if (foundS) return 1;
        (bool foundM, uint256 c) = _search(s.multisPointers, s.nMultis, MULTI_BYTES, k);
        return foundM ? c : 0;
    }

    // --- internals ---

    /// @dev Slice `buf` into SSTORE2 chunks of at most cap entries, each
    ///      padded with READ_PADDING zero bytes for safe 32-byte reads.
    function _writeChunks(bytes memory buf, uint256 nEntries, uint256 width)
        private
        returns (address[] memory ptrs)
    {
        if (nEntries == 0) return ptrs;
        uint256 cap = MAX_CHUNK_DATA_BYTES / width;
        uint256 nChunks = (nEntries + cap - 1) / cap;
        ptrs = new address[](nChunks);
        for (uint256 k; k < nChunks; ++k) {
            uint256 startEntry = k * cap;
            uint256 take = nEntries - startEntry;
            if (take > cap) take = cap;
            uint256 dataBytes = take * width;
            bytes memory chunk = new bytes(dataBytes + READ_PADDING);
            uint256 srcOff = startEntry * width;
            assembly {
                mcopy(add(chunk, 0x20), add(add(buf, 0x20), srcOff), dataBytes)
            }
            ptrs[k] = SSTORE2.write(chunk);
        }
    }

    /// @dev Global binary search over a section. All chunks except the last
    ///      hold exactly `cap` entries, so entry i lives in chunk i/cap at
    ///      local offset (i % cap) * width; no per-chunk metadata needed.
    function _search(
        address[] storage ptrs,
        uint256 n,
        uint256 width,
        uint256 key
    ) private view returns (bool found, uint256 count) {
        if (n == 0) return (false, 0);
        uint256 cap = MAX_CHUNK_DATA_BYTES / width;
        uint256 lo;
        uint256 hi = n;
        while (lo < hi) {
            uint256 mid;
            unchecked { mid = (lo + hi) >> 1; }
            (uint256 km, uint256 cm) = _readAt(ptrs[mid / cap], (mid % cap) * width);
            if (km == key) return (true, cm);
            if (km < key) {
                unchecked { lo = mid + 1; }
            } else {
                hi = mid;
            }
        }
        return (false, 0);
    }

    /// @dev Read the 32-byte word at `byteOff` of a chunk. Chunks carry
    ///      READ_PADDING trailing zeros so this never overruns for any valid
    ///      entry offset. Top 20 bytes = address; next 4 = count (multis only;
    ///      for singles those bytes belong to the next entry and are ignored).
    function _readAt(address ptr, uint256 byteOff)
        private
        view
        returns (uint256 key, uint256 cnt)
    {
        bytes memory raw = SSTORE2.read(ptr, byteOff, byteOff + 32);
        uint256 word;
        assembly {
            word := mload(add(raw, 0x20))
        }
        key = word >> 96;
        cnt = (word >> 64) & 0xffffffff;
    }

    // ========================================================================
    // Chunk table (v2: unlimited holders)
    // ========================================================================
    //
    // A Mode-B token's snapshot is an ordered list of immutable per-chunk
    // sections (each an independent `build()` call staged via
    // `storeSnapshotChunk`). The token serializes those sections into ONE
    // SSTORE2 blob — the "chunk table" — instead of copying pointer arrays into
    // storage. Layout:
    //
    //   header  (20 B): nChunks · nHolders · nSingles · nMultis · nPointers
    //                   (5 × uint32, big-endian)
    //   records (180 B each, one per chunk, address-ascending & non-overlapping):
    //     firstAddr(20) · lastAddr(20) · chunkRoot(32) ·
    //     nSingles(4) · nMultis(4) · ptrs(5 × 20)
    //   + READ_PADDING trailing zero bytes for safe 32-byte over-reads.
    //
    // `readCountChunked` is an OUTER binary search over the records'
    // [firstAddr, lastAddr] ranges, then the existing per-section search logic
    // (`_searchMem`, a memory-pointer twin of `_search`) INNER over the matched
    // chunk's singles/multis pointers. The canonical chunk size is bounded so a
    // chunk needs ≤ MAX_PTRS_PER_CHUNK section pointers (enforced at staging and
    // here).

    struct ChunkView {
        Snapshot snap;
        address firstAddr;
        address lastAddr;
        uint96 totalCounts;
    }

    error ChunkTooLarge();

    uint256 internal constant TABLE_HEADER_BYTES = 20;
    uint256 internal constant CHUNK_RECORD_BYTES = 180;
    uint256 internal constant MAX_PTRS_PER_CHUNK = 5;

    // Record field byte offsets (relative to the record start).
    uint256 private constant REC_FIRST = 0;
    uint256 private constant REC_LAST = 20;
    uint256 private constant REC_ROOT = 40;
    uint256 private constant REC_NSINGLES = 72;
    uint256 private constant REC_NMULTIS = 76;
    uint256 private constant REC_PTRS = 80;

    /// @dev Serialize the per-chunk sections + roots into one SSTORE2 blob and
    ///      return its address. The header totals are accumulated here (not
    ///      trusted from the caller) so the token's diagnostics are anchored to
    ///      the immutable chunk data. Reverts `ChunkTooLarge` if any chunk needs
    ///      more than `MAX_PTRS_PER_CHUNK` section pointers (only reachable with
    ///      a hand-crafted over-size staged chunk; the frontend chunks well
    ///      under this).
    function serializeChunkTable(ChunkView[] calldata chunks, bytes32[] calldata roots)
        internal
        returns (address table)
    {
        uint256 nChunks = chunks.length;
        uint256 blobLen = TABLE_HEADER_BYTES + nChunks * CHUNK_RECORD_BYTES + READ_PADDING;
        bytes memory blob = new bytes(blobLen);

        uint256 nHolders;
        uint256 nSingles;
        uint256 nMultis;
        uint256 nPointers;

        for (uint256 i; i < nChunks; ++i) {
            Snapshot calldata snap = chunks[i].snap;
            uint256 nSPtrs = snap.singlesPointers.length;
            uint256 nMPtrs = snap.multisPointers.length;
            if (nSPtrs + nMPtrs > MAX_PTRS_PER_CHUNK) revert ChunkTooLarge();

            nHolders += snap.nHolders;
            nSingles += snap.nSingles;
            nMultis += snap.nMultis;
            nPointers += nSPtrs + nMPtrs;

            uint256 recOff = TABLE_HEADER_BYTES + i * CHUNK_RECORD_BYTES;
            uint256 fa = uint256(uint160(chunks[i].firstAddr));
            uint256 la = uint256(uint160(chunks[i].lastAddr));
            bytes32 root = roots[i];
            uint256 s = snap.nSingles;
            uint256 m = snap.nMultis;
            // Fields written in ascending offset order: each fixed-width write
            // zero-fills ahead, and the next field overwrites that fill.
            assembly {
                let base := add(add(blob, 0x20), recOff)
                mstore(base, shl(96, fa)) // firstAddr @0 (20 B)
                mstore(add(base, 20), shl(96, la)) // lastAddr @20 (20 B)
                mstore(add(base, 40), root) // chunkRoot @40 (32 B)
                mstore(add(base, 72), shl(224, s)) // nSingles @72 (4 B)
                mstore(add(base, 76), shl(224, m)) // nMultis @76 (4 B)
            }
            // Pointers @80: singles first, then multis (mirrors Snapshot order).
            for (uint256 j; j < nSPtrs; ++j) {
                uint256 ptr = uint256(uint160(snap.singlesPointers[j]));
                assembly {
                    mstore(add(add(add(blob, 0x20), recOff), add(80, mul(j, 20))), shl(96, ptr))
                }
            }
            for (uint256 j; j < nMPtrs; ++j) {
                uint256 ptr = uint256(uint160(snap.multisPointers[j]));
                uint256 slot = nSPtrs + j;
                assembly {
                    mstore(add(add(add(blob, 0x20), recOff), add(80, mul(slot, 20))), shl(96, ptr))
                }
            }
        }

        // Header, masked into [0,20) so record 0's firstAddr in [20,40) survives
        // (the write only touches [0,32); the mask preserves [20,32), and [32,40)
        // is in the next word, untouched).
        assembly {
            let hbase := add(blob, 0x20)
            let existing := mload(hbase)
            let hdr :=
                or(
                    or(or(shl(224, nChunks), shl(192, nHolders)), or(shl(160, nSingles), shl(128, nMultis))),
                    shl(96, nPointers)
                )
            mstore(hbase, or(hdr, and(existing, 0xffffffffffffffffffffffff)))
        }

        table = SSTORE2.write(blob);
    }

    /// @dev The chunk table's aggregate header (all totals across chunks).
    function chunkTableHeader(address table)
        internal
        view
        returns (uint32 nChunks, uint32 nHolders, uint32 nSingles, uint32 nMultis, uint32 nPointers)
    {
        bytes memory h = SSTORE2.read(table, 0, 32);
        uint256 w;
        assembly {
            w := mload(add(h, 0x20))
        }
        nChunks = uint32(w >> 224);
        nHolders = uint32(w >> 192);
        nSingles = uint32(w >> 160);
        nMultis = uint32(w >> 128);
        nPointers = uint32(w >> 96);
    }

    /// @dev The content-address (keccak256 of its entries) of chunk `i`. Used by
    ///      `emitMints` to verify a submitted page against the FULL addresses it
    ///      commits, so a page can never announce a forged holder.
    function chunkRootAt(address table, uint256 i) internal view returns (bytes32 root) {
        uint256 recOff = TABLE_HEADER_BYTES + i * CHUNK_RECORD_BYTES;
        bytes memory r = SSTORE2.read(table, recOff + REC_ROOT, recOff + REC_ROOT + 32);
        assembly {
            root := mload(add(r, 0x20))
        }
    }

    /// @dev Count for `who` over the whole chunk table: outer binary search for
    ///      the chunk whose address range contains `who`, then the inner
    ///      per-section search. Returns 0 if `who` falls in a gap between chunks
    ///      or is absent from the matched chunk.
    function readCountChunked(address table, address who) internal view returns (uint256) {
        uint256 k = addrKey(who);
        (uint32 nChunks,,,,) = chunkTableHeader(table);
        uint256 lo;
        uint256 hi = nChunks;
        while (lo < hi) {
            uint256 mid;
            unchecked {
                mid = (lo + hi) >> 1;
            }
            (uint256 fa, uint256 la) = _recordAddrBounds(table, mid);
            if (k < fa) {
                hi = mid;
            } else if (k > la) {
                unchecked {
                    lo = mid + 1;
                }
            } else {
                return _innerCount(table, mid, k);
            }
        }
        return 0;
    }

    /// @dev Global pointer index → the SSTORE2 data-contract address it names,
    ///      walking records (singles pointers then multis pointers per chunk).
    ///      Diagnostics only; returns address(0) past the last pointer.
    function chunkTablePointerAt(address table, uint256 globalIdx) internal view returns (address) {
        (uint32 nChunks,,,,) = chunkTableHeader(table);
        for (uint256 c; c < nChunks; ++c) {
            (uint256 nSingles, uint256 nMultis) = _recordCounts(table, c);
            uint256 nSPtrs = _ceilDiv(nSingles, MAX_CHUNK_DATA_BYTES / SINGLE_BYTES);
            uint256 nMPtrs = _ceilDiv(nMultis, MAX_CHUNK_DATA_BYTES / MULTI_BYTES);
            uint256 tot = nSPtrs + nMPtrs;
            if (globalIdx < tot) return _recordPointer(table, c, globalIdx);
            unchecked {
                globalIdx -= tot;
            }
        }
        return address(0);
    }

    // --- chunk-table internals ---

    function _ceilDiv(uint256 a, uint256 b) private pure returns (uint256) {
        return a == 0 ? 0 : (a + b - 1) / b;
    }

    /// @dev Read the 20-byte value (top-aligned) at `off` of the table blob.
    function _read20(address table, uint256 off) private view returns (uint256 v) {
        bytes memory b = SSTORE2.read(table, off, off + 20);
        uint256 w;
        assembly {
            w := mload(add(b, 0x20))
        }
        v = w >> 96;
    }

    /// @dev [firstAddr, lastAddr] of record `i` (20 bytes each). Two separate
    ///      20-byte reads: the pair spans 40 bytes, so one 32-byte word can't
    ///      hold both.
    function _recordAddrBounds(address table, uint256 i)
        private
        view
        returns (uint256 fa, uint256 la)
    {
        uint256 recOff = TABLE_HEADER_BYTES + i * CHUNK_RECORD_BYTES;
        fa = _read20(table, recOff + REC_FIRST);
        la = _read20(table, recOff + REC_LAST);
    }

    /// @dev (nSingles, nMultis) of record `i`.
    function _recordCounts(address table, uint256 i)
        private
        view
        returns (uint256 nSingles, uint256 nMultis)
    {
        uint256 recOff = TABLE_HEADER_BYTES + i * CHUNK_RECORD_BYTES;
        bytes memory b = SSTORE2.read(table, recOff + REC_NSINGLES, recOff + REC_NSINGLES + 8);
        uint256 w;
        assembly {
            w := mload(add(b, 0x20))
        }
        nSingles = w >> 224;
        nMultis = (w >> 192) & 0xffffffff;
    }

    /// @dev Pointer slot `slot` of record `i` (top 20 bytes of the 20-byte read).
    function _recordPointer(address table, uint256 i, uint256 slot) private view returns (address) {
        uint256 off = TABLE_HEADER_BYTES + i * CHUNK_RECORD_BYTES + REC_PTRS + slot * 20;
        return address(uint160(_read20(table, off)));
    }

    /// @dev Inner count within the matched chunk `i`: 1 if `key` is in the
    ///      chunk's singles, the stored count if in its multis, else 0. Reads
    ///      the record tail (counts + pointers) once, then runs `_searchMem`.
    function _innerCount(address table, uint256 i, uint256 key) private view returns (uint256) {
        uint256 recOff = TABLE_HEADER_BYTES + i * CHUNK_RECORD_BYTES;
        // Tail = nSingles(4) · nMultis(4) · ptrs(5×20) = 108 bytes.
        bytes memory tail = SSTORE2.read(table, recOff + REC_NSINGLES, recOff + CHUNK_RECORD_BYTES);
        uint256 nSingles;
        uint256 nMultis;
        assembly {
            let w := mload(add(tail, 0x20))
            nSingles := shr(224, w)
            nMultis := and(shr(192, w), 0xffffffff)
        }
        uint256 nSPtrs = _ceilDiv(nSingles, MAX_CHUNK_DATA_BYTES / SINGLE_BYTES);
        uint256 nMPtrs = _ceilDiv(nMultis, MAX_CHUNK_DATA_BYTES / MULTI_BYTES);

        address[] memory singlesPtrs = new address[](nSPtrs);
        address[] memory multisPtrs = new address[](nMPtrs);
        for (uint256 j; j < nSPtrs; ++j) singlesPtrs[j] = _ptrFromTail(tail, j);
        for (uint256 j; j < nMPtrs; ++j) multisPtrs[j] = _ptrFromTail(tail, nSPtrs + j);

        (bool foundS,) = _searchMem(singlesPtrs, nSingles, SINGLE_BYTES, key);
        if (foundS) return 1;
        (bool foundM, uint256 c) = _searchMem(multisPtrs, nMultis, MULTI_BYTES, key);
        return foundM ? c : 0;
    }

    /// @dev Read pointer `slot` (0-indexed over the record's 5 slots) from the
    ///      already-loaded record tail. Pointers begin at tail offset 8 (after
    ///      the two count words); the top 20 bytes of the 32-byte load are it.
    function _ptrFromTail(bytes memory tail, uint256 slot) private pure returns (address a) {
        uint256 off = 8 + slot * 20;
        uint256 w;
        assembly {
            w := mload(add(add(tail, 0x20), off))
        }
        a = address(uint160(w >> 96));
    }

    /// @dev Memory-pointer twin of `_search`: identical logic (uniform per-chunk
    ///      capacity, valid within a single `build()` call), reading the pointer
    ///      array from memory instead of storage.
    function _searchMem(address[] memory ptrs, uint256 n, uint256 width, uint256 key)
        private
        view
        returns (bool found, uint256 count)
    {
        if (n == 0) return (false, 0);
        uint256 cap = MAX_CHUNK_DATA_BYTES / width;
        uint256 lo;
        uint256 hi = n;
        while (lo < hi) {
            uint256 mid;
            unchecked {
                mid = (lo + hi) >> 1;
            }
            (uint256 km, uint256 cm) = _readAt(ptrs[mid / cap], (mid % cap) * width);
            if (km == key) return (true, cm);
            if (km < key) {
                unchecked {
                    lo = mid + 1;
                }
            } else {
                hi = mid;
            }
        }
        return (false, 0);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "solady/=lib/solady/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.