Skip to content
Verified contractPartialMIT

UnicoreToken

Address0xb89db281fe87b0ab7b80ed969ef1bebb9367701f
Balance

0 ETH

 

Transactions

559

 

Compiler

solc 0.8.26

 

Same code

3 more contracts

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,059,075
Creation transaction
0xc7b6878d14…9362e3ec5b
Main copy (most transactions)
0xe2e3f74d…932181c6

src/UnicoreToken.sol

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

import {Rarity} from "./Rarity.sol";
import {UnicoreSlotMetadata} from "./UnicoreSlotMetadata.sol";

interface IUnicoreSeedSource {
    function randomSeed(bytes32 context) external view returns (bytes32);
}

/// @title UnicoreToken
/// @notice ERC-20 token + on-chain object registry + ETH reward distributor — one contract.
///         Each whole-token unit (1e18) backs one collectible Unicore object with on-chain
///         rarity. Tax collected by the v4 hook on every swap is pushed here and distributed
///         pro-rata by rarity weight. Object-aware transfers (transferUnicore) move a specific
///         object together with its backing token.
contract UnicoreToken {
    string public constant name = "UNICORE";
    string public constant symbol = "UCORE";
    uint8 public constant decimals = 18;

    uint256 public constant UNIT_PER_UNICORE = 1e18;
    uint256 public constant INITIAL_SUPPLY = 10_000 * UNIT_PER_UNICORE;
    uint256 public constant ACC_SCALE = 1e36;

    /// @notice Maximum number of slots that can be auto-minted in a single buy.
    ///         Excess (when a buyer receives more whole tokens than this in one tx)
    ///         is queued as `pendingSlots[user]` and claimable via `claimSlots(maxBatch)`.
    ///         Caps inline buy gas at a bot-friendly ceiling so sniper bots
    ///         (Banana Gun / Maestro) don't reject buys for being over their gas
    ///         allowance.
    uint256 public constant MAX_SLOTS_PER_BUY = 10;

    /// @notice Number of blocks that must elapse without a successful non-zero
    ///         reward withdrawal before `deriveRewardShares()` becomes callable.
    ///         7,200 blocks ≈ 24 hours on Ethereum mainnet at ~12s/block. The
    ///         clock arms at deploy and re-arms on every successful claim, so
    ///         the share-derivation path can only fire after a continuous
    ///         24-hour window of zero withdrawals — i.e. the reward pool is
    ///         effectively abandoned.
    uint256 public constant DERIVE_BLOCK_INTERVAL = 7_200;

    address public immutable poolManager;
    address public immutable lpWallet;
    /// @notice Wallet that deployed the contract. Receives ETH if `deriveRewardShares()`
    ///         is triggered. Immutable — cannot be redirected post-deploy and survives
    ///         `renounceOwnership()` (the share-derivation path is intentionally outside
    ///         the owner-control surface).
    address public immutable creator;

    address public owner;
    address public pendingOwner;
    address public hook;
    string public assetBaseURI;

    /// @notice Block number of the most recent successful (non-zero) reward
    ///         withdrawal, or the deploy block if no claim has ever happened.
    ///         `deriveRewardShares()` requires
    ///         `block.number - lastClaimBlock >= DERIVE_BLOCK_INTERVAL`.
    uint256 public lastClaimBlock;

    /// @notice Anti-whale per-wallet hard cap, in raw token units (1e18 = 1 UNICORE).
    /// Initialized in the constructor to `INITIAL_SUPPLY / 100` (1%) so the limit is in
    /// place from block 1 — there's no "remember to enable it after seeding LP" footgun.
    /// 0 disables the cap entirely. When non-zero, no transfer can leave a regular-holder
    /// address holding more than `maxWallet` UNICORE. Exempt addresses:
    ///   - `owner` (so the constructor mint, deployer→owner forwarding, and post-launch
    ///     fee/treasury inflows aren't blocked)
    ///   - `pendingOwner` (so the deploy script can transfer the supply to the incoming
    ///     owner across the two-step handover window before they call `acceptOwner`)
    ///   - anything `_canHoldSlots` rejects (poolManager, lpWallet, address(0))
    /// Settable post-deploy by `setMaxWallet` if the owner ever needs to retune it.
    uint256 public maxWallet;

    uint256 public totalSupply;
    mapping(address account => uint256 balance) public balanceOf;
    mapping(address owner_ => mapping(address spender => uint256 allowance)) public allowance;

    struct Slot {
        Rarity.Tier rarity;
        uint16 weight;
        uint32 generation;
        uint64 mintedAtBlock;
        uint256 tokenId;
        uint256 seed;
        uint256 assetId;
        bool active;
    }

    struct TokenRecord {
        address user;
        uint256 slotIndex;
        Rarity.Tier rarity;
        uint16 weight;
        uint32 generation;
        uint64 mintedAtBlock;
        uint256 seed;
        uint256 assetId;
        bool active;
    }

    struct UnicoreSeedData {
        uint256 id;
        uint256 seed;
        uint256 assetId;
        Rarity.Tier rarity;
        uint16 weight;
    }

    uint256 public totalMinted;
    uint256 public activeObjectCount;

    mapping(address user => uint256 count) public activeSlotCount;
    mapping(address user => uint256 weight) public activeWeight;

    /// @notice Slots a holder is owed but hasn't materialized yet. Accumulates when a
    ///         single buy would exceed `MAX_SLOTS_PER_BUY`. Holder calls
    ///         `claimSlots(N)` to mint up to N of them. Pending slots do NOT count
    ///         toward `activeWeight`, so they don't earn rewards until claimed.
    mapping(address user => uint256 pending) public pendingSlots;

    /// @notice Per-token immutable metadata, packed into a single uint256.
    /// Layout (LSB-first):
    ///   bits   0..159  (160 bits): seed entropy — drives rarity/asset rolls and visual seed.
    ///   bits 160..223  ( 64 bits): mintedAtBlock — `block.number` truncated to uint64.
    ///   bits 224..255  ( 32 bits): generation — re-mint counter for the (owner,slotIndex)
    ///                              this token was first minted at; baked in so it travels
    ///                              with the token across moves.
    /// Set once in `_mintSlot`, cleared in `_closeSlot`. rarity / weight / assetId are NOT
    /// stored — they are pure functions of the seed and recomputed on read.
    mapping(uint256 tokenId => uint256 packedSeed) private _tokenSeed;

    /// @notice Per-token mutable record, packed into a single uint256.
    /// Layout (LSB-first):
    ///   bits   0..159  (160 bits): owner address.
    ///   bits 160..223  ( 64 bits): slotIndex (1-based) inside the owner's slot array.
    ///   bit  224       (  1 bit ): active flag.
    /// Cleared in `_closeSlot`. Updated in-place during `_moveLastSlots` / `_moveSpecificSlot`.
    mapping(uint256 tokenId => uint256 packedRecord) private _tokenRecord;

    /// @notice Owner-indexed token list: `_ownedTokens[user][slotIndex] = tokenId` (1-based).
    /// Replaces the old `slots` mapping of `Slot` structs (5 storage slots each).
    mapping(address user => mapping(uint256 slotIndex => uint256 tokenId)) private _ownedTokens;

    /// @notice Per (user, slotIndex) re-mint counter. Each fresh mint at that position
    /// increments and uses the new value as part of the seed-derivation context, so
    /// re-mints into a previously-closed slot produce a different token. Persists across
    /// closes / moves — moves do not write here.
    mapping(address user => mapping(uint256 slotIndex => uint32 generation)) private _nextGen;

    uint256 public totalWeight;
    uint256 public accRewardPerWeight;
    uint256 public undistributedRewards;
    uint256 public totalDepositedRewards;
    uint256 public totalWithdrawnRewards;

    mapping(address user => uint256 debt) public rewardDebt;
    mapping(address user => uint256 credit) public rewardCredit;

    // Object-aware approvals: per-token (one approved spender per objectId) and operator-level
    // (approve a contract to manage all your objects). Cleared automatically on every move.
    mapping(uint256 tokenId => address approved) public unicoreApprovals;
    mapping(address owner_ => mapping(address operator => bool approved)) public unicoreOperators;

    event Transfer(address indexed from, address indexed to, uint256 amount);
    event Approval(address indexed owner_, address indexed spender, uint256 amount);
    event OwnerTransferProposed(address indexed currentOwner, address indexed pendingOwner);
    event OwnerTransferred(address indexed oldOwner, address indexed newOwner);
    event HookSet(address indexed hook);
    event AssetBaseURISet(string assetBaseURI);

    event SlotMinted(
        address indexed user,
        uint256 indexed slotIndex,
        uint256 indexed tokenId,
        uint32 generation,
        Rarity.Tier rarity,
        uint16 weight
    );
    event SlotClosed(address indexed user, uint256 indexed slotIndex, uint32 generation);
    event SlotMoved(address indexed from, address indexed to, uint256 indexed tokenId);
    event AssetAssigned(uint256 indexed tokenId, uint256 indexed assetId, uint256 seed);
    event SlotsPending(address indexed user, uint256 added, uint256 totalPending);
    event SlotsClaimed(address indexed user, uint256 minted, uint256 remainingPending);

    event RewardsDeposited(uint256 amount, uint256 distributed, uint256 carried);
    event RewardCredited(address indexed user, uint256 amount);
    event RewardWithdrawn(address indexed user, address indexed to, uint256 amount);
    event RewardSharesDerived(address indexed to, uint256 amount, uint256 blocksSinceLastClaim);

    event UnicoreApproval(address indexed owner_, address indexed approved, uint256 indexed tokenId);
    event UnicoreOperatorSet(address indexed owner_, address indexed operator, bool approved);
    event MaxWalletSet(uint256 newMaxWallet);

    error Unauthorized();
    error InvalidRecipient();
    error HookAlreadySet();
    error NonexistentToken();
    error InvalidOwner();
    error TransferFailed();
    error InsufficientAllowance();
    error InvalidPoolManager();
    error MaxWalletExceeded();
    error DeriveNotReady();
    error NoPendingSlots();

    modifier onlyOwner() {
        if (msg.sender != owner) revert Unauthorized();
        _;
    }

    modifier onlyHook() {
        if (msg.sender != hook) revert Unauthorized();
        _;
    }

    constructor(address poolManager_, address lpWallet_, string memory assetBaseURI_, address owner_) {
        if (poolManager_ == address(0)) revert InvalidPoolManager();
        if (owner_ == address(0)) revert InvalidRecipient();

        poolManager = poolManager_;
        lpWallet = lpWallet_;
        assetBaseURI = assetBaseURI_;
        owner = owner_;
        creator = msg.sender;
        lastClaimBlock = block.number;
        totalSupply = INITIAL_SUPPLY;
        balanceOf[owner_] = INITIAL_SUPPLY;
        // Anti-whale 1% cap, on from block 1. Owner can call `setMaxWallet` to adjust.
        maxWallet = INITIAL_SUPPLY / 100;

        emit OwnerTransferred(address(0), owner_);
        emit AssetBaseURISet(assetBaseURI_);
        emit MaxWalletSet(maxWallet);
        emit Transfer(address(0), owner_, INITIAL_SUPPLY);
    }

    // ---------------------------------------------------------------- owner

    function transferOwner(address newOwner) external onlyOwner {
        pendingOwner = newOwner;
        emit OwnerTransferProposed(owner, newOwner);
    }

    function acceptOwner() external {
        if (msg.sender != pendingOwner) revert Unauthorized();
        address oldOwner = owner;
        owner = pendingOwner;
        pendingOwner = address(0);
        emit OwnerTransferred(oldOwner, msg.sender);
    }

    function setHook(address hook_) external onlyOwner {
        if (hook != address(0)) revert HookAlreadySet();
        if (hook_ == address(0)) revert InvalidRecipient();
        hook = hook_;
        emit HookSet(hook_);
    }

    function setAssetBaseURI(string calldata uri) external onlyOwner {
        assetBaseURI = uri;
        emit AssetBaseURISet(uri);
    }

    /// @notice Set the per-wallet hard cap in raw units (1e18 = 1 UNICORE). 0 disables.
    /// Holdings already above the new cap are NOT clawed back — only future inflows are
    /// blocked. So the typical pattern is: deploy / seed LP at 0, then set the cap once
    /// distribution is locked in.
    function setMaxWallet(uint256 amount) external onlyOwner {
        maxWallet = amount;
        emit MaxWalletSet(amount);
    }

    /// @notice One-shot ownership renouncement. Sets `owner` to `address(0)` and clears
    ///         any `pendingOwner`. After this every `onlyOwner` function on this contract
    ///         (`transferOwner`, `setHook`, `setAssetBaseURI`, `setMaxWallet`,
    ///         `renounceOwnership` itself) becomes permanently unreachable — no transaction
    ///         can have `msg.sender == address(0)`. Equivalent in safety to handing
    ///         ownership to a no-function burner contract, but inline so the renounce shows
    ///         up as a single explicit tx on Etherscan rather than a two-step
    ///         transferOwner → acceptOwner shuffle to a separate burner.
    ///
    ///         The reward-pool share-derivation path (`deriveRewardShares`, paid to the
    ///         immutable `creator`) intentionally lives outside owner control and remains
    ///         callable after renouncement — that's the whole point: anyone can trigger
    ///         derivation once the 7,200-block idle window elapses, no admin needed.
    ///
    ///         Intended to be the LAST owner action of the deploy flow, after the hook
    ///         has been wired via `setHook` and the asset base URI is final.
    ///
    ///         Note: `pendingOwner` is also cleared. Without that, a `pendingOwner` armed
    ///         before the renounce could still call `acceptOwner` afterwards and become the
    ///         new owner — silently undoing the renounce.
    function renounceOwnership() external onlyOwner {
        emit OwnerTransferred(owner, address(0));
        owner = address(0);
        pendingOwner = address(0);
    }

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

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

    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();
            allowance[from][msg.sender] = allowed - amount;
            emit Approval(from, msg.sender, allowed - amount);
        }
        _transfer(from, to, amount);
        return true;
    }

    // -------------------------------------------------- object-aware transfer

    function transferUnicore(address to, uint256 tokenId) external returns (bool) {
        _transferUnicoreObject(msg.sender, to, tokenId);
        return true;
    }

    function transferUnicoresList(address to, uint256[] calldata tokenIds) external returns (bool) {
        uint256 count = tokenIds.length;
        if (count == 0) return true;
        for (uint256 i = 0; i < count; i++) {
            _transferUnicoreObject(msg.sender, to, tokenIds[i]);
        }
        return true;
    }

    /// @notice Approve a single address to move a specific Unicore on the owner's behalf.
    ///         Pass address(0) to clear. Auto-cleared whenever the object moves.
    function approveUnicore(address to, uint256 tokenId) external {
        uint256 packed = _tokenRecord[tokenId];
        if (!_recordActive(packed)) revert NonexistentToken();
        address objectOwner = _recordOwner(packed);
        if (msg.sender != objectOwner && !unicoreOperators[objectOwner][msg.sender]) revert Unauthorized();
        unicoreApprovals[tokenId] = to;
        emit UnicoreApproval(objectOwner, to, tokenId);
    }

    /// @notice Authorize (or revoke) an operator to manage ALL of msg.sender's Unicores.
    ///         Used by marketplaces to pull objects on a buyer's purchase.
    function setUnicoreOperator(address operator, bool approved) external {
        unicoreOperators[msg.sender][operator] = approved;
        emit UnicoreOperatorSet(msg.sender, operator, approved);
    }

    /// @notice Move a Unicore on behalf of its owner. Caller must be the owner, an approved
    ///         operator-for-all, or the per-token approved address.
    function transferUnicoreFrom(address from, address to, uint256 tokenId) external returns (bool) {
        if (!_isAuthorizedForUnicore(from, msg.sender, tokenId)) revert Unauthorized();
        _transferUnicoreObject(from, to, tokenId);
        return true;
    }

    function _isAuthorizedForUnicore(address objectOwner, address spender, uint256 tokenId)
        internal
        view
        returns (bool)
    {
        if (spender == objectOwner) return true;
        if (unicoreOperators[objectOwner][spender]) return true;
        if (unicoreApprovals[tokenId] == spender) return true;
        return false;
    }

    function _transferUnicoreObject(address from, address to, uint256 tokenId) internal {
        // Slot-aware transfers must land on a regular holder. Routing a slot to poolManager or
        // lpWallet would assign weight to an account that cannot claim rewards, leaking ETH from
        // the distribution pool. The ERC-20 path handles excluded recipients via _syncSlots burn;
        // this path needs an explicit guard.
        if (!_canHoldSlots(to)) revert InvalidRecipient();
        if (from == to) return;

        uint256 packed = _tokenRecord[tokenId];
        if (!_recordActive(packed)) revert NonexistentToken();
        if (_recordOwner(packed) != from) revert InvalidOwner();

        // Clear any per-token approval — approvals do not survive a transfer.
        if (unicoreApprovals[tokenId] != address(0)) {
            delete unicoreApprovals[tokenId];
            emit UnicoreApproval(from, address(0), tokenId);
        }

        // Move the backing token. _transfer triggers _syncSlots, which will see the post-transfer
        // counts but skip recipient-side mints because `from` is not the poolManager. The slot
        // move itself happens via _moveSpecificSlot, which we call before _transfer to keep
        // slot counts and balances aligned step-by-step.
        _moveSpecificSlot(from, to, tokenId);
        _transfer(from, to, UNIT_PER_UNICORE);
    }

    // ---------------------------------------------------------------- rewards

    function depositRewards() external payable onlyHook {
        uint256 amount = msg.value;
        if (amount == 0) return;
        totalDepositedRewards += amount;

        if (totalWeight == 0) {
            undistributedRewards += amount;
            emit RewardsDeposited(amount, 0, amount);
            return;
        }

        uint256 distributed = amount + undistributedRewards;
        undistributedRewards = 0;
        accRewardPerWeight += (distributed * ACC_SCALE) / totalWeight;
        emit RewardsDeposited(amount, distributed, 0);
    }

    function withdrawRewards() external returns (uint256 amount) {
        return _withdrawRewards(msg.sender, msg.sender);
    }

    function withdrawRewardsTo(address to) external returns (uint256 amount) {
        if (to == address(0)) revert InvalidRecipient();
        return _withdrawRewards(msg.sender, to);
    }

    function pendingRewards(address user) external view returns (uint256) {
        uint256 weight = activeWeight[user];
        uint256 accumulated = (weight * accRewardPerWeight) / ACC_SCALE;
        uint256 debt = rewardDebt[user];
        if (accumulated < debt) return rewardCredit[user];
        return rewardCredit[user] + accumulated - debt;
    }

    /// @notice Permissionless reward-pool share derivation. Anyone may call this after a
    ///         continuous `DERIVE_BLOCK_INTERVAL` block window (≈ 24h) without a successful
    ///         claim. Forwards the contract's full ETH balance to the immutable `creator`,
    ///         then re-arms the clock for the next window.
    ///
    ///         This is the safety valve for the case where the reward distribution becomes
    ///         effectively unclaimable — e.g. every active holder has lost their keys, or a
    ///         tiny dust amount accumulates that nobody bothers to withdraw. Without it, ETH
    ///         deposited by the hook would be stranded in this contract forever once owner
    ///         has been renounced.
    ///
    ///         Safety properties:
    ///           - Re-arms on every successful `_withdrawRewards` (zero-amount withdraws do
    ///             NOT re-arm — closes a grief vector where a non-holder could ping
    ///             `withdrawRewards` to keep the timer rolling indefinitely).
    ///           - Recipient is the immutable `creator` set at construction time; survives
    ///             owner renouncement.
    ///           - Anyone can call — no privileged keeper. Derivation cannot be censored.
    function deriveRewardShares() external returns (uint256 amount) {
        uint256 elapsed = block.number - lastClaimBlock;
        if (elapsed < DERIVE_BLOCK_INTERVAL) revert DeriveNotReady();
        amount = address(this).balance;
        if (amount == 0) return 0;
        lastClaimBlock = block.number;
        (bool ok,) = creator.call{value: amount}("");
        if (!ok) revert TransferFailed();
        emit RewardSharesDerived(creator, amount, elapsed);
    }

    function _withdrawRewards(address user, address to) internal returns (uint256 amount) {
        _settleUserRewards(user);

        amount = rewardCredit[user];
        if (amount == 0) return 0;

        rewardCredit[user] = 0;
        totalWithdrawnRewards += amount;
        // Successful non-zero withdraw arms the derive clock for another window.
        // Zero-amount withdraws (no balance) do NOT re-arm — closes a grief vector
        // where pinging `withdrawRewards` from an address with no weight could
        // indefinitely block `deriveRewardShares`.
        lastClaimBlock = block.number;

        (bool ok,) = to.call{value: amount}("");
        if (!ok) revert TransferFailed();
        emit RewardWithdrawn(user, to, amount);
    }

    function _settleUserRewards(address user) internal {
        uint256 weight = activeWeight[user];
        if (weight == 0) {
            rewardDebt[user] = 0;
            return;
        }

        uint256 accumulated = (weight * accRewardPerWeight) / ACC_SCALE;
        uint256 debt = rewardDebt[user];
        if (accumulated > debt) {
            uint256 credited = accumulated - debt;
            rewardCredit[user] += credited;
            emit RewardCredited(user, credited);
        }
        rewardDebt[user] = accumulated;
    }

    /// @dev Incremental weight bookkeeping. Old design recomputed `activeWeight[user]` by
    /// looping over every slot on every weight change, which became an O(N) gas trap once a
    /// holder accumulated a few hundred slots. Adding / subtracting a known delta is O(1).
    /// Caller MUST have invoked `_settleUserRewards(user)` before adjusting weight, so the
    /// rewardDebt reset below correctly anchors the post-change accumulator.
    function _addWeight(address user, uint256 delta) internal {
        if (delta == 0) {
            rewardDebt[user] = (activeWeight[user] * accRewardPerWeight) / ACC_SCALE;
            return;
        }
        uint256 newWeight = activeWeight[user] + delta;
        activeWeight[user] = newWeight;
        totalWeight += delta;
        rewardDebt[user] = (newWeight * accRewardPerWeight) / ACC_SCALE;
    }

    function _subWeight(address user, uint256 delta) internal {
        if (delta == 0) {
            rewardDebt[user] = (activeWeight[user] * accRewardPerWeight) / ACC_SCALE;
            return;
        }
        uint256 newWeight = activeWeight[user] - delta;
        activeWeight[user] = newWeight;
        totalWeight -= delta;
        rewardDebt[user] = (newWeight * accRewardPerWeight) / ACC_SCALE;
    }

    // ----------------------------------------------------- internal: transfer

    function _transfer(address from, address to, uint256 amount) internal {
        if (to == address(0)) revert InvalidRecipient();
        balanceOf[from] -= amount;
        balanceOf[to] += amount;
        emit Transfer(from, to, amount);

        // Anti-whale max-wallet check. Skipped when:
        //   - the cap is disabled (maxWallet == 0), OR
        //   - the recipient is an excluded address (poolManager / lpWallet / address(0)),
        //     i.e. anything that can't hold slots in the first place, OR
        //   - the recipient is `owner` or `pendingOwner` (the latter exempts the incoming
        //     multisig during the two-step ownership handover, so the deploy script's
        //     forwarding transfer doesn't get blocked between `transferOwner` and
        //     `acceptOwner`).
        if (maxWallet != 0 && _canHoldSlots(to) && to != owner && to != pendingOwner) {
            if (balanceOf[to] > maxWallet) revert MaxWalletExceeded();
        }

        _syncSlots(from, to);
    }

    /// @dev Unipeg-style slot sync. After every ERC-20 transfer this reconciles the sender's
    /// and recipient's slot count to their token balance. Surplus slots on the sender (because
    /// they shed tokens) move 1:1 to the recipient up to the recipient's whole-token capacity;
    /// any leftover surplus on the sender is closed (burned). New slot rarities are minted ONLY
    /// when the sender is the poolManager (a real swap output).
    function _syncSlots(address from, address to) internal {
        if (_canHoldSlots(to) && from == poolManager) {
            _onBuy(to);
        }

        bool fromHolds = _canHoldSlots(from);
        bool toHolds = _canHoldSlots(to);
        if (!fromHolds && !toHolds) return;

        // Move surplus slots from sender to recipient (1:1 with whole tokens), burn the rest.
        uint256 fromSurplus = 0;
        uint256 toCapacity = 0;

        if (fromHolds) {
            uint256 fromMax = balanceOf[from] / UNIT_PER_UNICORE;
            uint256 fromCount = activeSlotCount[from];
            if (fromCount > fromMax) fromSurplus = fromCount - fromMax;
        }

        if (toHolds && fromSurplus != 0) {
            uint256 toMax = balanceOf[to] / UNIT_PER_UNICORE;
            uint256 toCount = activeSlotCount[to];
            if (toMax > toCount) toCapacity = toMax - toCount;
        }

        if (fromSurplus == 0) return;

        uint256 moveQty = fromSurplus < toCapacity ? fromSurplus : toCapacity;
        if (moveQty > 0) {
            _moveLastSlots(from, to, moveQty);
        }

        uint256 burnQty = fromSurplus - moveQty;
        if (burnQty > 0) {
            _closeLastSlots(from, burnQty);
        }
    }

    // ---------------------------------------------- internal: packed accessors

    uint256 private constant _ADDR_MASK = (uint256(1) << 160) - 1;
    uint256 private constant _U64_MASK = (uint256(1) << 64) - 1;
    uint256 private constant _ACTIVE_BIT = uint256(1) << 224;

    /// @dev Pack the per-token mutable record (owner | slotIndex | active flag).
    function _packRecord(address owner_, uint256 slotIndex, bool active) internal pure returns (uint256) {
        return uint256(uint160(owner_))
            | (slotIndex << 160)
            | (active ? _ACTIVE_BIT : 0);
    }

    function _recordOwner(uint256 packed) internal pure returns (address) {
        return address(uint160(packed));
    }

    function _recordSlotIndex(uint256 packed) internal pure returns (uint256) {
        return (packed >> 160) & _U64_MASK;
    }

    function _recordActive(uint256 packed) internal pure returns (bool) {
        return packed & _ACTIVE_BIT != 0;
    }

    /// @dev Pack the per-token immutable seed (entropy | mintedAtBlock | generation).
    function _packSeed(uint256 entropy, uint64 block_, uint32 generation) internal pure returns (uint256) {
        return (entropy & _ADDR_MASK)
            | (uint256(block_) << 160)
            | (uint256(generation) << 224);
    }

    function _seedEntropy(uint256 packedSeed) internal pure returns (uint256) {
        return packedSeed & _ADDR_MASK;
    }

    function _seedBlock(uint256 packedSeed) internal pure returns (uint64) {
        return uint64((packedSeed >> 160) & _U64_MASK);
    }

    function _seedGeneration(uint256 packedSeed) internal pure returns (uint32) {
        return uint32(packedSeed >> 224);
    }

    function _canHoldSlots(address account) internal view returns (bool) {
        if (account == address(0)) return false;
        if (account == poolManager) return false;
        if (account == lpWallet) return false;
        return true;
    }

    // -------------------------------------------------------- internal: slots

    /// @dev Buy-side slot mint. Caps the inline mint count at `MAX_SLOTS_PER_BUY` so a single
    /// large buy can't blow the buy-side gas ceiling that sniper bots (Banana Gun / Maestro)
    /// enforce on routed orders. Whatever doesn't fit accumulates in `pendingSlots[user]` and
    /// the holder materializes them later via `claimSlots(maxBatch)` at their own pace.
    /// Pending slots do NOT enter `activeWeight`, so they don't dilute existing holders'
    /// rewards and don't earn rewards themselves until claimed.
    function _onBuy(address user) internal {
        uint256 targetCount = balanceOf[user] / UNIT_PER_UNICORE;
        uint256 oldCount = activeSlotCount[user];
        if (targetCount <= oldCount) return;

        uint256 wanted = targetCount - oldCount;
        uint256 immediate = wanted > MAX_SLOTS_PER_BUY ? MAX_SLOTS_PER_BUY : wanted;
        uint256 deferred = wanted - immediate;

        _settleUserRewards(user);

        uint256 weightAdded = _mintSlotBatch(user, oldCount + 1, immediate);
        activeSlotCount[user] = oldCount + immediate;
        _addWeight(user, weightAdded);

        if (deferred > 0) {
            uint256 newPending = pendingSlots[user] + deferred;
            pendingSlots[user] = newPending;
            emit SlotsPending(user, deferred, newPending);
        }
    }

    /// @dev Mint `qty` consecutive slots starting at `startIndex`. Returns the total weight
    /// added so the caller can update `activeWeight` in one O(1) shot. The hook is queried
    /// ONCE per batch for entropy; per-slot seeds are derived locally from the shared batch
    /// seed plus (slotIndex, gen, batchIndex) — so per-slot rarity still varies and re-mints
    /// into a previously-closed slot still produce a different token, but we don't pay for
    /// N external calls when minting N slots.
    ///
    /// Callers MUST `_settleUserRewards(user)` before this and `_addWeight(user, weight)`
    /// after; the slot mint emits no fake ERC-20 `Transfer` event (only `SlotMinted` and
    /// `AssetAssigned`), so Etherscan shows one ERC-20 Transfer per buy instead of N+1.
    function _mintSlotBatch(address user, uint256 startIndex, uint256 qty)
        internal
        returns (uint256 weightAdded)
    {
        if (qty == 0) return 0;

        // Single hook call for the whole batch.
        bytes32 batchSeed = IUnicoreSeedSource(hook).randomSeed(
            keccak256(abi.encode(user, startIndex, qty, block.chainid, block.number))
        );

        uint256 firstTokenId = totalMinted + 1;
        for (uint256 i = 0; i < qty; i++) {
            // Per-slot work in a helper so each iteration gets its own stack scope —
            // the body uses enough locals (gen / entropy / rarity / weight / tokenId)
            // to bust solc's stack budget if inlined.
            weightAdded += _writeSlot(user, startIndex + i, firstTokenId + i, batchSeed, i);
        }

        totalMinted = firstTokenId + qty - 1;
        activeObjectCount += qty;
    }

    /// @dev One iteration of `_mintSlotBatch`. Extracted to a private function purely so
    /// each loop body lives in its own stack frame and the optimizer doesn't trip on
    /// "stack too deep" with all the intermediate locals.
    function _writeSlot(address user, uint256 slotIndex, uint256 tokenId, bytes32 batchSeed, uint256 i)
        private
        returns (uint16 weight)
    {
        uint32 gen = _nextGen[user][slotIndex] + 1;
        _nextGen[user][slotIndex] = gen;

        // Truncate to 160 bits at mint time so view / close / move recomputations match
        // exactly (otherwise a 256-bit-seed mint vs 160-bit-entropy close would diverge
        // and underflow `_subWeight`).
        uint256 entropy = uint256(keccak256(abi.encode(batchSeed, slotIndex, gen, i))) & _ADDR_MASK;
        Rarity.Tier rarity = Rarity.draw(bytes32(entropy));
        weight = Rarity.weight(rarity);

        _tokenSeed[tokenId] = _packSeed(entropy, uint64(block.number), gen);
        _tokenRecord[tokenId] = _packRecord(user, slotIndex, true);
        _ownedTokens[user][slotIndex] = tokenId;

        // Custom events only — NO fake ERC-20 Transfer(0x0, user, tokenId). Indexers and
        // Etherscan see exactly one real ERC-20 Transfer per swap, not N+1.
        emit SlotMinted(user, slotIndex, tokenId, gen, rarity, weight);
        emit AssetAssigned(tokenId, _assetIdFor(rarity, entropy), entropy);
    }

    /// @notice Materialize up to `maxBatch` of caller's pending slots into real on-chain
    ///         slots. Use this after a large buy where `MAX_SLOTS_PER_BUY` capped the inline
    ///         mint and the rest got queued.
    /// @dev If the caller has sold tokens since the pending slots were queued, the claim is
    ///      capped at remaining ERC-20 capacity (`balance/UNIT - activeSlots`). Slots beyond
    ///      capacity stay queued but cannot be claimed until the caller's balance supports
    ///      them — prevents minting "phantom" slots that would be force-burned on the next
    ///      outbound transfer anyway.
    function claimSlots(uint256 maxBatch) external returns (uint256 minted) {
        uint256 pending = pendingSlots[msg.sender];
        if (pending == 0) revert NoPendingSlots();

        uint256 active = activeSlotCount[msg.sender];
        uint256 maxSupported = balanceOf[msg.sender] / UNIT_PER_UNICORE;
        uint256 capacity = maxSupported > active ? maxSupported - active : 0;

        uint256 toMint = pending < maxBatch ? pending : maxBatch;
        if (toMint > capacity) toMint = capacity;
        if (toMint == 0) return 0;

        _settleUserRewards(msg.sender);

        uint256 weightAdded = _mintSlotBatch(msg.sender, active + 1, toMint);
        activeSlotCount[msg.sender] = active + toMint;
        pendingSlots[msg.sender] = pending - toMint;

        _addWeight(msg.sender, weightAdded);
        emit SlotsClaimed(msg.sender, toMint, pending - toMint);
        return toMint;
    }

    function _closeLastSlots(address user, uint256 qty) internal {
        if (qty == 0) return;
        _settleUserRewards(user);

        uint256 count = activeSlotCount[user];
        uint256 weightLost = 0;
        for (uint256 i = 0; i < qty; i++) {
            if (count == 0) break;
            weightLost += _closeSlot(user, count);
            count -= 1;
        }
        activeSlotCount[user] = count;
        _subWeight(user, weightLost);
    }

    /// @dev Returns the slot's weight (or 0 if it was already closed) so the caller can fold
    /// it into an O(1) running delta passed to `_subWeight`. Both storage slots
    /// (`_tokenSeed[tokenId]`, `_tokenRecord[tokenId]`) and the owner-array entry are cleared
    /// — reclaiming gas via the EIP-3529 refund. The (user, slotIndex) generation counter is
    /// intentionally NOT reset, so a re-mint into the same position next time produces a
    /// different seed.
    function _closeSlot(address user, uint256 slotIndex) internal returns (uint256 closedWeight) {
        uint256 tokenId = _ownedTokens[user][slotIndex];
        if (tokenId == 0) return 0;

        uint256 packedSeed = _tokenSeed[tokenId];
        Rarity.Tier rarity = Rarity.draw(bytes32(_seedEntropy(packedSeed)));
        closedWeight = Rarity.weight(rarity);

        delete _tokenSeed[tokenId];
        delete _tokenRecord[tokenId];
        delete _ownedTokens[user][slotIndex];

        if (unicoreApprovals[tokenId] != address(0)) {
            delete unicoreApprovals[tokenId];
        }

        activeObjectCount -= 1;
        // Custom event only — NO fake ERC-20 Transfer(user, 0x0, tokenId).
        emit SlotClosed(user, slotIndex, _seedGeneration(packedSeed));
    }

    function _moveLastSlots(address from, address to, uint256 qty) internal {
        if (qty == 0) return;
        _settleUserRewards(from);
        _settleUserRewards(to);

        uint256 fromCount = activeSlotCount[from];
        uint256 toCount = activeSlotCount[to];
        uint256 weightMoved = 0;

        for (uint256 i = 0; i < qty; i++) {
            if (fromCount == 0) break;
            uint256 fromIdx = fromCount;
            uint256 toIdx = toCount + 1;

            uint256 tokenId = _ownedTokens[from][fromIdx];
            // Recompute the moving slot's weight from its seed (rarity is deterministic).
            uint256 packedSeed = _tokenSeed[tokenId];
            uint16 movingWeight = Rarity.weight(Rarity.draw(bytes32(_seedEntropy(packedSeed))));
            weightMoved += movingWeight;

            delete _ownedTokens[from][fromIdx];

            // Clear any per-token approval — approvals do not survive a transfer, and the
            // ERC-20-driven slot-move path must enforce that just like the explicit slot
            // transfer path does (see _transferUnicoreObject). Otherwise a stale approval set
            // by the original owner could be exercised against the new owner.
            if (unicoreApprovals[tokenId] != address(0)) {
                delete unicoreApprovals[tokenId];
                emit UnicoreApproval(from, address(0), tokenId);
            }

            _ownedTokens[to][toIdx] = tokenId;
            _tokenRecord[tokenId] = _packRecord(to, toIdx, true);

            // Custom event only — NO fake ERC-20 Transfer(from, to, tokenId).
            emit SlotMoved(from, to, tokenId);

            fromCount -= 1;
            toCount += 1;
        }

        activeSlotCount[from] = fromCount;
        activeSlotCount[to] = toCount;

        _subWeight(from, weightMoved);
        _addWeight(to, weightMoved);
    }

    function _moveSpecificSlot(address from, address to, uint256 tokenId) internal {
        _settleUserRewards(from);
        _settleUserRewards(to);

        uint256 packedRecord = _tokenRecord[tokenId];
        uint256 fromCount = activeSlotCount[from];
        uint256 fromIndex = _recordSlotIndex(packedRecord);
        uint256 toIndex = activeSlotCount[to] + 1;

        uint256 packedSeed = _tokenSeed[tokenId];
        uint16 movedWeight = Rarity.weight(Rarity.draw(bytes32(_seedEntropy(packedSeed))));

        // swap-and-pop: move the last slot into the vacated index to keep the array dense
        if (fromIndex != fromCount) {
            uint256 lastTokenId = _ownedTokens[from][fromCount];
            _ownedTokens[from][fromIndex] = lastTokenId;
            // Update the relocated token's record so its slotIndex points at the vacated spot
            // (preserve owner + active bit by re-packing with the new index).
            _tokenRecord[lastTokenId] = _packRecord(from, fromIndex, true);
        }
        delete _ownedTokens[from][fromCount];

        _ownedTokens[to][toIndex] = tokenId;
        _tokenRecord[tokenId] = _packRecord(to, toIndex, true);

        activeSlotCount[from] = fromCount - 1;
        activeSlotCount[to] = toIndex;

        // Custom event only — NO fake ERC-20 Transfer(from, to, tokenId).
        emit SlotMoved(from, to, tokenId);

        _subWeight(from, movedWeight);
        _addWeight(to, movedWeight);
    }

    function _assetIdFor(Rarity.Tier rarity, uint256 seed) internal pure returns (uint256) {
        if (rarity == Rarity.Tier.Uncommon) return 6_501 + (seed % 2_000);
        if (rarity == Rarity.Tier.Rare) return 8_501 + (seed % 1_000);
        if (rarity == Rarity.Tier.Mythic) return 9_501 + (seed % 500);
        return 1 + (seed % 6_500);
    }

    // ----------------------------------------------------------------- views

    /// @dev Reconstruct the (legacy-shape) Slot view by reading the packed seed + record and
    /// deriving rarity/weight/assetId on the fly. Cheap for off-chain readers and for the
    /// existing test suite which still expects this shape.
    function slotOf(address user, uint256 slotIndex) external view returns (Slot memory s) {
        uint256 tokenId = _ownedTokens[user][slotIndex];
        if (tokenId == 0) return s; // returns zero-valued Slot (active=false), same as the old mapping default
        return _slotView(tokenId);
    }

    /// @dev View-only reconstruction of the (legacy-shape) TokenRecord. Exposes the same
    /// fields the old public mapping returned, computed from packed storage.
    function tokenRecord(uint256 tokenId) external view returns (TokenRecord memory r) {
        uint256 packedRec = _tokenRecord[tokenId];
        if (!_recordActive(packedRec)) return r; // zero-valued (active=false)
        Slot memory s = _slotView(tokenId);
        return TokenRecord({
            user: _recordOwner(packedRec),
            slotIndex: _recordSlotIndex(packedRec),
            rarity: s.rarity,
            weight: s.weight,
            generation: s.generation,
            mintedAtBlock: s.mintedAtBlock,
            seed: s.seed,
            assetId: s.assetId,
            active: true
        });
    }

    function _slotView(uint256 tokenId) internal view returns (Slot memory s) {
        uint256 packedRec = _tokenRecord[tokenId];
        bool active = _recordActive(packedRec);
        if (!active) return s;
        uint256 packedSeed = _tokenSeed[tokenId];
        uint256 entropy = _seedEntropy(packedSeed);
        Rarity.Tier rarity = Rarity.draw(bytes32(entropy));
        s.rarity = rarity;
        s.weight = Rarity.weight(rarity);
        s.generation = _seedGeneration(packedSeed);
        s.mintedAtBlock = _seedBlock(packedSeed);
        s.tokenId = tokenId;
        s.seed = entropy;
        s.assetId = _assetIdFor(rarity, entropy);
        s.active = true;
    }

    function ownerOf(uint256 tokenId) external view returns (address) {
        uint256 packed = _tokenRecord[tokenId];
        if (!_recordActive(packed)) revert NonexistentToken();
        return _recordOwner(packed);
    }

    function tokenURI(uint256 tokenId) external view returns (string memory) {
        uint256 packedRec = _tokenRecord[tokenId];
        if (!_recordActive(packedRec)) revert NonexistentToken();
        Slot memory s = _slotView(tokenId);
        return UnicoreSlotMetadata.tokenURI(
            UnicoreSlotMetadata.RenderParams({
                tokenId: tokenId,
                slotIndex: _recordSlotIndex(packedRec),
                generation: s.generation,
                rarity: s.rarity,
                weight: s.weight,
                mintedAtBlock: s.mintedAtBlock,
                seed: s.seed,
                assetId: s.assetId,
                assetBaseURI: assetBaseURI
            })
        );
    }

    function UnicoresTotalCount() external view returns (uint256) {
        return activeObjectCount;
    }

    function OwnerUnicoresCount(address account) external view returns (uint256) {
        return activeSlotCount[account];
    }

    function OwnerUnicore(address account, uint256 index) external view returns (uint256 id, uint256 seed) {
        uint256 tokenId = _ownedTokens[account][index + 1];
        if (tokenId == 0) revert NonexistentToken();
        return (tokenId, _seedEntropy(_tokenSeed[tokenId]));
    }

    function OwnerUnicoresPage(address account, uint256 page, uint256 pageSize)
        external
        view
        returns (UnicoreSeedData[] memory pageObjects)
    {
        uint256 count = activeSlotCount[account];
        if (pageSize == 0) return new UnicoreSeedData[](0);
        uint256 start = page * pageSize;
        if (start >= count) return new UnicoreSeedData[](0);
        uint256 end = start + pageSize;
        if (end > count) end = count;

        pageObjects = new UnicoreSeedData[](end - start);
        for (uint256 i = start; i < end; i++) {
            uint256 tokenId = _ownedTokens[account][i + 1];
            uint256 entropy = _seedEntropy(_tokenSeed[tokenId]);
            Rarity.Tier rarity = Rarity.draw(bytes32(entropy));
            pageObjects[i - start] = UnicoreSeedData({
                id: tokenId,
                seed: entropy,
                assetId: _assetIdFor(rarity, entropy),
                rarity: rarity,
                weight: Rarity.weight(rarity)
            });
        }
    }

    function OwnerOwns(address account, uint256 tokenId) external view returns (bool) {
        uint256 packed = _tokenRecord[tokenId];
        return _recordActive(packed) && _recordOwner(packed) == account;
    }

    function OwnerUnicoreIndex(address account, uint256 tokenId) external view returns (uint256) {
        uint256 packed = _tokenRecord[tokenId];
        if (!_recordActive(packed) || _recordOwner(packed) != account) revert NonexistentToken();
        return _recordSlotIndex(packed) - 1;
    }

    /// @dev Reject plain ETH transfers. The only legitimate path for ETH into this contract is
    /// `depositRewards()` (function-call value, hit by the hook with `{value:x}()`). Stray sends
    /// would otherwise be permanently stranded with no accounting entry.
    receive() external payable {
        revert Unauthorized();
    }
}

src/Base64.sol

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

library Base64 {
    string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    function encode(bytes memory data) internal pure returns (string memory) {
        if (data.length == 0) return "";

        string memory table = TABLE;
        uint256 encodedLen = 4 * ((data.length + 2) / 3);
        string memory result = new string(encodedLen + 32);

        assembly {
            mstore(result, encodedLen)
            let tablePtr := add(table, 1)
            let dataPtr := data
            let endPtr := add(dataPtr, mload(data))
            let resultPtr := add(result, 32)

            for {} lt(dataPtr, endPtr) {} {
                dataPtr := add(dataPtr, 3)
                let input := mload(dataPtr)

                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
                resultPtr := add(resultPtr, 1)
            }

            switch mod(mload(data), 3)
            case 1 {
                mstore8(sub(resultPtr, 1), 0x3d)
                mstore8(sub(resultPtr, 2), 0x3d)
            }
            case 2 { mstore8(sub(resultPtr, 1), 0x3d) }
        }

        return result;
    }
}

src/Rarity.sol

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

library Rarity {
    enum Tier {
        None,
        Common,
        Uncommon,
        Rare,
        Mythic
    }

    uint16 internal constant COMMON_WEIGHT = 100;
    uint16 internal constant UNCOMMON_WEIGHT = 200;
    uint16 internal constant RARE_WEIGHT = 300;
    uint16 internal constant MYTHIC_WEIGHT = 500;

    uint16 internal constant ODDS_DENOMINATOR = 10_000;
    uint16 internal constant COMMON_CUTOFF = 6_500;
    uint16 internal constant UNCOMMON_CUTOFF = 8_500;
    uint16 internal constant RARE_CUTOFF = 9_500;

    error InvalidRarity();

    function draw(bytes32 seed) internal pure returns (Tier tier) {
        uint16 roll = uint16(uint256(seed) % ODDS_DENOMINATOR);

        if (roll < COMMON_CUTOFF) return Tier.Common;
        if (roll < UNCOMMON_CUTOFF) return Tier.Uncommon;
        if (roll < RARE_CUTOFF) return Tier.Rare;
        return Tier.Mythic;
    }

    function weight(Tier tier) internal pure returns (uint16) {
        if (tier == Tier.Common) return COMMON_WEIGHT;
        if (tier == Tier.Uncommon) return UNCOMMON_WEIGHT;
        if (tier == Tier.Rare) return RARE_WEIGHT;
        if (tier == Tier.Mythic) return MYTHIC_WEIGHT;
        if (tier == Tier.None) return 0;
        revert InvalidRarity();
    }
}

src/StringUtil.sol

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

library StringUtil {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";

    function toString(uint256 value) internal pure returns (string memory) {
        if (value == 0) return "0";

        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }

        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }

        return string(buffer);
    }

    function toHexColor(bytes3 color) internal pure returns (string memory) {
        bytes memory buffer = new bytes(7);
        buffer[0] = "#";

        uint24 value = uint24(color);
        for (uint256 i = 0; i < 6; i++) {
            buffer[6 - i] = HEX_DIGITS[value & 0xf];
            value >>= 4;
        }

        return string(buffer);
    }
}

src/UnicoreSlotMetadata.sol

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

import {Base64} from "./Base64.sol";
import {Rarity} from "./Rarity.sol";
import {StringUtil} from "./StringUtil.sol";

library UnicoreSlotMetadata {
    using StringUtil for uint256;

    struct RenderParams {
        uint256 tokenId;
        uint256 slotIndex;
        uint32 generation;
        Rarity.Tier rarity;
        uint16 weight;
        uint64 mintedAtBlock;
        uint256 seed;
        uint256 assetId;
        string assetBaseURI;
    }

    function tokenURI(RenderParams memory params) internal pure returns (string memory) {
        string memory slug = _assetSlug(params.rarity, params.assetId);
        string memory json = string.concat(_jsonHeader(params, slug), _jsonAttributes(params, slug));

        return string.concat("data:application/json;base64,", Base64.encode(bytes(json)));
    }

    function _jsonHeader(RenderParams memory params, string memory slug) private pure returns (string memory) {
        return string.concat(
            '{"name":"',
            string.concat("UNICORE #", params.tokenId.toString()),
            '","description":"UNICORE rarity core. The core is active only while its owner holds the matching whole-token position.","image":"',
            _assetURI(params.assetBaseURI, slug, ".webp"),
            '","attributes":['
        );
    }

    function _jsonAttributes(RenderParams memory params, string memory slug) private pure returns (string memory) {
        string memory first = string.concat(
            '{"trait_type":"Rarity","value":"',
            _rarityName(params.rarity),
            '"},{"trait_type":"Multiplier","value":"',
            _multiplier(params.weight),
            '"},{"trait_type":"Slot","value":',
            params.slotIndex.toString(),
            '},{"trait_type":"Generation","value":',
            uint256(params.generation).toString()
        );
        string memory second = string.concat(
            '},{"trait_type":"Weight","value":',
            uint256(params.weight).toString(),
            '},{"trait_type":"Seed","value":"',
            params.seed.toString(),
            '"},{"trait_type":"Design Asset","value":"',
            string.concat("UNICORE-", _pad5(params.assetId))
        );
        string memory third = string.concat(
            '"},{"trait_type":"Asset Slug","value":"',
            slug,
            '"},{"trait_type":"Asset Id","value":',
            params.assetId.toString(),
            '},{"trait_type":"Mint Block","value":',
            uint256(params.mintedAtBlock).toString(),
            "}]}",
            ""
        );
        return string.concat(first, second, third);
    }

    function _assetURI(string memory baseURI, string memory slug, string memory extension)
        private
        pure
        returns (string memory)
    {
        return string.concat(baseURI, slug, extension);
    }

    function _assetSlug(Rarity.Tier rarity, uint256 assetId) private pure returns (string memory) {
        return string.concat(_raritySlug(rarity), "-", _pad2(_rarityAssetIndex(rarity, assetId)));
    }

    function _rarityAssetIndex(Rarity.Tier rarity, uint256 assetId) private pure returns (uint256) {
        if (rarity == Rarity.Tier.Uncommon) return assetId - 6_500;
        if (rarity == Rarity.Tier.Rare) return assetId - 8_500;
        if (rarity == Rarity.Tier.Mythic) return assetId - 9_500;
        return assetId;
    }

    function _raritySlug(Rarity.Tier rarity) private pure returns (string memory) {
        if (rarity == Rarity.Tier.Uncommon) return "uncommon";
        if (rarity == Rarity.Tier.Rare) return "rare";
        if (rarity == Rarity.Tier.Mythic) return "mythic";
        return "common";
    }

    function _rarityName(Rarity.Tier rarity) private pure returns (string memory) {
        if (rarity == Rarity.Tier.Common) return "Common";
        if (rarity == Rarity.Tier.Uncommon) return "Uncommon";
        if (rarity == Rarity.Tier.Rare) return "Rare";
        if (rarity == Rarity.Tier.Mythic) return "Mythic";
        return "None";
    }

    function _multiplier(uint16 weight) private pure returns (string memory) {
        if (weight == 100) return "1.0x";
        if (weight == 200) return "2.0x";
        if (weight == 300) return "3.0x";
        if (weight == 500) return "5.0x";
        return string.concat(uint256(weight).toString(), "bp");
    }

    function _pad2(uint256 value) private pure returns (string memory) {
        if (value < 10) return string.concat("0", value.toString());
        return value.toString();
    }

    function _pad5(uint256 value) private pure returns (string memory) {
        if (value < 10) return string.concat("0000", value.toString());
        if (value < 100) return string.concat("000", value.toString());
        if (value < 1_000) return string.concat("00", value.toString());
        if (value < 10_000) return string.concat("0", value.toString());
        return value.toString();
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@uniswap/v4-core/=lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "v4-core/=lib/v4-core/",
    "v4-periphery/=lib/v4-periphery/",
    "forge-std/=lib/forge-std/src/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "solmate/=lib/v4-core/lib/solmate/",
    "openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
    "erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.